diff --git a/dist/cli.js b/dist/cli.js index 1a3877e..560e034 100755 --- a/dist/cli.js +++ b/dist/cli.js @@ -24423,6 +24423,9 @@ var init_solana_balance = __esm({ getWalletAddress() { return this.walletAddress; } + getAssetSymbol() { + return "USDC"; + } /** * Check native SOL balance (in lamports). Useful for detecting users who * funded with SOL instead of USDC. @@ -24476,6 +24479,7 @@ var init_solana_balance = __esm({ return { balance, balanceUSD: `$${dollars.toFixed(2)}`, + assetSymbol: "USDC", isLow: balance < 1000000n, isEmpty: balance < 100n, walletAddress: this.walletAddress @@ -41823,8 +41827,73 @@ var RpcError2 = class extends Error { } }; +// src/payment-asset.ts +var DEFAULT_BASE_PAYMENT_ASSET = { + chain: "base", + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + symbol: "USDC", + decimals: 6, + name: "USD Coin", + transferMethod: "eip3009" +}; +function isHexAddress(value) { + return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value); +} +function normalizeBasePaymentAsset(value) { + if (!value || typeof value !== "object") return void 0; + const candidate = value; + if (!isHexAddress(candidate.asset)) return void 0; + if (typeof candidate.symbol !== "string" || candidate.symbol.trim() === "") return void 0; + if (typeof candidate.decimals !== "number" || !Number.isInteger(candidate.decimals) || candidate.decimals < 0) { + return void 0; + } + if (typeof candidate.name !== "string" || candidate.name.trim() === "") return void 0; + if (candidate.transferMethod !== void 0 && candidate.transferMethod !== "eip3009") { + return void 0; + } + return { + chain: "base", + asset: candidate.asset, + symbol: candidate.symbol.trim().toUpperCase(), + decimals: candidate.decimals, + name: candidate.name.trim(), + transferMethod: "eip3009", + priority: typeof candidate.priority === "number" ? candidate.priority : void 0, + enabled: typeof candidate.enabled === "boolean" ? candidate.enabled : void 0 + }; +} +function sortAssets(assets) { + return [...assets].sort( + (a, b) => (a.priority ?? Number.MAX_SAFE_INTEGER) - (b.priority ?? Number.MAX_SAFE_INTEGER) + ); +} +function normalizeBasePaymentAssets(value) { + if (!value || typeof value !== "object") return [DEFAULT_BASE_PAYMENT_ASSET]; + const payload = value; + const candidateList = Array.isArray(payload.paymentAssets) ? payload.paymentAssets : [ + payload.paymentAsset, + payload.base, + payload + ]; + const normalized = candidateList.map((candidate) => normalizeBasePaymentAsset(candidate)).filter((asset) => Boolean(asset)).filter((asset) => asset.enabled !== false && asset.transferMethod === "eip3009"); + return sortAssets( + normalized.length > 0 ? normalized : [DEFAULT_BASE_PAYMENT_ASSET] + ); +} +async function fetchBasePaymentAssets(apiBase, baseFetch = fetch) { + try { + const response = await baseFetch(`${apiBase.replace(/\/+$/, "")}/v1/payment-metadata?chain=base`, { + headers: { Accept: "application/json" } + }); + if (!response.ok) return [DEFAULT_BASE_PAYMENT_ASSET]; + const payload = await response.json(); + return normalizeBasePaymentAssets(payload); + } catch { + return [DEFAULT_BASE_PAYMENT_ASSET]; + } +} + // src/balance.ts -var USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; var CACHE_TTL_MS = 3e4; var BALANCE_THRESHOLDS = { /** Low balance warning threshold: $1.00 */ @@ -41832,15 +41901,18 @@ var BALANCE_THRESHOLDS = { /** Effectively zero threshold: $0.0001 (covers dust/rounding) */ ZERO_THRESHOLD: 100n }; -var BalanceMonitor = class { +var BalanceMonitor = class _BalanceMonitor { client; walletAddress; - /** Cached balance (null = not yet fetched) */ - cachedBalance = null; - /** Timestamp when cache was last updated */ - cachedAt = 0; - constructor(walletAddress) { + assetMonitors = /* @__PURE__ */ new Map(); + state; + constructor(walletAddress, asset = DEFAULT_BASE_PAYMENT_ASSET) { this.walletAddress = walletAddress; + this.state = { + asset, + cachedBalance: null, + cachedAt: 0 + }; this.client = createPublicClient({ chain: base, transport: http(void 0, { @@ -41854,21 +41926,22 @@ var BalanceMonitor = class { * Uses cache if valid, otherwise fetches from RPC. */ async checkBalance() { + const state = this.state; const now = Date.now(); - if (this.cachedBalance !== null && this.cachedBalance > 0n && now - this.cachedAt < CACHE_TTL_MS) { - return this.buildInfo(this.cachedBalance); + if (state.cachedBalance !== null && state.cachedBalance > 0n && now - state.cachedAt < CACHE_TTL_MS) { + return this.buildInfo(state.cachedBalance, state.asset); } - const balance = await this.fetchBalance(); + const balance = await this.fetchBalance(state.asset); if (balance > 0n) { - this.cachedBalance = balance; - this.cachedAt = now; + state.cachedBalance = balance; + state.cachedAt = now; } - return this.buildInfo(balance); + return this.buildInfo(balance, state.asset); } /** * Check if balance is sufficient for an estimated cost. * - * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals) + * @param estimatedCostMicros - Estimated cost in USD micros (6 decimals) */ async checkSufficient(estimatedCostMicros) { const info = await this.checkBalance(); @@ -41879,18 +41952,31 @@ var BalanceMonitor = class { return { sufficient: false, info, - shortfall: this.formatUSDC(shortfall) + shortfall: this.formatUSD(shortfall) }; } + get cachedBalance() { + return this.state.cachedBalance; + } + set cachedBalance(value) { + this.state.cachedBalance = value; + } + get cachedAt() { + return this.state.cachedAt; + } + set cachedAt(value) { + this.state.cachedAt = value; + } /** * Optimistically deduct estimated cost from cached balance. * Call this after a successful payment to keep cache accurate. * - * @param amountMicros - Amount to deduct in USDC smallest unit + * @param amountMicros - Amount to deduct in USD micros */ deductEstimated(amountMicros) { - if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) { - this.cachedBalance -= amountMicros; + const state = this.state; + if (state.cachedBalance !== null && state.cachedBalance >= amountMicros) { + state.cachedBalance -= amountMicros; } } /** @@ -41898,8 +41984,9 @@ var BalanceMonitor = class { * Call this after a payment failure to get accurate balance. */ invalidate() { - this.cachedBalance = null; - this.cachedAt = 0; + const state = this.state; + state.cachedBalance = null; + state.cachedAt = 0; } /** * Force refresh balance from RPC (ignores cache). @@ -41908,43 +41995,77 @@ var BalanceMonitor = class { this.invalidate(); return this.checkBalance(); } + setAsset(asset) { + const currentAsset = this.state.asset; + if (currentAsset.asset.toLowerCase() !== asset.asset.toLowerCase() || currentAsset.symbol !== asset.symbol || currentAsset.decimals !== asset.decimals) { + this.state = this.getSharedMonitorForAsset(asset).state; + } + } + getAsset() { + return this.state.asset; + } /** - * Format USDC amount (in micros) as "$X.XX". + * Format a stablecoin amount (normalized to USD micros) as "$X.XX". */ - formatUSDC(amountMicros) { + formatUSD(amountMicros) { const dollars = Number(amountMicros) / 1e6; return `$${dollars.toFixed(2)}`; } + formatUSDC(amountMicros) { + return this.formatUSD(amountMicros); + } /** * Get the wallet address being monitored. */ getWalletAddress() { return this.walletAddress; } + getAssetSymbol() { + return this.state.asset.symbol; + } + getSharedMonitorForAsset(asset) { + if (this.state.asset.asset.toLowerCase() === asset.asset.toLowerCase() && this.state.asset.symbol === asset.symbol && this.state.asset.decimals === asset.decimals) { + return this; + } + const key = `${asset.asset.toLowerCase()}:${asset.symbol}:${asset.decimals}`; + const existing = this.assetMonitors.get(key); + if (existing) return existing; + const monitor = new _BalanceMonitor(this.walletAddress, asset); + this.assetMonitors.set(key, monitor); + return monitor; + } /** Fetch balance from RPC */ - async fetchBalance() { + async fetchBalance(asset) { try { const balance = await this.client.readContract({ - address: USDC_BASE, + address: asset.asset, abi: erc20Abi, functionName: "balanceOf", args: [this.walletAddress] }); - return balance; + return this.toUsdMicros(balance, asset); } catch (error) { throw new RpcError2(error instanceof Error ? error.message : "Unknown error", error); } } /** Build BalanceInfo from raw balance */ - buildInfo(balance) { + buildInfo(balance, asset) { return { balance, - balanceUSD: this.formatUSDC(balance), + balanceUSD: this.formatUSD(balance), + assetSymbol: asset.symbol, isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS, isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD, walletAddress: this.walletAddress }; } + toUsdMicros(rawAmount, asset) { + if (asset.decimals === 6) return rawAmount; + if (asset.decimals > 6) { + return rawAmount / 10n ** BigInt(asset.decimals - 6); + } + return rawAmount * 10n ** BigInt(6 - asset.decimals); + } }; // src/auth.ts @@ -46839,7 +46960,16 @@ async function readBodyWithTimeout(body, timeoutMs = MODEL_BODY_READ_TIMEOUT_MS) } return chunks; } -function transformPaymentError(errorBody) { +function transformPaymentError(errorBody, opts) { + const baseAssetSymbol = opts?.baseAssetSymbol || DEFAULT_BASE_PAYMENT_ASSET.symbol; + const baseAssetDecimals = opts?.baseAssetDecimals ?? DEFAULT_BASE_PAYMENT_ASSET.decimals; + const formatRawAssetAmount = (amountRaw, decimals) => { + const divisor = 10n ** BigInt(decimals); + const whole = amountRaw / divisor; + const remainder = amountRaw % divisor; + const scaledFraction = decimals >= 6 ? remainder / 10n ** BigInt(decimals - 6) : remainder * 10n ** BigInt(6 - decimals); + return `${whole.toString()}.${scaledFraction.toString().padStart(6, "0")}`; + }; try { const parsed = JSON.parse(errorBody); if (parsed.error === "Payment verification failed" && parsed.details) { @@ -46851,20 +46981,20 @@ function transformPaymentError(errorBody) { /insufficient balance:\s*(\d+)\s*<\s*(\d+)/i ); if (balanceMatch) { - const currentMicros = parseInt(balanceMatch[1], 10); - const requiredMicros = parseInt(balanceMatch[2], 10); - const currentUSD = (currentMicros / 1e6).toFixed(6); - const requiredUSD = (requiredMicros / 1e6).toFixed(6); + const currentRaw = BigInt(balanceMatch[1]); + const requiredRaw = BigInt(balanceMatch[2]); + const currentUSD = formatRawAssetAmount(currentRaw, baseAssetDecimals); + const requiredUSD = formatRawAssetAmount(requiredRaw, baseAssetDecimals); const wallet = innerJson.payer || "unknown"; const shortWallet = wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet; return JSON.stringify({ error: { - message: `Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`, + message: `Insufficient ${baseAssetSymbol} balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`, type: "insufficient_funds", wallet, current_balance_usd: currentUSD, required_usd: requiredUSD, - help: `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free` + help: `Fund wallet ${shortWallet} with ${baseAssetSymbol} on Base, or use free model: /model free` } }); } @@ -46961,6 +47091,13 @@ function transformPaymentError(errorBody) { } return errorBody; } +function formatStableAmount(amountRaw, decimals) { + const divisor = 10n ** BigInt(decimals); + const whole = amountRaw / divisor; + const remainder = amountRaw % divisor; + const scaledFraction = decimals >= 6 ? remainder / 10n ** BigInt(decimals - 6) : remainder * 10n ** BigInt(6 - decimals); + return `${whole.toString()}.${scaledFraction.toString().padStart(6, "0")}`; +} function categorizeError(status, body) { if (status === 401) return "auth_failure"; if (status === 402) return "payment_error"; @@ -47060,7 +47197,12 @@ async function checkExistingProxy(port) { if (response.ok) { const data = await response.json(); if (data.status === "ok" && data.wallet) { - return { wallet: data.wallet, paymentChain: data.paymentChain }; + return { + wallet: data.wallet, + paymentChain: data.paymentChain, + paymentAssets: data.paymentAssets, + selectedPaymentAsset: data.selectedPaymentAsset ?? data.paymentAsset + }; } } return void 0; @@ -47521,6 +47663,9 @@ async function startProxy(options) { const solanaPrivateKeyBytes = typeof options.wallet === "string" ? void 0 : options.wallet.solanaPrivateKeyBytes; const paymentChain = options.paymentChain ?? await resolvePaymentChain(); const apiBase = options.apiBase ?? (paymentChain === "solana" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API); + let activeBasePaymentAssets = paymentChain === "base" ? await fetchBasePaymentAssets(apiBase).catch(() => void 0) ?? [DEFAULT_BASE_PAYMENT_ASSET] : [DEFAULT_BASE_PAYMENT_ASSET]; + let activeBasePaymentAsset = activeBasePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET; + let lastSelectedBasePaymentAsset = activeBasePaymentAsset; if (paymentChain === "solana" && !solanaPrivateKeyBytes) { console.warn( `[ClawRouter] \u26A0 Payment chain is Solana but no mnemonic found \u2014 falling back to Base (EVM).` @@ -47533,19 +47678,18 @@ async function startProxy(options) { console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`); } const listenPort = options.port ?? getProxyPort(); - const existingProxy = await checkExistingProxy(listenPort); - if (existingProxy) { + const buildReuseHandle = async (existingProxyData) => { const account2 = privateKeyToAccount(walletKey); const baseUrl2 = `http://127.0.0.1:${listenPort}`; - if (existingProxy.wallet !== account2.address) { + if (existingProxyData.wallet !== account2.address) { console.warn( - `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account2.address}. Reusing existing proxy.` + `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxyData.wallet}, but current config uses ${account2.address}. Reusing existing proxy.` ); } - if (existingProxy.paymentChain) { - if (existingProxy.paymentChain !== paymentChain) { + if (existingProxyData.paymentChain) { + if (existingProxyData.paymentChain !== paymentChain) { throw new Error( - `Existing proxy on port ${listenPort} is using ${existingProxy.paymentChain} but ${paymentChain} was requested. Stop the existing proxy first or use a different port.` + `Existing proxy on port ${listenPort} is using ${existingProxyData.paymentChain} but ${paymentChain} was requested. Stop the existing proxy first or use a different port.` ); } } else if (paymentChain !== "base") { @@ -47562,23 +47706,38 @@ async function startProxy(options) { const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes); reuseSolanaAddress = solanaSigner.address; } - let balanceMonitor2; + let reuseBalanceMonitor; if (paymentChain === "solana" && reuseSolanaAddress) { const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports)); - balanceMonitor2 = new SolanaBalanceMonitor2(reuseSolanaAddress); + reuseBalanceMonitor = new SolanaBalanceMonitor2(reuseSolanaAddress); } else { - balanceMonitor2 = new BalanceMonitor(account2.address); + if (existingProxyData.paymentAssets?.length) { + activeBasePaymentAssets = existingProxyData.paymentAssets; + } + const selectedPaymentAssetId = typeof existingProxyData.selectedPaymentAsset === "string" ? existingProxyData.selectedPaymentAsset.toLowerCase() : existingProxyData.selectedPaymentAsset?.asset?.toLowerCase(); + const selectedPaymentAsset = selectedPaymentAssetId ? activeBasePaymentAssets.find((asset) => asset.asset.toLowerCase() === selectedPaymentAssetId) : void 0; + if (selectedPaymentAsset) { + activeBasePaymentAsset = selectedPaymentAsset; + lastSelectedBasePaymentAsset = selectedPaymentAsset; + } + reuseBalanceMonitor = new BalanceMonitor(account2.address, activeBasePaymentAsset); } options.onReady?.(listenPort); return { port: listenPort, baseUrl: baseUrl2, - walletAddress: existingProxy.wallet, + walletAddress: existingProxyData.wallet, solanaAddress: reuseSolanaAddress, - balanceMonitor: balanceMonitor2, + paymentAsset: paymentChain === "base" ? activeBasePaymentAsset : void 0, + paymentAssets: paymentChain === "base" ? activeBasePaymentAssets : void 0, + balanceMonitor: reuseBalanceMonitor, close: async () => { } }; + }; + const existingProxy = await checkExistingProxy(listenPort); + if (existingProxy) { + return buildReuseHandle(existingProxy); } const account = privateKeyToAccount(walletKey); const evmPublicClient = createPublicClient({ chain: base, transport: http() }); @@ -47596,12 +47755,27 @@ async function startProxy(options) { } x402.onAfterPaymentCreation(async (context) => { const network = context.selectedRequirements.network; + if (network.startsWith("eip155")) { + activeBasePaymentAssets = await fetchBasePaymentAssets(apiBase).catch(() => void 0) ?? activeBasePaymentAssets; + const refreshedActiveAsset = activeBasePaymentAssets.find( + (asset) => asset.asset.toLowerCase() === activeBasePaymentAsset.asset.toLowerCase() + ); + if (refreshedActiveAsset) { + activeBasePaymentAsset = refreshedActiveAsset; + } + } const chain3 = network.startsWith("eip155") ? "Base (EVM)" : network.startsWith("solana") ? "Solana" : network; - const amountMicros = parseInt(context.selectedRequirements.amount || "0", 10); - const amountUsd = amountMicros / 1e6; + const amountRaw = BigInt(context.selectedRequirements.amount || "0"); + const selectedRequirementsWithDecimals = context.selectedRequirements; + const amountDecimals = selectedRequirementsWithDecimals.decimals ?? (network.startsWith("eip155") ? activeBasePaymentAsset.decimals : 6); + const amountUsdText = formatStableAmount(amountRaw, amountDecimals); + const amountUsd = Number.parseFloat(amountUsdText); const store = paymentStore.getStore(); - if (store) store.amountUsd = amountUsd; - console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsd.toFixed(6)}`); + if (store) { + store.amountUsd = amountUsd; + store.amountUsdText = amountUsdText; + } + console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsdText}`); }); const payFetch = createPayFetchWithPreAuth(fetch, x402, void 0, { skipPreAuth: paymentChain === "solana" @@ -47613,7 +47787,7 @@ async function startProxy(options) { const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports)); balanceMonitor = new SolanaBalanceMonitor2(solanaAddress); } else { - balanceMonitor = new BalanceMonitor(account.address); + balanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset); } const routingConfig = mergeRoutingConfig(options.routingConfig); const modelPricing = buildModelPricing(); @@ -47627,7 +47801,7 @@ async function startProxy(options) { const sessionJournal = new SessionJournal(); const connections = /* @__PURE__ */ new Set(); const server = createServer((req, res) => { - paymentStore.run({ amountUsd: 0 }, async () => { + paymentStore.run({ amountUsd: 0, amountUsdText: "0.000000" }, async () => { req.on("error", (err) => { console.error(`[ClawRouter] Request stream error: ${err.message}`); }); @@ -47652,15 +47826,44 @@ async function startProxy(options) { wallet: account.address, paymentChain }; + if (paymentChain === "base") { + response.paymentAsset = activeBasePaymentAsset.asset; + response.paymentAssetSymbol = activeBasePaymentAsset.symbol; + response.paymentAssetDecimals = activeBasePaymentAsset.decimals; + response.paymentAssets = activeBasePaymentAssets; + response.selectedPaymentAsset = lastSelectedBasePaymentAsset.asset; + response.selectedPaymentAssetSymbol = lastSelectedBasePaymentAsset.symbol; + } if (solanaAddress) { response.solana = solanaAddress; } if (full) { try { - const balanceInfo = await balanceMonitor.checkBalance(); - response.balance = balanceInfo.balanceUSD; - response.isLow = balanceInfo.isLow; - response.isEmpty = balanceInfo.isEmpty; + if (paymentChain === "base") { + const assetBalances = await Promise.all( + activeBasePaymentAssets.map(async (asset) => { + const monitor = new BalanceMonitor(account.address, asset); + const balanceInfo = await monitor.checkBalance(); + return { + asset: asset.asset, + symbol: asset.symbol, + decimals: asset.decimals, + balance: balanceInfo.balanceUSD, + isLow: balanceInfo.isLow, + isEmpty: balanceInfo.isEmpty + }; + }) + ); + response.assetBalances = assetBalances; + response.balance = assetBalances[0]?.balance ?? "$0.00"; + response.isLow = assetBalances[0]?.isLow ?? true; + response.isEmpty = assetBalances.every((asset) => asset.isEmpty); + } else { + const balanceInfo = await balanceMonitor.checkBalance(); + response.balance = balanceInfo.balanceUSD; + response.isLow = balanceInfo.isLow; + response.isEmpty = balanceInfo.isEmpty; + } } catch { response.balanceError = "Could not fetch balance"; } @@ -48006,7 +48209,13 @@ async function startProxy(options) { balanceMonitor, sessionStore, responseCache2, - sessionJournal + sessionJournal, + () => activeBasePaymentAsset.symbol, + () => activeBasePaymentAssets, + (asset) => { + lastSelectedBasePaymentAsset = asset; + activeBasePaymentAsset = asset; + } ); } catch (err) { const error = err instanceof Error ? err : new Error(String(err)); @@ -48041,7 +48250,9 @@ async function startProxy(options) { rejectAttempt({ code: "REUSE_EXISTING", wallet: existingProxy2.wallet, - existingChain: existingProxy2.paymentChain + existingChain: existingProxy2.paymentChain, + paymentAssets: existingProxy2.paymentAssets, + selectedPaymentAsset: existingProxy2.selectedPaymentAsset }); return; } @@ -48081,16 +48292,12 @@ async function startProxy(options) { { cause: err } ); } - const baseUrl2 = `http://127.0.0.1:${listenPort}`; - options.onReady?.(listenPort); - return { - port: listenPort, - baseUrl: baseUrl2, - walletAddress: error.wallet, - balanceMonitor, - close: async () => { - } - }; + return buildReuseHandle({ + wallet: error.wallet, + paymentChain: error.existingChain, + paymentAssets: error.paymentAssets, + selectedPaymentAsset: error.selectedPaymentAsset + }); } if (error.code === "RETRY") { await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS)); @@ -48139,6 +48346,8 @@ async function startProxy(options) { baseUrl, walletAddress: account.address, solanaAddress, + paymentAsset: paymentChain === "base" ? activeBasePaymentAsset : void 0, + paymentAssets: paymentChain === "base" ? activeBasePaymentAssets : void 0, balanceMonitor, close: () => new Promise((res, rej) => { const timeout = setTimeout(() => { @@ -48239,7 +48448,7 @@ async function tryModelRequest(upstreamUrl, method, headers, body, modelId, maxT }; } } -async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, deduplicator, balanceMonitor, sessionStore, responseCache2, sessionJournal) { +async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, deduplicator, balanceMonitor, sessionStore, responseCache2, sessionJournal, getBaseAssetSymbol, getBasePaymentAssets, onBaseAssetSelected) { const startTime = Date.now(); const upstreamUrl = `${apiBase}${req.url}`; const bodyChunks = []; @@ -48262,6 +48471,8 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de let accumulatedContent = ""; let responseInputTokens; let responseOutputTokens; + let requestBalanceMonitor = balanceMonitor; + let requestBasePaymentAsset = getBasePaymentAssets()[0]; const isChatCompletion = req.url?.includes("/chat/completions"); const sessionId = getSessionId(req.headers); let effectiveSessionId = sessionId; @@ -49032,7 +49243,30 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de if (estimated) { estimatedCostMicros = BigInt(estimated); const bufferedCostMicros = estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100)) / 100n; - const sufficiency = await balanceMonitor.checkSufficient(bufferedCostMicros); + if (balanceMonitor instanceof BalanceMonitor) { + const baseAssets = getBasePaymentAssets(); + let selected; + for (const asset of baseAssets) { + const monitor = balanceMonitor.getSharedMonitorForAsset(asset); + const sufficiency2 = await monitor.checkSufficient(bufferedCostMicros); + if (!selected) { + selected = { asset, monitor, sufficiency: sufficiency2 }; + } + if (sufficiency2.sufficient) { + selected = { asset, monitor, sufficiency: sufficiency2 }; + break; + } + } + if (selected) { + requestBasePaymentAsset = selected.asset; + requestBalanceMonitor = selected.monitor; + onBaseAssetSelected(selected.asset); + console.log( + `[ClawRouter] Base payment asset selected: ${selected.asset.symbol} (${selected.sufficiency.info.balanceUSD})` + ); + } + } + const sufficiency = await requestBalanceMonitor.checkSufficient(bufferedCostMicros); if (sufficiency.info.isEmpty || !sufficiency.sufficient) { const originalModel = modelId; console.log( @@ -49050,12 +49284,14 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de `; options.onLowBalance?.({ balanceUSD: sufficiency.info.balanceUSD, - walletAddress: sufficiency.info.walletAddress + walletAddress: sufficiency.info.walletAddress, + assetSymbol: sufficiency.info.assetSymbol }); } else if (sufficiency.info.isLow) { options.onLowBalance?.({ balanceUSD: sufficiency.info.balanceUSD, - walletAddress: sufficiency.info.walletAddress + walletAddress: sufficiency.info.walletAddress, + assetSymbol: sufficiency.info.assetSymbol }); } } @@ -49388,7 +49624,7 @@ data: [DONE] i = freeIdx - 1; continue; } - if (freeIdx === -1) { + if (freeIdx === -1 && !excludeList.has(FREE_MODEL)) { modelsToTry.push(FREE_MODEL); console.log(`[ClawRouter] Payment error \u2014 appending free model: ${FREE_MODEL}`); continue; @@ -49525,7 +49761,10 @@ data: [DONE] console.log(`[ClawRouter] ${structuredMessage}`); const rawErrBody = lastError?.body || structuredMessage; const errStatus = lastError?.status || 502; - const transformedErr = transformPaymentError(rawErrBody); + const transformedErr = transformPaymentError(rawErrBody, { + baseAssetSymbol: requestBasePaymentAsset.symbol, + baseAssetDecimals: requestBasePaymentAsset.decimals + }); if (headersSentEarly) { let errPayload; try { @@ -49827,7 +50066,7 @@ data: [DONE] } } if (estimatedCostMicros !== void 0) { - balanceMonitor.deductEstimated(estimatedCostMicros); + requestBalanceMonitor.deductEstimated(estimatedCostMicros); } completed = true; } catch (err) { @@ -49837,7 +50076,7 @@ data: [DONE] heartbeatInterval = void 0; } deduplicator.removeInflight(dedupKey); - balanceMonitor.invalidate(); + requestBalanceMonitor.invalidate(); if (err instanceof Error && err.name === "AbortError") { throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err }); } @@ -49946,6 +50185,21 @@ function red(text) { function yellow(text) { return `\x1B[33m\u26A0\x1B[0m ${text}`; } +function getBuyLinkForAsset(symbol) { + const normalized = symbol.trim().toUpperCase(); + const knownLinks = { + USDC: "https://www.coinbase.com/price/usd-coin", + EURC: "https://www.coinbase.com/price/euro-coin" + }; + const knownUrl = knownLinks[normalized]; + if (knownUrl) { + return { label: `Get ${normalized}`, url: knownUrl }; + } + return { + label: `Find ${normalized} on Coinbase`, + url: `https://www.coinbase.com/search?q=${encodeURIComponent(normalized)}` + }; +} function collectSystemInfo() { return { os: `${platform()} ${arch()}`, @@ -49968,7 +50222,8 @@ async function collectWalletInfo() { isLow: false, isEmpty: true, source: null, - paymentChain: "base" + paymentChain: "base", + paymentAsset: DEFAULT_BASE_PAYMENT_ASSET }; } let solanaAddress = null; @@ -49979,6 +50234,7 @@ async function collectWalletInfo() { } } const paymentChain = await resolvePaymentChain(); + let paymentAsset = DEFAULT_BASE_PAYMENT_ASSET; try { let balanceInfo; if (paymentChain === "solana" && solanaAddress) { @@ -49986,8 +50242,21 @@ async function collectWalletInfo() { const monitor = new SolanaBalanceMonitor2(solanaAddress); balanceInfo = await monitor.checkBalance(); } else { - const monitor = new BalanceMonitor(address2); - balanceInfo = await monitor.checkBalance(); + const paymentAssets = await fetchBasePaymentAssets("https://blockrun.ai/api").catch(() => void 0) ?? [DEFAULT_BASE_PAYMENT_ASSET]; + const assetBalances = await Promise.all( + paymentAssets.map(async (asset) => { + const monitor = new BalanceMonitor(address2, asset); + const info = await monitor.checkBalance(); + return { asset, info }; + }) + ); + const selectedBalance = assetBalances.find(({ info }) => !info.isLow && !info.isEmpty) ?? assetBalances.find(({ info }) => !info.isEmpty) ?? assetBalances[0]; + paymentAsset = selectedBalance?.asset ?? DEFAULT_BASE_PAYMENT_ASSET; + balanceInfo = { + balanceUSD: selectedBalance?.info.balanceUSD ?? null, + isLow: assetBalances.length > 0 ? assetBalances.every(({ info }) => info.isLow) : false, + isEmpty: assetBalances.length > 0 ? assetBalances.every(({ info }) => info.isEmpty) : true + }; } return { exists: true, @@ -49998,7 +50267,8 @@ async function collectWalletInfo() { isLow: balanceInfo.isLow, isEmpty: balanceInfo.isEmpty, source, - paymentChain + paymentChain, + paymentAsset }; } catch { return { @@ -50010,7 +50280,8 @@ async function collectWalletInfo() { isLow: false, isEmpty: false, source, - paymentChain + paymentChain, + paymentAsset }; } } catch { @@ -50023,7 +50294,8 @@ async function collectWalletInfo() { isLow: false, isEmpty: true, source: null, - paymentChain: "base" + paymentChain: "base", + paymentAsset: DEFAULT_BASE_PAYMENT_ASSET }; } } @@ -50078,8 +50350,11 @@ function identifyIssues(result) { issues.push("No wallet found"); } if (result.wallet.isEmpty) { - const chain3 = result.wallet.paymentChain === "solana" ? "Solana" : "Base"; - issues.push(`Wallet is empty - need to fund with USDC on ${chain3}`); + if (result.wallet.paymentChain === "solana") { + issues.push("Wallet is empty - need to fund with USDC on Solana"); + } else { + issues.push(`Wallet is empty - need to fund with ${result.wallet.paymentAsset.symbol} on Base`); + } if (result.wallet.paymentChain === "base" && result.wallet.solanaAddress) { issues.push("Tip: if you funded Solana, run /wallet solana to switch chains"); } @@ -50110,9 +50385,12 @@ function printDiagnostics(result) { console.log(` ${green(`Solana Address: ${result.wallet.solanaAddress}`)}`); } const chainLabel = result.wallet.paymentChain === "solana" ? "Solana" : "Base"; + const assetLabel = result.wallet.paymentChain === "solana" ? "USDC" : result.wallet.paymentAsset.symbol; console.log(` ${green(`Chain: ${chainLabel}`)}`); if (result.wallet.isEmpty) { - console.log(` ${red(`Balance: $0.00 - NEED TO FUND WITH USDC ON ${chainLabel.toUpperCase()}!`)}`); + console.log( + ` ${red(`Balance: $0.00 - NEED TO FUND WITH ${assetLabel} ON ${chainLabel.toUpperCase()}!`)}` + ); if (result.wallet.paymentChain === "base" && result.wallet.solanaAddress) { console.log(` ${yellow(`Tip: funded Solana instead? Run /wallet solana to switch`)}`); } @@ -50167,12 +50445,18 @@ var DOCTOR_MODELS = { }; async function analyzeWithAI(diagnostics, userQuestion, model = "sonnet") { if (diagnostics.wallet.isEmpty) { + const paymentAsset = diagnostics.wallet.paymentAsset; + const buyLink = getBuyLinkForAsset(paymentAsset.symbol); console.log("\n\u{1F4B3} Wallet is empty - cannot call AI for analysis."); - console.log(` Fund your EVM wallet with USDC on Base: ${diagnostics.wallet.address}`); - if (diagnostics.wallet.solanaAddress) { + console.log( + diagnostics.wallet.paymentChain === "solana" ? ` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress ?? diagnostics.wallet.address}` : ` Fund your EVM wallet with ${paymentAsset.symbol} on Base: ${diagnostics.wallet.address}` + ); + if (diagnostics.wallet.paymentChain === "base" && diagnostics.wallet.solanaAddress) { console.log(` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress}`); } - console.log(" Get USDC: https://www.coinbase.com/price/usd-coin"); + console.log( + diagnostics.wallet.paymentChain === "solana" ? " Get USDC: https://www.coinbase.com/price/usd-coin" : ` ${buyLink.label}: ${buyLink.url}` + ); console.log(" Bridge to Base: https://bridge.base.org\n"); return; } @@ -50508,7 +50792,9 @@ ClawRouter Partner APIs (v${VERSION}) console.log(`[ClawRouter] [${decision.tier}] ${decision.model} $${cost} (saved ${saved}%)`); }, onLowBalance: (info) => { - console.warn(`[ClawRouter] Low balance: ${info.balanceUSD}. Fund: ${info.walletAddress}`); + console.warn( + `[ClawRouter] Low balance: ${info.balanceUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}` + ); }, onInsufficientFunds: (info) => { console.error( @@ -50523,7 +50809,9 @@ ClawRouter Partner APIs (v${VERSION}) const balance = await proxy.balanceMonitor.checkBalance(); if (balance.isEmpty) { console.log(`[ClawRouter] Wallet balance: $0.00 (using FREE model)`); - console.log(`[ClawRouter] Fund wallet for premium models: ${displayAddress}`); + console.log( + `[ClawRouter] Fund wallet with ${balance.assetSymbol} for premium models: ${displayAddress}` + ); } else if (balance.isLow) { console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD} (low)`); } else { diff --git a/dist/cli.js.map b/dist/cli.js.map index a313699..e7a0a33 100644 --- a/dist/cli.js.map +++ b/dist/cli.js.map @@ -1 +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/abitype/src/human-readable/parseAbiItem.ts","../node_modules/abitype/src/human-readable/parseAbiParameters.ts","../node_modules/abitype/src/exports/index.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/version.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/errors/data.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/@noble/hashes/src/_u64.ts","../node_modules/@noble/hashes/src/cryptoNode.ts","../node_modules/@noble/hashes/src/utils.ts","../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/toEventSelector.ts","../node_modules/viem/errors/address.ts","../node_modules/viem/utils/lru.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/address/isAddress.ts","../node_modules/viem/utils/data/concat.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/regex.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/utils/hash/toFunctionSelector.ts","../node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/viem/constants/solidity.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/utils/encoding/fromBytes.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/abi/formatAbiItemWithArgs.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/errors/request.ts","../node_modules/viem/errors/rpc.ts","../node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/hashes/src/sha2.ts","../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","../node_modules/viem/errors/node.ts","../node_modules/viem/utils/errors/getNodeError.ts","../node_modules/viem/utils/formatters/extract.ts","../node_modules/viem/utils/formatters/formatter.ts","../node_modules/viem/utils/formatters/transactionRequest.ts","../node_modules/viem/utils/stateOverride.ts","../node_modules/viem/constants/number.ts","../node_modules/viem/utils/transaction/assertRequest.ts","../node_modules/viem/utils/address/isAddressEqual.ts","../node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/ox/core/version.ts","../node_modules/ox/core/internal/errors.ts","../node_modules/ox/core/Errors.ts","../node_modules/ox/core/internal/bytes.ts","../node_modules/ox/core/internal/hex.ts","../node_modules/ox/core/Json.ts","../node_modules/ox/core/Bytes.ts","../node_modules/ox/core/Hex.ts","../node_modules/ox/core/Withdrawal.ts","../node_modules/ox/core/BlockOverrides.ts","../node_modules/viem/constants/abis.ts","../node_modules/viem/constants/contract.ts","../node_modules/viem/constants/contracts.ts","../node_modules/viem/errors/chain.ts","../node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/viem/utils/errors/getCallError.ts","../node_modules/viem/utils/promise/withResolvers.ts","../node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/viem/errors/ccip.ts","../node_modules/viem/utils/abi/decodeFunctionData.ts","../node_modules/viem/utils/abi/encodeErrorResult.ts","../node_modules/viem/utils/abi/encodeFunctionResult.ts","../node_modules/viem/utils/ens/localBatchGatewayRequest.ts","../node_modules/viem/utils/ccip.ts","../node_modules/viem/actions/public/call.ts","../node_modules/@solana/errors/src/codes.ts","../node_modules/@solana/errors/src/context.ts","../node_modules/@solana/errors/src/messages.ts","../node_modules/@solana/errors/src/message-formatter.ts","../node_modules/@solana/errors/src/error.ts","../node_modules/@solana/errors/src/stack-trace.ts","../node_modules/@solana/errors/src/rpc-enum-errors.ts","../node_modules/@solana/errors/src/instruction-error.ts","../node_modules/@solana/errors/src/transaction-error.ts","../node_modules/@solana/errors/src/json-rpc-error.ts","../node_modules/@solana/errors/src/simulation-errors.ts","../node_modules/@solana/codecs-core/src/bytes.ts","../node_modules/@solana/codecs-core/src/codec.ts","../node_modules/@solana/codecs-core/src/combine-codec.ts","../node_modules/@solana/codecs-core/src/add-codec-sentinel.ts","../node_modules/@solana/codecs-core/src/assertions.ts","../node_modules/@solana/codecs-core/src/add-codec-size-prefix.ts","../node_modules/@solana/codecs-core/src/array-buffers.ts","../node_modules/@solana/codecs-core/src/decoder-entire-byte-array.ts","../node_modules/@solana/codecs-core/src/fix-codec-size.ts","../node_modules/@solana/codecs-core/src/offset-codec.ts","../node_modules/@solana/codecs-core/src/resize-codec.ts","../node_modules/@solana/codecs-core/src/pad-codec.ts","../node_modules/@solana/codecs-core/src/reverse-codec.ts","../node_modules/@solana/codecs-core/src/transform-codec.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base10.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/codecs-strings/src/baseX-reslice.ts","../node_modules/@solana/codecs-strings/src/base64.ts","../node_modules/@solana/codecs-strings/src/null-characters.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/codecs-strings/src/utf8.ts","../node_modules/@solana/accounts/src/account.ts","../node_modules/@solana/accounts/src/decode-account.ts","../node_modules/@solana/accounts/src/parse-account.ts","../node_modules/@solana/accounts/src/fetch-account.ts","../node_modules/@solana/accounts/src/maybe-account.ts","../node_modules/@solana/assertions/src/crypto.ts","../node_modules/@solana/assertions/src/subtle-crypto.ts","../node_modules/@solana/addresses/src/address.ts","../node_modules/@solana/addresses/src/vendor/noble/ed25519.ts","../node_modules/@solana/addresses/src/curve-internal.ts","../node_modules/@solana/addresses/src/curve.ts","../node_modules/@solana/addresses/src/program-derived-address.ts","../node_modules/@solana/addresses/src/public-key.ts","../node_modules/@solana/codecs-numbers/src/assertions.ts","../node_modules/@solana/codecs-numbers/src/common.ts","../node_modules/@solana/codecs-numbers/src/utils.ts","../node_modules/@solana/codecs-numbers/src/f32.ts","../node_modules/@solana/codecs-numbers/src/f64.ts","../node_modules/@solana/codecs-numbers/src/i128.ts","../node_modules/@solana/codecs-numbers/src/i16.ts","../node_modules/@solana/codecs-numbers/src/i32.ts","../node_modules/@solana/codecs-numbers/src/i64.ts","../node_modules/@solana/codecs-numbers/src/i8.ts","../node_modules/@solana/codecs-numbers/src/short-u16.ts","../node_modules/@solana/codecs-numbers/src/u128.ts","../node_modules/@solana/codecs-numbers/src/u16.ts","../node_modules/@solana/codecs-numbers/src/u32.ts","../node_modules/@solana/codecs-numbers/src/u64.ts","../node_modules/@solana/codecs-numbers/src/u8.ts","../node_modules/@solana/codecs-data-structures/src/assertions.ts","../node_modules/@solana/codecs-data-structures/src/utils.ts","../node_modules/@solana/codecs-data-structures/src/array.ts","../node_modules/@solana/codecs-data-structures/src/bit-array.ts","../node_modules/@solana/codecs-data-structures/src/boolean.ts","../node_modules/@solana/codecs-data-structures/src/bytes.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-data-structures/src/constant.ts","../node_modules/@solana/codecs-data-structures/src/tuple.ts","../node_modules/@solana/codecs-data-structures/src/union.ts","../node_modules/@solana/codecs-data-structures/src/discriminated-union.ts","../node_modules/@solana/codecs-data-structures/src/enum-helpers.ts","../node_modules/@solana/codecs-data-structures/src/enum.ts","../node_modules/@solana/codecs-data-structures/src/hidden-prefix.ts","../node_modules/@solana/codecs-data-structures/src/hidden-suffix.ts","../node_modules/@solana/codecs-data-structures/src/literal-union.ts","../node_modules/@solana/codecs-data-structures/src/map.ts","../node_modules/@solana/codecs-data-structures/src/unit.ts","../node_modules/@solana/codecs-data-structures/src/nullable.ts","../node_modules/@solana/codecs-data-structures/src/set.ts","../node_modules/@solana/codecs-data-structures/src/struct.ts","../node_modules/@solana/options/src/option.ts","../node_modules/@solana/options/src/unwrap-option.ts","../node_modules/@solana/options/src/option-codec.ts","../node_modules/@solana/options/src/unwrap-option-recursively.ts","../node_modules/@solana/codecs/dist/index.node.mjs","../node_modules/@solana/functional/src/pipe.ts","../node_modules/@solana/instructions/src/instruction.ts","../node_modules/@solana/instructions/src/roles.ts","../node_modules/@solana/rpc-types/src/blockhash.ts","../node_modules/@solana/rpc-types/src/cluster-url.ts","../node_modules/@solana/rpc-types/src/commitment.ts","../node_modules/@solana/rpc-types/src/lamports.ts","../node_modules/@solana/rpc-types/src/stringified-bigint.ts","../node_modules/@solana/rpc-types/src/stringified-number.ts","../node_modules/@solana/rpc-types/src/unix-timestamp.ts","../node_modules/@solana/transaction-messages/src/blockhash.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/transaction-messages/src/codecs/address-table-lookup.ts","../node_modules/@solana/transaction-messages/src/codecs/header.ts","../node_modules/@solana/transaction-messages/src/codecs/instruction.ts","../node_modules/@solana/transaction-messages/src/transaction-message.ts","../node_modules/@solana/transaction-messages/src/codecs/transaction-version.ts","../node_modules/@solana/transaction-messages/src/codecs/message.ts","../node_modules/@solana/transaction-messages/src/compile/accounts.ts","../node_modules/@solana/transaction-messages/src/compile/address-table-lookups.ts","../node_modules/@solana/transaction-messages/src/compile/header.ts","../node_modules/@solana/transaction-messages/src/compile/instructions.ts","../node_modules/@solana/transaction-messages/src/compile/lifetime-token.ts","../node_modules/@solana/transaction-messages/src/compile/static-accounts.ts","../node_modules/@solana/transaction-messages/src/compile/message.ts","../node_modules/@solana/transaction-messages/src/compress-transaction-message.ts","../node_modules/@solana/transaction-messages/src/create-transaction-message.ts","../node_modules/@solana/transaction-messages/src/durable-nonce-instruction.ts","../node_modules/@solana/transaction-messages/src/durable-nonce.ts","../node_modules/@solana/transaction-messages/src/fee-payer.ts","../node_modules/@solana/transaction-messages/src/instructions.ts","../node_modules/@solana/transaction-messages/src/decompile-message.ts","../node_modules/@solana/keys/src/algorithm.ts","../node_modules/@solana/keys/src/private-key.ts","../node_modules/@solana/keys/src/public-key.ts","../node_modules/@solana/keys/src/signatures.ts","../node_modules/@solana/keys/src/key-pair.ts","../node_modules/@solana/transactions/src/codecs/signatures-encoder.ts","../node_modules/@solana/transactions/src/codecs/transaction-codec.ts","../node_modules/@solana/transactions/src/lifetime.ts","../node_modules/@solana/transactions/src/compile-transaction.ts","../node_modules/@solana/transactions/src/signatures.ts","../node_modules/@solana/transactions/src/wire-transaction.ts","../node_modules/@solana/transactions/src/transaction-size.ts","../node_modules/@solana/transactions/src/sendable-transaction.ts","../node_modules/@solana/transactions/src/transaction-message-size.ts","../node_modules/@solana/promises/src/race.ts","../node_modules/@solana/promises/src/abortable.ts","../node_modules/@solana/instruction-plans/src/instruction-plan.ts","../node_modules/@solana/instruction-plans/src/append-instruction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-result.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-executor.ts","../node_modules/@solana/instruction-plans/src/transaction-planner.ts","../node_modules/@solana/offchain-messages/src/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/signing-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-common.ts","../node_modules/@solana/offchain-messages/src/codecs/signatures.ts","../node_modules/@solana/offchain-messages/src/codecs/envelope.ts","../node_modules/@solana/offchain-messages/src/content.ts","../node_modules/@solana/offchain-messages/src/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/content.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message.ts","../node_modules/@solana/offchain-messages/src/envelope-common.ts","../node_modules/@solana/offchain-messages/src/envelope-v0.ts","../node_modules/@solana/offchain-messages/src/envelope-v1.ts","../node_modules/@solana/offchain-messages/src/envelope.ts","../node_modules/@solana/offchain-messages/src/signatures.ts","../node_modules/@solana/plugin-core/src/client.ts","../node_modules/@solana/programs/src/program-error.ts","../node_modules/@solana/rpc-spec-types/src/parse-json-with-bigints.ts","../node_modules/@solana/rpc-spec-types/src/rpc-message.ts","../node_modules/@solana/rpc-spec-types/src/stringify-json-with-bigints.ts","../node_modules/@solana/rpc-spec/src/rpc.ts","../node_modules/@solana/rpc-spec/src/rpc-api.ts","../node_modules/@solana/rpc-spec/src/rpc-transport.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast-internal.ts","../node_modules/@solana/rpc-transformers/src/tree-traversal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-options-object-position-config.ts","../node_modules/@solana/rpc-transformers/src/request-transformer.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast-internal.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-result.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-allowed-numeric-values.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-throw-solana-error.ts","../node_modules/@solana/rpc-transformers/src/response-transformer.ts","../node_modules/@solana/rpc-api/src/index.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-headers.ts","../node_modules/@solana/rpc-transport-http/src/http-transport.ts","../node_modules/@solana/rpc-transport-http/src/is-solana-request.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-for-solana-rpc.ts","../node_modules/@solana/fast-stable-stringify/src/index.ts","../node_modules/@solana/rpc/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc/src/rpc-request-coalescer.ts","../node_modules/@solana/rpc/src/rpc-request-deduplication.ts","../node_modules/@solana/rpc/src/rpc-transport.ts","../node_modules/@solana/rpc/src/rpc.ts","../node_modules/@solana/rpc-parsed-types/dist/index.node.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/subscribable/src/async-iterable.ts","../node_modules/@solana/subscribable/src/data-publisher.ts","../node_modules/@solana/subscribable/src/demultiplex.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-api.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-channel.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-pubsub-plan.ts","../node_modules/@solana/rpc-subscriptions-api/src/index.ts","../node_modules/ws/lib/constants.js","../node_modules/ws/lib/buffer-util.js","../node_modules/ws/lib/limiter.js","../node_modules/ws/lib/permessage-deflate.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/stream.js","../node_modules/ws/lib/subprotocol.js","../node_modules/ws/lib/websocket-server.js","../node_modules/ws/wrapper.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/ws-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-channel-websocket/src/websocket-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-autopinger.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool-internal.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json-bigint.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-coalescer.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-transport.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions.ts","../node_modules/@solana/signers/src/deduplicate-signers.ts","../node_modules/@solana/signers/src/transaction-modifying-signer.ts","../node_modules/@solana/signers/src/transaction-partial-signer.ts","../node_modules/@solana/signers/src/transaction-sending-signer.ts","../node_modules/@solana/signers/src/transaction-signer.ts","../node_modules/@solana/signers/src/account-signer-meta.ts","../node_modules/@solana/signers/src/add-signers.ts","../node_modules/@solana/signers/src/fee-payer-signer.ts","../node_modules/@solana/signers/src/message-partial-signer.ts","../node_modules/@solana/signers/src/keypair-signer.ts","../node_modules/@solana/signers/src/message-modifying-signer.ts","../node_modules/@solana/signers/src/message-signer.ts","../node_modules/@solana/signers/src/noop-signer.ts","../node_modules/@solana/signers/src/offchain-message-signer.ts","../node_modules/@solana/signers/src/sign-offchain-message.ts","../node_modules/@solana/signers/src/transaction-with-single-sending-signer.ts","../node_modules/@solana/signers/src/sign-transaction.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/signers/src/signable-message.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-blockheight.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-nonce.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-recent-signature.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-timeout.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-racer.ts","../node_modules/@solana/transaction-confirmation/src/waiters.ts","../node_modules/@solana/kit/src/airdrop-internal.ts","../node_modules/@solana/kit/src/airdrop.ts","../node_modules/@solana/kit/src/fetch-lookup-tables.ts","../node_modules/@solana/kit/src/decompile-transaction-message-fetching-lookup-tables.ts","../node_modules/@solana/kit/src/get-minimum-balance-for-rent-exemption.ts","../node_modules/@solana/kit/src/send-transaction-internal.ts","../node_modules/@solana/kit/src/send-and-confirm-durable-nonce-transaction.ts","../node_modules/@solana/kit/src/send-and-confirm-transaction.ts","../node_modules/@solana/kit/src/send-transaction-without-confirming.ts","../src/solana-balance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/programs/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/errors/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/instructions/createAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/createMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/mintToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/transferToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/decryptableBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/encryptedBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extension.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extensionType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/tokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/transferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/applyConfidentialPendingBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialDeposit.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransferWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialWithdraw.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/configureConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createNativeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emitTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emptyConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMintCloseAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeNonTransferableMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePausableConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePermanentDelegate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeScaledUiAmountMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroup.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroupMember.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferFeeConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/pause.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/reallocate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/removeTokenMetadataKey.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/resume.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferCheckedWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMultiplierScaledUiMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateRateInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupMaxSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawExcessLamports.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccounts.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccountsForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getInitializeInstructionsForExtensions.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getTokenSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getMintSize.ts","../node_modules/@x402/svm/src/constants.ts","../node_modules/@x402/svm/src/utils.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/programs/computeBudget.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestHeapFrame.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestUnits.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitPrice.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setLoadedAccountsDataSizeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/constants.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/internal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateAndSetComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimitInternal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputePrice.ts","../node_modules/@x402/svm/src/exact/client/scheme.ts","../node_modules/@x402/svm/src/v1/index.ts","../node_modules/@x402/svm/src/exact/v1/client/scheme.ts","../node_modules/@x402/svm/src/exact/client/register.ts","../src/proxy.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/utils/abi/encodeEventTopics.ts","../node_modules/viem/errors/log.ts","../node_modules/viem/actions/public/createContractEventFilter.ts","../node_modules/viem/utils/filters/createFilterRequestScope.ts","../node_modules/viem/actions/public/estimateContractGas.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/viem/utils/authorization/hashAuthorization.ts","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/utils/authorization/recoverAuthorizationAddress.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/getTransactionCount.ts","../node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../node_modules/@noble/hashes/src/sha256.ts","../node_modules/viem/utils/hash/sha256.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/utils/transaction/getTransactionType.ts","../node_modules/viem/actions/public/fillTransaction.ts","../node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/public/getContractEvents.ts","../node_modules/viem/utils/abi/parseEventLogs.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/actions/public/getLogs.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/viem/actions/public/watchContractEvent.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/getFilterChanges.ts","../node_modules/viem/actions/public/uninstallFilter.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/viem/actions/ens/getEnsResolver.ts","../node_modules/viem/clients/decorators/public.ts","../node_modules/viem/actions/public/createAccessList.ts","../node_modules/viem/actions/public/createBlockFilter.ts","../node_modules/viem/actions/public/createEventFilter.ts","../node_modules/viem/actions/public/createPendingTransactionFilter.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/getBlobBaseFee.ts","../node_modules/viem/actions/public/getBlockTransactionCount.ts","../node_modules/viem/actions/public/getCode.ts","../node_modules/viem/actions/public/getDelegation.ts","../node_modules/viem/errors/eip712.ts","../node_modules/viem/actions/public/getEip712Domain.ts","../node_modules/viem/actions/public/getFeeHistory.ts","../node_modules/viem/utils/formatters/feeHistory.ts","../node_modules/viem/actions/public/getFilterLogs.ts","../node_modules/viem/actions/public/getProof.ts","../node_modules/viem/utils/authorization/serializeAuthorizationList.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/authorization/verifyAuthorization.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/utils/promise/withDedupe.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/utils/index.ts","../node_modules/viem/utils/rpc/http.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/utils/rpc/id.ts","../node_modules/viem/utils/signature/hashMessage.ts","../node_modules/viem/constants/strings.ts","../node_modules/viem/utils/signature/toPrefixedMessage.ts","../node_modules/viem/utils/signature/hashTypedData.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/errors/typedData.ts","../node_modules/ox/erc8010/SignatureErc8010.ts","../node_modules/ox/core/AbiParameters.ts","../node_modules/ox/core/Address.ts","../node_modules/ox/core/internal/lru.ts","../node_modules/ox/core/Caches.ts","../node_modules/ox/core/Hash.ts","../node_modules/ox/core/PublicKey.ts","../node_modules/ox/core/internal/abiParameters.ts","../node_modules/ox/core/Solidity.ts","../node_modules/ox/core/internal/cursor.ts","../node_modules/ox/core/Authorization.ts","../node_modules/ox/core/Rlp.ts","../node_modules/ox/node_modules/@noble/curves/src/secp256k1.ts","../node_modules/ox/node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/ox/core/Signature.ts","../node_modules/ox/core/Secp256k1.ts","../node_modules/viem/utils/formatters/proof.ts","../node_modules/viem/actions/public/getStorageAt.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/actions/public/getTransactionConfirmations.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/viem/actions/public/simulateBlocks.ts","../node_modules/ox/core/AbiItem.ts","../node_modules/ox/core/internal/abiItem.ts","../node_modules/ox/core/AbiConstructor.ts","../node_modules/ox/core/AbiFunction.ts","../node_modules/viem/actions/public/simulateCalls.ts","../node_modules/viem/constants/address.ts","../node_modules/ox/erc6492/SignatureErc6492.ts","../node_modules/viem/actions/public/verifyHash.ts","../node_modules/viem/utils/signature/serializeSignature.ts","../node_modules/viem/actions/public/verifyMessage.ts","../node_modules/viem/actions/public/verifyTypedData.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/actions/public/watchBlocks.ts","../node_modules/viem/actions/public/watchEvent.ts","../node_modules/viem/actions/public/watchPendingTransactions.ts","../node_modules/viem/utils/siwe/parseSiweMessage.ts","../node_modules/viem/utils/siwe/validateSiweMessage.ts","../node_modules/viem/actions/siwe/verifySiweMessage.ts","../node_modules/viem/actions/wallet/sendRawTransactionSync.ts","../node_modules/viem/clients/createPublicClient.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/index.ts","../node_modules/viem/op-stack/contracts.ts","../node_modules/viem/op-stack/formatters.ts","../node_modules/viem/op-stack/serializers.ts","../node_modules/viem/op-stack/chainConfig.ts","../node_modules/viem/chains/definitions/base.ts","../node_modules/@scure/base/index.ts","../node_modules/@noble/hashes/src/pbkdf2.ts","../node_modules/@scure/bip39/esm/index.js","../node_modules/viem/accounts/privateKeyToAccount.ts","../node_modules/viem/accounts/toAccount.ts","../node_modules/viem/accounts/utils/sign.ts","../node_modules/viem/accounts/utils/signAuthorization.ts","../node_modules/viem/accounts/utils/signMessage.ts","../node_modules/viem/accounts/utils/signTransaction.ts","../node_modules/viem/accounts/utils/signTypedData.ts","../node_modules/@scure/bip39/esm/wordlists/english.js","../node_modules/@x402/core/src/index.ts","../node_modules/@x402/core/src/utils/index.ts","../node_modules/@x402/core/src/http/x402HTTPResourceServer.ts","../node_modules/@x402/core/src/http/httpFacilitatorClient.ts","../node_modules/@x402/core/src/http/x402HTTPClient.ts","../node_modules/@x402/core/src/http/index.ts","../node_modules/@x402/core/src/client/x402Client.ts","../node_modules/@x402/fetch/src/index.ts","../src/payment-preauth.ts","../node_modules/@x402/evm/src/exact/extensions.ts","../node_modules/@x402/evm/src/exact/v1/client/scheme.ts","../node_modules/@x402/evm/src/constants.ts","../node_modules/@x402/evm/src/utils.ts","../node_modules/@x402/evm/src/exact/v1/facilitator/scheme.ts","../node_modules/@x402/evm/src/exact/facilitator/errors.ts","../node_modules/@x402/evm/src/exact/facilitator/eip3009-utils.ts","../node_modules/@x402/evm/src/multicall.ts","../node_modules/@x402/evm/src/v1/index.ts","../node_modules/@x402/evm/src/exact/client/scheme.ts","../node_modules/@x402/evm/src/exact/client/eip3009.ts","../node_modules/@x402/evm/src/exact/client/permit2.ts","../node_modules/@x402/evm/src/exact/client/eip2612.ts","../node_modules/@x402/evm/src/exact/client/erc20approval.ts","../node_modules/@x402/evm/src/exact/client/rpc.ts","../node_modules/@x402/evm/src/exact/client/register.ts","../node_modules/@x402/evm/src/signer.ts","../src/router/rules.ts","../src/router/selector.ts","../src/router/strategy.ts","../src/router/config.ts","../src/router/index.ts","../src/models.ts","../src/logger.ts","../src/stats.ts","../src/fs-read.ts","../src/version.ts","../src/dedup.ts","../src/response-cache.ts","../src/errors.ts","../src/balance.ts","../src/auth.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@noble/curves/src/utils.ts","../node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/@noble/curves/src/secp256k1.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_md.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/legacy.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@scure/bip32/node_modules/@scure/base/index.ts","../node_modules/@scure/bip32/index.ts","../src/wallet.ts","../node_modules/@noble/hashes/src/sha512.ts","../src/compression/types.ts","../src/compression/layers/deduplication.ts","../src/compression/layers/whitespace.ts","../src/compression/codebook.ts","../src/compression/layers/dictionary.ts","../src/compression/layers/paths.ts","../src/compression/layers/json-compact.ts","../src/compression/layers/observation.ts","../src/compression/layers/dynamic-codebook.ts","../src/compression/index.ts","../src/session.ts","../src/updater.ts","../src/exclude-models.ts","../src/config.ts","../src/journal.ts","../src/report.ts","../src/doctor.ts","../src/partners/registry.ts","../src/cli.ts"],"sourcesContent":["export const version = '1.2.3'\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}\nexport function execFallbackSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(fallbackSignatureRegex, 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} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @param structs Struct definitions to include in cache key\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}${structKey}`\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 execFallbackSignature,\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 return parseFunctionSignature(signature, structs)\n\n if (isEventSignature(signature))\n return parseEventSignature(signature, structs)\n\n if (isErrorSignature(signature))\n return parseErrorSignature(signature, structs)\n\n if (isConstructorSignature(signature))\n return parseConstructorSignature(signature, structs)\n\n if (isFallbackSignature(signature)) return parseFallbackSignature(signature)\n\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nexport function parseFunctionSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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\nexport function parseEventSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'event', inputs: abiParameters }\n}\n\nexport function parseErrorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'error', inputs: abiParameters }\n}\n\nexport function parseConstructorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n}\n\nexport function parseFallbackSignature(signature: string) {\n const match = execFallbackSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'fallback' })\n\n return {\n type: 'fallback',\n stateMutability: match.stateMutability ?? 'nonpayable',\n }\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\\spayable)?)(?(?:\\[\\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 if (match.type === 'address payable') {\n type = 'address'\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 structs\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 { Abi } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiItemError } from './errors/abiItem.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signature, 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 item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * type Result = ParseAbiItem<'function balanceOf(address owner) view returns (uint256)'>\n * // ^? type Result = { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * type Result = ParseAbiItem<\n * // ^? type Result = { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * ['function foo(Baz bar) view returns (string)', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n> =\n | (signature extends string\n ? string extends signature\n ? Abi[number]\n : signature extends Signature // Validate signature\n ? ParseSignature\n : never\n : never)\n | (signature extends readonly string[]\n ? string[] extends signature\n ? Abi[number] // Return generic Abi item since type was no inferrable\n : signature extends Signatures // Validate signature\n ? ParseStructs extends infer structs\n ? {\n [key in keyof signature]: ParseSignature<\n signature[key] extends string ? signature[key] : never,\n structs\n >\n } extends infer mapped extends readonly unknown[]\n ? // Filter out `never` since those are structs\n Filter[0] extends infer result\n ? result extends undefined // convert `undefined` to `never` (e.g. `ParseAbiItem<['struct Foo { string name; }']>`)\n ? never\n : result\n : never\n : never\n : never\n : never\n : never)\n\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint256)')\n * // ^? const abiItem: { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * const abiItem = parseAbiItem([\n * // ^? const abiItem: { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * 'function foo(Baz bar) view returns (string)',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n>(\n signature: Narrow &\n (\n | (signature extends string\n ? string extends signature\n ? unknown\n : Signature\n : never)\n | (signature extends readonly string[]\n ? signature extends readonly [] // empty array\n ? Error<'At least one signature required.'>\n : string[] extends signature\n ? unknown\n : Signatures\n : never)\n ),\n): ParseAbiItem {\n let abiItem: ParseAbiItem | undefined\n if (typeof signature === 'string')\n abiItem = parseSignature(signature) as ParseAbiItem\n else {\n const structs = parseStructs(signature as readonly string[])\n const length = signature.length as number\n for (let i = 0; i < length; i++) {\n const signature_ = (signature as readonly string[])[i]!\n if (isStructSignature(signature_)) continue\n abiItem = parseSignature(signature_, structs) as ParseAbiItem\n break\n }\n }\n\n if (!abiItem) throw new InvalidAbiItemError({ signature })\n return abiItem as ParseAbiItem\n}\n","import type { AbiParameter } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiParametersError } from './errors/abiParameter.js'\nimport { isStructSignature, modifiers } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { splitParameters } from './runtime/utils.js'\nimport { parseAbiParameter as parseAbiParameter_ } from './runtime/utils.js'\nimport type { IsStructSignature, Modifier } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { SplitParameters } from './types/utils.js'\nimport type { ParseAbiParameters as ParseAbiParameters_ } from './types/utils.js'\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * type Result = ParseAbiParameters('address from, address to, uint256 amount')\n * // ^? type Result: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * type Result = ParseAbiParameters<\n * // ^? type Result: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * ['Baz bar', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n> =\n | (params extends string\n ? params extends ''\n ? never\n : string extends params\n ? readonly AbiParameter[]\n : ParseAbiParameters_, { modifier: Modifier }>\n : never)\n | (params extends readonly string[]\n ? string[] extends params\n ? AbiParameter // Return generic AbiParameter item since type was no inferrable\n : ParseStructs extends infer structs\n ? {\n [key in keyof params]: params[key] extends string\n ? IsStructSignature extends true\n ? never\n : ParseAbiParameters_<\n SplitParameters,\n { modifier: Modifier; structs: structs }\n >\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends readonly [...infer content]\n ? content['length'] extends 0\n ? never\n : DeepFlatten\n : never\n : never\n : never\n : never)\n\n/**\n * Flatten all members of {@link T}\n *\n * @param T - List of items to flatten\n * @param Acc - The accumulator used while recursing\n * @returns The flattened array\n *\n * @example\n * type Result = DeepFlatten<[['a', 'b'], [['c']]]>\n * // ^? type Result = ['a', 'b', 'c']\n */\ntype DeepFlatten<\n T extends readonly unknown[],\n Acc extends readonly unknown[] = readonly [],\n> = T extends readonly [infer head, ...infer tail]\n ? tail extends undefined\n ? never\n : head extends readonly unknown[]\n ? DeepFlatten]>\n : DeepFlatten\n : Acc\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * const abiParameters = parseAbiParameters('address from, address to, uint256 amount')\n * // ^? const abiParameters: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * const abiParameters = parseAbiParameters([\n * // ^? const abiParameters: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * 'Baz bar',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n>(\n params: Narrow &\n (\n | (params extends string\n ? params extends ''\n ? Error<'Empty string is not allowed.'>\n : unknown\n : never)\n | (params extends readonly string[]\n ? params extends readonly [] // empty array\n ? Error<'At least one parameter required.'>\n : string[] extends params\n ? unknown\n : unknown // TODO: Validate param string\n : never)\n ),\n): ParseAbiParameters {\n const abiParameters: AbiParameter[] = []\n if (typeof params === 'string') {\n const parameters = splitParameters(params)\n const length = parameters.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(parseAbiParameter_(parameters[i]!, { modifiers }))\n }\n } else {\n const structs = parseStructs(params as readonly string[])\n const length = params.length as number\n for (let i = 0; i < length; i++) {\n const signature = (params as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n const parameters = splitParameters(signature)\n const length = parameters.length\n for (let k = 0; k < length; k++) {\n abiParameters.push(\n parseAbiParameter_(parameters[k]!, { modifiers, structs }),\n )\n }\n }\n }\n\n if (abiParameters.length === 0)\n throw new InvalidAbiParametersError({ params })\n\n return abiParameters as ParseAbiParameters\n}\n","export type {\n Abi,\n AbiConstructor,\n AbiError,\n AbiEvent,\n AbiEventParameter,\n AbiFallback,\n AbiFunction,\n AbiInternalType,\n AbiItemType,\n AbiParameter,\n AbiParameterKind,\n AbiReceive,\n AbiStateMutability,\n AbiType,\n Address,\n SolidityAddress,\n SolidityArray,\n SolidityArrayWithoutTuple,\n SolidityArrayWithTuple,\n SolidityBool,\n SolidityBytes,\n SolidityFixedArrayRange,\n SolidityFixedArraySizeLookup,\n SolidityFunction,\n SolidityInt,\n SolidityString,\n SolidityTuple,\n TypedData,\n TypedDataDomain,\n TypedDataParameter,\n TypedDataType,\n} from '../abi.js'\n\n// biome-ignore lint/performance/noBarrelFile: \nexport { BaseError } from '../errors.js'\n\nexport type { Narrow } from '../narrow.js'\nexport { narrow } from '../narrow.js'\n\nexport type {\n Register,\n DefaultRegister,\n ResolvedRegister,\n} from '../register.js'\n\nexport type {\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n AbiTypeToPrimitiveType,\n ExtractAbiError,\n ExtractAbiErrorNames,\n ExtractAbiErrors,\n ExtractAbiEvent,\n ExtractAbiEventNames,\n ExtractAbiEvents,\n ExtractAbiFunction,\n ExtractAbiFunctionNames,\n ExtractAbiFunctions,\n IsAbi,\n IsTypedData,\n TypedDataToPrimitiveTypes,\n} from '../utils.js'\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Human-Readable\n\nexport {\n formatAbi,\n type FormatAbi,\n} from '../human-readable/formatAbi.js'\n\nexport {\n formatAbiItem,\n type FormatAbiItem,\n} from '../human-readable/formatAbiItem.js'\n\nexport {\n formatAbiParameter,\n type FormatAbiParameter,\n} from '../human-readable/formatAbiParameter.js'\n\nexport {\n formatAbiParameters,\n type FormatAbiParameters,\n} from '../human-readable/formatAbiParameters.js'\n\nexport { parseAbi, type ParseAbi } from '../human-readable/parseAbi.js'\n\nexport {\n parseAbiItem,\n type ParseAbiItem,\n} from '../human-readable/parseAbiItem.js'\n\nexport {\n parseAbiParameter,\n type ParseAbiParameter,\n} from '../human-readable/parseAbiParameter.js'\n\nexport {\n parseAbiParameters,\n type ParseAbiParameters,\n} from '../human-readable/parseAbiParameters.js'\n\nexport {\n UnknownTypeError,\n InvalidAbiItemError,\n UnknownSolidityTypeError,\n} from '../human-readable/errors/abiItem.js'\n\nexport {\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n SolidityProtectedKeywordError,\n InvalidParameterError,\n InvalidAbiParametersError,\n InvalidAbiParameterError,\n} from '../human-readable/errors/abiParameter.js'\n\nexport {\n InvalidStructSignatureError,\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../human-readable/errors/signature.js'\n\nexport { InvalidParenthesisError } from '../human-readable/errors/splitParameters.js'\n\nexport { CircularReferenceError } from '../human-readable/errors/struct.js'\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","export const version = '2.46.3'\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 { 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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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 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 IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\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 =\n | HexToBigIntErrorType\n | IntegerOutOfRangeErrorType\n | 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 const value = hexToBigInt(hex, opts)\n const number = Number(value)\n if (!Number.isSafeInteger(number))\n throw new IntegerOutOfRangeError({\n max: `${Number.MAX_SAFE_INTEGER}`,\n min: `${Number.MIN_SAFE_INTEGER}`,\n signed: opts.signed,\n size: opts.size,\n value: `${value}n`,\n })\n return number\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","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * Internal webcrypto alias.\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 * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\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","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\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';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\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\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\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\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 abstract clone(): T;\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\n/** Hash function */\nexport type CHash = ReturnType;\n/** Hash function with output */\nexport type CHashO = ReturnType;\n/** XOF with output */\nexport type CHashXO = ReturnType;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher>(\n hashCons: () => Hash\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash;\n} {\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 createOptHasher, T extends Object>(\n hashCons: (opts?: T) => Hash\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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 createXOFer, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\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 Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\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 IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\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/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\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 clean(B);\n}\n\n/** Keccak sponge function. */\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\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\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(): void {\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): 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(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\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 createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__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 { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.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 { 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 { 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'\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 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 { 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","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","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 AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\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 boolToHex,\n type NumberToHexErrorType,\n numberToHex,\n type StringToHexErrorType,\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, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\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 { 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 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\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 (\n argType === 'object' &&\n isArgOfType(\n Object.values(arg as unknown[] | Record)[\n index\n ],\n component as AbiParameter,\n )\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","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","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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.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 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 { 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 = NegativeOffsetErrorType | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetErrorType | 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 ?? bytes,\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 assertSize,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\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 {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.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 AbiParameterKind,\n true\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 never\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, 10), 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', 10)\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 { AbiParameter } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\nimport { stringify } from '../stringify.js'\n\nexport type FormatAbiItemWithArgsErrorType = ErrorType\n\nexport function formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName = true,\n includeName = false,\n}: {\n abiItem: AbiItem\n args: readonly unknown[]\n includeFunctionName?: boolean | undefined\n includeName?: boolean | undefined\n}) {\n if (!('name' in abiItem)) return\n if (!('inputs' in abiItem)) return\n if (!abiItem.inputs) return\n return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n .map(\n (input: AbiParameter, i: number) =>\n `${includeName && input.name ? `${input.name}: ` : ''}${\n typeof args[i] === 'object' ? stringify(args[i]) : args[i]\n }`,\n )\n .join(', ')})`\n}\n","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 {\n TransactionReceipt,\n TransactionType,\n} 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 TransactionReceiptRevertedErrorType =\n TransactionReceiptRevertedError & {\n name: 'TransactionReceiptRevertedError'\n }\nexport class TransactionReceiptRevertedError extends BaseError {\n receipt: TransactionReceipt\n\n constructor({ receipt }: { receipt: TransactionReceipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n })\n\n this.receipt = receipt\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 raw?: Hex | 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\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://4byte.sourcify.dev/?q=${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.raw = data\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 { 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 url: string\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 this.url = url\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n url: string\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 this.url = url\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n url: string | undefined\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 this.url = url\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n url: string\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 this.url = url\n }\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n | -1\n | -32700 // Parse error\n | -32600 // Invalid request\n | -32601 // Method not found\n | -32602 // Invalid params\n | -32603 // Internal error\n | -32000 // Invalid input\n | -32001 // Resource not found\n | -32002 // Resource unavailable\n | -32003 // Transaction rejected\n | -32004 // Method not supported\n | -32005 // Limit exceeded\n | -32006 // JSON-RPC version not supported\n | -32042 // Method not found\n\ntype RpcErrorOptions = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : (code ?? unknownErrorCode)\n ) as code_\n }\n}\n\nexport type ProviderRpcErrorCode =\n | 4001 // User Rejected Request\n | 4100 // Unauthorized\n | 4200 // Unsupported Method\n | 4900 // Disconnected\n | 4901 // Chain Disconnected\n | 4902 // Chain Not Recognized\n | 5700 // Unsupported non-optional capability\n | 5710 // Unsupported chain id\n | 5720 // Duplicate ID\n | 5730 // Unknown bundle id\n | 5740 // Bundle too large\n | 5750 // Atomic-ready wallet rejected upgrade\n | 5760 // Atomicity not supported\n | 7000 // WalletConnect Session Settlement Failed\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n T = undefined,\n> extends RpcError {\n data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions & {\n data?: T | undefined\n }\n >,\n ) {\n super(cause, options)\n\n this.data = options.data\n }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n code: -32700\n name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage:\n 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n })\n }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n code: -32600\n name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n code: -32601\n name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n code: -32602\n name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n code: -32603\n name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n code: -32000\n name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n code: -32001\n name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n override name = 'ResourceNotFoundRpcError'\n static code = -32001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n })\n }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n code: -32002\n name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n })\n }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n code: -32003\n name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n code: -32004\n name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not supported.`,\n })\n }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n code: -32005\n name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n })\n }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n JsonRpcVersionUnsupportedError & {\n code: -32006\n name: 'JsonRpcVersionUnsupportedError'\n }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n })\n }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n code: 4001\n name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n code: 4100\n name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage:\n 'The requested method and/or account has not been authorized by the user.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n UnsupportedProviderMethodError & {\n code: 4200\n name: 'UnsupportedProviderMethodError'\n }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n code: 4900\n name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n })\n }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n code: 4901\n name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n code: 4902\n name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported non-optional capability\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedNonOptionalCapabilityErrorType =\n UnsupportedNonOptionalCapabilityError & {\n code: 5700\n name: 'UnsupportedNonOptionalCapabilityError'\n }\nexport class UnsupportedNonOptionalCapabilityError extends ProviderRpcError {\n static code = 5700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedNonOptionalCapabilityError.code,\n name: 'UnsupportedNonOptionalCapabilityError',\n shortMessage:\n 'This Wallet does not support a capability that was not marked as optional.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported chain id\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedChainIdErrorType = UnsupportedChainIdError & {\n code: 5710\n name: 'UnsupportedChainIdError'\n}\nexport class UnsupportedChainIdError extends ProviderRpcError {\n static code = 5710 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedChainIdError.code,\n name: 'UnsupportedChainIdError',\n shortMessage: 'This Wallet does not support the requested chain ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Duplicate ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type DuplicateIdErrorType = DuplicateIdError & {\n code: 5720\n name: 'DuplicateIdError'\n}\nexport class DuplicateIdError extends ProviderRpcError {\n static code = 5720 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: DuplicateIdError.code,\n name: 'DuplicateIdError',\n shortMessage: 'There is already a bundle submitted with this ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unknown bundle ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnknownBundleIdErrorType = UnknownBundleIdError & {\n code: 5730\n name: 'UnknownBundleIdError'\n}\nexport class UnknownBundleIdError extends ProviderRpcError {\n static code = 5730 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnknownBundleIdError.code,\n name: 'UnknownBundleIdError',\n shortMessage: 'This bundle id is unknown / has not been submitted',\n })\n }\n}\n\n/**\n * Subclass for an \"Bundle too large\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type BundleTooLargeErrorType = BundleTooLargeError & {\n code: 5740\n name: 'BundleTooLargeError'\n}\nexport class BundleTooLargeError extends ProviderRpcError {\n static code = 5740 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: BundleTooLargeError.code,\n name: 'BundleTooLargeError',\n shortMessage: 'The call bundle is too large for the Wallet to process.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomic-ready wallet rejected upgrade\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicReadyWalletRejectedUpgradeErrorType =\n AtomicReadyWalletRejectedUpgradeError & {\n code: 5750\n name: 'AtomicReadyWalletRejectedUpgradeError'\n }\nexport class AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {\n static code = 5750 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicReadyWalletRejectedUpgradeError.code,\n name: 'AtomicReadyWalletRejectedUpgradeError',\n shortMessage:\n 'The Wallet can support atomicity after an upgrade, but the user rejected the upgrade.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomicity not supported\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicityNotSupportedErrorType = AtomicityNotSupportedError & {\n code: 5760\n name: 'AtomicityNotSupportedError'\n}\nexport class AtomicityNotSupportedError extends ProviderRpcError {\n static code = 5760 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicityNotSupportedError.code,\n name: 'AtomicityNotSupportedError',\n shortMessage:\n 'The wallet does not support atomic execution but the request requires it.',\n })\n }\n}\n\n/**\n * Subclass for a \"Session Settlement Failed\" WalletConnect error.\n *\n * WalletConnect https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n */\nexport type WalletConnectSessionSettlementErrorType =\n WalletConnectSessionSettlementError & {\n code: 7000\n name: 'WalletConnectSessionSettlementError'\n }\nexport class WalletConnectSessionSettlementError extends ProviderRpcError {\n static code = 7000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: WalletConnectSessionSettlementError.code,\n name: 'WalletConnectSessionSettlementError',\n shortMessage: 'WalletConnect session settlement failed.',\n })\n }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): 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/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\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 protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\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 clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\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(): Uint8Array {\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 clone(): HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC;\n} = (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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * hash-to-curve from RFC 9380.\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\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.ts';\nimport { FpInvertBatch, type IField, mod } from './modular.ts';\nimport type { CHash } from './utils.ts';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.ts';\n\nexport type UnicodeOrBytes = string | Uint8Array;\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 */\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/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\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/**\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 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\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 * [RFC 9380 5.2](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 type XY = (x: T, y: T) => { x: T; y: T };\nexport type XYRatio = [T[], T[], T[], T[]]; // xn/xd, yn/yd\nexport function isogenyMap>(field: F, map: XYRatio): XY {\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 [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\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 };\nexport type HTFMethod = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint;\nexport type MapMethod = (scalars: bigint[]) => H2CPoint;\nexport type Hasher = {\n hashToCurve: HTFMethod;\n encodeToCurve: HTFMethod;\n mapToCurve: MapMethod;\n defaults: Opts & { encodeDST?: UnicodeOrBytes };\n};\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n defaults: Opts & { encodeDST?: UnicodeOrBytes }\n): Hasher {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n function map(num: bigint[]) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial: H2CPoint) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n\n return {\n defaults,\n\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): H2CPoint {\n const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options } as Opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\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): H2CPoint {\n const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options } as Opts);\n return clear(map(u[0]));\n },\n\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]): H2CPoint {\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n };\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\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|gas required exceeds allowance/\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 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 { 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 { Prettify } from '../../types/utils.js'\n\nexport type DefineFormatterErrorType = ErrorType\n\nexport function defineFormatter(\n type: type,\n format: (args: parameters, action?: string | undefined) => returnType,\n) {\n return <\n parametersOverride,\n returnTypeOverride,\n exclude extends (keyof parameters | keyof parametersOverride)[] = [],\n >({\n exclude,\n format: overrides,\n }: {\n exclude?: exclude | undefined\n format: (\n args: parametersOverride,\n action?: string | undefined,\n ) => returnTypeOverride\n }) => {\n return {\n exclude,\n format: (args: parametersOverride, action?: string | undefined) => {\n const formatted = format(args as any, action)\n if (exclude) {\n for (const key of exclude) {\n delete (formatted as any)[key]\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n } as Prettify & {\n [_key in exclude[number]]: never\n }\n },\n type,\n }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { AuthorizationList } from '../../types/authorization.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type {\n RpcAuthorizationList,\n RpcTransactionRequest,\n} 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 & { account?: Account | undefined },\n _?: string | undefined,\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 (request.account) rpcRequest.from = request.account.address\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.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : 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","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 type { FeeConflictErrorType } 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 { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = 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\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 } 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, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/** @internal */\nexport const version = '0.1.1'\n","import { version } from '../version.js'\n\n/** @internal */\nexport function getUrl(url: string) {\n return url\n}\n\n/** @internal */\nexport function getVersion() {\n return version\n}\n\n/** @internal */\nexport function prettyPrint(args: unknown) {\n if (!args) return ''\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","import { getVersion } from './internal/errors.js'\n\nexport type GlobalErrorType = Error & {\n name: name\n}\n\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError<\n cause extends Error | undefined = undefined,\n> extends Error {\n details: string\n docs?: string | undefined\n docsOrigin?: string | undefined\n docsPath?: string | undefined\n shortMessage: string\n showVersion?: boolean | undefined\n version?: string | undefined\n\n override cause: cause\n override name = 'BaseError'\n\n static defaultStaticOptions = {\n docsOrigin: 'https://oxlib.sh',\n showVersion: false,\n version: `ox@${getVersion()}`,\n } satisfies BaseError.GlobalOptions\n\n static setStaticOptions(options: BaseError.GlobalOptions) {\n BaseError.prototype.docsOrigin = options.docsOrigin\n BaseError.prototype.showVersion = options.showVersion\n BaseError.prototype.version = options.version\n }\n\n static {\n BaseError.setStaticOptions(BaseError.defaultStaticOptions)\n }\n\n constructor(shortMessage: string, options: BaseError.Options = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details) return options.cause.details\n if (options.cause.shortMessage) return options.cause.shortMessage\n }\n if (\n options.cause &&\n 'details' in options.cause &&\n typeof options.cause.details === 'string'\n )\n return options.cause.details\n if (options.cause?.message) return options.cause.message\n return options.details!\n })()\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath\n return options.docsPath\n })()\n\n const docsBaseUrl = options.docsOrigin ?? BaseError.prototype.docsOrigin\n const docs = `${docsBaseUrl}${docsPath ?? ''}`\n const showVersion = Boolean(\n options.version ?? BaseError.prototype.showVersion,\n )\n const version = options.version ?? BaseError.prototype.version\n\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath || showVersion\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n showVersion ? `Version: ${version}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n')\n\n super(message, options.cause ? { cause: options.cause } : undefined)\n\n this.cause = options.cause as any\n this.details = details\n this.docs = docs\n this.docsOrigin = docsBaseUrl\n this.docsPath = docsPath\n this.shortMessage = shortMessage\n this.showVersion = showVersion\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\nexport declare namespace BaseError {\n type Options = {\n /** Cause of the error. */\n cause?: cause | undefined\n /** Details of the error. */\n details?: string | undefined\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Path of the docs. */\n docsPath?: string | undefined\n /** Meta messages to add to the error. */\n metaMessages?: (string | undefined)[] | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n\n type GlobalOptions = {\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Whether to show the version of the library in the error message. */\n showVersion?: boolean | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n}\n\n/** @internal */\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import * as Bytes from '../Bytes.js'\nimport type * as Errors from '../Errors.js'\n\n/** @internal */\nexport function assertSize(bytes: Bytes.Bytes, size_: number): void {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Bytes.size.ErrorType\n | Bytes.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n export type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start\n ) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n })\n }\n}\n\n/** @internal */\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\n/** @internal */\nexport function 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\n/** @internal */\nexport function pad(bytes: Bytes.Bytes, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n if (size === 0) return bytes\n if (bytes.length > size)\n throw new Bytes.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\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Bytes.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Bytes.Bytes,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value\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 return data as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\n\n/** @internal */\nexport function assertSize(hex: Hex.Hex, size_: number): void {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Hex.size.ErrorType\n | Hex.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(value: Hex.Hex, start?: number | undefined) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Hex.Hex,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start\n ) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n })\n }\n}\n\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function pad(hex_: Hex.Hex, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n\n if (size === 0) return hex_\n\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}` as Hex.Hex\n}\n\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n type ErrorType = Hex.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Hex.Hex,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value.replace('0x', '')\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 (data === '0') return '0x'\n if (dir === 'right' && data.length % 2 === 1) return `0x${data}0`\n return `0x${data}` as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Hex.Hex\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from './Errors.js'\n\nconst bigIntSuffix = '#__bigint'\n\n/**\n * Serializes a value to a canonical JSON string as defined by\n * [RFC 8785 (JSON Canonicalization Scheme)](https://www.rfc-editor.org/rfc/rfc8785).\n *\n * - Object keys are sorted recursively by UTF-16 code unit comparison.\n * - Primitives are serialized per ECMAScript rules (no trailing zeros on numbers, etc.).\n * - No whitespace is inserted.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ b: 2, a: 1 })\n * // @log: '{\"a\":1,\"b\":2}'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ z: [3, { y: 1, x: 2 }], a: 'hello' })\n * // @log: '{\"a\":\"hello\",\"z\":[3,{\"x\":2,\"y\":1}]}'\n * ```\n *\n * @param value - The value to canonicalize.\n * @returns The canonical JSON string.\n */\nexport function canonicalize(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'string')\n return JSON.stringify(value)\n if (typeof value === 'number') {\n if (!Number.isFinite(value))\n throw new TypeError('Cannot canonicalize non-finite number')\n return Object.is(value, -0) ? '0' : JSON.stringify(value)\n }\n if (typeof value === 'bigint')\n throw new TypeError('Cannot canonicalize bigint')\n if (Array.isArray(value))\n return `[${value.map((item) => canonicalize(item)).join(',')}]`\n if (typeof value === 'object') {\n const entries = Object.keys(value as Record)\n .sort()\n .reduce((acc, key) => {\n const v = (value as Record)[key]\n if (v !== undefined)\n acc.push(`${JSON.stringify(key)}:${canonicalize(v)}`)\n return acc\n }, [])\n return `{${entries.join(',')}}`\n }\n return undefined as never\n}\n\nexport declare namespace canonicalize {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(\n string: string,\n reviver?: ((this: any, key: string, value: any) => any) | undefined,\n) {\n return JSON.parse(string, (key, value_) => {\n const value = value_\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length))\n return typeof reviver === 'function' ? reviver(key, value) : value\n })\n}\n\nexport declare namespace parse {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(\n value: any,\n replacer?: ((this: any, key: string, value: any) => any) | null | undefined,\n space?: string | number | undefined,\n) {\n return JSON.stringify(\n value,\n (key, value) => {\n if (typeof replacer === 'function') return replacer(key, value)\n if (typeof value === 'bigint') return value.toString() + bigIntSuffix\n return value\n },\n space,\n )\n}\n\nexport declare namespace stringify {\n type ErrorType = Errors.GlobalErrorType\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/bytes.js'\nimport * as internal_hex from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst decoder = /*#__PURE__*/ new TextDecoder()\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/** Root type for a Bytes array. */\nexport type Bytes = Uint8Array\n\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value: unknown): asserts value is Bytes {\n if (value instanceof Uint8Array) return\n if (!value) throw new InvalidBytesTypeError(value)\n if (typeof value !== 'object') throw new InvalidBytesTypeError(value)\n if (!('BYTES_PER_ELEMENT' in value)) throw new InvalidBytesTypeError(value)\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value)\n}\n\nexport declare namespace assert {\n type ErrorType = InvalidBytesTypeError | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values: readonly Bytes[]): Bytes {\n let length = 0\n for (const arr of values) {\n length += arr.length\n }\n const result = new Uint8Array(length)\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i]\n result.set(arr!, index)\n index += arr!.length\n }\n return result\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value: Hex.Hex | Bytes | readonly number[]): Bytes {\n if (value instanceof Uint8Array) return value\n if (typeof value === 'string') return fromHex(value)\n return fromArray(value)\n}\n\nexport declare namespace from {\n type ErrorType =\n | fromHex.ErrorType\n | fromArray.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value: readonly number[] | Uint8Array): Bytes {\n return value instanceof Uint8Array ? value : new Uint8Array(value)\n}\n\nexport declare namespace fromArray {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value: boolean, options: fromBoolean.Options = {}) {\n const { size } = options\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padLeft(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {\n const { size } = options\n\n let hex = value\n if (size) {\n internal_hex.assertSize(value, size)\n hex = Hex.padRight(value, 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 = internal.charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`,\n )\n }\n bytes[index] = (nibbleLeft << 4) | nibbleRight\n }\n return bytes\n}\n\nexport declare namespace fromHex {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_hex.assertSize.ErrorType\n | Hex.padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(\n value: bigint | number,\n options?: fromNumber.Options | undefined,\n) {\n const hex = Hex.fromNumber(value, options)\n return fromHex(hex)\n}\n\nexport declare namespace fromNumber {\n export type Options = Hex.fromNumber.Options\n\n export type ErrorType =\n | Hex.fromNumber.ErrorType\n | fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Bytes {\n const { size } = options\n\n const bytes = encoder.encode(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padRight(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromString {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA: Bytes, bytesB: Bytes) {\n return equalBytes(bytesA, bytesB)\n}\n\nexport declare namespace isEqual {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(\n value: Bytes,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(\n value: Bytes,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length: number): Bytes {\n return crypto.getRandomValues(new Uint8Array(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value: Bytes): number {\n return value.length\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(\n value: Bytes,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Bytes {\n const { strict } = options\n internal.assertStartOffset(value, start)\n const value_ = value.slice(start, end)\n if (strict) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n export type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes: Bytes, options: toBigInt.Options = {}): bigint {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toBigInt(hex, options)\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(\n bytes: Bytes,\n options: toBoolean.Options = {},\n): boolean {\n const { size } = options\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimLeft(bytes_)\n }\n if (bytes_.length > 1 || bytes_[0]! > 1)\n throw new InvalidBytesBooleanError(bytes_)\n return Boolean(bytes_[0])\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes, options: toHex.Options = {}): Hex.Hex {\n return Hex.fromBytes(value, options)\n}\n\nexport declare namespace toHex {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes: Bytes, options: toNumber.Options = {}): number {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toNumber(hex, options)\n}\n\nexport declare namespace toNumber {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes: Bytes, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimRight(bytes_)\n }\n return decoder.decode(bytes_)\n}\n\nexport declare namespace toString {\n export type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n export type ErrorType =\n | internal.assertSize.ErrorType\n | trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n export type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value: unknown): value is Bytes {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesBooleanError'\n\n constructor(bytes: Bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n })\n }\n}\n\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`,\n {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Bytes.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as internal_bytes from './internal/bytes.js'\nimport * as internal from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\n/** Root type for a Hex string. */\nexport type Hex = `0x${string}`\n\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(\n value: unknown,\n options: assert.Options = {},\n): asserts value is Hex {\n const { strict = false } = options\n if (!value) throw new InvalidHexTypeError(value)\n if (typeof value !== 'string') throw new InvalidHexTypeError(value)\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value)) throw new InvalidHexValueError(value)\n }\n if (!value.startsWith('0x')) throw new InvalidHexValueError(value)\n}\n\nexport declare namespace assert {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | InvalidHexTypeError\n | InvalidHexValueError\n | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values: readonly Hex[]): Hex {\n return `0x${(values as Hex[]).reduce((acc, x) => acc + x.replace('0x', ''), '')}`\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value: Hex | Bytes.Bytes | readonly number[]): Hex {\n if (value instanceof Uint8Array) return fromBytes(value)\n if (Array.isArray(value)) return fromBytes(new Uint8Array(value))\n return value as never\n}\n\nexport declare namespace from {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(\n value: boolean,\n options: fromBoolean.Options = {},\n): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padLeft(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(\n value: Bytes.Bytes,\n options: fromBytes.Options = {},\n): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) string += hexes[value[i]!]\n const hex = `0x${string}` as const\n\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padRight(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBytes {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(\n value: number | bigint,\n options: fromNumber.Options = {},\n): Hex {\n const { signed, size } = options\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 stringValue = (\n signed && value_ < 0 ? BigInt.asUintN(size * 8, BigInt(value_)) : value_\n ).toString(16)\n\n const hex = `0x${stringValue}` as Hex\n if (size) return padLeft(hex, size) as Hex\n return hex\n}\n\nexport declare namespace fromNumber {\n type Options =\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\n type ErrorType =\n | IntegerOutOfRangeError\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Hex {\n return fromBytes(encoder.encode(value), options)\n}\n\nexport declare namespace fromString {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA: Hex, hexB: Hex) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB))\n}\n\nexport declare namespace isEqual {\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(\n value: Hex,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(\n value: Hex,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length: number): Hex {\n return fromBytes(Bytes.random(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(\n value: Hex,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Hex {\n const { strict } = options\n internal.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) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value: Hex): number {\n return Math.ceil((value.length - 2) / 2)\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value: Hex): trimLeft.ReturnType {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value: Hex): trimRight.ReturnType {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {\n const { signed } = options\n\n if (options.size) internal.assertSize(hex, options.size)\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n\n const max_signed = max_unsigned >> 1n\n\n if (value <= max_signed) return value\n return value - max_unsigned - 1n\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType = internal.assertSize.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex: Hex, options: toBoolean.Options = {}): boolean {\n if (options.size) internal.assertSize(hex, options.size)\n const hex_ = trimLeft(hex)\n if (hex_ === '0x') return false\n if (hex_ === '0x1') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | InvalidHexBooleanError\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex: Hex, options: toBytes.Options = {}): Bytes.Bytes {\n return Bytes.fromHex(hex, options)\n}\n\nexport declare namespace toBytes {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex: Hex, options: toNumber.Options = {}): number {\n const { signed, size } = options\n if (!signed && !size) return Number(hex)\n return Number(toBigInt(hex, options))\n}\n\nexport declare namespace toNumber {\n type Options = toBigInt.Options\n\n type ErrorType = toBigInt.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex: Hex, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes = Bytes.fromHex(hex)\n if (size) {\n internal_bytes.assertSize(bytes, size)\n bytes = Bytes.trimRight(bytes)\n }\n return new TextDecoder().decode(bytes)\n}\n\nexport declare namespace toString {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_bytes.assertSize.ErrorType\n | Bytes.fromHex.ErrorType\n | Bytes.trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(\n value: unknown,\n options: validate.Options = {},\n): value is Hex {\n const { strict = false } = options\n try {\n assert(value, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n override readonly name = 'Hex.IntegerOutOfRangeError'\n\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` : ''\n }${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`,\n )\n }\n}\n\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexBooleanError'\n\n constructor(hex: Hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`,\n {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexValueError'\n\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidLengthError'\n\n constructor(value: Hex) {\n super(\n `Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`,\n {\n metaMessages: ['It must be an even length.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Hex.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Hex.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Hex.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/** A Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Withdrawal = {\n address: Hex.Hex\n amount: bigintType\n index: numberType\n validatorIndex: numberType\n}\n\n/** An RPC Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Rpc = Withdrawal\n\n/**\n * Converts a {@link ox#Withdrawal.Rpc} to an {@link ox#Withdrawal.Withdrawal}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.fromRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: '0x620323',\n * index: '0x0',\n * validatorIndex: '0x1',\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: 6423331n,\n * // @log: index: 0,\n * // @log: validatorIndex: 1\n * // @log: }\n * ```\n *\n * @param withdrawal - The RPC withdrawal to convert.\n * @returns An instantiated {@link ox#Withdrawal.Withdrawal}.\n */\nexport function fromRpc(withdrawal: Rpc): Withdrawal {\n return {\n ...withdrawal,\n amount: BigInt(withdrawal.amount),\n index: Number(withdrawal.index),\n validatorIndex: Number(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace fromRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Withdrawal.Withdrawal} to an {@link ox#Withdrawal.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.toRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: 6423331n,\n * index: 0,\n * validatorIndex: 1,\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: '0x620323',\n * // @log: index: '0x0',\n * // @log: validatorIndex: '0x1',\n * // @log: }\n * ```\n *\n * @param withdrawal - The Withdrawal to convert.\n * @returns An RPC Withdrawal.\n */\nexport function toRpc(withdrawal: Withdrawal): Rpc {\n return {\n address: withdrawal.address,\n amount: Hex.fromNumber(withdrawal.amount),\n index: Hex.fromNumber(withdrawal.index),\n validatorIndex: Hex.fromNumber(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace toRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Address from './Address.js'\nimport * as Hex from './Hex.js'\nimport * as Withdrawal from './Withdrawal.js'\n\n/**\n * Block overrides.\n */\nexport type BlockOverrides = {\n /** Base fee per gas. */\n baseFeePerGas?: bigintType | undefined\n /** Blob base fee. */\n blobBaseFee?: bigintType | undefined\n /** Fee recipient (also known as coinbase). */\n feeRecipient?: Address.Address | undefined\n /** Gas limit. */\n gasLimit?: bigintType | undefined\n /** Block number. */\n number?: bigintType | undefined\n /** The previous value of randomness beacon. */\n prevRandao?: bigintType | undefined\n /** Block timestamp. */\n time?: bigintType | undefined\n /** Withdrawals made by validators. */\n withdrawals?: Withdrawal.Withdrawal[] | undefined\n}\n\n/**\n * RPC block overrides.\n */\nexport type Rpc = BlockOverrides\n\n/**\n * Converts an {@link ox#BlockOverrides.Rpc} to an {@link ox#BlockOverrides.BlockOverrides}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.fromRpc({\n * baseFeePerGas: '0x1',\n * blobBaseFee: '0x2',\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: '0x4',\n * number: '0x5',\n * prevRandao: '0x6',\n * time: '0x1234567890',\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: '0x1',\n * index: '0x0',\n * validatorIndex: '0x1',\n * },\n * ],\n * })\n * ```\n *\n * @param rpcBlockOverrides - The RPC block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.BlockOverrides}.\n */\nexport function fromRpc(rpcBlockOverrides: Rpc): BlockOverrides {\n return {\n ...(rpcBlockOverrides.baseFeePerGas && {\n baseFeePerGas: BigInt(rpcBlockOverrides.baseFeePerGas),\n }),\n ...(rpcBlockOverrides.blobBaseFee && {\n blobBaseFee: BigInt(rpcBlockOverrides.blobBaseFee),\n }),\n ...(rpcBlockOverrides.feeRecipient && {\n feeRecipient: rpcBlockOverrides.feeRecipient,\n }),\n ...(rpcBlockOverrides.gasLimit && {\n gasLimit: BigInt(rpcBlockOverrides.gasLimit),\n }),\n ...(rpcBlockOverrides.number && {\n number: BigInt(rpcBlockOverrides.number),\n }),\n ...(rpcBlockOverrides.prevRandao && {\n prevRandao: BigInt(rpcBlockOverrides.prevRandao),\n }),\n ...(rpcBlockOverrides.time && {\n time: BigInt(rpcBlockOverrides.time),\n }),\n ...(rpcBlockOverrides.withdrawals && {\n withdrawals: rpcBlockOverrides.withdrawals.map(Withdrawal.fromRpc),\n }),\n }\n}\n\n/**\n * Converts an {@link ox#BlockOverrides.BlockOverrides} to an {@link ox#BlockOverrides.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.toRpc({\n * baseFeePerGas: 1n,\n * blobBaseFee: 2n,\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: 4n,\n * number: 5n,\n * prevRandao: 6n,\n * time: 78187493520n,\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: 1n,\n * index: 0,\n * validatorIndex: 1,\n * },\n * ],\n * })\n * ```\n *\n * @param blockOverrides - The block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.Rpc}.\n */\nexport function toRpc(blockOverrides: BlockOverrides): Rpc {\n return {\n ...(typeof blockOverrides.baseFeePerGas === 'bigint' && {\n baseFeePerGas: Hex.fromNumber(blockOverrides.baseFeePerGas),\n }),\n ...(typeof blockOverrides.blobBaseFee === 'bigint' && {\n blobBaseFee: Hex.fromNumber(blockOverrides.blobBaseFee),\n }),\n ...(typeof blockOverrides.feeRecipient === 'string' && {\n feeRecipient: blockOverrides.feeRecipient,\n }),\n ...(typeof blockOverrides.gasLimit === 'bigint' && {\n gasLimit: Hex.fromNumber(blockOverrides.gasLimit),\n }),\n ...(typeof blockOverrides.number === 'bigint' && {\n number: Hex.fromNumber(blockOverrides.number),\n }),\n ...(typeof blockOverrides.prevRandao === 'bigint' && {\n prevRandao: Hex.fromNumber(blockOverrides.prevRandao),\n }),\n ...(typeof blockOverrides.time === 'bigint' && {\n time: Hex.fromNumber(blockOverrides.time),\n }),\n ...(blockOverrides.withdrawals && {\n withdrawals: blockOverrides.withdrawals.map(Withdrawal.toRpc),\n }),\n }\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 {\n inputs: [\n {\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n\nexport const batchGatewayAbi = [\n {\n name: 'query',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n type: 'tuple[]',\n name: 'queries',\n components: [\n {\n type: 'address',\n name: 'sender',\n },\n {\n type: 'string[]',\n name: 'urls',\n },\n {\n type: 'bytes',\n name: 'data',\n },\n ],\n },\n ],\n outputs: [\n {\n type: 'bool[]',\n name: 'failures',\n },\n {\n type: 'bytes[]',\n name: 'responses',\n },\n ],\n },\n {\n name: 'HttpError',\n type: 'error',\n inputs: [\n {\n type: 'uint16',\n name: 'status',\n },\n {\n type: 'string',\n name: 'message',\n },\n ],\n },\n] as const\n\nconst universalResolverErrors = [\n {\n inputs: [\n {\n name: 'dns',\n type: 'bytes',\n },\n ],\n name: 'DNSDecodingFailed',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'ens',\n type: 'string',\n },\n ],\n name: 'DNSEncodingFailed',\n type: 'error',\n },\n {\n inputs: [],\n name: 'EmptyAddress',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'HttpError',\n type: 'error',\n },\n {\n inputs: [],\n name: 'InvalidBatchGatewayResponse',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'errorData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n {\n name: 'resolver',\n type: 'address',\n },\n ],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n ],\n name: 'ResolverNotFound',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'primary',\n type: 'string',\n },\n {\n name: 'primaryAddress',\n type: 'bytes',\n },\n ],\n name: 'ReverseAddressMismatch',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'selector',\n type: 'bytes4',\n },\n ],\n name: 'UnsupportedResolverProfile',\n type: 'error',\n },\n] as const\n\nexport const universalResolverResolveAbi = [\n ...universalResolverErrors,\n {\n name: 'resolveWithGateways',\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: 'reverseWithGateways',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'uint256', name: 'coinType' },\n { type: 'string[]', name: 'gateways' },\n ],\n outputs: [\n { type: 'string', name: 'resolvedName' },\n { type: 'address', name: 'resolver' },\n { type: 'address', name: 'reverseResolver' },\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 erc1271Abi = [\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 erc6492SignatureValidatorAbi = [\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-1155 Multi Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-1155) */\nexport const erc1155Abi = [\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'needed',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InsufficientBalance',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'approver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidApprover',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: 'idsLength',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'valuesLength',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InvalidArrayLength',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidOperator',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidReceiver',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidSender',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'ERC1155MissingApprovalForAll',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n ],\n name: 'TransferBatch',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'TransferSingle',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'string',\n name: 'value',\n type: 'string',\n },\n {\n indexed: true,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'URI',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address[]',\n name: 'accounts',\n type: 'address[]',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n ],\n name: 'balanceOfBatch',\n outputs: [\n {\n internalType: 'uint256[]',\n name: '',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'isApprovedForAll',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'interfaceId',\n type: 'bytes4',\n },\n ],\n name: 'supportsInterface',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'uri',\n outputs: [\n {\n internalType: 'string',\n name: '',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\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: 'tokenId',\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 erc6492SignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\nexport const multicall3Bytecode =\n '0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033'\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 { 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 {\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 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","/** @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 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 { Abi, AbiStateMutability } from 'abitype'\n\nimport { AbiFunctionSignatureNotFoundError } from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type SliceErrorType, 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 DecodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = {\n abi: abi\n data: Hex\n}\n\nexport type DecodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allFunctionNames extends\n ContractFunctionName = ContractFunctionName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [functionName in allFunctionNames]: {\n args: ContractFunctionArgs\n functionName: functionName\n }\n }[allFunctionNames]\n >\n : {\n args: readonly unknown[] | undefined\n functionName: string\n }\n\nexport type DecodeFunctionDataErrorType =\n | AbiFunctionSignatureNotFoundError\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | SliceErrorType\n | ErrorType\n\nexport function decodeFunctionData(\n parameters: DecodeFunctionDataParameters,\n) {\n const { abi, data } = parameters as DecodeFunctionDataParameters\n const signature = slice(data, 0, 4)\n const description = abi.find(\n (x) =>\n x.type === 'function' &&\n signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!description)\n throw new AbiFunctionSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeFunctionData',\n })\n return {\n functionName: (description as { name: string }).name,\n args: ('inputs' in description &&\n description.inputs &&\n description.inputs.length > 0\n ? decodeAbiParameters(description.inputs, slice(data, 4))\n : undefined) as readonly unknown[] | undefined,\n } as DecodeFunctionDataReturnType\n}\n","import type { Abi, ExtractAbiErrors } from 'abitype'\n\nimport {\n AbiErrorInputsNotFoundError,\n AbiErrorNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\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 { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeErrorResult'\n\nexport type EncodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n errorName extends ContractErrorName | undefined = ContractErrorName,\n ///\n hasErrors = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiErrors] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractErrorArgs<\n abi,\n errorName extends ContractErrorName\n ? errorName\n : ContractErrorName\n >,\n allErrorNames = ContractErrorName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { errorName?: errorName | allErrorNames | undefined }\n : { errorName: errorName | allErrorNames }\n : { errorName?: errorName | allErrorNames | undefined }\n> &\n (hasErrors extends true ? unknown : never)\n\nexport type EncodeErrorResultReturnType = Hex\n\nexport type EncodeErrorResultErrorType =\n | GetAbiItemErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | EncodeAbiParametersErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function encodeErrorResult<\n const abi extends Abi | readonly unknown[],\n errorName extends ContractErrorName | undefined = undefined,\n>(\n parameters: EncodeErrorResultParameters,\n): EncodeErrorResultReturnType {\n const { abi, errorName, args } = parameters as EncodeErrorResultParameters\n\n let abiItem = abi[0]\n if (errorName) {\n const item = getAbiItem({ abi, args, name: errorName })\n if (!item) throw new AbiErrorNotFoundError(errorName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'error')\n throw new AbiErrorNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toFunctionSelector(definition)\n\n let data: Hex = '0x'\n if (args && args.length > 0) {\n if (!abiItem.inputs)\n throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath })\n data = encodeAbiParameters(abiItem.inputs, args)\n }\n return concatHex([signature, data])\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n AbiFunctionOutputsNotFoundError,\n InvalidArrayError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionName,\n ContractFunctionReturnType,\n} from '../../types/contract.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 GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionResult'\n\nexport type EncodeFunctionResultParameters<\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 allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n result?:\n | ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n never // allow all args. required for overloads to work.\n >\n | undefined\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 (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionResultReturnType = Hex\n\nexport type EncodeFunctionResultErrorType =\n | AbiFunctionOutputsNotFoundError\n | AbiFunctionNotFoundError\n | EncodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function encodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionResultParameters,\n): EncodeFunctionResultReturnType {\n const { abi, functionName, result } =\n parameters as EncodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, 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\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath })\n\n const values = (() => {\n if (abiItem.outputs.length === 0) return []\n if (abiItem.outputs.length === 1) return [result]\n if (Array.isArray(result)) return result\n throw new InvalidArrayError(result)\n })()\n\n return encodeAbiParameters(abiItem.outputs, values)\n}\n","import { batchGatewayAbi } from '../../constants/abis.js'\nimport { solidityError } from '../../constants/solidity.js'\nimport type { Hex } from '../../types/misc.js'\nimport { decodeFunctionData } from '../abi/decodeFunctionData.js'\nimport { encodeErrorResult } from '../abi/encodeErrorResult.js'\nimport { encodeFunctionResult } from '../abi/encodeFunctionResult.js'\nimport type {\n CcipRequestErrorType,\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../ccip.js'\n\nexport const localBatchGatewayUrl = 'x-batch-gateway:true'\n\nexport async function localBatchGatewayRequest(parameters: {\n data: Hex\n ccipRequest: (\n parameters: CcipRequestParameters,\n ) => Promise\n}): Promise {\n const { data, ccipRequest } = parameters\n\n const {\n args: [queries],\n } = decodeFunctionData({ abi: batchGatewayAbi, data })\n\n const failures: boolean[] = []\n const responses: Hex[] = []\n await Promise.all(\n queries.map(async (query, i) => {\n try {\n responses[i] = query.urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({ data: query.data, ccipRequest })\n : await ccipRequest(query)\n failures[i] = false\n } catch (err) {\n failures[i] = true\n responses[i] = encodeError(err as CcipRequestErrorType)\n }\n }),\n )\n\n return encodeFunctionResult({\n abi: batchGatewayAbi,\n functionName: 'query',\n result: [failures, responses],\n })\n}\n\nfunction encodeError(error: CcipRequestErrorType): Hex {\n if (error.name === 'HttpRequestError' && error.status)\n return encodeErrorResult({\n abi: batchGatewayAbi,\n errorName: 'HttpError',\n args: [error.status, error.shortMessage],\n })\n return encodeErrorResult({\n abi: [solidityError],\n errorName: 'Error',\n args: ['shortMessage' in error ? error.shortMessage : error.message],\n })\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Client } from '../clients/createClient.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 { ErrorType } from '../errors/utils.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.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 {\n localBatchGatewayRequest,\n localBatchGatewayUrl,\n} from './ens/localBatchGatewayRequest.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 = urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({\n data: callData,\n ccipRequest: ccipRequest_,\n })\n : 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.toLowerCase()).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","import { type Address, parseAbi } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\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 multicall3Bytecode,\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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } 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 /** Block overrides for the call. */\n blockOverrides?: BlockOverrides.BlockOverrides | 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 authorizationList,\n batch = Boolean(client.batch?.multicall),\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n accessList,\n blobs,\n blockOverrides,\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 =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcBlockOverrides = blockOverrides\n ? BlockOverrides.toRpc(blockOverrides)\n : undefined\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 {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\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,\n 'call',\n ) as TransactionRequest\n\n if (\n batch &&\n shouldPerformMulticall({ request }) &&\n !rpcStateOverride &&\n !rpcBlockOverrides\n ) {\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 params = (() => {\n const base = [\n request as ExactPartial,\n block,\n ] as const\n if (rpcStateOverride && rpcBlockOverrides)\n return [...base, rpcStateOverride, rpcBlockOverrides] as const\n if (rpcStateOverride) return [...base, rpcStateOverride] as const\n if (rpcBlockOverrides) return [...base, {}, rpcBlockOverrides] as const\n return base\n })()\n\n const response = await client.request({\n method: 'eth_call',\n params,\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 {\n batchSize = 1024,\n deployless = false,\n wait = 0,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n data,\n to,\n } = args\n\n const multicallAddress = (() => {\n if (deployless) return null\n if (args.multicallAddress) return args.multicallAddress\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new ClientChainNotConfiguredError()\n })()\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? 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 ...(multicallAddress === null\n ? {\n data: toDeploylessCallViaBytecodeData({\n code: multicall3Bytecode,\n data: calldata,\n }),\n }\n : { to: multicallAddress, data: calldata }),\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: { code: Hex; data: Hex }) {\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","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @module\n * @privateRemarks\n * WARNING:\n * - Don't remove error codes\n * - Don't change or reorder error codes.\n *\n * Good naming conventions:\n * - Prefixing common errors — e.g. under the same package — can be a good way to namespace them. E.g. All codec-related errors start with `SOLANA_ERROR__CODECS__`.\n * - Use consistent names — e.g. choose `PDA` or `PROGRAM_DERIVED_ADDRESS` and stick with it. Ensure your names are consistent with existing error codes. The decision might have been made for you.\n * - Recommended prefixes and suffixes:\n * - `MALFORMED_`: Some input was not constructed properly. E.g. `MALFORMED_BASE58_ENCODED_ADDRESS`.\n * - `INVALID_`: Some input is invalid (other than because it was MALFORMED). E.g. `INVALID_NUMBER_OF_BYTES`.\n * - `EXPECTED_`: Some input was different than expected, no need to specify the \"GOT\" part unless necessary. E.g. `EXPECTED_DECODED_ACCOUNT`.\n * - `_CANNOT_`: Some operation cannot be performed or some input cannot be used due to some condition. E.g. `CANNOT_DECODE_EMPTY_BYTE_ARRAY` or `PDA_CANNOT_END_WITH_PDA_MARKER`.\n * - `_MUST_BE_`: Some condition must be true. E.g. `NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE`.\n * - `_FAILED_TO_`: Tried to perform some operation and failed. E.g. `FAILED_TO_DECODE_ACCOUNT`.\n * - `_NOT_FOUND`: Some operation lead to not finding something. E.g. `ACCOUNT_NOT_FOUND`.\n * - `_OUT_OF_RANGE`: Some value is out of range. E.g. `ENUM_DISCRIMINATOR_OUT_OF_RANGE`.\n * - `_EXCEEDED`: Some limit was exceeded. E.g. `PDA_MAX_SEED_LENGTH_EXCEEDED`.\n * - `_MISMATCH`: Some elements do not match. E.g. `ENCODER_DECODER_FIXED_SIZE_MISMATCH`.\n * - `_MISSING`: Some required input is missing. E.g. `TRANSACTION_FEE_PAYER_MISSING`.\n * - `_UNIMPLEMENTED`: Some required component is not available in the environment. E.g. `SUBTLE_CRYPTO_VERIFY_FUNCTION_UNIMPLEMENTED`.\n */\nexport const SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nexport const SOLANA_ERROR__INVALID_NONCE = 2;\nexport const SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nexport const SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nexport const SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nexport const SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nexport const SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nexport const SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nexport const SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nexport const SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\n\n// JSON-RPC-related errors.\n// Reserve error codes in the range [-32768, -32000]\n// Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs\nexport const SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nexport const SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nexport const SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nexport const SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\n\n// Addresses-related errors.\n// Reserve error codes in the range [2800000-2800999].\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 2800000;\nexport const SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nexport const SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nexport const SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nexport const SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nexport const SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nexport const SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nexport const SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\n\n// Account-related errors.\n// Reserve error codes in the range [3230000-3230999].\nexport const SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 3230000;\nexport const SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nexport const SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\n\n// Subtle-Crypto-related errors.\n// Reserve error codes in the range [3610000-3610999].\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 3610000;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\n\n// Crypto-related errors.\n// Reserve error codes in the range [3611000-3611050].\nexport const SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611000;\n\n// Key-related errors.\n// Reserve error codes in the range [3704000-3704999].\nexport const SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704000;\nexport const SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nexport const SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nexport const SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nexport const SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\n\n// Instruction-related errors.\n// Reserve error codes in the range [4128000-4128999].\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128000;\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nexport const SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\n\n// Instruction errors.\n// Reserve error codes starting with [4615000-4615999] for the Rust enum `InstructionError`.\n// Error names here are dictated by the RPC (see ./instruction-error.ts).\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615000;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\n\n// Signer-related errors.\n// Reserve error codes in the range [5508000-5508999].\nexport const SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508000;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nexport const SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\n\n// Offchain-message-related errors.\n// Reserve error codes in the range [5607000-5607999].\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED = 5607000;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE = 5607001;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE = 5607002;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH = 5607003;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH = 5607004;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO = 5607005;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED = 5607006;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH = 5607007;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH = 5607008;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY = 5607009;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO = 5607010;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING = 5607011;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH = 5607012;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE = 5607013;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION = 5607014;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED = 5607015;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE = 5607016;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE = 5607017;\n\n// Transaction-related errors.\n// Reserve error codes in the range [5663000-5663999].\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663000;\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nexport const SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nexport const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nexport const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nexport const SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;\nexport const SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;\n\n// Transaction errors.\n// Reserve error codes starting with [7050000-7050999] for the Rust enum `TransactionError`.\n// Error names here are dictated by the RPC (see ./transaction-error.ts).\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 7050000;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\n// `InstructionError` intentionally omitted.\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\n\n// Instruction plan related errors.\n// Reserve error codes in the range [7618000-7618999].\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618000;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED = 7618004;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND = 7618005;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN = 7618006;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN = 7618007;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT = 7618008;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT = 7618009;\n\n// Codec-related errors.\n// Reserve error codes in the range [8078000-8078999].\nexport const SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078000;\nexport const SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nexport const SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nexport const SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nexport const SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nexport const SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nexport const SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nexport const SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nexport const SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nexport const SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nexport const SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nexport const SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nexport const SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nexport const SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nexport const SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nexport const SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nexport const SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nexport const SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nexport const SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nexport const SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nexport const SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;\n\n// RPC-related errors.\n// Reserve error codes in the range [8100000-8100999].\nexport const SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 8100000;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nexport const SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\n\n// RPC-Subscriptions-related errors.\n// Reserve error codes in the range [8190000-8190999].\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 8190000;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\n\n// Invariant violation errors.\n// Reserve error codes in the range [9900000-9900999].\n// These errors should only be thrown when there is a bug with the\n// library itself and should, in theory, never reach the end user.\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 9900000;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;\n\n/**\n * A union of every Solana error code\n *\n * @privateRemarks\n * You might be wondering why this is not a TypeScript enum or const enum.\n *\n * One of the goals of this library is to enable people to use some or none of it without having to\n * bundle all of it.\n *\n * If we made the set of error codes an enum then anyone who imported it (even if to only use a\n * single error code) would be forced to bundle every code and its label.\n *\n * Const enums appear to solve this problem by letting the compiler inline only the codes that are\n * actually used. Unfortunately exporting ambient (const) enums from a library like `@solana/errors`\n * is not safe, for a variety of reasons covered here: https://stackoverflow.com/a/28818850\n */\nexport type SolanaErrorCode =\n | typeof SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND\n | typeof SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE\n | typeof SOLANA_ERROR__ADDRESSES__MALFORMED_PDA\n | typeof SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE\n | typeof SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER\n | typeof SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED\n | typeof SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS\n | typeof SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE\n | typeof SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__INVALID_CONSTANT\n | typeof SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS\n | typeof SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE\n | typeof SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES\n | typeof SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA\n | typeof SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH\n | typeof SOLANA_ERROR__INVALID_NONCE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE\n | typeof SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_PARAMS\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_REQUEST\n | typeof SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND\n | typeof SOLANA_ERROR__JSON_RPC__PARSE_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SCAN_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION\n | typeof SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY\n | typeof SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE\n | typeof SOLANA_ERROR__MALFORMED_BIGINT_STRING\n | typeof SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR\n | typeof SOLANA_ERROR__MALFORMED_NUMBER_STRING\n | typeof SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD\n | typeof SOLANA_ERROR__RPC__INTEGER_OVERFLOW\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID\n | typeof SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING\n | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES\n | typeof SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE\n | typeof SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE\n | typeof SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT;\n\n/**\n * Errors of this type are understood to have an optional {@link SolanaError} nested inside as\n * `cause`.\n */\nexport type SolanaErrorCodeWithCause = typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE;\n\n/**\n * Errors of this type have a deprecated `cause` property. Consumers should use the error's\n * `context` instead to access relevant error information.\n */\nexport type SolanaErrorCodeWithDeprecatedCause =\n typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @privateRemarks\n * WARNING:\n * - Don't change or remove members of an error's context.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SolanaErrorCode,\n} from './codes';\nimport { RpcSimulateTransactionResult } from './json-rpc-error';\n\ntype BasicInstructionErrorContext = { [P in T]: { index: number } };\n\ntype DefaultUnspecifiedErrorContextToUndefined = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype ReadonlyContextValue = {\n [P in keyof T]: Readonly;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit {\n readonly [n: number]: number;\n}\n\n/** A amount of bytes. */\ntype Bytes = number;\n\n/**\n * A map of every {@link SolanaError} code to the type of its `context` property.\n */\nexport type SolanaErrorContext = ReadonlyContextValue<\n DefaultUnspecifiedErrorContextToUndefined<\n BasicInstructionErrorContext<\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n > & {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: {\n putativeAddress: string;\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: {\n actual: number;\n maxSeeds: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: {\n actual: number;\n index: number;\n maxSeedLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: {\n bump: number;\n };\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: {\n currentBlockHeight: bigint;\n lastValidBlockHeight: bigint;\n };\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: {\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: {\n stringValues: readonly string[];\n };\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: {\n encodedBytes: ReadonlyUint8Array;\n hexEncodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: {\n decoderFixedSize: number;\n encoderFixedSize: number;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: {\n decoderMaxSize: number | undefined;\n encoderMaxSize: number | undefined;\n };\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n formattedValidDiscriminators: string;\n validDiscriminators: readonly number[];\n };\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: {\n expectedLength: number;\n numExcessBytes: number;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: {\n codecDescription: string;\n expectedSize: number;\n hexZeroValue: string;\n zeroValue: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n expected: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: {\n constant: ReadonlyUint8Array;\n data: ReadonlyUint8Array;\n hexConstant: string;\n hexData: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: {\n formattedNumericalValues: string;\n numericalValues: readonly number[];\n stringValues: readonly string[];\n variant: number | string | symbol;\n };\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: {\n actual: bigint | number;\n codecDescription: string;\n expected: bigint | number;\n };\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: {\n alphabet: string;\n base: number;\n value: string;\n };\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n maxRange: number;\n minRange: number;\n };\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: {\n codecDescription: string;\n max: bigint | number;\n min: bigint | number;\n value: bigint | number;\n };\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: {\n bytesLength: number;\n codecDescription: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: {\n decodedBytes: ReadonlyUint8Array;\n hexDecodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: {\n maxRange: number;\n minRange: number;\n variant: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: {\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: {\n code: number;\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: {\n errorName: string;\n index: number;\n instructionErrorContext?: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: {\n numBytesRequired: number;\n numFreeBytes: number;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n instructionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n transactionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]: {\n actualKind: string;\n expectedKind: string;\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: {\n data?: ReadonlyUint8Array;\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: {\n accountAddresses?: readonly string[];\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: {\n actualProgramAddress: string;\n expectedProgramAddress: string;\n };\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__INVALID_NONCE]: {\n actualNonceValue: string;\n expectedNonceValue: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: {\n cacheKey: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: {\n channelName: string;\n supportedChannelNames: readonly string[];\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: {\n unexpectedValue: unknown;\n };\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: {\n currentBlockHeight: bigint;\n rewardsCompleteBlockHeight: bigint;\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: {\n contextSlot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: {\n numSlotsBehind?: number;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: Omit<\n RpcSimulateTransactionResult,\n 'err'\n >;\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: {\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: {\n byteLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: {\n error: unknown;\n message: string;\n };\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: {\n nonceAccountAddress: string;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]: {\n missingRequiredSigners: readonly string[];\n unexpectedSigners: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]: {\n actualBytes: number;\n maxBytes: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]: {\n actualMessageFormat: number;\n expectedMessageFormat: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]: {\n actualLength: number;\n specifiedLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signatoryAddresses: readonly string[];\n signaturesLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]: {\n signatoriesWithInvalidSignatures: readonly string[];\n signatoriesWithMissingSignatures: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]: {\n actualVersion: number;\n expectedVersion: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: {\n notificationName: string;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: {\n errorEvent: Event;\n };\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: {\n method: string;\n params: readonly unknown[];\n };\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: {\n argumentLabel: string;\n keyPath: readonly (number | string | symbol)[];\n methodName: string;\n optionalPathLabel: string;\n path?: string;\n value: bigint;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: {\n headers: Headers;\n message: string;\n statusCode: number;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: {\n headers: readonly string[];\n };\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: {\n key: CryptoKey;\n };\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: {\n value: bigint;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: {\n errorName: string;\n transactionErrorContext?: unknown;\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: {\n transactionSize: Bytes;\n transactionSizeLimit: Bytes;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: {\n lookupTableAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: {\n highestKnownIndex: number;\n highestRequestedIndex: number;\n lookupTableAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: {\n unitsConsumed: number;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signaturesLength: number;\n signerAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: {\n nonce: string;\n };\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: {\n actualVersion: number;\n };\n }\n >\n>;\n\nexport function decodeEncodedContext(encodedContext: string): object {\n const decodedUrlString = __NODEJS__ ? Buffer.from(encodedContext, 'base64').toString('utf8') : atob(encodedContext);\n return Object.fromEntries(new URLSearchParams(decodedUrlString).entries());\n}\n\nfunction encodeValue(value: unknown): string {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join('%2C%20' /* \", \" */);\n return '%5B' /* \"[\" */ + commaSeparatedValues + /* \"]\" */ '%5D';\n } else if (typeof value === 'bigint') {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null\n ? // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...(value as object) }\n : value,\n ),\n );\n }\n}\n\nfunction encodeObjectContextEntry([key, value]: [string, unknown]): `${typeof key}=${string}` {\n return `${key}=${encodeValue(value)}`;\n}\n\nexport function encodeContextObject(context: object): string {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join('&');\n return __NODEJS__ ? Buffer.from(searchParamsString, 'utf8').toString('base64') : btoa(searchParamsString);\n}\n","/* eslint-disable sort-keys-fix/sort-keys-fix */\n/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors#adding-a-new-error\n *\n * WARNING:\n * - Don't change the meaning of an error message.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,\n SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,\n SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,\n SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,\n SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,\n SolanaErrorCode,\n} from './codes';\n\n/**\n * A map of every {@link SolanaError} code to the error message shown to developers in development\n * mode.\n */\nexport const SolanaErrorMessages: Readonly<{\n // This type makes this data structure exhaustive with respect to `SolanaErrorCode`.\n // TypeScript will fail to build this project if add an error code without a message.\n [P in SolanaErrorCode]: string;\n}> = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: 'Account not found at address: $address',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:\n 'Not all accounts were decoded. Encoded accounts found at addresses: $addresses.',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: 'Expected decoded account at address: $address',\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: 'Failed to decode account data at address: $address',\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: 'Accounts not found at addresses: $addresses',\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:\n 'Unable to find a viable program address bump seed.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: '$putativeAddress is not a base58-encoded address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:\n 'Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: 'The `CryptoKey` must be an `Ed25519` public key.',\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:\n '$putativeOffCurveAddress is not a base58-encoded off-curve address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: 'Invalid seeds; point must fall off the Ed25519 curve.',\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:\n 'Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].',\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:\n 'A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.',\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:\n 'The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.',\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:\n 'Expected program derived address bump to be in the range [0, 255], got: $bump.',\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: 'Program address cannot end with PDA marker.',\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:\n 'The network has progressed past the last block for which this transaction could have been committed.',\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:\n 'Codec [$codecDescription] cannot decode empty byte arrays.',\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:\n 'Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.',\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:\n 'Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:\n 'Encoder and decoder must either both be fixed-size or variable-size.',\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.',\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: 'Expected a fixed-size codec, got a variable-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected a positive byte length, got $bytesLength.',\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: 'Expected a variable-size codec, got a fixed-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:\n 'Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].',\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected $expected bytes, got $bytesLength.',\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]:\n 'Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].',\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:\n 'Invalid discriminated union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:\n 'Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.',\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:\n 'Invalid literal union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:\n 'Expected [$codecDescription] to have $expected items, got $actual.',\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: 'Invalid value $value for base $base with alphabet $alphabet.',\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.',\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.',\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.',\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:\n 'Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].',\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:\n 'Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.',\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:\n 'This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?',\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: 'No random values implementation could be found.',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: 'instruction requires an uninitialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:\n 'instruction tries to borrow reference for an account which is already borrowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'instruction left account with an outstanding borrowed reference',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:\n \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: 'account data too small for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: 'instruction expected an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:\n 'An account does not have enough lamports to be rent-exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: 'Program arithmetic overflowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: 'Failed to serialize or deserialize account data: $encodedData',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:\n 'Builtin programs must consume compute units',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: 'Cross-program invocation call depth too deep',\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: 'Computational budget exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: 'custom program error: #$code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: 'instruction contains duplicate accounts',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:\n 'instruction modifications of multiply-passed account differ',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: 'executable accounts must be rent exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: 'instruction changed executable accounts data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:\n 'instruction changed the balance of an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: 'instruction changed executable bit of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:\n 'instruction modified data of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:\n 'instruction spent from the balance of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: 'generic instruction error',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: 'Provided owner is not allowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: 'Account is immutable',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: 'Incorrect authority provided',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: 'incorrect program id for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: 'insufficient funds for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: 'invalid account data for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: 'Invalid account owner',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: 'invalid program argument',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: 'program returned invalid error code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: 'invalid instruction data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: 'Failed to reallocate account data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: 'Provided seeds do not result in a valid address',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:\n 'Accounts data allocations exceeded the maximum allowed per transaction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: 'Max accounts exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: 'Max instruction trace length exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:\n 'Length of the seed is too long for address generation',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: 'An account required by the instruction is missing',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: 'missing required signature for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:\n 'instruction illegally modified the program id of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: 'insufficient account keys for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:\n 'Cross-program invocation with unauthorized signer or writable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:\n 'Failed to create program execution environment',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: 'Program failed to compile',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: 'Program failed to complete',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: 'instruction modified data of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:\n 'instruction changed the balance of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:\n 'Cross-program invocation reentrancy not allowed for this instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: 'instruction modified rent epoch of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:\n 'sum of account balances before and after instruction do not match',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: 'instruction requires an initialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: '',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: 'Unsupported program id',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: 'Unsupported sysvar',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: 'Invalid instruction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: 'The provided instruction plan is empty.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]:\n 'No failed transaction plan result was found in the provided transaction plan result.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]:\n 'This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved — e.g. by targetting RPCs that support transaction bundles.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:\n 'The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:\n 'The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: 'Invalid transaction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:\n 'No more instructions to pack; the message packer has completed the instruction plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]:\n 'Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]:\n 'Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]:\n 'Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]:\n 'Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: 'The instruction does not have any accounts.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: 'The instruction does not have any data.',\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:\n 'Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.',\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:\n 'Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__INVALID_NONCE]:\n 'The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`',\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:\n 'Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It ' +\n 'should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:\n 'Invariant violation: This data publisher does not publish to the channel named ' +\n '`$channelName`. Supported channels include $supportedChannelNames.',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:\n 'Invariant violation: WebSocket message iterator state is corrupt; iterated without first ' +\n 'resolving existing message promise. It should be impossible to hit this error; please ' +\n 'file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:\n 'Invariant violation: WebSocket message iterator is missing state storage. It should be ' +\n 'impossible to hit this error; please file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:\n 'Invariant violation: Switch statement non-exhaustive. Received unexpected value ' +\n '`$unexpectedValue`. It should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: 'JSON-RPC error: Internal JSON-RPC error ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: 'JSON-RPC error: Invalid method parameter(s) ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:\n 'JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:\n 'JSON-RPC error: The method does not exist / is not available ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:\n 'JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:\n 'Epoch rewards period still active at slot $slot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:\n 'Failed to query long-term storage; please try again',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: 'Minimum context slot has not been reached',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: 'Node is unhealthy; behind by $numSlotsBehind slots',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: 'No snapshot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: 'Transaction simulation failed',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:\n \"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:\n 'Transaction history is not available from this node',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: 'Transaction signature length mismatch',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:\n 'Transaction signature verification failure',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: '$__serverMessage',\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: 'Key pair bytes must be of length 64, got $byteLength.',\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:\n 'Expected private key bytes with length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:\n 'Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:\n 'The provided private key does not match the provided public key.',\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.',\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: 'Lamports value must be in the range [0, 2e64-1]',\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: '`$value` cannot be parsed as a `BigInt`',\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: '$message',\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: '`$value` cannot be parsed as a `Number`',\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: 'No nonce account could be found at address `$nonceAccountAddress`',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]:\n 'Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]:\n 'Attempted to sign an offchain message with an address that is not a signer for it',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]:\n 'The signer addresses in this offchain message envelope do not match the list of ' +\n 'required signers in the message preamble. These unexpected signers were present in the ' +\n 'envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope ' +\n '`[$missingSigners]`.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]:\n 'The message body provided has a byte-length of $actualBytes. The maximum allowable ' +\n 'byte-length is $maxBytes',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]:\n 'Expected message format $expectedMessageFormat, got $actualMessageFormat',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]:\n 'The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]: 'Offchain message content must be non-empty',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]:\n 'Offchain message must specify the address of at least one required signer',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]:\n 'Offchain message envelope must reserve space for at least one signature',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]:\n 'The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]:\n 'The signatories of this offchain message must be listed in lexicographical order',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]:\n 'An address must be listed no more than once among the signatories of an offchain message',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]:\n 'Offchain message is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]:\n 'Offchain message signature verification failed. Signature mismatch for required ' +\n 'signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories ' +\n '[$signatoriesWithMissingSignatures]',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]:\n 'The message body provided contains characters whose codes fall outside the allowed ' +\n 'range. In order to ensure clear-signing compatiblity with hardware wallets, the message ' +\n 'may only contain line feeds and characters in the range [\\\\x20-\\\\x7e].',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]:\n 'Expected offchain message version $expectedVersion. Got $actualVersion.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding offchain messages with version ' +\n '$unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:\n \"The notification name must end in 'Notifications' and the API must supply a \" +\n \"subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:\n 'WebSocket was closed before payload could be added to the send buffer',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: 'WebSocket connection closed',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: 'WebSocket failed to connect',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:\n 'Failed to obtain a subscription id from the server',\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: 'Could not find an API plan for RPC method: `$method`',\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:\n 'The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was ' +\n '`$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: 'HTTP error ($statusCode): $message',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:\n 'HTTP header(s) forbidden: $headers. Learn more at ' +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.',\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:\n 'Multiple distinct signers were identified for address `$address`. Please ensure that ' +\n 'you are using the same signer instance for each address.',\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:\n 'The provided value does not implement the `KeyPairSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:\n 'The provided value does not implement the `MessageModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:\n 'The provided value does not implement the `MessagePartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:\n 'The provided value does not implement any of the `MessageSigner` interfaces',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:\n 'The provided value does not implement the `TransactionModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:\n 'The provided value does not implement the `TransactionPartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:\n 'The provided value does not implement the `TransactionSendingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:\n 'The provided value does not implement any of the `TransactionSigner` interfaces',\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:\n 'More than one `TransactionSendingSigner` was identified.',\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:\n 'No `TransactionSendingSigner` was identified. Please provide a valid ' +\n '`TransactionWithSingleSendingSigner` transaction.',\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:\n 'Wallet account signers do not support signing multiple messages/transactions in a single operation',\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: 'Cannot export a non-extractable key.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: 'No digest implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall ' +\n '@solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]:\n 'No signature verification implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: 'No key generation implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: 'No signing implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: 'No key export implementation could be found.',\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]:\n 'Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'Transaction processing left an account with an outstanding borrowed reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: 'Account in use',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: 'Account loaded twice',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]:\n 'Attempt to debit an account but found no record of a prior credit.',\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]:\n \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: 'This transaction has already been processed',\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: 'Blockhash not found',\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: 'Loader call chain is too deep',\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]:\n 'Transactions are currently disabled due to cluster maintenance',\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]:\n 'Transaction contains a duplicate instruction ($index) that is not allowed',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: 'Insufficient funds for fee',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]:\n 'Transaction results in an account ($accountIndex) with insufficient funds for rent',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: 'This account may not be used to pay transaction fees',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: 'Transaction contains an invalid account reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]:\n 'Transaction loads an address table account with invalid data',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]:\n 'Transaction address table lookup uses an invalid index',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]:\n 'Transaction loads an address table account with an invalid owner',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]:\n 'LoadedAccountsDataSizeLimit set for transaction must be greater than 0.',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]:\n 'This program may not be used for executing instructions',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]:\n 'Transaction leaves an account with a lower balance than rent-exempt minimum',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]:\n 'Transaction loads a writable account that cannot be written',\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]:\n 'Transaction exceeded max loaded accounts data size cap',\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]:\n 'Transaction requires a fee but has no signature present',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: 'Attempt to load a program that does not exist',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]:\n 'Execution of the program referenced by account at index $accountIndex is temporarily restricted.',\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: 'ResanitizationNeeded',\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: 'Transaction failed to sanitize accounts offsets correctly',\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: 'Transaction did not pass signature verification',\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: 'Transaction locked too many accounts',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]:\n 'Sum of account balances before and after transaction do not match',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: 'The transaction failed with the error `$errorName`',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: 'Transaction version is unsupported',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]:\n 'Transaction would exceed account data limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]:\n 'Transaction would exceed total account data limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]:\n 'Transaction would exceed max account limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]:\n 'Transaction would exceed max Block Cost Limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: 'Transaction would exceed max Vote Cost Limit',\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]:\n 'Attempted to sign a transaction with an address that is not a signer for it',\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: 'Transaction is missing an address at index: $index.',\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]:\n 'Transaction has no expected signers therefore it cannot be encoded',\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]:\n 'Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: 'Transaction does not have a blockhash lifetime',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: 'Transaction is not a durable nonce transaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]:\n 'Contents of these address lookup tables unknown: $lookupTableAddresses',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]:\n 'Lookup of address at index $highestRequestedIndex failed for lookup table ' +\n '`$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table ' +\n 'may have been extended since its contents were retrieved',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: 'No fee payer set in CompiledTransaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]:\n 'Could not find program address at index $index',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Failed to estimate the compute unit consumption for this transaction message. This is ' +\n 'likely because simulating the transaction failed. Inspect the `cause` property of this ' +\n 'error to learn more',\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Transaction failed when it was simulated in order to estimate the compute unit consumption. ' +\n 'The compute unit estimate provided is for a transaction that failed when simulated and may not ' +\n 'be representative of the compute units this transaction would consume if successful. Inspect the ' +\n '`cause` property of this error to learn more',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: 'Transaction is missing a fee payer.',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]:\n \"Could not determine this transaction's signature. Make sure that the transaction has \" +\n 'been signed by its fee payer.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]:\n 'Transaction first instruction is not advance nonce account instruction.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]:\n 'Transaction with no instructions cannot be durable nonce transaction.',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]:\n 'This transaction includes an address (`$programAddress`) which is both ' +\n 'invoked and set as the fee payer. Program addresses may not pay fees',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]:\n 'This transaction includes an address (`$programAddress`) which is both invoked and ' +\n 'marked writable. Program addresses may not be writable',\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]:\n 'The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.',\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: 'Transaction is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]:\n 'Transaction version must be in the range [0, 127]. `$actualVersion` given',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]:\n 'The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction.',\n};\n","import { SolanaErrorCode } from './codes';\nimport { encodeContextObject } from './context';\nimport { SolanaErrorMessages } from './messages';\n\nconst enum StateType {\n EscapeSequence,\n Text,\n Variable,\n}\ntype State = Readonly<{\n [START_INDEX]: number;\n [TYPE]: StateType;\n}>;\nconst START_INDEX = 'i';\nconst TYPE = 't';\n\nexport function getHumanReadableErrorMessage(\n code: TErrorCode,\n context: object = {},\n): string {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return '';\n }\n let state: State;\n function commitStateUpTo(endIndex?: number) {\n if (state[TYPE] === StateType.Variable) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n\n fragments.push(\n variableName in context\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName as keyof typeof context]}`\n : `$${variableName}`,\n );\n } else if (state[TYPE] === StateType.Text) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments: string[] = [];\n messageFormatString.split('').forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]:\n messageFormatString[0] === '\\\\'\n ? StateType.EscapeSequence\n : messageFormatString[0] === '$'\n ? StateType.Variable\n : StateType.Text,\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case StateType.EscapeSequence:\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n break;\n case StateType.Text:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n }\n break;\n case StateType.Variable:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join('');\n}\n\nexport function getErrorMessage(\n code: TErrorCode,\n context: Record = {},\n): string {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n /**\n * DANGER: Be sure that the shell command is escaped in such a way that makes it\n * impossible for someone to craft malicious context values that would result in\n * an exploit against anyone who bindly copy/pastes it into their terminal.\n */\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n","import { SolanaErrorCode, SolanaErrorCodeWithCause, SolanaErrorCodeWithDeprecatedCause } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { getErrorMessage } from './message-formatter';\n\n/**\n * A variant of {@link SolanaError} where the `cause` property is deprecated.\n *\n * This type is returned by {@link isSolanaError} when checking for error codes in\n * {@link SolanaErrorCodeWithDeprecatedCause}. Accessing `cause` on these errors will show\n * a deprecation warning in IDEs that support JSDoc `@deprecated` tags.\n */\nexport interface SolanaErrorWithDeprecatedCause<\n TErrorCode extends SolanaErrorCodeWithDeprecatedCause = SolanaErrorCodeWithDeprecatedCause,\n> extends Omit, 'cause'> {\n /**\n * @deprecated The `cause` property is deprecated for this error code.\n * Use the error's `context` property instead to access relevant error information.\n */\n readonly cause?: unknown;\n}\n\n/**\n * A type guard that returns `true` if the input is a {@link SolanaError}, optionally with a\n * particular error code.\n *\n * When the `code` argument is supplied and the input is a {@link SolanaError}, TypeScript will\n * refine the error's {@link SolanaError#context | `context`} property to the type associated with\n * that error code. You can use that context to render useful error messages, or to make\n * context-aware decisions that help your application to recover from the error.\n *\n * @example\n * ```ts\n * import {\n * SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE,\n * SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n * isSolanaError,\n * } from '@solana/errors';\n * import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions';\n *\n * try {\n * const transactionSignature = getSignatureFromTransaction(tx);\n * assertIsFullySignedTransaction(tx);\n * /* ... *\\/\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * displayError(\n * \"We can't send this transaction without signatures for these addresses:\\n- %s\",\n * // The type of the `context` object is now refined to contain `addresses`.\n * e.context.addresses.join('\\n- '),\n * );\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) {\n * if (!tx.feePayer) {\n * displayError('Choose a fee payer for this transaction before sending it');\n * } else {\n * displayError('The fee payer still needs to sign for this transaction');\n * }\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function isSolanaError(\n e: unknown,\n code: TErrorCode,\n): e is SolanaErrorWithDeprecatedCause;\nexport function isSolanaError(\n e: unknown,\n code?: TErrorCode,\n): e is SolanaError;\nexport function isSolanaError(\n e: unknown,\n /**\n * When supplied, this function will require that the input is a {@link SolanaError} _and_ that\n * its error code is exactly this value.\n */\n code?: TErrorCode,\n): e is SolanaError {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError).context.__code === code;\n }\n return true;\n }\n return false;\n}\n\ntype SolanaErrorCodedContext = {\n [P in SolanaErrorCode]: Readonly<{\n __code: P;\n }> &\n (SolanaErrorContext[P] extends undefined ? object : SolanaErrorContext[P]);\n};\n\n/**\n * Encapsulates an error's stacktrace, a Solana-specific numeric code that indicates what went\n * wrong, and optional context if the type of error indicated by the code supports it.\n */\nexport class SolanaError extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n readonly cause?: TErrorCode extends SolanaErrorCodeWithCause ? SolanaError : unknown = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n readonly context: SolanaErrorCodedContext[TErrorCode];\n constructor(\n ...[code, contextAndErrorOptions]: SolanaErrorContext[TErrorCode] extends undefined\n ? [code: TErrorCode, errorOptions?: ErrorOptions | undefined]\n : [code: TErrorCode, contextAndErrorOptions: SolanaErrorContext[TErrorCode] & (ErrorOptions | undefined)]\n ) {\n let context: SolanaErrorContext[TErrorCode] | undefined;\n let errorOptions: ErrorOptions | undefined;\n if (contextAndErrorOptions) {\n Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {\n // If the `ErrorOptions` type ever changes, update this code.\n if (name === 'cause') {\n errorOptions = { cause: descriptor.value };\n } else {\n if (context === undefined) {\n context = {\n __code: code,\n } as unknown as SolanaErrorContext[TErrorCode];\n }\n Object.defineProperty(context, name, descriptor);\n }\n });\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = Object.freeze(\n context === undefined\n ? {\n __code: code,\n }\n : context,\n ) as SolanaErrorCodedContext[TErrorCode];\n // This is necessary so that `isSolanaError()` can identify a `SolanaError` without having\n // to import the class for use in an `instanceof` check.\n this.name = 'SolanaError';\n }\n}\n","export function safeCaptureStackTrace(...args: Parameters): void {\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(...args);\n }\n}\n","import { SolanaErrorCode } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\n\ntype Config = Readonly<{\n /**\n * Oh, hello. You might wonder what in tarnation is going on here. Allow us to explain.\n *\n * One of the goals of `@solana/errors` is to allow errors that are not interesting to your\n * application to shake out of your app bundle in production. This means that we must never\n * export large hardcoded maps of error codes/messages.\n *\n * Unfortunately, where instruction and transaction errors from the RPC are concerned, we have\n * no choice but to keep a map between the RPC `rpcEnumError` enum name and its corresponding\n * `SolanaError` code. In the interest of implementing that map in as few bytes of source code\n * as possible, we do the following:\n *\n * 1. Reserve a block of sequential error codes for the enum in question\n * 2. Hardcode the list of enum names in that same order\n * 3. Match the enum error name from the RPC with its index in that list, and reconstruct the\n * `SolanaError` code by adding the `errorCodeBaseOffset` to that index\n */\n errorCodeBaseOffset: number;\n getErrorContext: (\n errorCode: SolanaErrorCode,\n rpcErrorName: string,\n rpcErrorContext?: unknown,\n ) => SolanaErrorContext[SolanaErrorCode];\n orderedErrorNames: string[];\n rpcEnumError: string | { [key: string]: unknown };\n}>;\n\nexport function getSolanaErrorFromRpcError(\n { errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }: Config,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructorOpt: Function,\n): SolanaError {\n let rpcErrorName;\n let rpcErrorContext;\n if (typeof rpcEnumError === 'string') {\n rpcErrorName = rpcEnumError;\n } else {\n rpcErrorName = Object.keys(rpcEnumError)[0];\n rpcErrorContext = rpcEnumError[rpcErrorName];\n }\n const codeOffset = orderedErrorNames.indexOf(rpcErrorName);\n const errorCode = (errorCodeBaseOffset + codeOffset) as SolanaErrorCode;\n const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);\n const err = new SolanaError(errorCode, errorContext);\n safeCaptureStackTrace(err, constructorOpt);\n return err;\n}\n","import { SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN } from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/solana-sdk/blob/master/instruction-error/src/lib.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'GenericError',\n 'InvalidArgument',\n 'InvalidInstructionData',\n 'InvalidAccountData',\n 'AccountDataTooSmall',\n 'InsufficientFunds',\n 'IncorrectProgramId',\n 'MissingRequiredSignature',\n 'AccountAlreadyInitialized',\n 'UninitializedAccount',\n 'UnbalancedInstruction',\n 'ModifiedProgramId',\n 'ExternalAccountLamportSpend',\n 'ExternalAccountDataModified',\n 'ReadonlyLamportChange',\n 'ReadonlyDataModified',\n 'DuplicateAccountIndex',\n 'ExecutableModified',\n 'RentEpochModified',\n 'NotEnoughAccountKeys',\n 'AccountDataSizeChanged',\n 'AccountNotExecutable',\n 'AccountBorrowFailed',\n 'AccountBorrowOutstanding',\n 'DuplicateAccountOutOfSync',\n 'Custom',\n 'InvalidError',\n 'ExecutableDataModified',\n 'ExecutableLamportChange',\n 'ExecutableAccountNotRentExempt',\n 'UnsupportedProgramId',\n 'CallDepth',\n 'MissingAccount',\n 'ReentrancyNotAllowed',\n 'MaxSeedLengthExceeded',\n 'InvalidSeeds',\n 'InvalidRealloc',\n 'ComputationalBudgetExceeded',\n 'PrivilegeEscalation',\n 'ProgramEnvironmentSetupFailure',\n 'ProgramFailedToComplete',\n 'ProgramFailedToCompile',\n 'Immutable',\n 'IncorrectAuthority',\n 'BorshIoError',\n 'AccountNotRentExempt',\n 'InvalidAccountOwner',\n 'ArithmeticOverflow',\n 'UnsupportedSysvar',\n 'IllegalOwner',\n 'MaxAccountsDataAllocationsExceeded',\n 'MaxAccountsExceeded',\n 'MaxInstructionTraceLengthExceeded',\n 'BuiltinProgramsMustConsumeComputeUnits',\n];\n\nexport function getSolanaErrorFromInstructionError(\n /**\n * The index of the instruction inside the transaction.\n */\n index: bigint | number,\n instructionError: string | { [key: string]: unknown },\n): SolanaError {\n const numberIndex = Number(index);\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 4615001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n index: numberIndex,\n ...(rpcErrorContext !== undefined ? { instructionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {\n return {\n code: Number(rpcErrorContext as bigint | number),\n index: numberIndex,\n };\n }\n return { index: numberIndex };\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: instructionError,\n },\n getSolanaErrorFromInstructionError,\n );\n}\n","import {\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n} from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromInstructionError } from './instruction-error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\n/**\n * How to add an error when an entry is added to the RPC `TransactionError` enum:\n *\n * 1. Follow the instructions in `./codes.ts` to add a corresponding Solana error code\n * 2. Add the `TransactionError` enum name in the same order as it appears in `./codes.ts`\n * 3. Add the new error name/code mapping to `./__tests__/transaction-error-test.ts`\n */\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'AccountInUse',\n 'AccountLoadedTwice',\n 'AccountNotFound',\n 'ProgramAccountNotFound',\n 'InsufficientFundsForFee',\n 'InvalidAccountForFee',\n 'AlreadyProcessed',\n 'BlockhashNotFound',\n // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`\n 'CallChainTooDeep',\n 'MissingSignatureForFee',\n 'InvalidAccountIndex',\n 'SignatureFailure',\n 'InvalidProgramForExecution',\n 'SanitizeFailure',\n 'ClusterMaintenance',\n 'AccountBorrowOutstanding',\n 'WouldExceedMaxBlockCostLimit',\n 'UnsupportedVersion',\n 'InvalidWritableAccount',\n 'WouldExceedMaxAccountCostLimit',\n 'WouldExceedAccountDataBlockLimit',\n 'TooManyAccountLocks',\n 'AddressLookupTableNotFound',\n 'InvalidAddressLookupTableOwner',\n 'InvalidAddressLookupTableData',\n 'InvalidAddressLookupTableIndex',\n 'InvalidRentPayingAccount',\n 'WouldExceedMaxVoteCostLimit',\n 'WouldExceedAccountDataTotalLimit',\n 'DuplicateInstruction',\n 'InsufficientFundsForRent',\n 'MaxLoadedAccountsDataSizeExceeded',\n 'InvalidLoadedAccountsDataSizeLimit',\n 'ResanitizationNeeded',\n 'ProgramExecutionTemporarilyRestricted',\n 'UnbalancedTransaction',\n];\n\nexport function getSolanaErrorFromTransactionError(transactionError: string | { [key: string]: unknown }): SolanaError {\n if (typeof transactionError === 'object' && 'InstructionError' in transactionError) {\n return getSolanaErrorFromInstructionError(\n ...(transactionError.InstructionError as Parameters),\n );\n }\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 7050001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n ...(rpcErrorContext !== undefined ? { transactionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {\n return {\n index: Number(rpcErrorContext as bigint | number),\n };\n } else if (\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT ||\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n ) {\n return {\n accountIndex: Number((rpcErrorContext as { account_index: bigint | number }).account_index),\n };\n }\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: transactionError,\n },\n getSolanaErrorFromTransactionError,\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SolanaErrorCode,\n} from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\nimport { getSolanaErrorFromTransactionError } from './transaction-error';\n\ninterface RpcErrorResponse {\n code: bigint | number;\n data?: unknown;\n message: string;\n}\n\ntype TransactionError = string | { [key: string]: unknown };\n\n/**\n * Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-types/src/response.rs\n * @hidden\n */\nexport interface RpcSimulateTransactionResult {\n accounts:\n | ({\n data:\n | string // LegacyBinary\n | {\n // Json\n parsed: unknown;\n program: string;\n space: bigint;\n }\n // Binary\n | [encodedBytes: string, encoding: 'base58' | 'base64' | 'base64+zstd' | 'binary' | 'jsonParsed'];\n executable: boolean;\n lamports: bigint;\n owner: string;\n rentEpoch: bigint;\n space?: bigint;\n } | null)[]\n | null;\n err: TransactionError | null;\n // Enabled by `enable_cpi_recording`\n innerInstructions?:\n | {\n index: number;\n instructions: (\n | {\n // Compiled\n accounts: number[];\n data: string;\n programIdIndex: number;\n stackHeight?: number;\n }\n | {\n // Parsed\n parsed: unknown;\n program: string;\n programId: string;\n stackHeight?: number;\n }\n | {\n // PartiallyDecoded\n accounts: string[];\n data: string;\n programId: string;\n stackHeight?: number;\n }\n )[];\n }[]\n | null;\n loadedAccountsDataSize: number | null;\n logs: string[] | null;\n replacementBlockhash: string | null;\n returnData: {\n data: [string, 'base64'];\n programId: string;\n } | null;\n unitsConsumed: bigint | null;\n}\n\nexport function getSolanaErrorFromJsonRpcError(putativeErrorResponse: unknown): SolanaError {\n let out: SolanaError;\n if (isRpcErrorResponse(putativeErrorResponse)) {\n const { code: rawCode, data, message } = putativeErrorResponse;\n const code = Number(rawCode);\n if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {\n const { err, ...preflightErrorContext } = data as RpcSimulateTransactionResult;\n const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;\n out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {\n ...preflightErrorContext,\n ...causeObject,\n });\n } else {\n let errorContext;\n switch (code) {\n case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:\n case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:\n case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:\n case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:\n case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:\n case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:\n // The server supplies no structured data, but rather a pre-formatted message. Put\n // the server message in `context` so as not to completely lose the data. The long\n // term fix for this is to add data to the server responses and modify the\n // messages in `@solana/errors` to be actual format strings.\n errorContext = { __serverMessage: message };\n break;\n default:\n if (typeof data === 'object' && !Array.isArray(data)) {\n errorContext = data;\n }\n }\n out = new SolanaError(code as SolanaErrorCode, errorContext as SolanaErrorContext[SolanaErrorCode]);\n }\n } else {\n const message =\n typeof putativeErrorResponse === 'object' &&\n putativeErrorResponse !== null &&\n 'message' in putativeErrorResponse &&\n typeof putativeErrorResponse.message === 'string'\n ? putativeErrorResponse.message\n : 'Malformed JSON-RPC error with no message attribute';\n out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });\n }\n safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);\n return out;\n}\n\nfunction isRpcErrorResponse(value: unknown): value is RpcErrorResponse {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'code' in value &&\n 'message' in value &&\n (typeof value.code === 'number' || typeof value.code === 'bigint') &&\n typeof value.message === 'string'\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaErrorCode,\n} from './codes';\nimport { isSolanaError } from './error';\n\n/**\n * Extracts the underlying cause from a simulation-related error.\n *\n * When a transaction simulation fails, the error is often wrapped in a\n * simulation-specific {@link SolanaError}. This function unwraps such errors\n * by returning the `cause` property, giving you access to the actual error\n * that triggered the simulation failure.\n *\n * If the provided error is not a simulation-related error, it is returned unchanged.\n *\n * The following error codes are considered simulation errors:\n * - {@link SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE}\n * - {@link SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT}\n *\n * @param error - The error to unwrap.\n * @return The underlying cause if the error is a simulation error, otherwise the original error.\n *\n * @example\n * Unwrapping a preflight failure to access the root cause.\n * ```ts\n * import { unwrapSimulationError } from '@solana/errors';\n *\n * try {\n * await sendTransaction(signedTransaction);\n * } catch (e) {\n * const cause = unwrapSimulationError(e);\n * console.log('Send transaction failed due to:', cause);\n * }\n * ```\n */\nexport function unwrapSimulationError(error: unknown): unknown {\n const simulationCodes: SolanaErrorCode[] = [\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n ];\n if (isSolanaError(error) && !!error.cause && simulationCodes.includes(error.context.__code)) {\n return error.cause;\n }\n return error;\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n *\n * @param byteArrays - The array of byte arrays to concatenate.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02]);\n * const bytes2 = new Uint8Array([]);\n * const bytes3 = new Uint8Array([0x03, 0x04]);\n * const bytes = mergeBytes([bytes1, bytes2, bytes3]);\n * // ^ [0x01, 0x02, 0x03, 0x04]\n * ```\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n *\n * @param bytes - The byte array to pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 2);\n * // bytes === paddedBytes\n * ```\n */\nexport function padBytes(bytes: Uint8Array, length: number): Uint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n}\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n *\n * @param bytes - The byte array to truncate or pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Truncates the byte array to the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // ^ [0x01, 0x02]\n * ```\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // bytes === fixedBytes\n * ```\n */\nexport const fixBytes = (bytes: ReadonlyUint8Array | Uint8Array, length: number): ReadonlyUint8Array | Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n\n/**\n * Returns true if and only if the provided `data` byte array contains\n * the provided `bytes` byte array at the specified `offset`.\n *\n * @param data - The byte sequence to search for.\n * @param bytes - The byte array in which to search for `data`.\n * @param offset - The position in `bytes` where the search begins.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const data = new Uint8Array([0x02, 0x03]);\n * containsBytes(bytes, data, 1); // true\n * containsBytes(bytes, data, 2); // false\n * ```\n */\nexport function containsBytes(\n data: ReadonlyUint8Array | Uint8Array,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset: number,\n): boolean {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n return bytesEqual(slice, bytes);\n}\n\n/**\n * Returns true if and only if the provided `bytes1` and `bytes2` byte arrays are equal.\n *\n * @param bytes1 - The first byte array to compare.\n * @param bytes2 - The second byte array to compare.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const bytes2 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * bytesEqual(bytes1, bytes2); // true\n * ```\n */\nexport function bytesEqual(bytes1: ReadonlyUint8Array | Uint8Array, bytes2: ReadonlyUint8Array | Uint8Array): boolean {\n return bytes1.length === bytes2.length && bytes1.every((value, index) => value === bytes2[index]);\n}\n","import {\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * This is a common interface for {@link FixedSizeEncoder} and {@link VariableSizeEncoder}.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n */\ntype BaseEncoder = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a fixed-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const encoder: FixedSizeEncoder;\n * const bytes = encoder.encode(42);\n * const size = encoder.fixedSize; // 4\n * ```\n *\n * @see {@link Encoder}\n * @see {@link VariableSizeEncoder}\n */\nexport type FixedSizeEncoder = BaseEncoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a variable-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * ```ts\n * const encoder: VariableSizeEncoder;\n * const bytes = encoder.encode('hello');\n * const size = encoder.getSizeFromValue('hello');\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n */\nexport type VariableSizeEncoder = BaseEncoder & {\n /** Returns the size of the encoded value in bytes for a given input. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * An `Encoder` can be either:\n * - A {@link FixedSizeEncoder}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeEncoder}, where encoded values can vary in size.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * Encoding a value into a new byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = encoder.encode('hello');\n * ```\n *\n * @example\n * Writing the encoded value into an existing byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = new Uint8Array(100);\n * const nextOffset = encoder.write('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Encoders` manually using the {@link createEncoder} function but it is more common\n * to compose multiple `Encoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Encoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonEncoder = (): Encoder =>\n * getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * ```\n *\n * Note that composed `Encoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Encoder()` is\n * a fixed-size encoder, while `addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())`\n * is a variable-size encoder. This makes the final `Person` encoder a variable-size encoder.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link createEncoder}\n */\nexport type Encoder = FixedSizeEncoder | VariableSizeEncoder;\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * This is a common interface for {@link FixedSizeDecoder} and {@link VariableSizeDecoder}.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n */\ntype BaseDecoder = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: ReadonlyUint8Array | Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: ReadonlyUint8Array | Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\n/**\n * An object that can decode a fixed-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const decoder: FixedSizeDecoder;\n * const value = decoder.decode(bytes);\n * const size = decoder.fixedSize; // 4\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type FixedSizeDecoder = BaseDecoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can decode a variable-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const decoder: VariableSizeDecoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder = BaseDecoder & {\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * An `Decoder` can be either:\n * - A {@link FixedSizeDecoder}, where all byte arrays have the same fixed size.\n * - A {@link VariableSizeDecoder}, where byte arrays can vary in size.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * Getting the decoded value from a byte array.\n * ```ts\n * const decoder: Decoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @example\n * Reading the decoded value from a byte array at a specific offset\n * and getting the offset of the next byte to read.\n * ```ts\n * const decoder: Decoder;\n * const [value, nextOffset] = decoder.read('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Decoders` manually using the {@link createDecoder} function but it is more common\n * to compose multiple `Decoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Decoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonDecoder = (): Decoder =>\n * getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * ```\n *\n * Note that composed `Decoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Decoder()` is\n * a fixed-size decoder, while `addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())`\n * is a variable-size decoder. This makes the final `Person` decoder a variable-size decoder.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link createDecoder}\n */\nexport type Decoder = FixedSizeDecoder | VariableSizeDecoder;\n\n/**\n * An object that can encode and decode a value to and from a fixed-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const codec: FixedSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.fixedSize; // 8\n * ```\n *\n * @see {@link Codec}\n * @see {@link VariableSizeCodec}\n */\nexport type FixedSizeCodec = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a variable-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec: VariableSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.getSizeFromValue(42);\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n */\nexport type VariableSizeCodec = VariableSizeDecoder & VariableSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a byte array.\n *\n * A `Codec` can be either:\n * - A {@link FixedSizeCodec}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeCodec}, where encoded values can vary in size.\n *\n * @example\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode('hello');\n * const value = codec.decode(bytes); // 'hello'\n * ```\n *\n * @remarks\n * For convenience, codecs can encode looser types than they decode.\n * That is, type {@link TFrom} can be a superset of type {@link TTo}.\n * For instance, a `Codec` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * It is worth noting that codecs are the union of encoders and decoders.\n * This means that a `Codec` can be combined from an `Encoder`\n * and a `Decoder` using the {@link combineCodec} function. This is particularly\n * useful for library authors who want to expose all three types of objects to their users.\n *\n * ```ts\n * const encoder: Encoder;\n * const decoder: Decoder;\n * const codec: Codec = combineCodec(encoder, decoder);\n * ```\n *\n * Aside from combining encoders and decoders, codecs can also be created from scratch using\n * the {@link createCodec} function but it is more common to compose multiple codecs together\n * using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create a `Codec` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonCodec = (): Codec =>\n * getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * ```\n *\n * Note that composed `Codec` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Codec()` is\n * a fixed-size codec, while `addCodecSizePrefix(getUtf8Codec(), getU32Codec())`\n * is a variable-size codec. This makes the final `Person` codec a variable-size codec.\n *\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link combineCodec}\n * @see {@link createCodec}\n */\nexport type Codec = FixedSizeCodec | VariableSizeCodec;\n\n/**\n * Gets the encoded size of a given value in bytes using the provided encoder.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @param value - The value to be encoded.\n * @param encoder - The encoder used to determine the encoded size.\n * @returns The size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const fixedSizeEncoder = { fixedSize: 4 };\n * getEncodedSize(123, fixedSizeEncoder); // Returns 4.\n *\n * const variableSizeEncoder = { getSizeFromValue: (value: string) => value.length };\n * getEncodedSize(\"hello\", variableSizeEncoder); // Returns 5.\n * ```\n *\n * @see {@link Encoder}\n */\nexport function getEncodedSize(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/**\n * Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and\n * either the `fixedSize` property (for {@link FixedSizeEncoder | FixedSizeEncoders}) or\n * the `getSizeFromValue` function (for {@link VariableSizeEncoder | VariableSizeEncoders}).\n *\n * Instead of manually implementing `encode`, this utility leverages the existing `write` function\n * and the size helpers to generate a complete encoder. The provided `encode` method will allocate\n * a new `Uint8Array` of the correct size and use `write` to populate it.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size encoders).\n *\n * @param encoder - An encoder object that implements `write`, but not `encode`.\n * - If the encoder has a `fixedSize` property, it is treated as a {@link FixedSizeEncoder}.\n * - Otherwise, it is treated as a {@link VariableSizeEncoder}.\n *\n * @returns A fully functional `Encoder` with both `write` and `encode` methods.\n *\n * @example\n * Creating a custom fixed-size encoder.\n * ```ts\n * const encoder = createEncoder({\n * fixedSize: 4,\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n * ```\n *\n * @example\n * Creating a custom variable-size encoder:\n * ```ts\n * const encoder = createEncoder({\n * getSizeFromValue: (value: string) => value.length,\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = encoder.encode(\"hello\");\n * // 0x68656c6c6f\n * ```\n *\n * @remarks\n * Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose\n * encoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createEncoder`.\n *\n * ```ts\n * // Fixed-size encoder for unsigned 32-bit integers.\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n *\n * // Variable-size encoder for 32-bytes prefixed UTF-8 strings.\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const bytes = encoder.encode(\"hello\");\n * // 0x0500000068656c6c6f\n *\n * // Variable-size encoder for custom objects.\n * type Person = { name: string; age: number };\n * const encoder: Encoder = getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * const bytes = encoder.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link getStructEncoder}\n * @see {@link getU32Encoder}\n * @see {@link getUtf8Encoder}\n * @see {@link addEncoderSizePrefix}\n */\nexport function createEncoder(\n encoder: Omit, 'encode'>,\n): FixedSizeEncoder;\nexport function createEncoder(encoder: Omit, 'encode'>): VariableSizeEncoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function.\n *\n * Instead of manually implementing `decode`, this utility leverages the existing `read` function\n * and the size properties to generate a complete decoder. The provided `decode` method will read\n * from a `Uint8Array` at the given offset and return the decoded value.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeDecoder} will be created, otherwise\n * a {@link VariableSizeDecoder} will be created.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size decoders).\n *\n * @param decoder - A decoder object that implements `read`, but not `decode`.\n * - If the decoder has a `fixedSize` property, it is treated as a {@link FixedSizeDecoder}.\n * - Otherwise, it is treated as a {@link VariableSizeDecoder}.\n *\n * @returns A fully functional `Decoder` with both `read` and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size decoder.\n * ```ts\n * const decoder = createDecoder({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size decoder:\n * ```ts\n * const decoder = createDecoder({\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111]));\n * // \"hello\"\n * ```\n *\n * @remarks\n * Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose\n * decoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createDecoder`.\n *\n * ```ts\n * // Fixed-size decoder for unsigned 32-bit integers.\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n *\n * // Variable-size decoder for 32-bytes prefixed UTF-8 strings.\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111]));\n * // \"hello\"\n *\n * // Variable-size decoder for custom objects.\n * type Person = { name: string; age: number };\n * const decoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0]));\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Decoder}\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link getStructDecoder}\n * @see {@link getU32Decoder}\n * @see {@link getUtf8Decoder}\n * @see {@link addDecoderSizePrefix}\n */\nexport function createDecoder(\n decoder: Omit, 'decode'>,\n): FixedSizeDecoder;\nexport function createDecoder(decoder: Omit, 'decode'>): VariableSizeDecoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/**\n * Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions.\n *\n * This utility combines the behavior of {@link createEncoder} and {@link createDecoder} to produce a fully functional `Codec`.\n * The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeCodec} will be created, otherwise\n * a {@link VariableSizeCodec} will be created.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param codec - A codec object that implements `write` and `read`, but not `encode` or `decode`.\n * - If the codec has a `fixedSize` property, it is treated as a {@link FixedSizeCodec}.\n * - Otherwise, it is treated as a {@link VariableSizeCodec}.\n *\n * @returns A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size codec.\n * ```ts\n * const codec = createCodec({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size codec:\n * ```ts\n * const codec = createCodec({\n * getSizeFromValue: (value: string) => value.length,\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = codec.encode(\"hello\");\n * // 0x68656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n * ```\n *\n * @remarks\n * This function effectively combines the behavior of {@link createEncoder} and {@link createDecoder}.\n * If you only need to encode or decode (but not both), consider using those functions instead.\n *\n * Here are some alternative examples using codec primitives instead of `createCodec`.\n *\n * ```ts\n * // Fixed-size codec for unsigned 32-bit integers.\n * const codec = getU32Codec();\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n *\n * // Variable-size codec for 32-bytes prefixed UTF-8 strings.\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const bytes = codec.encode(\"hello\");\n * // 0x0500000068656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n *\n * // Variable-size codec for custom objects.\n * type Person = { name: string; age: number };\n * const codec: Codec = getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * const bytes = codec.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * const value = codec.decode(bytes);\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link createEncoder}\n * @see {@link createDecoder}\n * @see {@link getStructCodec}\n * @see {@link getU32Codec}\n * @see {@link getUtf8Codec}\n * @see {@link addCodecSizePrefix}\n */\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): FixedSizeCodec;\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): VariableSizeCodec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is fixed-size.\n *\n * A fixed-size object is identified by the presence of a `fixedSize` property.\n * If this property exists, the object is considered a {@link FixedSizeCodec},\n * {@link FixedSizeEncoder}, or {@link FixedSizeDecoder}.\n * Otherwise, it is assumed to be a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is fixed-size, `false` otherwise.\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isFixedSize(encoder); // true\n * ```\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isFixedSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is commonly used to distinguish between fixed-size and variable-size objects at runtime.\n * If you need to enforce this distinction with type assertions, consider using {@link assertIsFixedSize}.\n *\n * @see {@link assertIsFixedSize}\n */\nexport function isFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): encoder is FixedSizeEncoder;\nexport function isFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): decoder is FixedSizeDecoder;\nexport function isFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): codec is FixedSizeCodec;\nexport function isFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is fixed-size.\n *\n * If the object is not fixed-size (i.e., it lacks a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not fixed-size.\n *\n * @example\n * Asserting a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsFixedSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsFixedSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isFixedSize}.\n * If you only need to check whether an object is fixed-size without throwing an error, use {@link isFixedSize} instead.\n *\n * @see {@link isFixedSize}\n */\nexport function assertIsFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): asserts encoder is FixedSizeEncoder;\nexport function assertIsFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): asserts decoder is FixedSizeDecoder;\nexport function assertIsFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): asserts codec is FixedSizeCodec;\nexport function assertIsFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is variable-size.\n *\n * A variable-size object is identified by the absence of a `fixedSize` property.\n * If this property is missing, the object is considered a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is variable-size, `false` otherwise.\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isVariableSize(encoder); // true\n * ```\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isVariableSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is the inverse of {@link isFixedSize}.\n *\n * @see {@link isFixedSize}\n * @see {@link assertIsVariableSize}\n */\nexport function isVariableSize(encoder: Encoder): encoder is VariableSizeEncoder;\nexport function isVariableSize(decoder: Decoder): decoder is VariableSizeDecoder;\nexport function isVariableSize(\n codec: Codec,\n): codec is VariableSizeCodec;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is variable-size.\n *\n * If the object is not variable-size (i.e., it has a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not variable-size.\n *\n * @example\n * Asserting a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsVariableSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsVariableSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isVariableSize}.\n * If you only need to check whether an object is variable-size without throwing an error, use {@link isVariableSize} instead.\n *\n * Also note that this function is the inverse of {@link assertIsFixedSize}.\n *\n * @see {@link isVariableSize}\n * @see {@link assertIsFixedSize}\n */\nexport function assertIsVariableSize(encoder: Encoder): asserts encoder is VariableSizeEncoder;\nexport function assertIsVariableSize(decoder: Decoder): asserts decoder is VariableSizeDecoder;\nexport function assertIsVariableSize(\n codec: Codec,\n): asserts codec is VariableSizeCodec;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an `Encoder` and a `Decoder` into a `Codec`.\n *\n * That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`.\n *\n * This allows for modular composition by keeping encoding and decoding logic separate\n * while still offering a convenient way to bundle them into a single `Codec`.\n * This is particularly useful for library maintainers who want to expose `Encoders`,\n * `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic.\n *\n * The provided `Encoder` and `Decoder` must be compatible in terms of:\n * - **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value.\n * - **Variable Size:** If either has a `maxSize` attribute, it must match the other.\n *\n * If these conditions are not met, a {@link SolanaError} will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param encoder - The `Encoder` to combine.\n * @param decoder - The `Decoder` to combine.\n * @returns A `Codec` that provides both `encode` and `decode` methods.\n *\n * @throws {SolanaError}\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH`\n * Thrown if the encoder and decoder have mismatched size types (fixed vs. variable).\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH`\n * Thrown if both are fixed-size but have different `fixedSize` values.\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH`\n * Thrown if the `maxSize` attributes do not match.\n *\n * @example\n * Creating a fixed-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = getU32Encoder();\n * const decoder = getU32Decoder();\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(42); // 0x2a000000\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Creating a variable-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(\"hello\"); // 0x0500000068656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec.\n * This allows users to import only what they need, improving tree-shaking efficiency.\n *\n * ```ts\n * type MyType = \\/* ... *\\/;\n * const getMyTypeEncoder = (): Encoder => { \\/* ... *\\/ };\n * const getMyTypeDecoder = (): Decoder => { \\/* ... *\\/ };\n * const getMyTypeCodec = (): Codec =>\n * combineCodec(getMyTypeEncoder(), getMyTypeDecoder());\n * ```\n *\n * @see {@link Codec}\n * @see {@link Encoder}\n * @see {@link Decoder}\n */\nexport function combineCodec(\n encoder: FixedSizeEncoder,\n decoder: FixedSizeDecoder,\n): FixedSizeCodec;\nexport function combineCodec(\n encoder: VariableSizeEncoder,\n decoder: VariableSizeDecoder,\n): VariableSizeCodec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {\n decoderFixedSize: decoder.fixedSize,\n encoderFixedSize: encoder.fixedSize,\n });\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {\n decoderMaxSize: decoder.maxSize,\n encoderMaxSize: encoder.maxSize,\n });\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SolanaError,\n} from '@solana/errors';\n\nimport { containsBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Creates an encoder that writes a `Uint8Array` sentinel after the encoded value.\n * This is useful to delimit the encoded value when being read by a decoder.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addEncoderSentinel(\n encoder: FixedSizeEncoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeEncoder;\nexport function addEncoderSentinel(\n encoder: Encoder,\n sentinel: ReadonlyUint8Array,\n): VariableSizeEncoder;\nexport function addEncoderSentinel(encoder: Encoder, sentinel: ReadonlyUint8Array): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds\n // and to avoid writing the sentinel as part of the encoded value.\n const encoderBytes = encoder.encode(value);\n if (findSentinelIndex(encoderBytes, sentinel) >= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {\n encodedBytes: encoderBytes,\n hexEncodedBytes: hexBytes(encoderBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n bytes.set(encoderBytes, offset);\n offset += encoderBytes.length;\n bytes.set(sentinel, offset);\n offset += sentinel.length;\n return offset;\n }) as Encoder['write'];\n\n if (isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });\n }\n\n return createEncoder({\n ...encoder,\n ...(encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {}),\n getSizeFromValue: value => encoder.getSizeFromValue(value) + sentinel.length,\n write,\n });\n}\n\n/**\n * Creates a decoder that continues reading until\n * a given `Uint8Array` sentinel is found.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addDecoderSentinel(\n decoder: FixedSizeDecoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): VariableSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): Decoder {\n const read = ((bytes, offset) => {\n const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);\n const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);\n if (sentinelIndex === -1) {\n throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {\n decodedBytes: candidateBytes,\n hexDecodedBytes: hexBytes(candidateBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds\n // and ensure that the sentinel is not part of the decoded value.\n return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];\n }) as Decoder['read'];\n\n if (isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });\n }\n\n return createDecoder({\n ...decoder,\n ...(decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {}),\n read,\n });\n}\n\n/**\n * Creates a Codec that writes a given `Uint8Array` sentinel after the encoded\n * value and, when decoding, continues reading until the sentinel is found.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255]));\n * codec.encode('hello');\n * // 0x68656c6c6fffff\n * // | └-- Our sentinel.\n * // └-- Our encoded string.\n * ```\n *\n * @remarks\n * Note that the sentinel _must not_ be present in the encoded data and\n * _must_ be present in the decoded data for this to work.\n * If this is not the case, dedicated errors will be thrown.\n *\n * ```ts\n * const sentinel = new Uint8Array([108, 108]); // 'll'\n * const codec = addCodecSentinel(getUtf8Codec(), sentinel);\n *\n * codec.encode('hello'); // Throws: sentinel is in encoded data.\n * codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data.\n * ```\n *\n * Separate {@link addEncoderSentinel} and {@link addDecoderSentinel} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello');\n * const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSentinel}\n * @see {@link addDecoderSentinel}\n */\nexport function addCodecSentinel(\n codec: FixedSizeCodec,\n sentinel: ReadonlyUint8Array,\n): FixedSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): VariableSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): Codec {\n return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));\n}\n\nfunction findSentinelIndex(bytes: ReadonlyUint8Array, sentinel: ReadonlyUint8Array) {\n return bytes.findIndex((byte, index, arr) => {\n if (sentinel.length === 1) return byte === sentinel[0];\n return containsBytes(arr, sentinel, index);\n });\n}\n\nfunction hexBytes(bytes: ReadonlyUint8Array): string {\n return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n","import {\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Asserts that a given byte array is not empty (after the optional provided offset).\n *\n * Returns void if the byte array is not empty but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n * If provided, the byte array is considered empty if it has no bytes after the offset.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws\n * ```\n */\nexport function assertByteArrayIsNotEmptyForCodec(\n codecDescription: string,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription,\n });\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode\n * (after the optional provided offset).\n *\n * Returns void if the byte array has at least the expected number\n * of bytes but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param expected - The minimum number of bytes expected in the byte array.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws\n * ```\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected,\n });\n }\n}\n\n/**\n * Asserts that a given offset is within the byte array bounds.\n * This range is between 0 and the byte array length and is inclusive.\n * An offset equals to the byte array length is considered a valid offset\n * as it allows the post-offset of codecs to signal the end of the byte array.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param offset - The offset to check.\n * @param bytesLength - The length of the byte array from which the offset should be within bounds.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws\n * ```\n */\nexport function assertByteArrayOffsetIsNotOutOfRange(codecDescription: string, offset: number, bytesLength: number) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset,\n });\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\ntype NumberEncoder = Encoder | Encoder;\ntype FixedSizeNumberEncoder =\n | FixedSizeEncoder\n | FixedSizeEncoder;\ntype NumberDecoder = Decoder | Decoder;\ntype FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\ntype NumberCodec = Codec | Codec;\ntype FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addEncoderSizePrefix(\n encoder: FixedSizeEncoder,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): VariableSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds.\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n }) as Encoder['write'];\n\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : (encoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n\n return createEncoder({\n ...encoder,\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: value => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write,\n });\n}\n\n/**\n * Bounds the size of the nested `decoder` by reading its encoded `prefix`.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addDecoderSizePrefix(\n decoder: FixedSizeDecoder,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): VariableSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): Decoder {\n const read = ((bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n // Slice the byte array to the contained size if necessary.\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec('addDecoderSizePrefix', size, bytes);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds.\n return [decoder.decode(bytes), offset + size];\n }) as Decoder['read'];\n\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : (decoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...(maxSize !== null ? { maxSize } : {}), read });\n}\n\n/**\n * Stores the byte size of any given codec as an encoded number prefix.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n * When encoding, the size of the encoded data is stored before the encoded data itself.\n * When decoding, the size is read first to know how many bytes to read next.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * For example, say we want to bound a variable-size base-58 string using a `u32` size prefix.\n * Here’s how you can use the `addCodecSizePrefix` function to achieve that.\n *\n * ```ts\n * const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());\n *\n * getU32Base58Codec().encode('hello world');\n * // 0x0b00000068656c6c6f20776f726c64\n * // | └-- Our encoded base-58 string.\n * // └-- Our encoded u32 size prefix.\n * ```\n *\n * @remarks\n * Separate {@link addEncoderSizePrefix} and {@link addDecoderSizePrefix} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');\n * const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSizePrefix}\n * @see {@link addDecoderSizePrefix}\n */\nexport function addCodecSizePrefix(\n codec: FixedSizeCodec,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): VariableSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): Codec {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Converts a `Uint8Array` to an `ArrayBuffer`. If the underlying buffer is a `SharedArrayBuffer`,\n * it will be copied to a non-shared buffer, for safety.\n *\n * @remarks\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nexport function toArrayBuffer(bytes: ReadonlyUint8Array | Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n let buffer: ArrayBuffer;\n if (typeof SharedArrayBuffer === 'undefined') {\n buffer = bytes.buffer as ArrayBuffer;\n } else if (bytes.buffer instanceof SharedArrayBuffer) {\n buffer = new ArrayBuffer(bytes.length);\n new Uint8Array(buffer).set(new Uint8Array(bytes));\n } else {\n buffer = bytes.buffer;\n }\n return (bytesOffset === 0 || bytesOffset === -bytes.byteLength) && bytesLength === bytes.byteLength\n ? buffer\n : buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, SolanaError } from '@solana/errors';\n\nimport { createDecoder, Decoder } from './codec';\n\n/**\n * Create a {@link Decoder} that asserts that the bytes provided to `decode` or `read` are fully consumed by the inner decoder\n * @param decoder A decoder to wrap\n * @returns A new decoder that will throw if provided with a byte array that it does not fully consume\n *\n * @typeParam T - The type of the decoder\n *\n * @remarks\n * Note that this compares the offset after encoding to the length of the input byte array\n *\n * The `offset` parameter to `decode` and `read` is still considered, and will affect the new offset that is compared to the byte array length\n *\n * The error that is thrown by the returned decoder is a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY`\n *\n * @example\n * Create a decoder that decodes a `u32` (4 bytes) and ensures the entire byte array is consumed\n * ```ts\n * const decoder = createDecoderThatUsesExactByteArray(getU32Decoder());\n * decoder.decode(new Uint8Array([0, 0, 0, 0])); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0])); // throws\n *\n * // with an offset\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0]), 1); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0, 0]), 1); // throws\n * ```\n */\nexport function createDecoderThatConsumesEntireByteArray(decoder: Decoder): Decoder {\n return createDecoder({\n ...decoder,\n read(bytes, offset) {\n const [value, newOffset] = decoder.read(bytes, offset);\n if (bytes.length > newOffset) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, {\n expectedLength: newOffset,\n numExcessBytes: bytes.length - newOffset,\n });\n }\n return [value, newOffset];\n },\n });\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * The resulting encoder ensures that encoded values always have the specified number of bytes.\n * If the original encoded value is larger than `fixedBytes`, it is truncated.\n * If it is smaller, it is padded with trailing zeroes.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @returns A `FixedSizeEncoder` that ensures a consistent output size.\n *\n * @example\n * ```ts\n * const encoder = fixEncoderSize(getUtf8Encoder(), 4);\n * encoder.encode(\"Hello\"); // 0x48656c6c (truncated)\n * encoder.encode(\"Hi\"); // 0x48690000 (padded)\n * encoder.encode(\"Hiya\"); // 0x48697961 (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixEncoderSize(\n encoder: Encoder,\n fixedBytes: TSize,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * The resulting decoder always reads exactly `fixedBytes` bytes from the input.\n * If the nested decoder is also fixed-size, the bytes are truncated or padded as needed.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @returns A `FixedSizeDecoder` that ensures a consistent input size.\n *\n * @example\n * ```ts\n * const decoder = fixDecoderSize(getUtf8Decoder(), 4);\n * decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // \"Hell\" (truncated)\n * decoder.decode(new Uint8Array([72, 105, 0, 0])); // \"Hi\" (zeroes ignored)\n * decoder.decode(new Uint8Array([72, 105, 121, 97])); // \"Hiya\" (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixEncoderSize}\n */\nexport function fixDecoderSize(\n decoder: Decoder,\n fixedBytes: TSize,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodecSize', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes.\n * When encoding:\n * - If the encoded value is larger than `fixedBytes`, it is truncated.\n * - If it is smaller, it is padded with trailing zeroes.\n * - If it is exactly `fixedBytes`, it remains unchanged.\n *\n * When decoding:\n * - Exactly `fixedBytes` bytes are read from the input.\n * - If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @returns A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size.\n *\n * @example\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 4);\n *\n * const bytes1 = codec.encode(\"Hello\"); // 0x48656c6c (truncated)\n * const value1 = codec.decode(bytes1); // \"Hell\"\n *\n * const bytes2 = codec.encode(\"Hi\"); // 0x48690000 (padded)\n * const value2 = codec.decode(bytes2); // \"Hi\"\n *\n * const bytes3 = codec.encode(\"Hiya\"); // 0x48697961 (same length)\n * const value3 = codec.decode(bytes3); // \"Hiya\"\n * ```\n *\n * @remarks\n * If you only need to enforce a fixed size for encoding, use {@link fixEncoderSize}.\n * If you only need to enforce a fixed size for decoding, use {@link fixDecoderSize}.\n *\n * ```ts\n * const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode(\"Hiya\");\n * const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);\n * ```\n *\n * @see {@link fixEncoderSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixCodecSize(\n codec: Codec,\n fixedBytes: TSize,\n): FixedSizeCodec {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));\n}\n","import { assertByteArrayOffsetIsNotOutOfRange } from './assertions';\nimport { Codec, createDecoder, createEncoder, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Configuration object for modifying the offset of an encoder, decoder, or codec.\n *\n * This type defines optional functions for adjusting the **pre-offset** (before encoding/decoding)\n * and the **post-offset** (after encoding/decoding). These functions allow precise control\n * over where data is written or read within a byte array.\n *\n * @property preOffset - A function that modifies the offset before encoding or decoding.\n * @property postOffset - A function that modifies the offset after encoding or decoding.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * };\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * };\n * ```\n *\n * @example\n * Using both pre-offset and post-offset together.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * postOffset: ({ postOffset }) => postOffset + 4,\n * };\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n * @see {@link offsetCodec}\n */\ntype OffsetConfig = {\n postOffset?: PostOffsetFunction;\n preOffset?: PreOffsetFunction;\n};\n\n/**\n * Scope provided to the `preOffset` and `postOffset` functions,\n * containing contextual information about the current encoding or decoding process.\n *\n * The pre-offset function modifies where encoding or decoding begins,\n * while the post-offset function modifies where the next operation continues.\n *\n * @property bytes - The entire byte array being encoded or decoded.\n * @property preOffset - The original offset before encoding or decoding starts.\n * @property wrapBytes - A helper function that wraps offsets around the byte array length.\n *\n * @example\n * Using `wrapBytes` to wrap a negative offset to the end of the byte array.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves to last 4 bytes\n * };\n * ```\n *\n * @example\n * Adjusting the offset dynamically based on the byte array size.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ bytes }) => bytes.length > 10 ? 4 : 2,\n * };\n * ```\n *\n * @see {@link PreOffsetFunction}\n * @see {@link PostOffsetFunction}\n */\ntype PreOffsetFunctionScope = {\n /** The entire byte array. */\n bytes: ReadonlyUint8Array | Uint8Array;\n /** The original offset prior to encode or decode. */\n preOffset: Offset;\n /** Wraps the offset to the byte array length. */\n wrapBytes: (offset: Offset) => Offset;\n};\n\n/**\n * A function that modifies the pre-offset before encoding or decoding.\n *\n * This function is used to adjust the starting position before writing\n * or reading data in a byte array.\n *\n * @param scope - The current encoding or decoding context.\n * @returns The new offset at which encoding or decoding should start.\n *\n * @example\n * Skipping the first 2 bytes before writing or reading.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ preOffset }) => preOffset + 2;\n * ```\n *\n * @example\n * Wrapping the offset to ensure it stays within bounds.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ wrapBytes, preOffset }) => wrapBytes(preOffset + 10);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PreOffsetFunction = (scope: PreOffsetFunctionScope) => Offset;\n\n/**\n * A function that modifies the post-offset after encoding or decoding.\n *\n * This function adjusts where the next encoder or decoder should start\n * after the current operation has completed.\n *\n * @param scope - The current encoding or decoding context, including the modified pre-offset\n * and the original post-offset.\n * @returns The new offset at which the next operation should begin.\n *\n * @example\n * Moving the post-offset forward by 4 bytes.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset }) => postOffset + 4;\n * ```\n *\n * @example\n * Wrapping the post-offset within the byte array length.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ wrapBytes, postOffset }) => wrapBytes(postOffset);\n * ```\n *\n * @example\n * Ensuring a minimum spacing of 8 bytes between values.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset, newPreOffset }) =>\n * Math.max(postOffset, newPreOffset + 8);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PostOffsetFunction = (\n scope: PreOffsetFunctionScope & {\n /** The modified offset used to encode or decode. */\n newPreOffset: Offset;\n /** The original offset returned by the encoder or decoder. */\n postOffset: Offset;\n },\n) => Offset;\n\n/**\n * Moves the offset of a given encoder before and/or after encoding.\n *\n * This function allows an encoder to write its encoded value at a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before encoding) and post-offset adjustments (after encoding).\n *\n * The pre-offset function determines where encoding should start, while the\n * post-offset function adjusts where the next encoder should continue writing.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new encoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Actually written at offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * const nextOffset = encoder.write(42, bytes, 0); // Next encoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to ensure an offset wraps around the byte array length.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Writes at bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetDecoder}\n */\nexport function offsetEncoder(encoder: TEncoder, config: OffsetConfig): TEncoder {\n return createEncoder({\n ...encoder,\n write: (value, bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPreOffset, bytes.length);\n const postOffset = encoder.write(value, bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPostOffset, bytes.length);\n return newPostOffset;\n },\n }) as TEncoder;\n}\n\n/**\n * Moves the offset of a given decoder before and/or after decoding.\n *\n * This function allows a decoder to read its input from a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before decoding) and post-offset adjustments (after decoding).\n *\n * The pre-offset function determines where decoding should start, while the\n * post-offset function adjusts where the next decoder should continue reading.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new decoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array([0, 0, 42, 0]); // Value starts at offset 2\n * decoder.read(bytes, 0); // Actually reads from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array([42, 0, 0, 0]);\n * const [value, nextOffset] = decoder.read(bytes, 0); // Next decoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to read from the last 4 bytes of an array.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 42]); // Value stored at the last 4 bytes\n * decoder.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetEncoder}\n */\nexport function offsetDecoder(decoder: TDecoder, config: OffsetConfig): TDecoder {\n return createDecoder({\n ...decoder,\n read: (bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPreOffset, bytes.length);\n const [value, postOffset] = decoder.read(bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPostOffset, bytes.length);\n return [value, newPostOffset];\n },\n }) as TDecoder;\n}\n\n/**\n * Moves the offset of a given codec before and/or after encoding and decoding.\n *\n * This function allows a codec to encode and decode values at custom offsets\n * within a byte array. It modifies both the **pre-offset** (where encoding/decoding starts)\n * and the **post-offset** (where the next operation should continue).\n *\n * This is particularly useful when working with structured binary formats\n * that require skipping reserved bytes, inserting padding, or aligning fields at\n * specific locations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new codec with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Actually written at offset 2\n * codec.read(bytes, 0); // Actually read from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0);\n * // Next encoding starts at offset 6 instead of 4\n * codec.read(bytes, 0);\n * // Next decoding starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to loop around negative offsets.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Writes at bytes.length - 4\n * codec.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you only need to adjust offsets for encoding, use {@link offsetEncoder}.\n * If you only need to adjust offsets for decoding, use {@link offsetDecoder}.\n *\n * ```ts\n * const bytes = new Uint8Array(10);\n * offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).write(42, bytes, 0);\n * const [value] = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).read(bytes, 0);\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n */\nexport function offsetCodec(codec: TCodec, config: OffsetConfig): TCodec {\n return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config)) as TCodec;\n}\n\n/** A modulo function that handles negative dividends and zero divisors. */\nfunction modulo(dividend: number, divisor: number) {\n if (divisor === 0) return 0;\n return ((dividend % divisor) + divisor) % divisor;\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Updates the size of a given encoder.\n *\n * This function modifies the size of an encoder using a provided transformation function.\n * For fixed-size encoders, it updates the `fixedSize` property, and for variable-size\n * encoders, it adjusts the size calculation based on the encoded value.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The original fixed size of the encoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param encoder - The encoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new encoder with the updated size.\n *\n * @example\n * Increasing the size of a `u16` encoder by 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU16Encoder(), size => size + 2);\n * encoder.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * ```\n *\n * @example\n * Shrinking a `u32` encoder to only use 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU32Encoder(), () => 2);\n * encoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeDecoder}\n */\nexport function resizeEncoder(\n encoder: FixedSizeEncoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder {\n if (isFixedSize(encoder)) {\n const fixedSize = resize(encoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return createEncoder({ ...encoder, fixedSize }) as TEncoder;\n }\n return createEncoder({\n ...encoder,\n getSizeFromValue: value => {\n const newSize = resize(encoder.getSizeFromValue(value));\n if (newSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: newSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return newSize;\n },\n }) as TEncoder;\n}\n\n/**\n * Updates the size of a given decoder.\n *\n * This function modifies the size of a decoder using a provided transformation function.\n * For fixed-size decoders, it updates the `fixedSize` property to reflect the new size.\n * Variable-size decoders remain unchanged, as their size is determined dynamically.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the decoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param decoder - The decoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new decoder with the updated size.\n *\n * @example\n * Expanding a `u16` decoder to read 4 bytes instead of 2.\n * ```ts\n * const decoder = resizeDecoder(getU16Decoder(), size => size + 2);\n * decoder.fixedSize; // 4\n * ```\n *\n * @example\n * Shrinking a `u32` decoder to only read 2 bytes.\n * ```ts\n * const decoder = resizeDecoder(getU32Decoder(), () => 2);\n * decoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeEncoder}\n */\nexport function resizeDecoder(\n decoder: FixedSizeDecoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder {\n if (isFixedSize(decoder)) {\n const fixedSize = resize(decoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeDecoder',\n });\n }\n return createDecoder({ ...decoder, fixedSize }) as TDecoder;\n }\n return decoder;\n}\n\n/**\n * Updates the size of a given codec.\n *\n * This function modifies the size of both the codec using a provided\n * transformation function. It is useful for adjusting the allocated byte size for\n * encoding and decoding without altering the underlying data structure.\n *\n * If the new size is negative, an error will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the encoded/decoded value (for fixed-size codecs).\n * @typeParam TNewSize - The new fixed size after resizing (for fixed-size codecs).\n *\n * @param codec - The codec whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new codec with the updated size.\n *\n * @example\n * Expanding a `u16` codec from 2 to 4 bytes.\n * ```ts\n * const codec = resizeCodec(getU16Codec(), size => size + 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (reads original two bytes)\n * ```\n *\n * @example\n * Shrinking a `u32` codec to only use 2 bytes.\n * ```ts\n * const codec = resizeCodec(getU32Codec(), () => 2);\n * codec.fixedSize; // 2\n * ```\n *\n * @remarks\n * If you only need to resize an encoder, use {@link resizeEncoder}.\n * If you only need to resize a decoder, use {@link resizeDecoder}.\n *\n * ```ts\n * const bytes = resizeEncoder(getU32Encoder(), (size) => size + 2).encode(0xffff);\n * const value = resizeDecoder(getU32Decoder(), (size) => size + 2).decode(bytes);\n * ```\n *\n * @see {@link resizeEncoder}\n * @see {@link resizeDecoder}\n */\nexport function resizeCodec(\n codec: FixedSizeCodec,\n resize: (size: TSize) => TNewSize,\n): FixedSizeCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec {\n return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize)) as TCodec;\n}\n","import { Codec, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { offsetDecoder, offsetEncoder } from './offset-codec';\nimport { resizeDecoder, resizeEncoder } from './resize-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Adds left padding to the given encoder, shifting the encoded value forward\n * by `offset` bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add before encoding.\n * @returns A new encoder with left padding applied.\n *\n * @example\n * ```ts\n * const encoder = padLeftEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given encoder, extending the encoded value by `offset`\n * bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add after encoding.\n * @returns A new encoder with right padding applied.\n *\n * @example\n * ```ts\n * const encoder = padRightEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0xffff0000 (two extra bytes added at the end)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightDecoder}\n */\nexport function padRightEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given decoder, shifting the decoding position forward\n * by `offset` bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip before decoding.\n * @returns A new decoder with left padding applied.\n *\n * @example\n * ```ts\n * const decoder = padLeftDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0, 0, 0x12, 0x34])); // 0xffff (reads from offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftEncoder}\n */\nexport function padLeftDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given decoder, extending the post-offset by `offset`\n * bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip after decoding.\n * @returns A new decoder with right padding applied.\n *\n * @example\n * ```ts\n * const decoder = padRightDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0x12, 0x34, 0, 0])); // 0xffff (ignores trailing bytes)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightEncoder}\n */\nexport function padRightDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given codec, shifting the encoding and decoding positions\n * forward by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * This ensures that values are read and written at a later position in the byte array,\n * while the padding bytes remain unused.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add before encoding and decoding.\n * @returns A new codec with left padding applied.\n *\n * @example\n * ```ts\n * const codec = padLeftCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * const value = codec.decode(bytes); // 0xffff (reads from offset 2)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padLeftEncoder}.\n * If you only need to apply padding for decoding, use {@link padLeftDecoder}.\n *\n * ```ts\n * const bytes = padLeftEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padLeftDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padLeftEncoder}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset)) as TCodec;\n}\n\n/**\n * Adds right padding to the given codec, extending the encoded and decoded value\n * by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * The extra bytes remain unused, ensuring that the next operation starts further\n * along the byte array.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add after encoding and decoding.\n * @returns A new codec with right padding applied.\n *\n * @example\n * ```ts\n * const codec = padRightCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (ignores padding bytes)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padRightEncoder}.\n * If you only need to apply padding for decoding, use {@link padRightDecoder}.\n *\n * ```ts\n * const bytes = padRightEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padRightDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padRightEncoder}\n * @see {@link padRightDecoder}\n */\nexport function padRightCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset)) as TCodec;\n}\n","import {\n assertIsFixedSize,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\nfunction copySourceToTargetInReverse(\n source: ReadonlyUint8Array,\n target_WILL_MUTATE: Uint8Array,\n sourceOffset: number,\n sourceLength: number,\n targetOffset: number = 0,\n) {\n while (sourceOffset < --sourceLength) {\n const leftValue = source[sourceOffset];\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];\n target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;\n sourceOffset++;\n }\n if (sourceOffset === sourceLength) {\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];\n }\n}\n\n/**\n * Reverses the bytes of a fixed-size encoder.\n *\n * Given a `FixedSizeEncoder`, this function returns a new `FixedSizeEncoder` that\n * reverses the bytes within the fixed-size byte array when encoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The fixed-size encoder to reverse.\n * @returns A new encoder that writes bytes in reverse order.\n *\n * @example\n * Encoding a `u16` value in reverse order.\n * ```ts\n * const encoder = reverseEncoder(getU16Encoder({ endian: Endian.Big }));\n * const bytes = encoder.encode(0x1234); // 0x3412 (bytes are flipped)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseDecoder}\n */\nexport function reverseEncoder(\n encoder: FixedSizeEncoder,\n): FixedSizeEncoder {\n assertIsFixedSize(encoder);\n return createEncoder({\n ...encoder,\n write: (value: TFrom, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n copySourceToTargetInReverse(\n bytes /* source */,\n bytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + encoder.fixedSize /* sourceLength */,\n );\n return newOffset;\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size decoder.\n *\n * Given a `FixedSizeDecoder`, this function returns a new `FixedSizeDecoder` that\n * reverses the bytes within the fixed-size byte array before decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the decoded value in bytes.\n *\n * @param decoder - The fixed-size decoder to reverse.\n * @returns A new decoder that reads bytes in reverse order.\n *\n * @example\n * Decoding a reversed `u16` value.\n * ```ts\n * const decoder = reverseDecoder(getU16Decoder({ endian: Endian.Big }));\n * const value = decoder.decode(new Uint8Array([0x34, 0x12])); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseEncoder}\n */\nexport function reverseDecoder(\n decoder: FixedSizeDecoder,\n): FixedSizeDecoder {\n assertIsFixedSize(decoder);\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reversedBytes = bytes.slice();\n copySourceToTargetInReverse(\n bytes /* source */,\n reversedBytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + decoder.fixedSize /* sourceLength */,\n );\n return decoder.read(reversedBytes, offset);\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size codec.\n *\n * Given a `FixedSizeCodec`, this function returns a new `FixedSizeCodec` that\n * reverses the bytes within the fixed-size byte array during encoding and decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded/decoded value in bytes.\n *\n * @param codec - The fixed-size codec to reverse.\n * @returns A new codec that encodes and decodes bytes in reverse order.\n *\n * @example\n * Reversing a `u16` codec.\n * ```ts\n * const codec = reverseCodec(getU16Codec({ endian: Endian.Big }));\n * const bytes = codec.encode(0x1234); // 0x3412 (bytes are flipped)\n * const value = codec.decode(bytes); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @remarks\n * If you only need to reverse an encoder, use {@link reverseEncoder}.\n * If you only need to reverse a decoder, use {@link reverseDecoder}.\n *\n * ```ts\n * const bytes = reverseEncoder(getU16Encoder()).encode(0x1234);\n * const value = reverseDecoder(getU16Decoder()).decode(bytes);\n * ```\n *\n * @see {@link reverseEncoder}\n * @see {@link reverseDecoder}\n */\nexport function reverseCodec(\n codec: FixedSizeCodec,\n): FixedSizeCodec {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Transforms an encoder by mapping its input values.\n *\n * This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B`\n * to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function.\n *\n * This is useful for handling type conversions, applying default values, or structuring data before encoding.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldFrom - The original type expected by the encoder.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n *\n * @param encoder - The encoder to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @returns A new encoder that accepts `TNewFrom` values and transforms them before encoding.\n *\n * @example\n * Encoding a string by counting its characters and storing the length as a `u32`.\n * ```ts\n * const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length);\n * encoder.encode(\"hello\"); // 0x05000000 (stores length 5)\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformDecoder}\n */\nexport function transformEncoder(\n encoder: FixedSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder;\nexport function transformEncoder(\n encoder: VariableSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Transforms a decoder by mapping its output values.\n *\n * This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A`\n * to be converted into values of type `B` after decoding. The transformation is applied via the `map` function.\n *\n * This is useful for post-processing, type conversions, or enriching decoded data.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldTo - The original type returned by the decoder.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param decoder - The decoder to transform.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding.\n * @returns A new decoder that decodes into `TNewTo`.\n *\n * @example\n * Decoding a stored `u32` length into a string of `'x'` characters.\n * ```ts\n * const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length));\n * decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // \"xxxxx\"\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformEncoder}\n */\nexport function transformDecoder(\n decoder: FixedSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder;\nexport function transformDecoder(\n decoder: VariableSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder {\n return createDecoder({\n ...decoder,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Transforms a codec by mapping its input and output values.\n *\n * This function takes an existing `Codec` and returns a `Codec`, allowing:\n * - Values of type `C` to be transformed into `A` before encoding.\n * - Values of type `B` to be transformed into `D` after decoding.\n *\n * This is useful for adapting codecs to work with different representations, handling default values, or\n * converting between primitive and structured types.\n *\n * @typeParam TOldFrom - The original type expected by the codec.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n * @typeParam TOldTo - The original type returned by the codec.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param codec - The codec to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding (optional).\n * @returns A new codec that encodes `TNewFrom` and decodes into `TNewTo`.\n *\n * @example\n * Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters.\n * ```ts\n * const codec = transformCodec(\n * getU32Codec(),\n * (value: string) => value.length, // Encode string length\n * (length) => 'x'.repeat(length) // Decode length into a string of 'x's\n * );\n *\n * const bytes = codec.encode(\"hello\"); // 0x05000000 (stores length 5)\n * const value = codec.decode(bytes); // \"xxxxx\"\n * ```\n *\n * @remarks\n * If only input transformation is needed, use {@link transformEncoder}.\n * If only output transformation is needed, use {@link transformDecoder}.\n *\n * ```ts\n * const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode(\"hello\");\n * const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes);\n * ```\n *\n * @see {@link transformEncoder}\n * @see {@link transformDecoder}\n */\nexport function transformCodec(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder['read']),\n });\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '0123456789';\n\n/**\n * Returns an encoder for base-10 strings.\n *\n * This encoder serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-10 strings.\n *\n * @example\n * Encoding a base-10 string.\n * ```ts\n * const encoder = getBase10Encoder();\n * const bytes = encoder.encode('1024'); // 0x0400\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-10 strings.\n *\n * This decoder deserializes base-10 encoded strings from a byte array.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-10 strings.\n *\n * @example\n * Decoding a base-10 string.\n * ```ts\n * const decoder = getBase10Decoder();\n * const value = decoder.decode(new Uint8Array([0x04, 0x00])); // \"1024\"\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-10 strings.\n *\n * This codec serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-10 strings.\n *\n * @example\n * Encoding and decoding a base-10 string.\n * ```ts\n * const codec = getBase10Codec();\n * const bytes = codec.encode('1024'); // 0x0400\n * const value = codec.decode(bytes); // \"1024\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-10 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase10Codec(), 5);\n * ```\n *\n * If you need a size-prefixed base-10 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase10Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase10Encoder} and {@link getBase10Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase10Encoder().encode('1024');\n * const value = getBase10Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase10Encoder}\n * @see {@link getBase10Decoder}\n */\nexport const getBase10Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings using bit re-slicing.\n *\n * This encoder serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to an alphabet, and encoding the result into a byte array.\n * This approach is commonly used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeEncoder` for encoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding a base-X string using bit re-slicing.\n * ```ts\n * const encoder = getBaseXResliceEncoder('elho', 2);\n * const bytes = encoder.encode('hellolol'); // 0x4aee\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.floor((value.length * bits) / 8),\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-X encoded strings using bit re-slicing.\n *\n * This decoder deserializes base-X encoded strings by re-slicing the bits of a byte array into\n * custom-sized chunks and mapping them to a specified alphabet.\n * This is typically used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeDecoder` for decoding base-X strings using bit re-slicing.\n *\n * @example\n * Decoding a base-X string using bit re-slicing.\n * ```ts\n * const decoder = getBaseXResliceDecoder('elho', 2);\n * const value = decoder.decode(new Uint8Array([0x4a, 0xee])); // \"hellolol\"\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): VariableSizeDecoder =>\n createDecoder({\n read(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-X strings using bit re-slicing.\n *\n * This codec serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to a given alphabet, and encoding the result into bytes.\n * It is particularly suited for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding and decoding a base-X string using bit re-slicing.\n * ```ts\n * const codec = getBaseXResliceCodec('elho', 2);\n * const bytes = codec.encode('hellolol'); // 0x4aee\n * const value = codec.decode(bytes); // \"hellolol\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXResliceCodec('elho', 2), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXResliceCodec('elho', 2), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXResliceEncoder} and {@link getBaseXResliceDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXResliceEncoder('elho', 2).encode('hellolol');\n * const value = getBaseXResliceDecoder('elho', 2).decode(bytes);\n * ```\n *\n * @see {@link getBaseXResliceEncoder}\n * @see {@link getBaseXResliceDecoder}\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): VariableSizeCodec =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n toArrayBuffer,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Returns an encoder for base-64 strings.\n *\n * This encoder serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-64 strings.\n *\n * @example\n * Encoding a base-64 string.\n * ```ts\n * const encoder = getBase64Encoder();\n * const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Encoder = (): VariableSizeEncoder => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return transformEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/**\n * Returns a decoder for base-64 strings.\n *\n * This decoder deserializes base-64 encoded strings from a byte array.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-64 strings.\n *\n * @example\n * Decoding a base-64 string.\n * ```ts\n * const decoder = getBase64Decoder();\n * const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // \"hello+world\"\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Decoder = (): VariableSizeDecoder => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(toArrayBuffer(bytes), offset).toString('base64'), bytes.length],\n });\n }\n\n return transformDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/**\n * Returns a codec for encoding and decoding base-64 strings.\n *\n * This codec serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-64 strings.\n *\n * @example\n * Encoding and decoding a base-64 string.\n * ```ts\n * const codec = getBase64Codec();\n * const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57\n * const value = codec.decode(bytes); // \"hello+world\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-64 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase64Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-64 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase64Encoder} and {@link getBase64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase64Encoder().encode('hello+world');\n * const value = getBase64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase64Encoder}\n * @see {@link getBase64Decoder}\n */\nexport const getBase64Codec = (): VariableSizeCodec => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**\n * Removes all null characters (`\\u0000`) from a string.\n *\n * This function cleans a string by stripping out any null characters,\n * which are often used as padding in fixed-size string encodings.\n *\n * @param value - The string to process.\n * @returns The input string with all null characters removed.\n *\n * @example\n * Removing null characters from a string.\n * ```ts\n * removeNullCharacters('hello\\u0000\\u0000'); // \"hello\"\n * ```\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters (`\\u0000`) at the end to reach a fixed length.\n *\n * If the input string is shorter than the specified length, it is padded with null characters\n * until it reaches the desired size. If it is already long enough, it remains unchanged.\n *\n * @param value - The string to pad.\n * @param chars - The total length of the resulting string, including padding.\n * @returns The input string padded with null characters up to the specified length.\n *\n * @example\n * Padding a string with null characters.\n * ```ts\n * padNullCharacters('hello', 8); // \"hello\\u0000\\u0000\\u0000\"\n * ```\n */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from '@solana/text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/**\n * Returns an encoder for UTF-8 strings.\n *\n * This encoder serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding UTF-8 strings.\n *\n * @example\n * Encoding a UTF-8 string.\n * ```ts\n * const encoder = getUtf8Encoder();\n * const bytes = encoder.encode('hello'); // 0x68656c6c6f\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Encoder = (): VariableSizeEncoder => {\n let textEncoder: TextEncoder;\n return createEncoder({\n getSizeFromValue: value => (textEncoder ||= new TextEncoder()).encode(value).length,\n write: (value: string, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new TextEncoder()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for UTF-8 strings.\n *\n * This decoder deserializes UTF-8 encoded strings from a byte array.\n * It reads all available bytes starting from the given offset.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding UTF-8 strings.\n *\n * @example\n * Decoding a UTF-8 string.\n * ```ts\n * const decoder = getUtf8Decoder();\n * const value = decoder.decode(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // \"hello\"\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Decoder = (): VariableSizeDecoder => {\n let textDecoder: TextDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding UTF-8 strings.\n *\n * This codec serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding UTF-8 strings.\n *\n * @example\n * Encoding and decoding a UTF-8 string.\n * ```ts\n * const codec = getUtf8Codec();\n * const bytes = codec.encode('hello'); // 0x68656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size UTF-8 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 5);\n * ```\n *\n * If you need a size-prefixed UTF-8 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getUtf8Encoder} and {@link getUtf8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getUtf8Encoder().encode('hello');\n * const value = getUtf8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getUtf8Encoder}\n * @see {@link getUtf8Decoder}\n */\nexport const getUtf8Codec = (): VariableSizeCodec => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","import type { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport type { Lamports } from '@solana/rpc-types';\n\n/**\n * The number of bytes required to store the {@link BaseAccount} information without its data.\n *\n * @example\n * ```ts\n * const myTotalAccountSize = myAccountDataSize + BASE_ACCOUNT_SIZE;\n * ```\n */\nexport const BASE_ACCOUNT_SIZE = 128;\n\n/**\n * Defines the attributes common to all Solana accounts. Namely, it contains everything stored\n * on-chain except the account data itself.\n *\n * @interface\n *\n * @example\n * ```ts\n * const BaseAccount: BaseAccount = {\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type BaseAccount = {\n readonly executable: boolean;\n readonly lamports: Lamports;\n readonly programAddress: Address;\n readonly space: bigint;\n};\n\n/**\n * Contains all the information relevant to a Solana account. It includes the account's address and\n * data, as well as the properties of {@link BaseAccount}.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Encoded\n * const myEncodedAccount: Account = {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n *\n * // Decoded\n * type MyAccountData = { name: string; age: number };\n * const myDecodedAccount: Account = {\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type Account = BaseAccount & {\n readonly address: Address;\n readonly data: TData;\n};\n\n/**\n * Represents an encoded account and is equivalent to an {@link Account} with `Uint8Array` account\n * data.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * } satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport type EncodedAccount = Account;\n","import type { Decoder, ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SolanaError,\n} from '@solana/errors';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/**\n * Transforms an {@link EncodedAccount} into an {@link Account} (or a {@link MaybeEncodedAccount}\n * into a {@link MaybeAccount}) by decoding the account data using the provided {@link Decoder}\n * instance.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: EncodedAccount<'1234..5678'>;\n * const myDecoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n *\n * const myDecodedAccount = decodeAccount(myAccount, myDecoder);\n * myDecodedAccount satisfies Account;\n * ```\n */\nexport function decodeAccount(\n encodedAccount: EncodedAccount,\n decoder: Decoder,\n): Account;\nexport function decodeAccount(\n encodedAccount: MaybeEncodedAccount,\n decoder: Decoder,\n): MaybeAccount;\nexport function decodeAccount(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n decoder: Decoder,\n): Account | MaybeAccount {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, {\n address: encodedAccount.address,\n });\n }\n}\n\nfunction accountExists(account: Account | MaybeAccount): account is Account {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/**\n * Asserts that an account stores decoded data, ie. not a `Uint8Array`.\n *\n * Note that it does not check the shape of the data matches the decoded type, only that it is not a\n * `Uint8Array`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: Account;\n * assertAccountDecoded(myAccount);\n *\n * // now the account data can be used as MyAccountData\n * account.data satisfies MyAccountData;\n * ```\n *\n * This is particularly useful for narrowing the result of fetching a JSON parsed account.\n *\n * ```ts\n * const account: MaybeAccount = await fetchJsonParsedAccount(\n * rpc,\n * '1234..5678' as Address,\n * );\n *\n * assertAccountDecoded(account);\n * // now we have a MaybeAccount\n * account satisfies MaybeAccount;\n * ```\n */\nexport function assertAccountDecoded(\n account: Account,\n): asserts account is Account;\nexport function assertAccountDecoded(\n account: MaybeAccount,\n): asserts account is MaybeAccount;\nexport function assertAccountDecoded(\n account: Account | MaybeAccount,\n): asserts account is Account | MaybeAccount {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, {\n address: account.address,\n });\n }\n}\n\n/**\n * Asserts that all input accounts store decoded data, ie. not a `Uint8Array`.\n *\n * As with {@link assertAccountDecoded} it does not check the shape of the data matches the decoded\n * type, only that it is not a `Uint8Array`.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccounts: Account[];\n * assertAccountsDecoded(myAccounts);\n *\n * // now the account data can be used as MyAccountData\n * for (const a of account) {\n * account.data satisfies MyAccountData;\n * }\n * ```\n */\nexport function assertAccountsDecoded(\n accounts: Account[],\n): asserts accounts is Account[];\nexport function assertAccountsDecoded(\n accounts: MaybeAccount[],\n): asserts accounts is MaybeAccount[];\nexport function assertAccountsDecoded(\n accounts: (Account | MaybeAccount)[],\n): asserts accounts is (Account | MaybeAccount)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, {\n addresses: encodedAddresses,\n });\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n} from '@solana/rpc-types';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type { JsonParsedDataResponse } from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/**\n * Parses a base64-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/**\n * Parses a base58-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse };\ntype ParsedAccountMeta = { program: string; type?: string };\ntype JsonParsedAccountData = TData & { parsedAccountMeta?: ParsedAccountMeta };\n\n/**\n * Parses an arbitrary `jsonParsed` account provided by the RPC client into an {@link Account} type\n * or a {@link MaybeAccount} type if the raw data can be set to `null`.\n *\n * The expected data type should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * const myAccount: Account = parseJsonRpcAccount(myJsonRpcAccount);\n * ```\n */\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount,\n): Account, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account, TAddress> | MaybeAccount, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = (rpcAccount.data.parsed.info || {}) as TData;\n\n if (rpcAccount.data.program || rpcAccount.data.parsed.type) {\n (data as JsonParsedAccountData).parsedAccountMeta = {\n program: rpcAccount.data.program,\n type: rpcAccount.data.parsed.type,\n };\n }\n\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n space: rpcAccount.space,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Rpc } from '@solana/rpc-spec';\nimport type { Commitment, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/**\n * Optional configuration for fetching a singular account.\n *\n * @interface\n */\nexport type FetchAccountConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the account as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches a {@link MaybeEncodedAccount} from the provided RPC client and address.\n *\n * It uses the {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} RPC method under the hood\n * with base64 encoding and an additional configuration object can be provided to customize the\n * behavior of the RPC call.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress);\n *\n * // With custom configuration.\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/**\n * Fetches a {@link MaybeAccount} from the provided RPC client and address by using\n * {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} under the hood with the `jsonParsed`\n * encoding.\n *\n * It may also return a {@link MaybeEncodedAccount} if the RPC client does not know how to parse the\n * account at the requested address. In any case, the expected data type should be explicitly\n * provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress);\n * myAccount satisfies MaybeAccount | MaybeEncodedAccount;\n *\n * // With custom configuration.\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchJsonParsedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise<\n | MaybeAccount\n | MaybeEncodedAccount\n> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(address, account as Parameters[1])\n : parseBase64RpcAccount(address, account as Parameters[1]);\n}\n\n/**\n * Optional configuration for fetching multiple accounts.\n *\n * @interface\n */\nexport type FetchAccountsConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the accounts as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches an array of {@link MaybeEncodedAccount | MaybeEncodedAccounts} from the provided RPC\n * client and an array of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with base64 encodings and an additional configuration object can be provided to\n * customize the behavior of the RPC call.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n *\n * @example\n * ```ts\n * const myAddressA = address('1234..5678');\n * const myAddressB = address('8765..4321');\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeEncodedAccount<'1234..5678'>;\n * myAccountB satisfies MaybeEncodedAccount<'8765..4321'>;\n *\n * // With custom configuration.\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount;\n };\n}\n\n/**\n * Fetches an array of {@link MaybeAccount | MaybeAccounts} from a provided RPC client and an array\n * of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with the `jsonParsed` encoding. It may also return a\n * {@link MaybeEncodedAccount} instead of the expected {@link MaybeAccount} if the RPC client does\n * not know how to parse some of the requested accounts. In any case, the array of expected data\n * types should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n * @typeParam TData - The expected types of these accounts' data.\n \n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * type MintData = { supply: bigint };\n * const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeAccount | MaybeEncodedAccount;\n * myAccountB satisfies MaybeAccount | MaybeEncodedAccount;\n * ```\n */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters[1]);\n }) as {\n [P in keyof TAddresses]:\n | MaybeAccount<\n TData[P & keyof TData] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P]\n >\n | MaybeEncodedAccount;\n } & {\n [P in keyof TData]:\n | MaybeAccount<\n TData[P] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P & keyof TAddresses]\n >\n | MaybeEncodedAccount;\n };\n}\n","import { Address } from '@solana/addresses';\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\n\nimport { Account } from './account';\n\n/**\n * Represents an account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type with an additional `exists`\n * attribute set to `true`. When it does not exist, it is represented by an object containing only\n * the address of the account and an `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Account exists\n * const myExistingAccount: MaybeAccount = {\n * exists: true,\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * // ...\n * };\n *\n * // Account does not exist\n * const myMissingAccount: MaybeAccount = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeAccount =\n | { readonly address: Address; readonly exists: false }\n | (Account & { readonly exists: true });\n\n/**\n * Represents an encoded account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type having its `TData` type\n * parameter set to `Uint8Array` with an additional `exists` attribute set to `true`. When it does\n * not exist, it is represented by an object containing only the address of the account and an\n * `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * // Encoded account exists\n * const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = {\n * exists: true,\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * // ...\n * };\n *\n * // Encoded account does not exist\n * const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeEncodedAccount = MaybeAccount;\n\n/**\n * Given a {@link MaybeAccount}, asserts that the account exists and allows it to be used as an\n * {@link Account} type going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccount: MaybeEncodedAccount<'1234..5678'>;\n * assertAccountExists(myAccount);\n *\n * // Now we can use myAccount as an `EncodedAccount`\n * myAccount satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport function assertAccountExists(\n account: MaybeAccount,\n): asserts account is Account & { exists: true } {\n if (!account.exists) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, { address: account.address });\n }\n}\n\n/**\n * Given an array of {@link MaybeAccount | MaybeAccounts}, asserts that all the accounts exist and\n * allows them to be used as an array of {@link Account | Accounts} going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccounts: MaybeEncodedAccount
[];\n * assertAccountsExist(myAccounts);\n *\n * // Now we can use them as an array of `EncodedAccounts`\n * for (const a of myAccounts) {\n * a satisfies EncodedAccount
;\n * }\n * ```\n */\nexport function assertAccountsExist(\n accounts: MaybeAccount[],\n): asserts accounts is (Account & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, { addresses: missingAddresses });\n }\n}\n","import { SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SolanaError } from '@solana/errors';\n\n/**\n * Throws an exception unless {@link Crypto#getRandomValues | `crypto.getRandomValues()`} is\n * available in the current JavaScript environment.\n */\nexport function assertPRNGIsAvailable() {\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.getRandomValues !== 'function') {\n throw new SolanaError(SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SolanaError,\n} from '@solana/errors';\n\nfunction assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT);\n }\n}\n\nlet cachedEd25519Decision: PromiseLike | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .then(() => {\n resolve((cachedEd25519Decision = true));\n })\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#digest | `crypto.subtle.digest()`} is available in\n * the current JavaScript environment.\n */\nexport function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#generateKey | `crypto.subtle.generateKey()`} is\n * available in the current JavaScript environment and has support for the Ed25519 curve.\n */\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED);\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#exportKey | `crypto.subtle.exportKey()`} is\n * available in the current JavaScript environment.\n */\nexport function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#sign | `crypto.subtle.sign()`} is available in the\n * current JavaScript environment.\n */\nexport function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);\n }\n}\n/**\n * Throws an exception unless {@link SubtleCrypto#verify | `crypto.subtle.verify()`} is available in\n * the current JavaScript environment.\n */\nexport function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n combineCodec,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * Represents a string that validates as a Solana address. Functions that require well-formed\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an arbitrary string as a base58-encoded address, use the\n * {@link address}, {@link assertIsAddress}, or {@link isAddress} functions in this package.\n */\nexport type Address = Brand, 'Address'>;\n\nlet memoizedBase58Encoder: Encoder | undefined;\nlet memoizedBase58Decoder: Decoder | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Address} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAddress } from '@solana/addresses';\n *\n * if (isAddress(ownerAddress)) {\n * // At this point, `ownerAddress` has been refined to a\n * // `Address` that can be used with the RPC.\n * const { value: lamports } = await rpc.getBalance(ownerAddress).send();\n * setBalanceLamports(lamports);\n * } else {\n * setError(`${ownerAddress} is not an address`);\n * }\n * ```\n */\nexport function isAddress(putativeAddress: string): putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n try {\n return base58Encoder.encode(putativeAddress).byteLength === 32;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an address or public\n * key, from an untrusted network API or user input. Use this function to assert that such an\n * arbitrary string is a base58-encoded address.\n *\n * @example\n * ```ts\n * import { assertIsAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // At this point, `address` is an `Address` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out not to be a base58-encoded address\n * }\n * }\n * ```\n */\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * Combines _asserting_ that a string is an address with _coercing_ it to the {@link Address} type.\n * It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good address as a string, it's more efficient to typecast it rather\n * than to use the {@link address} helper, because the helper unconditionally performs validation on\n * its input.\n * >\n * > ```ts\n * > import { Address } from '@solana/addresses';\n * >\n * > const MEMO_PROGRAM_ADDRESS =\n * > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;\n * > ```\n */\nexport function address(putativeAddress: TAddress): Address {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded address to a byte array.\n *\n * @example\n * ```ts\n * import { getAddressEncoder } from '@solana/addresses';\n *\n * const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;\n * const addressEncoder = getAddressEncoder();\n * const addressBytes = addressEncoder.encode(address);\n * // Uint8Array(32) [\n * // 150, 183, 190, 48, 171, 8, 39, 156,\n * // 122, 213, 172, 108, 193, 95, 26, 158,\n * // 149, 243, 115, 254, 20, 200, 36, 30,\n * // 248, 179, 178, 232, 220, 89, 53, 127\n * // ]\n * ```\n */\nexport function getAddressEncoder(): FixedSizeEncoder {\n return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), putativeAddress =>\n address(putativeAddress),\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an address to the\n * base58-encoded representation of that address.\n *\n * @example\n * ```ts\n * import { getAddressDecoder } from '@solana/addresses';\n *\n * const addressBytes = new Uint8Array([\n * 150, 183, 190, 48, 171, 8, 39, 156,\n * 122, 213, 172, 108, 193, 95, 26, 158,\n * 149, 243, 115, 254, 20, 200, 36, 30,\n * 248, 179, 178, 232, 220, 89, 53, 127\n * ]);\n * const addressDecoder = getAddressDecoder();\n * const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka\n * ```\n */\nexport function getAddressDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded address.\n *\n * @see {@link getAddressDecoder}\n * @see {@link getAddressEncoder}\n */\nexport function getAddressCodec(): FixedSizeCodec {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\n\nimport { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: ReadonlyUint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport function compressedPointBytesAreOnCurve(bytes: ReadonlyUint8Array): boolean {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SolanaError } from '@solana/errors';\nimport type { AffinePoint } from '@solana/nominal-types';\n\nimport { type Address, getAddressCodec } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * Represents an {@link Address} that validates as being off-curve. Functions that require off-curve\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an address as being off-curve, use the {@link offCurveAddress},\n * {@link assertIsOffCurveAddress}, or {@link isOffCurveAddress} functions in this package.\n */\nexport type OffCurveAddress = AffinePoint, 'invalid'>;\n\n/**\n * A type guard that returns `true` if the input address conforms to the {@link OffCurveAddress}\n * type, and refines its type for use in your application.\n *\n * @example\n * ```ts\n * import { isOffCurveAddress } from '@solana/addresses';\n *\n * if (isOffCurveAddress(accountAddress)) {\n * // At this point, `accountAddress` has been refined to a\n * // `OffCurveAddress` that can be used within your business logic.\n * const { value: account } = await rpc.getAccountInfo(accountAddress).send();\n * } else {\n * setError(`${accountAddress} is not off-curve`);\n * }\n * ```\n */\nexport function isOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): putativeOffCurveAddress is OffCurveAddress {\n const addressBytes = getAddressCodec().encode(putativeOffCurveAddress);\n return compressedPointBytesAreOnCurve(addressBytes) === false;\n}\n\n/**\n * From time to time you might acquire an {@link Address}, that you expect to validate as an\n * off-curve address, from an untrusted source. Use this function to assert that such an address is\n * off-curve.\n *\n * @example\n * ```ts\n * import { assertIsOffCurveAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that the input conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `OffCurveAddress`.\n * assertIsOffCurveAddress(address);\n * // At this point, `address` is an `OffCurveAddress` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out to NOT be a base58-encoded off-curve address\n * }\n * }\n * ```\n */\nexport function assertIsOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): asserts putativeOffCurveAddress is OffCurveAddress {\n if (!isOffCurveAddress(putativeOffCurveAddress)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS);\n }\n}\n\n/**\n * Combines _asserting_ that an {@link Address} is off-curve with _coercing_ it to the\n * {@link OffCurveAddress} type. It's most useful with untrusted input.\n */\nexport function offCurveAddress(\n putativeOffCurveAddress: TAddress,\n): OffCurveAddress {\n assertIsOffCurveAddress(putativeOffCurveAddress);\n return putativeOffCurveAddress;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\nimport { bytesEqual, type ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nimport { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * A tuple representing a program derived address (derived from the address of some program and a\n * set of seeds) and the associated bump seed used to ensure that the address, as derived, does not\n * fall on the Ed25519 curve.\n *\n * Whenever you need to validate an arbitrary tuple as one that represents a program derived\n * address, use the {@link assertIsProgramDerivedAddress} or {@link isProgramDerivedAddress}\n * functions in this package.\n */\nexport type ProgramDerivedAddress = Readonly<\n [Address, ProgramDerivedAddressBump]\n>;\n\n/**\n * Represents an integer in the range [0,255] used in the derivation of a program derived address to\n * ensure that it does not fall on the Ed25519 curve.\n */\nexport type ProgramDerivedAddressBump = Brand;\n\n/**\n * A type guard that returns `true` if the input tuple conforms to the {@link ProgramDerivedAddress}\n * type, and refines its type for use in your program.\n *\n * @see The {@link isAddress} function for an example of how to use a type guard.\n */\nexport function isProgramDerivedAddress(\n value: unknown,\n): value is ProgramDerivedAddress {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * In the event that you receive an address/bump-seed tuple from some untrusted source, use this\n * function to assert that it conforms to the {@link ProgramDerivedAddress} interface.\n *\n * @see The {@link assertIsAddress} function for an example of how to use an assertion function.\n */\nexport function assertIsProgramDerivedAddress(\n value: unknown,\n): asserts value is ProgramDerivedAddress {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {\n bump: value[1],\n });\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = ReadonlyUint8Array | string;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise
{\n assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {\n actual: seeds.length,\n maxSeeds: MAX_SEEDS,\n });\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: bytes.byteLength,\n index: ii,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (compressedPointBytesAreOnCurve(addressBytes)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\n\n/**\n * Given a program's {@link Address} and up to 16 {@link Seed | Seeds}, this method will return the\n * program derived address (PDA) associated with each.\n *\n * @example\n * ```ts\n * import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses';\n *\n * const addressEncoder = getAddressEncoder();\n * const [pda, bumpSeed] = await getProgramDerivedAddress({\n * programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address,\n * seeds: [\n * // Owner\n * addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address),\n * // Token program\n * addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address),\n * // Mint\n * addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address),\n * ],\n * });\n * ```\n */\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);\n}\n\n/**\n * Returns a base58-encoded address derived from some base address, some program address, and a seed\n * string or byte array.\n *\n * @example\n * ```ts\n * import { createAddressWithSeed } from '@solana/addresses';\n *\n * const derivedAddress = await createAddressWithSeed({\n * // The private key associated with this address will be able to sign for `derivedAddress`.\n * baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address,\n * // Only this program will be able to write data to this account.\n * programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address,\n * seed: 'data-account',\n * });\n * ```\n */\nexport async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise
{\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: seedBytes.byteLength,\n index: 0,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES.length), new Uint8Array(PDA_MARKER_BYTES))\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';\n\nimport { Address, getAddressDecoder, getAddressEncoder } from './address';\n\n/**\n * Given a public {@link CryptoKey}, this method will return its associated {@link Address}.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const address = await getAddressFromPublicKey(publicKey);\n * ```\n */\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise
{\n assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\n/**\n * Given an {@link Address}, return a {@link CryptoKey} that can be used to verify signatures.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const publicKey = await getPublicKeyFromAddress(address);\n * ```\n */\nexport async function getPublicKeyFromAddress(address: Address) {\n const addressBytes = getAddressEncoder().encode(address);\n return await crypto.subtle.importKey('raw', addressBytes, { name: 'Ed25519' }, true /* extractable */, ['verify']);\n}\n","import { SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\n/**\n * Ensures that a given number falls within a specified range.\n *\n * If the number is outside the allowed range, an error is thrown.\n * This function is primarily used to validate values before encoding them in a codec.\n *\n * @param codecDescription - A string describing the codec that is performing the validation.\n * @param min - The minimum allowed value (inclusive).\n * @param max - The maximum allowed value (inclusive).\n * @param value - The number to validate.\n *\n * @throws {@link SolanaError} if the value is out of range.\n *\n * @example\n * Validating a number within range.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 42); // Passes\n * ```\n *\n * @example\n * Throwing an error for an out-of-range value.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 300); // Throws\n * ```\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: bigint | number,\n max: bigint | number,\n value: bigint | number,\n) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value,\n });\n }\n}\n","import { Codec, Decoder, Encoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n/**\n * Represents an encoder for numbers and bigints.\n *\n * This type allows encoding values that are either `number` or `bigint`.\n * Depending on the specific implementation, the encoded output may have a fixed or variable size.\n *\n * @see {@link FixedSizeNumberEncoder}\n */\nexport type NumberEncoder = Encoder;\n\n/**\n * Represents a fixed-size encoder for numbers and bigints.\n *\n * This encoder serializes values using an exact number of bytes, defined by `TSize`.\n *\n * @typeParam TSize - The number of bytes used for encoding.\n *\n * @see {@link NumberEncoder}\n */\nexport type FixedSizeNumberEncoder = FixedSizeEncoder;\n\n/**\n * Represents a decoder for numbers and bigints.\n *\n * This type supports decoding values as either `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberDecoder}\n */\nexport type NumberDecoder = Decoder | Decoder;\n\n/**\n * Represents a fixed-size decoder for numbers and bigints.\n *\n * This decoder reads a fixed number of bytes (`TSize`) and converts them into a `number` or `bigint`.\n *\n * @typeParam TSize - The number of bytes expected for decoding.\n *\n * @see {@link NumberDecoder}\n */\nexport type FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\n\n/**\n * Represents a codec for encoding and decoding numbers and bigints.\n *\n * - The encoded value can be either a `number` or a `bigint`.\n * - The decoded value will always be either a `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberCodec}\n */\nexport type NumberCodec = Codec | Codec;\n\n/**\n * Represents a fixed-size codec for encoding and decoding numbers and bigints.\n *\n * This codec uses a specific number of bytes (`TSize`) for serialization.\n * The encoded value can be either a `number` or `bigint`, but the decoded value will always be a `number` or `bigint`,\n * depending on the implementation.\n *\n * @typeParam TSize - The number of bytes used for encoding and decoding.\n *\n * @see {@link NumberCodec}\n */\nexport type FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Configuration options for number codecs that use more than one byte.\n *\n * This configuration applies to all number codecs except `u8` and `i8`,\n * allowing the user to specify the endianness of serialization.\n */\nexport type NumberCodecConfig = {\n /**\n * Specifies whether numbers should be encoded in little-endian or big-endian format.\n *\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the byte order used for number serialization.\n *\n * - `Little`: The least significant byte is stored first.\n * - `Big`: The most significant byte is stored first.\n */\nexport enum Endian {\n Little,\n Big,\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n toArrayBuffer,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n config?: NumberCodecConfig;\n name: string;\n size: TSize;\n};\n\ntype NumberFactoryEncoderInput = NumberFactorySharedInput & {\n range?: [bigint | number, bigint | number];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.Big ? false : true;\n}\n\nexport function numberEncoderFactory(\n input: NumberFactoryEncoderInput,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory(\n input: NumberFactoryDecoderInput,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\n });\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit floating-point numbers (`f32`).\n *\n * This encoder serializes `f32` values using 4 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f32` values.\n *\n * @example\n * Encoding an `f32` value.\n * ```ts\n * const encoder = getF32Encoder();\n * const bytes = encoder.encode(-1.5); // 0x0000c0bf\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit floating-point numbers (`f32`).\n *\n * This decoder deserializes `f32` values from 4 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f32` values.\n *\n * @example\n * Decoding an `f32` value.\n * ```ts\n * const decoder = getF32Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`).\n *\n * This codec serializes `f32` values using 4 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f32` values.\n *\n * @example\n * Encoding and decoding an `f32` value.\n * ```ts\n * const codec = getF32Codec();\n * const bytes = codec.encode(-1.5); // 0x0000c0bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbfc00000\n * ```\n *\n * @remarks\n * `f32` values follow the IEEE 754 single-precision floating-point standard.\n * Precision loss may occur for certain values.\n *\n * - If you need higher precision, consider using {@link getF64Codec}.\n * - If you need integer values, consider using {@link getI32Codec} or {@link getU32Codec}.\n *\n * Separate {@link getF32Encoder} and {@link getF32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF32Encoder().encode(-1.5);\n * const value = getF32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF32Encoder}\n * @see {@link getF32Decoder}\n */\nexport const getF32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit floating-point numbers (`f64`).\n *\n * This encoder serializes `f64` values using 8 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f64` values.\n *\n * @example\n * Encoding an `f64` value.\n * ```ts\n * const encoder = getF64Encoder();\n * const bytes = encoder.encode(-1.5); // 0x000000000000f8bf\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f64',\n set: (view, value, le) => view.setFloat64(0, Number(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit floating-point numbers (`f64`).\n *\n * This decoder deserializes `f64` values from 8 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f64` values.\n *\n * @example\n * Decoding an `f64` value.\n * ```ts\n * const decoder = getF64Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: 'f64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`).\n *\n * This codec serializes `f64` values using 8 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f64` values.\n *\n * @example\n * Encoding and decoding an `f64` value.\n * ```ts\n * const codec = getF64Codec();\n * const bytes = codec.encode(-1.5); // 0x000000000000f8bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbff8000000000000\n * ```\n *\n * @remarks\n * `f64` values follow the IEEE 754 double-precision floating-point standard.\n * Precision loss may still occur but is significantly lower than `f32`.\n *\n * - If you need smaller floating-point values, consider using {@link getF32Codec}.\n * - If you need integer values, consider using {@link getI64Codec} or {@link getU64Codec}.\n *\n * Separate {@link getF64Encoder} and {@link getF64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF64Encoder().encode(-1.5);\n * const value = getF64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF64Encoder}\n * @see {@link getF64Decoder}\n */\nexport const getF64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF64Encoder(config), getF64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit signed integers (`i128`).\n *\n * This encoder serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i128` values.\n *\n * @example\n * Encoding an `i128` value.\n * ```ts\n * const encoder = getI128Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i128',\n range: [-BigInt('0x7fffffffffffffffffffffffffffffff') - 1n, BigInt('0x7fffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit signed integers (`i128`).\n *\n * This decoder deserializes `i128` values from 16 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i128` values.\n *\n * @example\n * Decoding an `i128` value.\n * ```ts\n * const decoder = getI128Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n * 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'i128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit signed integers (`i128`).\n *\n * This codec serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i128` values.\n *\n * @example\n * Encoding and decoding an `i128` value.\n * ```ts\n * const codec = getI128Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^127` and `2^127 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI64Codec} or {@link getI32Codec}.\n * - If you need a larger signed integer, consider using a custom codec.\n * - If you need unsigned integers, consider using {@link getU128Codec}.\n *\n * Separate {@link getI128Encoder} and {@link getI128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI128Encoder().encode(-42);\n * const value = getI128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI128Encoder}\n * @see {@link getI128Decoder}\n */\nexport const getI128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI128Encoder(config), getI128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit signed integers (`i16`).\n *\n * This encoder serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i16` values.\n *\n * @example\n * Encoding an `i16` value.\n * ```ts\n * const encoder = getI16Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ff\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i16',\n range: [-Number('0x7fff') - 1, Number('0x7fff')],\n set: (view, value, le) => view.setInt16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit signed integers (`i16`).\n *\n * This decoder deserializes `i16` values from 2 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i16` values.\n *\n * @example\n * Decoding an `i16` value.\n * ```ts\n * const decoder = getI16Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff])); // -42\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: 'i16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit signed integers (`i16`).\n *\n * This codec serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i16` values.\n *\n * @example\n * Encoding and decoding an `i16` value.\n * ```ts\n * const codec = getI16Codec();\n * const bytes = codec.encode(-42); // 0xd6ff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^15` (`-32,768`) and `2^15 - 1` (`32,767`).\n *\n * - If you need a smaller signed integer, consider using {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI32Codec}.\n * - If you need unsigned integers, consider using {@link getU16Codec}.\n *\n * Separate {@link getI16Encoder} and {@link getI16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI16Encoder().encode(-42);\n * const value = getI16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI16Encoder}\n * @see {@link getI16Decoder}\n */\nexport const getI16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI16Encoder(config), getI16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit signed integers (`i32`).\n *\n * This encoder serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i32` values.\n *\n * @example\n * Encoding an `i32` value.\n * ```ts\n * const encoder = getI32Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ffffff\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i32',\n range: [-Number('0x7fffffff') - 1, Number('0x7fffffff')],\n set: (view, value, le) => view.setInt32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit signed integers (`i32`).\n *\n * This decoder deserializes `i32` values from 4 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i32` values.\n *\n * @example\n * Decoding an `i32` value.\n * ```ts\n * const decoder = getI32Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff, 0xff, 0xff])); // -42\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: 'i32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit signed integers (`i32`).\n *\n * This codec serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i32` values.\n *\n * @example\n * Encoding and decoding an `i32` value.\n * ```ts\n * const codec = getI32Codec();\n * const bytes = codec.encode(-42); // 0xd6ffffff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^31` (`-2,147,483,648`) and `2^31 - 1` (`2,147,483,647`).\n *\n * - If you need a smaller signed integer, consider using {@link getI16Codec} or {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI64Codec}.\n * - If you need unsigned integers, consider using {@link getU32Codec}.\n *\n * Separate {@link getI32Encoder} and {@link getI32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI32Encoder().encode(-42);\n * const value = getI32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI32Encoder}\n * @see {@link getI32Decoder}\n */\nexport const getI32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI32Encoder(config), getI32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit signed integers (`i64`).\n *\n * This encoder serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i64` values.\n *\n * @example\n * Encoding an `i64` value.\n * ```ts\n * const encoder = getI64Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffff\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit signed integers (`i64`).\n *\n * This decoder deserializes `i64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i64` values.\n *\n * @example\n * Decoding an `i64` value.\n * ```ts\n * const decoder = getI64Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit signed integers (`i64`).\n *\n * This codec serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i64` values.\n *\n * @example\n * Encoding and decoding an `i64` value.\n * ```ts\n * const codec = getI64Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^63` and `2^63 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI32Codec} or {@link getI16Codec}.\n * - If you need a larger signed integer, consider using {@link getI128Codec}.\n * - If you need unsigned integers, consider using {@link getU64Codec}.\n *\n * Separate {@link getI64Encoder} and {@link getI64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI64Encoder().encode(-42);\n * const value = getI64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI64Encoder}\n * @see {@link getI64Decoder}\n */\nexport const getI64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit signed integers (`i8`).\n *\n * This encoder serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `i8` values.\n *\n * @example\n * Encoding an `i8` value.\n * ```ts\n * const encoder = getI8Encoder();\n * const bytes = encoder.encode(-42); // 0xd6\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit signed integers (`i8`).\n *\n * This decoder deserializes `i8` values from 1 byte.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `i8` values.\n *\n * @example\n * Decoding an `i8` value.\n * ```ts\n * const decoder = getI8Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6])); // -42\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit signed integers (`i8`).\n *\n * This codec serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `i8` values.\n *\n * @example\n * Encoding and decoding an `i8` value.\n * ```ts\n * const codec = getI8Codec();\n * const bytes = codec.encode(-42); // 0xd6\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @remarks\n * This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`).\n *\n * - If you need a larger signed integer, consider using {@link getI16Codec}.\n * - If you need an unsigned integer, consider using {@link getU8Codec}.\n *\n * Separate {@link getI8Encoder} and {@link getI8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI8Encoder().encode(-42);\n * const value = getI8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI8Encoder}\n * @see {@link getI8Decoder}\n */\nexport const getI8Codec = (): FixedSizeCodec =>\n combineCodec(getI8Encoder(), getI8Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n Offset,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Returns an encoder for `shortU16` values.\n *\n * This encoder serializes `shortU16` values using **1 to 3 bytes**.\n * Smaller values use fewer bytes, while larger values take up more space.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding `shortU16` values.\n *\n * @example\n * Encoding a `shortU16` value.\n * ```ts\n * const encoder = getShortU16Encoder();\n * encoder.encode(42); // 0x2a\n * encoder.encode(128); // 0x8001\n * encoder.encode(16384); // 0x808001\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: bigint | number): number => {\n if (value <= 0b01111111) return 1;\n if (value <= 0b0011111111111111) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value: bigint | number, bytes: Uint8Array, offset: Offset): Offset => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = Number(value) >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n shortU16Bytes[ii - 1] |= 0b10000000;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n },\n });\n\n/**\n * Returns a decoder for `shortU16` values.\n *\n * This decoder deserializes `shortU16` values from **1 to 3 bytes**.\n * The number of bytes used depends on the encoded value.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding `shortU16` values.\n *\n * @example\n * Decoding a `shortU16` value.\n * ```ts\n * const decoder = getShortU16Decoder();\n * decoder.decode(new Uint8Array([0x2a])); // 42\n * decoder.decode(new Uint8Array([0x80, 0x01])); // 128\n * decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n maxSize: 3,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset): [number, Offset] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding `shortU16` values.\n *\n * It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.\n * The larger the value, the more bytes it uses.\n *\n * - If the value is `<= 0x7f` (127), it is stored in a **single byte**\n * and the first bit is set to `0` to indicate the end of the value.\n * - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.\n * - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.\n *\n * In other words, the encoding scheme follows this structure:\n *\n * ```txt\n * 0XXXXXXX <- Values 0 to 127 (1 byte)\n * 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)\n * 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)\n * ```\n *\n * @returns A `VariableSizeCodec` for encoding and decoding `shortU16` values.\n *\n * @example\n * Encoding and decoding `shortU16` values.\n * ```ts\n * const codec = getShortU16Codec();\n * const bytes1 = codec.encode(42); // 0x2a\n * const bytes2 = codec.encode(128); // 0x8001\n * const bytes3 = codec.encode(16384); // 0x808001\n *\n * codec.decode(bytes1); // 42\n * codec.decode(bytes2); // 128\n * codec.decode(bytes3); // 16384\n * ```\n *\n * @remarks\n * This codec efficiently stores small numbers, making it useful for transactions and compact representations.\n *\n * If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.\n *\n * Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getShortU16Encoder().encode(42);\n * const value = getShortU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getShortU16Encoder}\n * @see {@link getShortU16Decoder}\n */\nexport const getShortU16Codec = (): VariableSizeCodec =>\n combineCodec(getShortU16Encoder(), getShortU16Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit unsigned integers (`u128`).\n *\n * This encoder serializes `u128` values using sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u128` values.\n *\n * @example\n * Encoding a `u128` value.\n * ```ts\n * const encoder = getU128Encoder();\n * const bytes = encoder.encode(42n); // 0x2a000000000000000000000000000000\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0n, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit unsigned integers (`u128`).\n *\n * This decoder deserializes `u128` values from sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u128` values.\n *\n * @example\n * Decoding a `u128` value.\n * ```ts\n * const decoder = getU128Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit unsigned integers (`u128`).\n *\n * This codec serializes `u128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u128` values.\n *\n * @example\n * Encoding and decoding a `u128` value.\n * ```ts\n * const codec = getU128Codec();\n * const bytes = codec.encode(42); // 0x2a000000000000000000000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000000000000000000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^128 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU64Codec} or {@link getU32Codec}.\n * - If you need signed integers, consider using {@link getI128Codec}.\n *\n * Separate {@link getU128Encoder} and {@link getU128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU128Encoder().encode(42);\n * const value = getU128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU128Encoder}\n * @see {@link getU128Decoder}\n */\nexport const getU128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit unsigned integers (`u16`).\n *\n * This encoder serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u16` values.\n *\n * @example\n * Encoding a `u16` value.\n * ```ts\n * const encoder = getU16Encoder();\n * const bytes = encoder.encode(42); // 0x2a00\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit unsigned integers (`u16`).\n *\n * This decoder deserializes `u16` values from two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u16` values.\n *\n * @example\n * Decoding a `u16` value.\n * ```ts\n * const decoder = getU16Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`).\n *\n * This codec serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u16` values.\n *\n * @example\n * Encoding and decoding a `u16` value.\n * ```ts\n * const codec = getU16Codec();\n * const bytes = codec.encode(42); // 0x2a00 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^16 - 1`.\n * If you need a larger range, consider using {@link getU32Codec} or {@link getU64Codec}.\n * For signed integers, use {@link getI16Codec}.\n *\n * Separate {@link getU16Encoder} and {@link getU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU16Encoder().encode(42);\n * const value = getU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU16Encoder}\n * @see {@link getU16Decoder}\n */\nexport const getU16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit unsigned integers (`u32`).\n *\n * This encoder serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u32` values.\n *\n * @example\n * Encoding a `u32` value.\n * ```ts\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42); // 0x2a000000\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u32',\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit unsigned integers (`u32`).\n *\n * This decoder deserializes `u32` values from four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u32` values.\n *\n * @example\n * Decoding a `u32` value.\n * ```ts\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`).\n *\n * This codec serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u32` values.\n *\n * @example\n * Encoding and decoding a `u32` value.\n * ```ts\n * const codec = getU32Codec();\n * const bytes = codec.encode(42); // 0x2a000000 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000002a\n * ```\n *\n * @remarks\n * This codec only supports values between `0` and `2^32 - 1`.\n * If you need a larger range, consider using {@link getU64Codec} or {@link getU128Codec}.\n * For signed integers, use {@link getI32Codec}.\n *\n * Separate {@link getU32Encoder} and {@link getU32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU32Encoder().encode(42);\n * const value = getU32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU32Encoder}\n * @see {@link getU32Decoder}\n */\nexport const getU32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU32Encoder(config), getU32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit unsigned integers (`u64`).\n *\n * This encoder serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `u64` values.\n *\n * @example\n * Encoding a `u64` value.\n * ```ts\n * const encoder = getU64Encoder();\n * const bytes = encoder.encode(42); // 0x2a00000000000000\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u64',\n range: [0n, BigInt('0xffffffffffffffff')],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit unsigned integers (`u64`).\n *\n * This decoder deserializes `u64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `u64` values.\n *\n * @example\n * Decoding a `u64` value.\n * ```ts\n * const decoder = getU64Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: 'u64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`).\n *\n * This codec serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u64` values.\n *\n * @example\n * Encoding and decoding a `u64` value.\n * ```ts\n * const codec = getU64Codec();\n * const bytes = codec.encode(42); // 0x2a00000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^64 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU32Codec} or {@link getU16Codec}.\n * - If you need a larger unsigned integer, consider using {@link getU128Codec}.\n * - If you need signed integers, consider using {@link getI64Codec}.\n *\n * Separate {@link getU64Encoder} and {@link getU64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU64Encoder().encode(42);\n * const value = getU64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU64Encoder}\n * @see {@link getU64Decoder}\n */\nexport const getU64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU64Encoder(config), getU64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit unsigned integers (`u8`).\n *\n * This encoder serializes `u8` values using a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `u8` values.\n *\n * @example\n * Encoding a `u8` value.\n * ```ts\n * const encoder = getU8Encoder();\n * const bytes = encoder.encode(42); // 0x2a\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'u8',\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit unsigned integers (`u8`).\n *\n * This decoder deserializes `u8` values from a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `u8` values.\n *\n * @example\n * Decoding a `u8` value.\n * ```ts\n * const decoder = getU8Decoder();\n * const value = decoder.decode(new Uint8Array([0xff])); // 255\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getUint8(0),\n name: 'u8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`).\n *\n * This codec serializes `u8` values using a single byte.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `u8` values.\n *\n * @example\n * Encoding and decoding a `u8` value.\n * ```ts\n * const codec = getU8Codec();\n * const bytes = codec.encode(255); // 0xff\n * const value = codec.decode(bytes); // 255\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^8 - 1` (0 to 255).\n * If you need larger integers, consider using {@link getU16Codec}, {@link getU32Codec}, or {@link getU64Codec}.\n * For signed integers, use {@link getI8Codec}.\n *\n * Separate {@link getU8Encoder} and {@link getU8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU8Encoder().encode(42);\n * const value = getU8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU8Encoder}\n * @see {@link getU8Decoder}\n */\nexport const getU8Codec = (): FixedSizeCodec =>\n combineCodec(getU8Encoder(), getU8Decoder());\n","import { SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SolanaError } from '@solana/errors';\n\n/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: bigint | number,\n actual: bigint | number,\n) {\n if (expected !== actual) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {\n actual,\n codecDescription,\n expected,\n });\n }\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\n/**\n * Functionally, this type helper is equivalent to the identity type — i.e. `type Identity = T`.\n * However, wrapping generic object mappings in this type significantly reduces the number\n * of instantiation expressions processed, which increases TypeScript performance and\n * prevents \"Type instantiation is excessively deep and possibly infinite\" errors.\n *\n * This works because TypeScript doesn't create a new level of nesting when encountering conditional generic types.\n * @see https://github.com/microsoft/TypeScript/issues/34933\n * @see https://github.com/kysely-org/kysely/pull/483\n */\nexport type DrainOuterGeneric = [T] extends [unknown] ? T : never;\n\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null,\n );\n}\n\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : (codec.maxSize ?? null);\n}\n","import {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } from './utils';\n\n/**\n * Defines the possible size strategies for array-like codecs (`array`, `map`, and `set`).\n *\n * The size of the collection can be determined using one of the following approaches:\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} to store a size prefix.\n * - A fixed `number` of items, enforcing an exact length.\n * - The string `\"remainder\"`, which infers the number of items by consuming the rest of the available bytes.\n * This option is only available when encoding fixed-size items.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayLikeCodecSize =\n | TPrefix\n | number\n | 'remainder';\n\n/**\n * Defines the configuration options for array codecs.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayCodecConfig = {\n /**\n * Specifies how the size of the array is determined.\n *\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} stores a size prefix before encoding the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length (only for fixed-size items).\n *\n * @defaultValue A `u32` size prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for arrays of values.\n *\n * This encoder serializes arrays by encoding each element using the provided item encoder.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TFrom - The type of the elements in the array.\n *\n * @param item - The encoder for each item in the array.\n * @param config - Optional configuration for the size encoding strategy.\n * @returns A `VariableSizeEncoder` for encoding arrays.\n *\n * @example\n * Encoding an array of `u8` numbers.\n * ```ts\n * const encoder = getArrayEncoder(getU8Encoder());\n * const bytes = encoder.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: FixedSizeEncoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config?: ArrayCodecConfig,\n): VariableSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig = {},\n): Encoder {\n const size = config.size ?? getU32Encoder();\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\n const prefixSize = typeof size === 'object' ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize,\n }),\n write: (array: TFrom[], bytes, offset) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, array.length);\n }\n if (typeof size === 'object') {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach(value => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for arrays of values.\n *\n * This decoder deserializes arrays by decoding each element using the provided item decoder.\n * By default, a `u32` size prefix is expected to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TTo - The type of the decoded elements in the array.\n *\n * @param item - The decoder for each item in the array.\n * @param config - Optional configuration for the size decoding strategy.\n * @returns A `VariableSizeDecoder` for decoding arrays.\n *\n * @example\n * Decoding an array of `u8` numbers.\n * ```ts\n * const decoder = getArrayDecoder(getU8Decoder());\n * const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // [1, 2, 3]\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayDecoder(\n item: Decoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: FixedSizeDecoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: Decoder,\n config?: ArrayCodecConfig,\n): VariableSizeDecoder;\nexport function getArrayDecoder(item: Decoder, config: ArrayCodecConfig = {}): Decoder {\n const size = config.size ?? getU32Decoder();\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n\n if (size === 'remainder') {\n while (offset < bytes.length) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n }\n\n const [resolvedSize, newOffset] = typeof size === 'number' ? [size, offset] : size.read(bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding arrays of values.\n *\n * This codec serializes arrays by encoding each element using the provided item codec.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * @typeParam TFrom - The type of the elements to encode.\n * @typeParam TTo - The type of the decoded elements.\n *\n * @param item - The codec for each item in the array.\n * @param config - Optional configuration for the size encoding/decoding strategy.\n * @returns A `VariableSizeCodec` for encoding and decoding arrays.\n *\n * @example\n * Encoding and decoding an array of `u8` numbers.\n * ```ts\n * const codec = getArrayCodec(getU8Codec());\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n *\n * const array = codec.decode(bytes);\n * // [1, 2, 3]\n * ```\n *\n * @example\n * Using a `u16` size prefix instead of `u32`.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix telling us to read 3 items.\n * ```\n *\n * @example\n * Using a fixed-size array of 3 items.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 3 });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. There must always be 3 items in the array.\n * ```\n *\n * @example\n * Using the `\"remainder\"` size strategy.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 'remainder' });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.\n * ```\n *\n * @remarks\n * The size of the array can be controlled using the `size` option:\n * - A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length.\n *\n * Separate {@link getArrayEncoder} and {@link getArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);\n * const array = getArrayDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getArrayEncoder}\n * @see {@link getArrayDecoder}\n */\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: FixedSizeCodec,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config?: ArrayCodecConfig,\n): VariableSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig = {},\n): Codec {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction computeArrayLikeCodecSize(size: number | object | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Defines the configuration options for bit array codecs.\n *\n * A bit array codec encodes an array of booleans into bits, packing them into bytes.\n * This configuration allows adjusting the bit ordering.\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n * @see {@link getBitArrayCodec}\n */\nexport type BitArrayCodecConfig = {\n /**\n * Determines whether the bits should be read in reverse order.\n *\n * - `false` (default): The first boolean is stored in the most significant bit (MSB-first).\n * - `true`: The first boolean is stored in the least significant bit (LSB-first).\n *\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Returns an encoder that packs an array of booleans into bits.\n *\n * This encoder converts a list of `boolean` values into a compact bit representation,\n * storing 8 booleans per byte.\n *\n * The `backward` config option determines whether the bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding the bit array.\n * @returns A `FixedSizeEncoder` for encoding bit arrays.\n *\n * @example\n * Encoding a bit array.\n * ```ts\n * const encoder = getBitArrayEncoder(1);\n *\n * encoder.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayEncoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeEncoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Returns a decoder that unpacks bits into an array of booleans.\n *\n * This decoder converts a compact bit representation back into a list of `boolean` values.\n * Each byte is expanded into 8 booleans.\n *\n * The `backward` config option determines whether the bits are read in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for decoding the bit array.\n * @returns A `FixedSizeDecoder` for decoding bit arrays.\n *\n * @example\n * Decoding a bit array.\n * ```ts\n * const decoder = getBitArrayDecoder(1);\n *\n * decoder.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayDecoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeDecoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec('bitArray', size, bytes, offset);\n const booleans: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\n slice.forEach(byte => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes boolean arrays as compact bit representations.\n *\n * This codec efficiently stores boolean arrays as bits, packing 8 values per byte.\n * The `backward` config option determines whether bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding and decoding the bit array.\n * @returns A `FixedSizeCodec` for encoding and decoding bit arrays.\n *\n * @example\n * Encoding and decoding a bit array.\n * ```ts\n * const codec = getBitArrayCodec(1);\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n *\n * codec.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @example\n * Encoding and decoding a bit array backwards.\n * ```ts\n * const codec = getBitArrayCodec(1, { backward: true });\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0x05 (0b00000101)\n *\n * codec.decode(new Uint8Array([0x05]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @remarks\n * Separate {@link getBitArrayEncoder} and {@link getBitArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBitArrayEncoder(1).encode([true, false, true, false]);\n * const value = getBitArrayDecoder(1).decode(bytes);\n * ```\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n */\nexport function getBitArrayCodec(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeCodec {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/**\n * Defines the configuration options for boolean codecs.\n *\n * A boolean codec encodes `true` as `1` and `false` as `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * @typeParam TSize - A number codec, encoder, or decoder used for boolean representation.\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n * @see {@link getBooleanCodec}\n */\nexport type BooleanCodecConfig = {\n /**\n * The number codec used to store boolean values.\n *\n * - By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * - A custom number codec can be provided to change the storage size.\n *\n * @defaultValue `u8`\n */\n size?: TSize;\n};\n\n/**\n * Returns an encoder for boolean values.\n *\n * This encoder converts `true` into `1` and `false` into `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for encoding booleans.\n * @returns A `FixedSizeEncoder` where `N` is the size of the number codec.\n *\n * @example\n * Encoding booleans.\n * ```ts\n * const encoder = getBooleanEncoder();\n *\n * encoder.encode(false); // 0x00\n * encoder.encode(true); // 0x01\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanEncoder(): FixedSizeEncoder;\nexport function getBooleanEncoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig): VariableSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig = {}): Encoder {\n return transformEncoder(config.size ?? getU8Encoder(), (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Returns a decoder for boolean values.\n *\n * This decoder reads a number and interprets `1` as `true` and `0` as `false`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for decoding booleans.\n * @returns A `FixedSizeDecoder` where `N` is the size of the number codec.\n *\n * @example\n * Decoding booleans.\n * ```ts\n * const decoder = getBooleanDecoder();\n *\n * decoder.decode(new Uint8Array([0x00])); // false\n * decoder.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanDecoder(): FixedSizeDecoder;\nexport function getBooleanDecoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig): VariableSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig = {}): Decoder {\n return transformDecoder(config.size ?? getU8Decoder(), (value: bigint | number): boolean => Number(value) === 1);\n}\n\n/**\n * Returns a codec for encoding and decoding boolean values.\n *\n * By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * The `size` option allows customizing the number codec used for storage.\n *\n * @param config - Configuration options for encoding and decoding booleans.\n * @returns A `FixedSizeCodec` where `N` is the size of the number codec.\n *\n * @example\n * Encoding and decoding booleans using a `u8` (default).\n * ```ts\n * const codec = getBooleanCodec();\n *\n * codec.encode(false); // 0x00\n * codec.encode(true); // 0x01\n *\n * codec.decode(new Uint8Array([0x00])); // false\n * codec.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @example\n * Encoding and decoding booleans using a custom number codec.\n * ```ts\n * const codec = getBooleanCodec({ size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * ```\n *\n * @remarks\n * Separate {@link getBooleanEncoder} and {@link getBooleanDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBooleanEncoder().encode(true);\n * const value = getBooleanDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n */\nexport function getBooleanCodec(): FixedSizeCodec;\nexport function getBooleanCodec(\n config: BooleanCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig): VariableSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig = {}): Codec {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for raw byte arrays.\n *\n * This encoder writes byte arrays exactly as provided without modification.\n *\n * The size of the encoded byte array is determined by the length of the input.\n * - To enforce a fixed size, consider using {@link fixEncoderSize}.\n * - To add a size prefix, use {@link addEncoderSizePrefix}.\n * - To add a sentinel value, use {@link addEncoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeEncoder`.\n *\n * @example\n * Encoding a byte array as-is.\n * ```ts\n * const encoder = getBytesEncoder();\n *\n * encoder.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * encoder.encode(new Uint8Array([255, 0, 127])); // 0xff007f\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => value.length,\n write: (value, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n },\n });\n}\n\n/**\n * Returns a decoder for raw byte arrays.\n *\n * This decoder reads byte arrays exactly as provided without modification.\n *\n * The decoded byte array extends from the provided offset to the end of the input.\n * - To enforce a fixed size, consider using {@link fixDecoderSize}.\n * - To add a size prefix, use {@link addDecoderSizePrefix}.\n * - To add a sentinel value, use {@link addDecoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeDecoder`.\n *\n * @example\n * Decoding a byte array as-is.\n * ```ts\n * const decoder = getBytesDecoder();\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Uint8Array([1, 2, 3])\n * decoder.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesDecoder(): VariableSizeDecoder {\n return createDecoder({\n read: (bytes, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding raw byte arrays.\n *\n * This codec serializes and deserializes byte arrays without modification.\n *\n * The size of the encoded and decoded byte array is determined dynamically.\n * This means, when reading, the codec will consume all remaining bytes in the input.\n * - To enforce a fixed size, consider using {@link fixCodecSize}.\n * - To add a size prefix, use {@link addCodecSizePrefix}.\n * - To add a sentinel value, use {@link addCodecSentinel}.\n *\n * @returns A `VariableSizeCodec`.\n *\n * @example\n * Encoding and decoding a byte array.\n * ```ts\n * const codec = getBytesCodec();\n *\n * codec.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * codec.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @remarks\n * Separate {@link getBytesEncoder} and {@link getBytesDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBytesEncoder().encode(new Uint8Array([1, 2, 3]));\n * const value = getBytesDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBytesEncoder}\n * @see {@link getBytesDecoder}\n */\nexport function getBytesCodec(): VariableSizeCodec {\n return combineCodec(getBytesEncoder(), getBytesDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n containsBytes,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getBase16Decoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__CODECS__INVALID_CONSTANT, SolanaError } from '@solana/errors';\n\n/**\n * Returns an encoder that always writes a predefined constant byte sequence.\n *\n * This encoder ensures that encoding always produces the specified byte array,\n * ignoring any input values.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence that will be written during encoding.\n *\n * @param constant - The predefined byte array to encode.\n * @returns A `FixedSizeEncoder` where `N` is the length of the constant.\n *\n * @example\n * Encoding a constant magic number.\n * ```ts\n * const encoder = getConstantEncoder(new Uint8Array([1, 2, 3, 4]));\n *\n * const bytes = encoder.encode();\n * // 0x01020304\n * // └──────┘ The predefined 4-byte constant.\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantEncoder(\n constant: TConstant,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: constant.length,\n write: (_, bytes, offset) => {\n bytes.set(constant, offset);\n return offset + constant.length;\n },\n });\n}\n\n/**\n * Returns a decoder that verifies a predefined constant byte sequence.\n *\n * This decoder reads the next bytes and checks that they match the provided constant.\n * If the bytes differ, it throws an error.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence expected during decoding.\n *\n * @param constant - The predefined byte array to verify.\n * @returns A `FixedSizeDecoder` where `N` is the length of the constant.\n *\n * @example\n * Decoding a constant magic number.\n * ```ts\n * const decoder = getConstantDecoder(new Uint8Array([1, 2, 3]));\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Passes\n * decoder.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantDecoder(\n constant: TConstant,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: constant.length,\n read: (bytes, offset) => {\n const base16 = getBase16Decoder();\n if (!containsBytes(bytes, constant, offset)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {\n constant,\n data: bytes,\n hexConstant: base16.decode(constant),\n hexData: base16.decode(bytes),\n offset,\n });\n }\n return [undefined, offset + constant.length];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes a predefined constant byte sequence.\n *\n * - **Encoding:** Always writes the specified byte array.\n * - **Decoding:** Asserts that the next bytes match the constant, throwing an error if they do not.\n *\n * This is useful for encoding fixed byte patterns required in a binary format or to use in\n * conjunction with other codecs such as {@link getHiddenPrefixCodec} or {@link getHiddenSuffixCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence to encode and verify during decoding.\n *\n * @param constant - The predefined byte array to encode and assert during decoding.\n * @returns A `FixedSizeCodec` where `N` is the length of the constant.\n *\n * @example\n * Encoding and decoding a constant magic number.\n * ```ts\n * const codec = getConstantCodec(new Uint8Array([1, 2, 3]));\n *\n * codec.encode(); // 0x010203\n * codec.decode(new Uint8Array([1, 2, 3])); // Passes\n * codec.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @remarks\n * Separate {@link getConstantEncoder} and {@link getConstantDecoder} functions are available.\n *\n * ```ts\n * const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode();\n * getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes);\n * ```\n *\n * @see {@link getConstantEncoder}\n * @see {@link getConstantDecoder}\n */\nexport function getConstantCodec(\n constant: TConstant,\n): FixedSizeCodec {\n return combineCodec(getConstantEncoder(constant), getConstantDecoder(constant));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for a tuple that can be encoded using a tuple codec.\n *\n * This type maps each provided item encoder to its corresponding value type.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n */\ntype GetEncoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for a tuple that can be decoded using a tuple codec.\n *\n * This type maps each provided item decoder to its corresponding value type.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n */\ntype GetDecoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for tuples.\n *\n * This encoder serializes a fixed-size array (tuple) by encoding its items\n * sequentially using the provided item encoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n *\n * @param items - The encoders for each item in the tuple.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples.\n *\n * @example\n * Encoding a tuple with 2 items.\n * ```ts\n * const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]);\n *\n * const bytes = encoder.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleEncoder[]>(\n items: TItems,\n): FixedSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): VariableSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): Encoder> {\n type TFrom = GetEncoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (value: TFrom, bytes, offset) => {\n assertValidNumberOfItemsForCodec('tuple', items.length, value.length);\n items.forEach((item, index) => {\n offset = item.write(value[index], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for tuples.\n *\n * This decoder deserializes a fixed-size array (tuple) by decoding its items\n * sequentially using the provided item decoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n *\n * @param items - The decoders for each item in the tuple.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples.\n *\n * @example\n * Decoding a tuple with 2 items.\n * ```ts\n * const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]);\n *\n * const tuple = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // ['Alice', 42]\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleDecoder[]>(\n items: TItems,\n): FixedSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): VariableSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): Decoder> {\n type TTo = GetDecoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const values = [] as Array & TTo;\n items.forEach(item => {\n const [newValue, newOffset] = item.read(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding tuples.\n *\n * This codec serializes tuples by encoding and decoding each item sequentially.\n *\n * Unlike the {@link getArrayCodec} codec, each item in the tuple has its own codec\n * and, therefore, can be of a different type.\n *\n * @typeParam TItems - An array of codecs, each corresponding to a tuple element.\n *\n * @param items - The codecs for each item in the tuple.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples.\n *\n * @example\n * Encoding and decoding a tuple with 2 items.\n * ```ts\n * const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]);\n *\n * const bytes = codec.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n *\n * const tuple = codec.decode(bytes);\n * // ['Alice', 42]\n * ```\n *\n * @remarks\n * Separate {@link getTupleEncoder} and {@link getTupleDecoder} functions are available.\n *\n * ```ts\n * const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()])\n * .encode(['Alice', 42]);\n *\n * const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()])\n * .decode(bytes);\n * ```\n *\n * @see {@link getTupleEncoder}\n * @see {@link getTupleDecoder}\n */\nexport function getTupleCodec[]>(\n items: TItems,\n): FixedSizeCodec, GetDecoderTypeFromItems & GetEncoderTypeFromItems>;\nexport function getTupleCodec[]>(\n items: TItems,\n): VariableSizeCodec<\n GetEncoderTypeFromItems,\n GetDecoderTypeFromItems & GetEncoderTypeFromItems\n>;\nexport function getTupleCodec[]>(\n items: TItems,\n): Codec, GetDecoderTypeFromItems & GetEncoderTypeFromItems> {\n return combineCodec(\n getTupleEncoder(items),\n getTupleDecoder(items) as Decoder & GetEncoderTypeFromItems>,\n );\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n Offset,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\nimport { DrainOuterGeneric, getMaxSize, maxCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for values that can be encoded using a union codec.\n *\n * This type maps the provided variant encoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n */\ntype GetEncoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Encoder ? TFrom : never;\n}>[number];\n\n/**\n * Infers the TypeScript type for values that can be decoded using a union codec.\n *\n * This type maps the provided variant decoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n */\ntype GetDecoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Decoder ? TFrom : never;\n}>[number];\n\ntype UnionEncoder[]> = TVariants extends readonly FixedSizeEncoder[]\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder[]> = TVariants extends readonly FixedSizeDecoder[]\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec[]> = TVariants extends readonly FixedSizeCodec[]\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for union types.\n *\n * This encoder serializes values by selecting the correct variant encoder\n * based on the `getIndexFromValue` function.\n *\n * Unlike other codecs, this encoder does not store the variant index.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n *\n * @param variants - The encoders for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @returns An `Encoder` for encoding union values.\n *\n * @example\n * Encoding a union of numbers and booleans.\n * ```ts\n * const encoder = getUnionEncoder(\n * [getU16Encoder(), getBooleanEncoder()],\n * value => (typeof value === 'number' ? 0 : 1)\n * );\n *\n * encoder.encode(42);\n * // 0x2a00\n * // └── Encoded number (42) as `u16`\n *\n * encoder.encode(true);\n * // 0x01\n * // └── Encoded boolean (`true`) as `u8`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionEncoder[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const write: Encoder['write'] = (variant, bytes, offset) => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return variants[index].write(variant, bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createEncoder({ fixedSize, write }) as UnionEncoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createEncoder({\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: variant => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return getEncodedSize(variant, variants[index]);\n },\n write,\n }) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for union types.\n *\n * This decoder deserializes values by selecting the correct variant decoder\n * based on the `getIndexFromBytes` function.\n *\n * Unlike other codecs, this decoder does not assume a stored discriminator.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n *\n * @param variants - The decoders for each variant of the union.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Decoder` for decoding union values.\n *\n * @example\n * Decoding a union of numbers and booleans.\n * ```ts\n * const decoder = getUnionDecoder(\n * [getU16Decoder(), getBooleanDecoder()],\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * decoder.decode(new Uint8Array([0x01])); // true\n * // Type is inferred as `number | boolean`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionDecoder[]>(\n variants: TVariants,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionDecoder {\n type TTo = GetDecoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const read: Decoder['read'] = (bytes, offset) => {\n const index = getIndexFromBytes(bytes, offset);\n assertValidVariantIndex(variants, index);\n return variants[index].read(bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createDecoder({ fixedSize, read }) as UnionDecoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createDecoder({ ...(maxSize !== null ? { maxSize } : {}), read }) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding union types.\n *\n * This codec serializes and deserializes union values by selecting the correct variant\n * based on the provided index functions.\n *\n * Unlike the {@link getDiscriminatedUnionCodec}, this codec does not assume a stored\n * discriminator and must be used with an explicit mechanism for managing discriminators.\n *\n * @typeParam TVariants - An array of codecs, each corresponding to a union variant.\n *\n * @param variants - The codecs for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Codec` for encoding and decoding union values.\n *\n * @example\n * Encoding and decoding a union of numbers and booleans.\n * ```ts\n * const codec = getUnionCodec(\n * [getU16Codec(), getBooleanCodec()],\n * value => (typeof value === 'number' ? 0 : 1),\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * const bytes1 = codec.encode(42); // 0x2a00\n * const value1: number | boolean = codec.decode(bytes1); // 42\n *\n * const bytes2 = codec.encode(true); // 0x01\n * const value2: number | boolean = codec.decode(bytes2); // true\n * ```\n *\n * @remarks\n * If you need a codec that includes a stored discriminator,\n * consider using {@link getDiscriminatedUnionCodec}.\n *\n * Separate {@link getUnionEncoder} and {@link getUnionDecoder} functions are also available.\n *\n * ```ts\n * const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42);\n * const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes);\n * ```\n *\n * @see {@link getUnionEncoder}\n * @see {@link getUnionDecoder}\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getUnionCodec[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionCodec {\n return combineCodec(\n getUnionEncoder(variants, getIndexFromValue),\n getUnionDecoder(variants as readonly Decoder[], getIndexFromBytes) as Decoder<\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction assertValidVariantIndex(variants: readonly unknown[], index: number) {\n if (typeof variants[index] === 'undefined') {\n throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {\n maxRange: variants.length - 1,\n minRange: 0,\n variant: index,\n });\n }\n}\n\nfunction getUnionFixedSize | Encoder)[]>(variants: TVariants) {\n if (variants.length === 0) return 0;\n if (!isFixedSize(variants[0])) return null;\n const variantSize = variants[0].fixedSize;\n const sameSizedVariants = variants.every(variant => isFixedSize(variant) && variant.fixedSize === variantSize);\n return sameSizedVariants ? variantSize : null;\n}\n\nfunction getUnionMaxSize | Encoder)[]>(variants: TVariants) {\n return maxCodecSizes(variants.map(variant => getMaxSize(variant)));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SolanaError } from '@solana/errors';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { DrainOuterGeneric } from './utils';\n\n/**\n * Represents a discriminated union using a specific discriminator property.\n *\n * A discriminated union is a TypeScript-friendly way to represent Rust-like enums.\n * Each variant in the union is distinguished by a shared discriminator property.\n *\n * @typeParam TDiscriminatorProperty - The name of the discriminator property.\n * @typeParam TDiscriminatorValue - The type of the discriminator value.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant\n * | { __kind: 'Write'; fields: [string] } // Tuple variant\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant\n * ```\n */\nexport type DiscriminatedUnion<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorValue extends string = string,\n> = {\n [P in TDiscriminatorProperty]: TDiscriminatorValue;\n};\n\n/**\n * Extracts a variant from a discriminated union based on its discriminator value.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type ClickEvent = GetDiscriminatedUnionVariant;\n * // -> { __kind: 'Move'; x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariant<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Extract>;\n\n/**\n * Extracts a variant from a discriminated union without its discriminator property.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type MoveContent = GetDiscriminatedUnionVariantContent;\n * // -> { x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariantContent<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Omit, TDiscriminatorProperty>;\n\n/**\n * Defines the configuration for discriminated union codecs.\n *\n * This configuration controls how the discriminator is stored and named.\n *\n * @typeParam TDiscriminatorProperty - The property name of the discriminator.\n * @typeParam TDiscriminatorSize - The codec used for the discriminator prefix.\n */\nexport type DiscriminatedUnionCodecConfig<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorSize = NumberCodec | NumberDecoder | NumberEncoder,\n> = {\n /**\n * The property name of the discriminator.\n * @defaultValue `__kind`\n */\n discriminator?: TDiscriminatorProperty;\n /**\n * The codec used to encode/decode the discriminator prefix.\n * @defaultValue `u8` prefix\n */\n size?: TDiscriminatorSize;\n};\n\ntype DiscriminatorValue = bigint | boolean | number | string | null | undefined;\ntype Variants = readonly (readonly [DiscriminatorValue, T])[];\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\ntype GetEncoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Encoder\n ? TFrom extends object\n ? TFrom\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype GetDecoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Decoder\n ? TTo extends object\n ? TTo\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype UnionEncoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for discriminated unions.\n *\n * This encoder serializes objects that follow the discriminated union pattern\n * by prefixing them with a numerical discriminator that represents their variant.\n *\n * Unlike {@link getUnionEncoder}, this encoder automatically extracts and processes\n * the discriminator property (default: `__kind`) from each variant.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant encoders as `[discriminator, encoder]` pairs.\n * @param config - Configuration options for encoding.\n * @returns An `Encoder` for encoding discriminated union objects.\n *\n * @example\n * Encoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageEncoder = getDiscriminatedUnionEncoder([\n * ['Quit', getUnitEncoder()],\n * ['Write', getStructEncoder([['fields', getTupleEncoder([addCodecSizePrefix(getUtf8Encoder(), getU32Encoder())])]])],\n * ['Move', getStructEncoder([['x', getI32Encoder()], ['y', getI32Encoder()]])]\n * ]);\n *\n * messageEncoder.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionEncoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const discriminatorProperty = (config.discriminator ?? '__kind') as TDiscriminatorProperty;\n const prefix = config.size ?? getU8Encoder();\n return getUnionEncoder(\n variants.map(([, variant], index) =>\n transformEncoder(getTupleEncoder([prefix, variant]), (value: TFrom): [number, TFrom] => [index, value]),\n ),\n value => getVariantDiscriminator(variants, value[discriminatorProperty]),\n ) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for discriminated unions.\n *\n * This decoder deserializes objects that follow the discriminated union pattern\n * by **reading a numerical discriminator** and mapping it to the corresponding variant.\n *\n * Unlike {@link getUnionDecoder}, this decoder automatically inserts the discriminator\n * property (default: `__kind`) into the decoded object.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant decoders as `[discriminator, decoder]` pairs.\n * @param config - Configuration options for decoding.\n * @returns A `Decoder` for decoding discriminated union objects.\n *\n * @example\n * Decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageDecoder = getDiscriminatedUnionDecoder([\n * ['Quit', getUnitDecoder()],\n * ['Write', getStructDecoder([['fields', getTupleDecoder([addCodecSizePrefix(getUtf8Decoder(), getU32Decoder())])]])],\n * ['Move', getStructDecoder([['x', getI32Decoder()], ['y', getI32Decoder()]])]\n * ]);\n *\n * messageDecoder.decode(new Uint8Array([0x02,0x05,0x00,0x00,0x00,0x06,0x00,0x00,0x00]));\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionDecoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionDecoder {\n const discriminatorProperty = config.discriminator ?? '__kind';\n const prefix = config.size ?? getU8Decoder();\n return getUnionDecoder(\n variants.map(([discriminator, variant]) =>\n transformDecoder(getTupleDecoder([prefix, variant]), ([, value]) => ({\n [discriminatorProperty]: discriminator,\n ...value,\n })),\n ),\n (bytes, offset) => Number(prefix.read(bytes, offset)[0]),\n ) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding {@link DiscriminatedUnion}.\n *\n * A {@link DiscriminatedUnion} is a TypeScript representation of Rust-like enums, where\n * each variant is distinguished by a discriminator field (default: `__kind`).\n *\n * This codec inserts a numerical prefix to represent the variant index.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant codecs as `[discriminator, codec]` pairs.\n * @param config - Configuration options for encoding/decoding.\n * @returns A `Codec` for encoding and decoding discriminated union objects.\n *\n * @example\n * Encoding and decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Quit', getUnitCodec()],\n * ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],\n * ['Move', getStructCodec([['x', getI32Codec()], ['y', getI32Codec()]])]\n * ]);\n *\n * messageCodec.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n *\n * const value = messageCodec.decode(bytes);\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @example\n * Using a `u32` discriminator instead of `u8`.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { size: getU32Codec() });\n *\n * codec.encode({ __kind: 'Quit' });\n * // 0x00000000\n * // └------┘ 4-byte discriminator (Index 0)\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00]));\n * // { __kind: 'Quit' }\n * ```\n *\n * @example\n * Customizing the discriminator property.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { discriminator: 'message' });\n *\n * codec.encode({ message: 'Quit' }); // 0x00\n * codec.decode(new Uint8Array([0x00])); // { message: 'Quit' }\n * ```\n *\n * @remarks\n * Separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available.\n *\n * ```ts\n * const bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' });\n * const message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes);\n * ```\n *\n * @see {@link getDiscriminatedUnionEncoder}\n * @see {@link getDiscriminatedUnionDecoder}\n */\nexport function getDiscriminatedUnionCodec<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionCodec {\n return combineCodec(\n getDiscriminatedUnionEncoder(variants, config) as Encoder<\n GetEncoderTypeFromVariants\n >,\n getDiscriminatedUnionDecoder(variants, config) as Decoder<\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction getVariantDiscriminator | Encoder>>(\n variants: TVariants,\n discriminatorValue: DiscriminatorValue,\n) {\n const discriminator = variants.findIndex(([key]) => discriminatorValue === key);\n if (discriminator < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, {\n value: discriminatorValue,\n variants: variants.map(([key]) => key),\n });\n }\n return discriminator;\n}\n","/**\n * Defines the \"lookup object\" of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * ```\n */\nexport type EnumLookupObject = { [key: string]: number | string };\n\n/**\n * Returns the allowed input for an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionInput = GetEnumFrom; // \"Left\" | \"Right\" | 0 | 1\n * ```\n */\nexport type GetEnumFrom = TEnum[keyof TEnum] | keyof TEnum;\n\n/**\n * Returns all the available variants of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionOutput = GetEnumTo; // 0 | 1\n * ```\n */\nexport type GetEnumTo = TEnum[keyof TEnum];\n\nexport function getEnumStats(constructor: EnumLookupObject) {\n const numericalValues = [...new Set(Object.values(constructor).filter(v => typeof v === 'number'))].sort();\n const enumRecord = Object.fromEntries(Object.entries(constructor).slice(numericalValues.length)) as Record<\n string,\n number | string\n >;\n const enumKeys = Object.keys(enumRecord);\n const enumValues = Object.values(enumRecord);\n const stringValues: string[] = [\n ...new Set([...enumKeys, ...enumValues.filter((v): v is string => typeof v === 'string')]),\n ];\n\n return { enumKeys, enumRecord, enumValues, numericalValues, stringValues };\n}\n\nexport function getEnumIndexFromVariant({\n enumKeys,\n enumValues,\n variant,\n}: {\n enumKeys: string[];\n enumValues: (number | string)[];\n variant: number | string | symbol;\n}): number {\n const valueIndex = findLastIndex(enumValues, value => value === variant);\n if (valueIndex >= 0) return valueIndex;\n return enumKeys.findIndex(key => key === variant);\n}\n\nexport function getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n}: {\n discriminator: number;\n enumKeys: string[];\n enumValues: (number | string)[];\n useValuesAsDiscriminators: boolean;\n}): number {\n if (!useValuesAsDiscriminators) {\n return discriminator >= 0 && discriminator < enumKeys.length ? discriminator : -1;\n }\n return findLastIndex(enumValues, value => value === discriminator);\n}\n\nfunction findLastIndex(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): number {\n let l = array.length;\n while (l--) {\n if (predicate(array[l], l, array)) return l;\n }\n return -1;\n}\n\nexport function formatNumericalValues(values: number[]): string {\n if (values.length === 0) return '';\n let range: [number, number] = [values[0], values[0]];\n const ranges: string[] = [];\n for (let index = 1; index < values.length; index++) {\n const value = values[index];\n if (range[1] + 1 === value) {\n range[1] = value;\n } else {\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n range = [value, value];\n }\n }\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n return ranges.join(', ');\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n EnumLookupObject,\n formatNumericalValues,\n GetEnumFrom,\n getEnumIndexFromDiscriminator,\n getEnumIndexFromVariant,\n getEnumStats,\n GetEnumTo,\n} from './enum-helpers';\n\n/**\n * Defines the configuration options for enum codecs.\n *\n * The `size` option determines the numerical encoding used for the enum's discriminant.\n * By default, enums are stored as a `u8` (1 byte).\n *\n * The `useValuesAsDiscriminators` option allows mapping the actual enum values\n * as discriminators instead of using their positional index.\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type EnumCodecConfig = {\n /**\n * The codec used to encode/decode the enum discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n\n /**\n * If set to `true`, the enum values themselves will be used as discriminators.\n * This is only valid for numerical enum values.\n *\n * @defaultValue `false`\n */\n useValuesAsDiscriminators?: boolean;\n};\n\n/**\n * Returns an encoder for enums.\n *\n * This encoder serializes enums as a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding the enum.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums.\n *\n * @example\n * Encoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const encoder = getEnumEncoder(Direction);\n *\n * encoder.encode(Direction.Up); // 0x00\n * encoder.encode(Direction.Down); // 0x01\n * encoder.encode(Direction.Left); // 0x02\n * encoder.encode(Direction.Right); // 0x03\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeEncoder, 1>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeEncoder>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Encoder> {\n const prefix = config.size ?? getU8Encoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues, stringValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformEncoder(prefix, (variant: GetEnumFrom): number => {\n const index = getEnumIndexFromVariant({ enumKeys, enumValues, variant });\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, {\n formattedNumericalValues: formatNumericalValues(numericalValues),\n numericalValues,\n stringValues,\n variant,\n });\n }\n return useValuesAsDiscriminators ? (enumValues[index] as number) : index;\n });\n}\n\n/**\n * Returns a decoder for enums.\n *\n * This decoder deserializes enums from a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for decoding the enum.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums.\n *\n * @example\n * Decoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const decoder = getEnumDecoder(Direction);\n *\n * decoder.decode(new Uint8Array([0x00])); // Direction.Up\n * decoder.decode(new Uint8Array([0x01])); // Direction.Down\n * decoder.decode(new Uint8Array([0x02])); // Direction.Left\n * decoder.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeDecoder, 1>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeDecoder>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Decoder> {\n const prefix = config.size ?? getU8Decoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformDecoder(prefix, (value: bigint | number): GetEnumTo => {\n const discriminator = Number(value);\n const index = getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n });\n if (index < 0) {\n const validDiscriminators = useValuesAsDiscriminators\n ? numericalValues\n : [...Array(enumKeys.length).keys()];\n throw new SolanaError(SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator,\n formattedValidDiscriminators: formatNumericalValues(validDiscriminators),\n validDiscriminators,\n });\n }\n return enumValues[index] as GetEnumTo;\n });\n}\n\n/**\n * Returns a codec for encoding and decoding enums.\n *\n * This codec serializes enums as a numerical discriminator, allowing them\n * to be efficiently stored and reconstructed from binary data.\n *\n * By default, the discriminator is derived from the positional index\n * of the enum variant, but it can be configured to use the enum's numeric values instead.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding and decoding the enum.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums.\n *\n * @example\n * Encoding and decoding enums using positional indexes.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const codec = getEnumCodec(Direction);\n *\n * codec.encode(Direction.Up); // 0x00\n * codec.encode(Direction.Down); // 0x01\n * codec.encode(Direction.Left); // 0x02\n * codec.encode(Direction.Right); // 0x03\n *\n * codec.decode(new Uint8Array([0x00])); // Direction.Up\n * codec.decode(new Uint8Array([0x01])); // Direction.Down\n * codec.decode(new Uint8Array([0x02])); // Direction.Left\n * codec.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @example\n * Encoding and decoding enums using their numeric values.\n * ```ts\n * enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 }\n * const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true });\n *\n * codec.encode(GameDifficulty.Easy); // 0x01\n * codec.encode(GameDifficulty.Normal); // 0x04\n * codec.encode(GameDifficulty.Hard); // 0x07\n * codec.encode(GameDifficulty.Expert); // 0x09\n *\n * codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy\n * codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal\n * codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard\n * codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert\n * ```\n *\n * Note that, when using values as discriminators, the enum values must be numerical.\n * Otherwise, an error will be thrown.\n *\n * ```ts\n * enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' }\n * getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error.\n * ```\n *\n * @example\n * Using a custom discriminator size.\n * ```ts\n * enum Status { Pending, Approved, Rejected }\n * const codec = getEnumCodec(Status, { size: getU16Codec() });\n *\n * codec.encode(Status.Pending); // 0x0000\n * codec.encode(Status.Approved); // 0x0100\n * codec.encode(Status.Rejected); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending\n * codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved\n * codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected\n * ```\n *\n * @remarks\n * Separate {@link getEnumEncoder} and {@link getEnumDecoder} functions are available.\n *\n * ```ts\n * const bytes = getEnumEncoder(Direction).encode(Direction.Up);\n * const value = getEnumDecoder(Direction).decode(bytes);\n * ```\n *\n * @see {@link getEnumEncoder}\n * @see {@link getEnumDecoder}\n */\nexport function getEnumCodec(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeCodec, GetEnumTo, 1>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetEnumTo, TSize>;\nexport function getEnumCodec(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeCodec, GetEnumTo>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Codec, GetEnumTo> {\n return combineCodec(getEnumEncoder(constructor, config), getEnumDecoder(constructor, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that prefixes encoded values with hidden data.\n *\n * This encoder applies a list of void encoders before encoding the main value.\n * The prefixed data is encoded before the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param prefixedEncoders - A list of void encoders that produce the hidden prefix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden prefix.\n *\n * @example\n * Prefixing a value with constants.\n * ```ts\n * const encoder = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixEncoder(\n encoder: FixedSizeEncoder,\n prefixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([...prefixedEncoders, encoder]) as Encoder,\n (value: TFrom) => [...prefixedEncoders.map(() => undefined), value] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden prefixed data before decoding the main value.\n *\n * This decoder applies a list of void decoders before decoding the main value.\n * The prefixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param prefixedDecoders - A list of void decoders that produce the hidden prefix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden prefix.\n *\n * @example\n * Decoding a value with prefixed constants.\n * ```ts\n * const decoder = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 0x48, 0x65, 0x6C, 0x6C, 0x6F]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixDecoder(\n decoder: FixedSizeDecoder,\n prefixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([...prefixedDecoders, decoder]) as Decoder,\n tuple => tuple[tuple.length - 1] as TTo,\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden prefix.\n *\n * - **Encoding:** Prefixes the value with hidden data before encoding.\n * - **Decoding:** Skips the hidden prefix before decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param prefixedCodecs - A list of void codecs that produce the hidden prefix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden prefix.\n *\n * @example\n * Encoding and decoding a value with prefixed constants.\n * ```ts\n * const codec = getHiddenPrefixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes before a value, consider using {@link padLeftCodec} instead.\n *\n * Separate {@link getHiddenPrefixEncoder} and {@link getHiddenPrefixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenPrefixEncoder}\n * @see {@link getHiddenPrefixDecoder}\n */\nexport function getHiddenPrefixCodec(\n codec: FixedSizeCodec,\n prefixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenPrefixEncoder(codec, prefixedCodecs), getHiddenPrefixDecoder(codec, prefixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that appends hidden data after the encoded value.\n *\n * This encoder applies a list of void encoders after encoding the main value.\n * The suffixed data is encoded after the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param suffixedEncoders - A list of void encoders that produce the hidden suffix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden suffix.\n *\n * @example\n * Suffixing a value with constants.\n * ```ts\n * const encoder = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixEncoder(\n encoder: FixedSizeEncoder,\n suffixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([encoder, ...suffixedEncoders]) as Encoder,\n (value: TFrom) => [value, ...suffixedEncoders.map(() => undefined)] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden suffixed data after decoding the main value.\n *\n * This decoder applies a list of void decoders after decoding the main value.\n * The suffixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param suffixedDecoders - A list of void decoders that produce the hidden suffix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden suffix.\n *\n * @example\n * Decoding a value with suffixed constants.\n * ```ts\n * const decoder = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F, 1, 2, 3, 4, 5, 6]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixDecoder(\n decoder: FixedSizeDecoder,\n suffixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([decoder, ...suffixedDecoders]) as Decoder,\n tuple => tuple[0],\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden suffix.\n *\n * - **Encoding:** Appends hidden data after encoding the main value.\n * - **Decoding:** Skips the hidden suffix after decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param suffixedCodecs - A list of void codecs that produce the hidden suffix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden suffix.\n *\n * @example\n * Encoding and decoding a value with suffixed constants.\n * ```ts\n * const codec = getHiddenSuffixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes after a value, consider using {@link padRightCodec} instead.\n *\n * Separate {@link getHiddenSuffixEncoder} and {@link getHiddenSuffixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenSuffixEncoder}\n * @see {@link getHiddenSuffixDecoder}\n */\nexport function getHiddenSuffixCodec(\n codec: FixedSizeCodec,\n suffixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenSuffixEncoder(codec, suffixedCodecs), getHiddenSuffixDecoder(codec, suffixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\n/**\n * Defines the configuration options for literal union codecs.\n *\n * A literal union codec encodes values from a predefined set of literals.\n * The `size` option determines the numerical encoding used for the discriminant.\n * By default, literals are stored as a `u8` (1 byte).\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type LiteralUnionCodecConfig = {\n /**\n * The codec used to encode/decode the discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n};\n\ntype Variant = bigint | boolean | number | string | null | undefined;\ntype GetTypeFromVariants = TVariants[number];\n\n/**\n * Returns an encoder for literal unions.\n *\n * This encoder serializes a value from a predefined set of literals\n * as a numerical index representing its position in the `variants` array.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding the literal union.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions.\n *\n * @example\n * Encoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']);\n *\n * sizeEncoder.encode('small'); // 0x00\n * sizeEncoder.encode('medium'); // 0x01\n * sizeEncoder.encode('large'); // 0x02\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n): FixedSizeEncoder, 1>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeEncoder>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Encoder> {\n const discriminator = config.size ?? getU8Encoder();\n return transformEncoder(discriminator, variant => {\n const index = variants.indexOf(variant);\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, {\n value: variant,\n variants,\n });\n }\n return index;\n });\n}\n\n/**\n * Returns a decoder for literal unions.\n *\n * This decoder deserializes a numerical index into a corresponding\n * value from a predefined set of literals.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for decoding the literal union.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions.\n *\n * @example\n * Decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']);\n *\n * sizeDecoder.decode(new Uint8Array([0x00])); // 'small'\n * sizeDecoder.decode(new Uint8Array([0x01])); // 'medium'\n * sizeDecoder.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n): FixedSizeDecoder, 1>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeDecoder>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Decoder> {\n const discriminator = config.size ?? getU8Decoder();\n return transformDecoder(discriminator, (index: bigint | number) => {\n if (index < 0 || index >= variants.length) {\n throw new SolanaError(SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator: index,\n maxRange: variants.length - 1,\n minRange: 0,\n });\n }\n return variants[Number(index)];\n });\n}\n\n/**\n * Returns a codec for encoding and decoding literal unions.\n *\n * A literal union codec serializes and deserializes values\n * from a predefined set of literals, using a numerical index\n * to represent each value in the `variants` array.\n *\n * This allows efficient storage and retrieval of common\n * predefined values such as enum-like structures in TypeScript.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding and decoding the literal union.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions.\n *\n * @example\n * Encoding and decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']);\n *\n * sizeCodec.encode('small'); // 0x00\n * sizeCodec.encode('medium'); // 0x01\n * sizeCodec.encode('large'); // 0x02\n *\n * sizeCodec.decode(new Uint8Array([0x00])); // 'small'\n * sizeCodec.decode(new Uint8Array([0x01])); // 'medium'\n * sizeCodec.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @example\n * Encoding and decoding a union of number literals.\n * ```ts\n * type Level = 10 | 20 | 30;\n * const levelCodec = getLiteralUnionCodec([10, 20, 30]);\n *\n * levelCodec.encode(10); // 0x00\n * levelCodec.encode(20); // 0x01\n * levelCodec.encode(30); // 0x02\n *\n * levelCodec.decode(new Uint8Array([0x00])); // 10\n * levelCodec.decode(new Uint8Array([0x01])); // 20\n * levelCodec.decode(new Uint8Array([0x02])); // 30\n * ```\n *\n * @example\n * Using a custom discriminator size with different variant types.\n * ```ts\n * type MaybeBoolean = false | true | \"either\";\n * const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n * codec.encode('either'); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * codec.decode(new Uint8Array([0x02, 0x00])); // 'either'\n * ```\n *\n * @remarks\n * Separate {@link getLiteralUnionEncoder} and {@link getLiteralUnionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green');\n * const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes);\n * ```\n *\n * @see {@link getLiteralUnionEncoder}\n * @see {@link getLiteralUnionDecoder}\n */\nexport function getLiteralUnionCodec(\n variants: TVariants,\n): FixedSizeCodec, GetTypeFromVariants, 1>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetTypeFromVariants, TSize>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeCodec>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Codec> {\n return combineCodec(getLiteralUnionEncoder(variants, config), getLiteralUnionDecoder(variants, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Defines the configuration options for map codecs.\n *\n * The `size` option determines how the number of entries in the map is stored.\n * It can be:\n * - A {@link NumberCodec} to prefix the map with its size.\n * - A fixed number of entries.\n * - `'remainder'`, which infers the number of entries based on the remaining bytes.\n * This option is only available for fixed-size keys and values.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used for the size prefix.\n */\nexport type MapCodecConfig = {\n /**\n * The size of the map.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for maps.\n *\n * This encoder serializes maps where the keys and values are encoded\n * using the provided key and value encoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n *\n * @param key - The encoder for the map's keys.\n * @param value - The encoder for the map's values.\n * @param config - Configuration options for encoding the map.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps.\n *\n * @example\n * Encoding a map with a `u32` size prefix.\n * ```ts\n * const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder());\n * const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getMapEncoder(\n key: FixedSizeEncoder,\n value: FixedSizeEncoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config?: MapCodecConfig,\n): VariableSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig = {},\n): Encoder> {\n return transformEncoder(\n getArrayEncoder(getTupleEncoder([key, value]), config as object),\n (map: Map): [TFromKey, TFromValue][] => [...map.entries()],\n );\n}\n\n/**\n * Returns a decoder for maps.\n *\n * This decoder deserializes maps where the keys and values are decoded\n * using the provided key and value decoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The decoder for the map's keys.\n * @param value - The decoder for the map's values.\n * @param config - Configuration options for decoding the map.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps.\n *\n * @example\n * Decoding a map with a `u32` size prefix.\n * ```ts\n * const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder());\n * const map = decoder.decode(new Uint8Array([\n * 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05\n * ]));\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getMapDecoder(\n key: FixedSizeDecoder,\n value: FixedSizeDecoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config?: MapCodecConfig,\n): VariableSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig = {},\n): Decoder> {\n return transformDecoder(\n getArrayDecoder(getTupleDecoder([key, value]), config as object) as Decoder<[TToKey, TToValue][]>,\n (entries: [TToKey, TToValue][]): Map => new Map(entries),\n );\n}\n\n/**\n * Returns a codec for encoding and decoding maps.\n *\n * This codec serializes maps where the key/value pairs are encoded\n * and decoded one after another using the provided key and value codecs.\n * The number of entries is determined by the `size` configuration and\n * defaults to a `u32` size prefix.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The codec for the map's keys.\n * @param value - The codec for the map's values.\n * @param config - Configuration options for encoding and decoding the map.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps.\n *\n * @example\n * Encoding and decoding a map with a `u32` size prefix (default).\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec());\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with a `u16` size prefix.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x0200616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 2-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a fixed-size map.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with remainder size.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n * // No size prefix, the size is inferred from the remaining bytes.\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @remarks\n * Separate {@link getMapEncoder} and {@link getMapDecoder} functions are available.\n * ```ts\n * const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]]));\n * const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getMapEncoder}\n * @see {@link getMapDecoder}\n */\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeCodec, Map, 0>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: FixedSizeCodec,\n value: FixedSizeCodec,\n config: MapCodecConfig & { size: number },\n): FixedSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config?: MapCodecConfig,\n): VariableSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig = {},\n): Codec, Map> {\n return combineCodec(getMapEncoder(key, value, config as object), getMapDecoder(key, value, config as object));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for `void` values.\n *\n * This encoder writes nothing to the byte array and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op encoder,\n * such as empty variants in {@link getDiscriminatedUnionEncoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeEncoder`, representing an empty encoder.\n *\n * @example\n * Encoding a `void` value.\n * ```ts\n * getUnitEncoder().encode(undefined); // Produces an empty byte array.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitEncoder(): FixedSizeEncoder {\n return createEncoder({\n fixedSize: 0,\n write: (_value, _bytes, offset) => offset,\n });\n}\n\n/**\n * Returns a decoder for `void` values.\n *\n * This decoder always returns `undefined` and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op decoder,\n * such as empty variants in {@link getDiscriminatedUnionDecoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeDecoder`, representing an empty decoder.\n *\n * @example\n * Decoding a `void` value.\n * ```ts\n * getUnitDecoder().decode(anyBytes); // Returns `undefined`.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitDecoder(): FixedSizeDecoder {\n return createDecoder({\n fixedSize: 0,\n read: (_bytes: ReadonlyUint8Array | Uint8Array, offset) => [undefined, offset],\n });\n}\n\n/**\n * Returns a codec for `void` values.\n *\n * This codec does nothing when encoding or decoding and has a fixed size of 0 bytes.\n * Namely, it always returns `undefined` when decoding and produces an empty byte array when encoding.\n *\n * This can be useful when working with structures that require a no-op codec,\n * such as empty variants in {@link getDiscriminatedUnionCodec}.\n *\n * @returns A `FixedSizeCodec`, representing an empty codec.\n *\n * @example\n * Encoding and decoding a `void` value.\n * ```ts\n * const codec = getUnitCodec();\n *\n * codec.encode(undefined); // Produces an empty byte array.\n * codec.decode(new Uint8Array([])); // Returns `undefined`.\n * ```\n *\n * @example\n * Using unit codecs as empty variants in a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Enter' }\n * | { __kind: 'Leave' }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Enter', getUnitCodec()], // <- No-op codec for empty data\n * ['Leave', getUnitCodec()], // <- No-op codec for empty data\n * ['Move', getStructCodec([...])]\n * ]);\n * ```\n *\n * @remarks\n * Separate {@link getUnitEncoder} and {@link getUnitDecoder} functions are available.\n *\n * ```ts\n * const bytes = getUnitEncoder().encode();\n * const value = getUnitDecoder().decode(bytes);\n * ```\n *\n * @see {@link getUnitEncoder}\n * @see {@link getUnitDecoder}\n */\nexport function getUnitCodec(): FixedSizeCodec {\n return combineCodec(getUnitEncoder(), getUnitDecoder());\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getBooleanDecoder, getBooleanEncoder } from './boolean';\nimport { getConstantDecoder, getConstantEncoder } from './constant';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { getUnitDecoder, getUnitEncoder } from './unit';\n\n/**\n * Defines the configuration options for nullable codecs.\n *\n * This configuration controls how nullable values are encoded and decoded.\n *\n * By default, nullable values are prefixed with a `u8` (0 = `null`, 1 = present).\n * The `noneValue` and `prefix` options allow customizing this behavior.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n * @see {@link getNullableCodec}\n */\nexport type NullableCodecConfig = {\n /**\n * Specifies how `null` values are represented in the encoded data.\n *\n * - By default, `null` values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec.\n * - Custom byte array: `null` values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; `null` values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between `null` and present values.\n *\n * - By default, a `u8` prefix is used (`0 = null`, `1 = present`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines `null`.\n * If no `noneValue` is set, `null` is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values, allowing `null` values to be encoded.\n *\n * This encoder serializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are replaced with the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values.\n *\n * @example\n * Encoding an optional number.\n * ```ts\n * const encoder = getNullableEncoder(getU32Encoder());\n *\n * encoder.encode(null); // 0x00\n * encoder.encode(42); // 0x012a000000\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config: NullableCodecConfig = {},\n): Encoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: TFrom): [boolean, TFrom] => [true, value]),\n ],\n variant => Number(variant !== null),\n );\n}\n\n/**\n * Returns a decoder for optional values, allowing `null` values to be recognized.\n *\n * This decoder deserializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes.\n * - If `noneValue` is a byte array, `null` values match the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values.\n *\n * @example\n * Decoding an optional number.\n * ```ts\n * const decoder = getNullableDecoder(getU32Decoder());\n *\n * decoder.decode(new Uint8Array([0x00])); // null\n * decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config: NullableCodecConfig = {},\n): Decoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => null),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]): TTo => value),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values, allowing `null` values to be handled.\n *\n * This codec serializes and deserializes optional values using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present).\n * This can be customized using a custom number codec or even disabled by setting\n * the `prefix` to `null`.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are represented by the provided constant.\n *\n * For more details on the configuration options, see {@link NullableCodecConfig}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding optional values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values.\n *\n * @example\n * Encoding and decoding an optional number using a `u8` prefix (default).\n * ```ts\n * const codec = getNullableCodec(getU32Codec());\n *\n * codec.encode(null); // 0x00\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' });\n *\n * codec.encode(null); // 0x0000000000\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with zeroes and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), {\n * noneValue: 'zeroes',\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0x00000000\n * codec.encode(42); // 0x2a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0xffff\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([0xff, 0xff])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @example\n * Identifying `null` values by the absence of bytes.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), { prefix: null });\n *\n * codec.encode(null); // Empty bytes\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @remarks\n * Separate {@link getNullableEncoder} and {@link getNullableDecoder} functions are available.\n *\n * ```ts\n * const bytes = getNullableEncoder(getU32Encoder()).encode(42);\n * const value = getNullableDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n */\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config: NullableCodecConfig = {},\n): Codec {\n type ConfigCast = NullableCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getNullableEncoder(item, config as ConfigCast),\n getNullableDecoder(item, config as ConfigCast),\n );\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\n\n/**\n * Defines the configuration options for set codecs.\n *\n * This configuration allows specifying how the size of the set is encoded.\n * The `size` option can be:\n *\n * - A {@link NumberCodec}, {@link NumberEncoder}, or {@link NumberDecoder} to store the size as a prefix.\n * - A fixed number of items, enforcing a strict length.\n * - The string `'remainder'` to infer the set size from the remaining bytes (only for fixed-size items).\n *\n * @typeParam TPrefix - The type used for encoding the size of the set.\n */\nexport type SetCodecConfig = {\n /**\n * The size encoding strategy for the set.\n * @defaultValue Uses a `u32` prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for sets of items.\n *\n * This encoder serializes `Set` values by encoding each item using the provided item encoder.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n *\n * @param item - The encoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns An `Encoder>` for encoding sets of items.\n *\n * @example\n * Encoding a set of `u8` numbers.\n * ```ts\n * const encoder = getSetEncoder(getU8Encoder());\n * const bytes = encoder.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getSetEncoder(\n item: FixedSizeEncoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config?: SetCodecConfig,\n): VariableSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig = {},\n): Encoder> {\n return transformEncoder(getArrayEncoder(item, config as object), (set: Set): TFrom[] => [...set]);\n}\n\n/**\n * Returns a decoder for sets of items.\n *\n * This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder.\n * The number of items is determined by a `u32` size prefix by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The decoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Decoder>` for decoding sets of items.\n *\n * @example\n * Decoding a set of `u8` numbers.\n * ```ts\n * const decoder = getSetDecoder(getU8Decoder());\n * const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // new Set([1, 2, 3])\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetDecoder(\n item: Decoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getSetDecoder(\n item: FixedSizeDecoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getSetDecoder(\n item: Decoder,\n config?: SetCodecConfig,\n): VariableSizeDecoder>;\nexport function getSetDecoder(item: Decoder, config: SetCodecConfig = {}): Decoder> {\n return transformDecoder(getArrayDecoder(item, config as object), (entries: TTo[]): Set => new Set(entries));\n}\n\n/**\n * Returns a codec for encoding and decoding sets of items.\n *\n * This codec serializes `Set` values by encoding each item using the provided item codec.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The codec to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Codec, Set>` for encoding and decoding sets.\n *\n * @example\n * Encoding and decoding a set of `u8` numbers.\n * ```ts\n * const codec = getSetCodec(getU8Codec());\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n *\n * const value = codec.decode(bytes);\n * // new Set([1, 2, 3])\n * ```\n *\n * @example\n * Using a `u16` prefix for size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix indicating 3 items.\n * ```\n *\n * @example\n * Using a fixed-size set.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 3 });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- Exactly 3 items of 1 byte each.\n * ```\n *\n * @example\n * Using remainder to infer set size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remaining bytes.\n * ```\n *\n * @remarks\n * Separate {@link getSetEncoder} and {@link getSetDecoder} functions are available.\n *\n * ```ts\n * const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3]));\n * const value = getSetDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getSetEncoder}\n * @see {@link getSetDecoder}\n */\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeCodec, Set, 0>;\nexport function getSetCodec(\n item: FixedSizeCodec,\n config: SetCodecConfig & { size: number },\n): FixedSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config?: SetCodecConfig,\n): VariableSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig = {},\n): Codec, Set> {\n return combineCodec(getSetEncoder(item, config as object), getSetDecoder(item, config as object));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Represents a collection of named fields used in struct codecs.\n *\n * Each field is defined as a tuple containing:\n * - A string key representing the field name.\n * - A codec used to encode and decode the field's value.\n *\n * @typeParam T - The codec type used for each field.\n */\ntype Fields = readonly (readonly [string, T])[];\n\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\n/**\n * Infers the TypeScript type for an object that can be encoded using a struct codec.\n *\n * This type maps the provided field encoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n */\ntype GetEncoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for an object that can be decoded using a struct codec.\n *\n * This type maps the provided field decoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n */\ntype GetDecoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for custom objects.\n *\n * This encoder serializes an object by encoding its fields sequentially,\n * using the provided field encoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n *\n * @param fields - The name and encoder of each field.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects.\n *\n * @example\n * Encoding a custom struct.\n * ```ts\n * const encoder = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]);\n *\n * const bytes = encoder.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructEncoder>>(\n fields: TFields,\n): FixedSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): VariableSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): Encoder> {\n type TFrom = GetEncoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n fields\n .map(([key, codec]) => getEncodedSize(value[key as keyof TFrom], codec))\n .reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (struct: TFrom, bytes, offset) => {\n fields.forEach(([key, codec]) => {\n offset = codec.write(struct[key as keyof TFrom], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for custom objects.\n *\n * This decoder deserializes an object by decoding its fields sequentially,\n * using the provided field decoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n *\n * @param fields - The name and decoder of each field.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects.\n *\n * @example\n * Decoding a custom struct.\n * ```ts\n * const decoder = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]);\n *\n * const struct = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructDecoder>>(\n fields: TFields,\n): FixedSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): VariableSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): Decoder> {\n type TTo = GetDecoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const struct = {} as TTo;\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.read(bytes, offset);\n offset = newOffset;\n struct[key as keyof TTo] = value;\n });\n return [struct, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding custom objects.\n *\n * This codec serializes objects by encoding and decoding each field sequentially.\n *\n * @typeParam TFields - The fields of the struct, each paired with a codec.\n *\n * @param fields - The name and codec of each field.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects.\n *\n * @example\n * Encoding and decoding a custom struct.\n * ```ts\n * const codec = getStructCodec([\n * ['name', fixCodecSize(getUtf8Codec(), 5)],\n * ['age', getU8Codec()]\n * ]);\n *\n * const bytes = codec.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n *\n * const struct = codec.decode(bytes);\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @remarks\n * Separate {@link getStructEncoder} and {@link getStructDecoder} functions are available.\n *\n * ```ts\n * const bytes = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]).encode({ name: 'Alice', age: 42 });\n *\n * const struct = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getStructEncoder}\n * @see {@link getStructDecoder}\n */\nexport function getStructCodec>>(\n fields: TFields,\n): FixedSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): VariableSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): Codec, GetDecoderTypeFromFields & GetEncoderTypeFromFields> {\n return combineCodec(\n getStructEncoder(fields),\n getStructDecoder(fields) as Decoder & GetEncoderTypeFromFields>,\n );\n}\n","/**\n * An implementation of the Rust `Option` type in JavaScript.\n *\n * In Rust, optional values are represented using `Option`, which can be either:\n * - `Some(T)`, indicating a present value.\n * - `None`, indicating the absence of a value.\n *\n * In JavaScript, this is typically represented as `T | null`. However, this approach fails with nested options.\n * For example, `Option>` in Rust would translate to `T | null | null` in JavaScript, which is equivalent to `T | null`.\n * This means there is no way to differentiate between `Some(None)` and `None`, making nested options impossible.\n *\n * This `Option` type helps solve this by mirroring Rust’s `Option` type.\n *\n * ```ts\n * type Option = Some | None;\n * type Some = { __option: 'Some'; value: T };\n * type None = { __option: 'None' };\n * ```\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Here's how you can create `Option` values.\n *\n * To improve developer experience, helper functions are available.\n * TypeScript can infer the type of `T` or it can be explicitly provided.\n *\n * ```ts\n * // Create an option with a value.\n * some('Hello World');\n * some(123);\n *\n * // Create an empty option.\n * none();\n * none();\n * ```\n *\n * @see {@link Some}\n * @see {@link None}\n * @see {@link some}\n * @see {@link none}\n */\nexport type Option = None | Some;\n\n/**\n * A flexible type that allows working with {@link Option} values or nullable values.\n *\n * It defines a looser type that can be used when encoding {@link Option | Options}.\n * This allows us to pass `null` or the nested value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Accepting both `Option` and `T | null` as input.\n * ```ts\n * function double(value: OptionOrNullable) {\n * const option = isOption(value) ? value : wrapNullable(value);\n * return isSome(option) ? option.value * 2 : 'No value';\n * }\n *\n * double(42); // 84\n * double(some(21)); // 42\n * double(none()); // \"No value\"\n * double(null); // \"No value\"\n * ```\n *\n * @see {@link Option}\n * @see {@link isOption}\n * @see {@link wrapNullable}\n */\nexport type OptionOrNullable = Option | T | null;\n\n/**\n * Represents an {@link Option} that contains a value.\n *\n * This type mirrors Rust’s `Some(T)`, indicating that a value is present.\n *\n * For more details, see {@link Option}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Creating a `Some` value.\n * ```ts\n * const value = some(42);\n * isSome(value); // true\n * isNone(value); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link some}\n * @see {@link isSome}\n */\nexport type Some = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an {@link Option} that contains no value.\n *\n * This type mirrors Rust’s `None`, indicating the absence of a value.\n *\n * For more details, see {@link Option}.\n *\n * @example\n * Creating a `None` value.\n * ```ts\n * const empty = none();\n * isNone(empty); // true\n * isSome(empty); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link none}\n * @see {@link isNone}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} that contains a value.\n *\n * This function explicitly wraps a value in an {@link Option} type.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param value - The value to wrap in an {@link Option}.\n * @returns An {@link Option} containing the provided value.\n *\n * @example\n * Wrapping a value in an `Option`.\n * ```ts\n * const option = some('Hello');\n * option.value; // \"Hello\"\n * isOption(option); // true\n * isSome(option); // true\n * isNone(option); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const some = (value: T): Option => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} that contains no value.\n *\n * This function explicitly represents an absent value.\n *\n * @typeParam T - The type of the expected absent value.\n *\n * @returns An {@link Option} containing no value.\n *\n * @example\n * Creating an empty `Option`.\n * ```ts\n * const empty = none();\n * isOption(empty); // true\n * isSome(empty); // false\n * isNone(empty); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const none = (): Option => ({ __option: 'None' });\n\n/**\n * Checks whether the given value is an {@link Option}.\n *\n * This function determines whether an input follows the `Option` structure.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param input - The value to check.\n * @returns `true` if the value is an {@link Option}, `false` otherwise.\n *\n * @example\n * Checking for `Option` values.\n * ```ts\n * isOption(some(42)); // true\n * isOption(none()); // true\n * isOption(42); // false\n * isOption(null); // false\n * isOption(\"anything else\"); // false\n * ```\n *\n * @see {@link Option}\n */\nexport const isOption = (input: unknown): input is Option =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Checks whether the given {@link Option} contains a value.\n *\n * This function acts as a type guard, ensuring the value is a {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link Some}, `false` otherwise.\n *\n * @example\n * Checking for `Some` values.\n * ```ts\n * isSome(some(42)); // true\n * isSome(none()); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const isSome = (option: Option): option is Some => option.__option === 'Some';\n\n/**\n * Checks whether the given {@link Option} contains no value.\n *\n * This function acts as a type guard, ensuring the value is a {@link None}.\n *\n * @typeParam T - The type of the expected value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link None}, `false` otherwise.\n *\n * @example\n * Checking for `None` values.\n * ```ts\n * isNone(some(42)); // false\n * isNone(none()); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const isNone = (option: Option): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option}, returning its contained value or a fallback.\n *\n * This function extracts the value `T` from an `Option` type.\n * - If the option is {@link Some}, it returns the contained value `T`.\n * - If the option is {@link None}, it returns the fallback value `U`, which defaults to `null`.\n *\n * @typeParam T - The type of the contained value.\n * @typeParam U - The type of the fallback value (defaults to `null`).\n *\n * @param option - The {@link Option} to unwrap.\n * @param fallback - A function that provides a fallback value if the option is {@link None}.\n * @returns The contained value if {@link Some}, otherwise the fallback value.\n *\n * @example\n * Unwrapping an `Option` with no fallback.\n * ```ts\n * unwrapOption(some('Hello World')); // \"Hello World\"\n * unwrapOption(none()); // null\n * ```\n *\n * @example\n * Providing a custom fallback value.\n * ```ts\n * unwrapOption(some('Hello World'), () => 'Default'); // \"Hello World\"\n * unwrapOption(none(), () => 'Default'); // \"Default\"\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport function unwrapOption(option: Option): T | null;\nexport function unwrapOption(option: Option, fallback: () => U): T | U;\nexport function unwrapOption(option: Option, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n *\n * - If the input value is `null`, this function returns {@link None}.\n * - Otherwise, it wraps the value in {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param nullable - The nullable value to wrap.\n * @returns An {@link Option} wrapping the value.\n *\n * @example\n * Wrapping nullable values.\n * ```ts\n * wrapNullable('Hello World'); // Option (Some)\n * wrapNullable(null); // Option (None)\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport const wrapNullable = (nullable: T | null): Option => (nullable !== null ? some(nullable) : none());\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getUnionDecoder,\n getUnionEncoder,\n getUnitDecoder,\n getUnitEncoder,\n} from '@solana/codecs-data-structures';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, None, none, Option, OptionOrNullable, Some, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/**\n * Defines the configuration options for {@link Option} codecs.\n *\n * The `getOptionCodec` function behaves similarly to {@link getNullableCodec}\n * but encodes `Option` types instead of `T | null` types.\n *\n * This configuration controls how {@link None} values are encoded and how presence\n * is determined when decoding.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n * @see {@link getOptionCodec}\n */\nexport type OptionCodecConfig = {\n /**\n * Specifies how {@link None} values are represented in the encoded data.\n *\n * - By default, {@link None} values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec for the item.\n * - Custom byte array: {@link None} values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; {@link None} values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between {@link None} and present values.\n *\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines {@link None}.\n * If no `noneValue` is set, {@link None} is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values using the {@link Option} type.\n *\n * This encoder serializes an {@link OptionOrNullable} value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, {@link None} values are encoded as zeroes.\n * - If `noneValue` is a byte array, {@link None} values are replaced with the provided constant.\n *\n * Unlike {@link getNullableEncoder}, this encoder accepts both {@link Option} and {@link Nullable} values.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values.\n *\n * @example\n * Encoding an optional string.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const encoder = getOptionEncoder(stringCodec);\n *\n * encoder.encode(some('Hi'));\n * encoder.encode('Hi');\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * encoder.encode(none());\n * encoder.encode(null);\n * // 0x00\n * // └-- 1-byte prefix (None).\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder, TSize>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config: OptionCodecConfig = {},\n): Encoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: None | null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: Some | TFrom): [boolean, TFrom] => [\n true,\n isOption(value) && isSome(value) ? value.value : value,\n ]),\n ],\n variant => {\n const option = isOption(variant) ? variant : wrapNullable(variant);\n return Number(isSome(option));\n },\n );\n}\n\n/**\n * Returns a decoder for optional values using the {@link Option} type.\n *\n * This decoder deserializes an `Option` value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes.\n * - If `noneValue` is a byte array, `None` values match the provided constant.\n *\n * Unlike {@link getNullableDecoder}, this decoder always outputs an {@link Option} type.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values.\n *\n * @example\n * Decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const decoder = getOptionDecoder(stringCodec);\n *\n * decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69]));\n * // some('Hi')\n *\n * decoder.decode(new Uint8Array([0x00]));\n * // none()\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder, TSize>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config: OptionCodecConfig = {},\n): Decoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => none()),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value)),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values using the {@link Option} type.\n *\n * This codec serializes and deserializes `Option` values using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `None` values are represented by the provided constant.\n * - If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes.\n *\n * For more details on the configuration options, see {@link OptionCodecConfig}.\n *\n * Note that this behaves similarly to {@link getNullableCodec}, except it\n * encodes {@link OptionOrNullable} values and decodes {@link Option} values.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding option values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values.\n *\n * @example\n * Encoding and decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode(some('Hi'));\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * const noneBytes = codec.encode(none());\n * // 0x00\n * // └-- 1-byte prefix (None).\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding nullable values.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode('Hi'); // 0x01020000004869\n * const noneBytes = codec.encode(null); // 0x00\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding an optional number with a fixed size.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' });\n *\n * const someBytes = codec.encode(some(42)); // 0x012a00\n * const noneBytes = codec.encode(none()); // 0x000000\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding {@link None} values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // 0xffff\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Identifying {@link None} values by the absence of bytes.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { prefix: null });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // new Uint8Array(0)\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @remarks\n * Separate {@link getOptionEncoder} and {@link getOptionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getOptionEncoder(getU32Encoder()).encode(some(42));\n * const value = getOptionDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n */\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec, Option, TSize>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec, Option>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config: OptionCodecConfig = {},\n): Codec, Option> {\n type ConfigCast = OptionCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getOptionEncoder(item, config as ConfigCast),\n getOptionDecoder(item, config as ConfigCast),\n );\n}\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Defines types that should not be recursively unwrapped.\n *\n * These types are preserved as-is when using {@link unwrapOptionRecursively}.\n *\n * @see {@link unwrapOptionRecursively}\n */\ntype UnUnwrappables =\n | Date\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | bigint\n | boolean\n | number\n | string\n | symbol\n | null\n | undefined;\n\n/**\n * A type that recursively unwraps nested {@link Option} types.\n *\n * This type resolves all nested {@link Option} values, ensuring\n * that deeply wrapped values are properly extracted.\n *\n * - If `T` is an {@link Option}, it resolves to the contained value.\n * - If `T` is a known primitive or immutable type, it remains unchanged.\n * - If `T` is an object or array, it recursively unwraps any options found.\n *\n * The fallback type `U` (default: `null`) is used in place of `None` values.\n *\n * @typeParam T - The type to be unwrapped.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @example\n * Resolving nested `Option` types.\n * ```ts\n * UnwrappedOption>>; // string\n * UnwrappedOption; // null\n * ```\n *\n * @example\n * Resolving options inside objects and arrays.\n * ```ts\n * UnwrappedOption<{ a: Some; b: None }>; // { a: number; b: null }\n * UnwrappedOption<[Some, None]>; // [number, null]\n * ```\n *\n * @see {@link unwrapOptionRecursively}\n */\nexport type UnwrappedOption =\n T extends Some\n ? UnwrappedOption\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption }\n : T extends Array\n ? Array>\n : T;\n\n/**\n * Recursively unwraps all nested {@link Option} types within a value.\n *\n * This function traverses a given value and removes all instances\n * of {@link Option}, replacing them with their contained values.\n *\n * - If an {@link Option} is encountered, its value is extracted.\n * - If an array or object is encountered, its elements are traversed recursively.\n * - If `None` is encountered, it is replaced with the fallback value (default: `null`).\n *\n * @typeParam T - The type of the input value.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @param input - The value to unwrap.\n * @param fallback - A function that provides a fallback value for `None` options.\n * @returns The recursively unwrapped value.\n *\n * @example\n * Recursively unwrapping nested options.\n * ```ts\n * unwrapOptionRecursively(some(some('Hello World'))); // \"Hello World\"\n * unwrapOptionRecursively(some(none())); // null\n * ```\n *\n * @example\n * Recursively unwrapping options inside objects and arrays.\n * ```ts\n * unwrapOptionRecursively({\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * });\n * // { a: \"hello\", b: null, c: [{ c1: 42 }, { c2: null }] }\n * ```\n *\n * @example\n * Using a fallback value for `None` options.\n * ```ts\n * unwrapOptionRecursively(\n * {\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * },\n * () => 'Default',\n * );\n * // { a: \"hello\", b: \"Default\", c: [{ c1: 42 }, { c2: \"Default\" }] }\n * ```\n *\n * @remarks\n * This function does not mutate objects or arrays.\n *\n * @see {@link Option}\n * @see {@link UnwrappedOption}\n */\nexport function unwrapOptionRecursively(input: T): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback: () => U): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback?: () => U): UnwrappedOption {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption;\n }\n\n const next = (x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption;\n return (fallback ? fallback() : null) as UnwrappedOption;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption;\n }\n return input as UnwrappedOption;\n}\n","export * from '@solana/codecs-core';\nexport * from '@solana/codecs-data-structures';\nexport * from '@solana/codecs-numbers';\nexport * from '@solana/codecs-strings';\nexport * from '@solana/options';\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","/**\n * A pipeline is a solution that allows you to perform successive transforms of a value using functions. This is useful when building up a transaction message.\n *\n * Until the [pipeline operator](https://github.com/tc39/proposal-pipeline-operator) becomes part of JavaScript you can use this utility to create pipelines.\n *\n * Following common implementations of pipe functions that use TypeScript, this function supports a maximum arity of 10 for type safety.\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```ts\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n *\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * @example Basic\n * ```ts\n * const add = (a, b) => a + b;\n * const add10 = x => add(x, 10);\n * const add100 = x => add(x, 100);\n * const sum = pipe(1, add10, add100);\n * sum === 111; // true\n * ```\n *\n * @example Building a Solana transaction message\n * ```ts\n * const transferTransactionMessage = pipe(\n * // The result of the first expression...\n * createTransactionMessage({ version: 0 }),\n * // ...gets passed as the sole argument to the next function in the pipeline.\n * tx => setTransactionMessageFeePayer(myAddress, tx),\n * // The return value of that function gets passed to the next...\n * tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n * // ...and so on.\n * tx => appendTransactionMessageInstruction(createTransferInstruction(myAddress, toAddress, amountInLamports), tx),\n * );\n * ```\n *\n * @returns The initial value\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n): TInitial;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n): R1;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n): R2;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n): R3;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n): R4;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n): R5;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n): R6;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n): R7;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n): R8;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n): R9;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n /** The function with which to transform the return value of the prior function */\n r9_r10: (r9: R9) => R10,\n): R10;\nexport function pipe(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { AccountLookupMeta, AccountMeta } from './accounts';\n\n/**\n * An instruction destined for a given program.\n *\n * @example\n * ```ts\n * type StakeProgramInstruction = Instruction<'StakeConfig11111111111111111111111111111111'>;\n * ```\n */\nexport interface Instruction<\n TProgramAddress extends string = string,\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n> {\n readonly accounts?: TAccounts;\n readonly data?: ReadonlyUint8Array;\n readonly programAddress: Address;\n}\n\n/**\n * An instruction that loads certain accounts.\n *\n * @example\n * ```ts\n * type InstructionWithTwoAccounts = InstructionWithAccounts<\n * [\n * WritableAccount, // First account\n * RentSysvar, // Second account\n * ]\n * >;\n * ```\n */\nexport interface InstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[],\n> extends Instruction {\n readonly accounts: TAccounts;\n}\n\nexport function isInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): instruction is TInstruction & { programAddress: Address } {\n return instruction.programAddress === programAddress;\n}\n\nexport function assertIsInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): asserts instruction is TInstruction & { programAddress: Address } {\n if (instruction.programAddress !== programAddress) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, {\n actualProgramAddress: instruction.programAddress,\n expectedProgramAddress: programAddress,\n });\n }\n}\n\nexport function isInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithAccounts & TInstruction {\n return instruction.accounts !== undefined;\n}\n\nexport function assertIsInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithAccounts & TInstruction {\n if (instruction.accounts === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, {\n data: instruction.data,\n programAddress: instruction.programAddress,\n });\n }\n}\n\n/**\n * An instruction whose data conforms to a certain type.\n *\n * This is most useful when you have a branded `Uint8Array` that represents a particular\n * instruction's data.\n *\n * @example A type for the \\`AdvanceNonce\\` instruction of the System program\n * ```ts\n * type AdvanceNonceAccountInstruction<\n * TNonceAccountAddress extends string = string,\n * TNonceAuthorityAddress extends string = string,\n * > = Instruction<'11111111111111111111111111111111'> &\n * InstructionWithAccounts<\n * [\n * WritableAccount,\n * ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n * ReadonlySignerAccount,\n * ]\n * > &\n * InstructionWithData;\n * ```\n */\nexport interface InstructionWithData extends Instruction {\n readonly data: TData;\n}\n\nexport function isInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithData & TInstruction {\n return instruction.data !== undefined;\n}\n\nexport function assertIsInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithData & TInstruction {\n if (instruction.data === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, {\n accountAddresses: instruction.accounts?.map(a => a.address),\n programAddress: instruction.programAddress,\n });\n }\n}\n","/**\n * Describes the purpose for which an account participates in a transaction.\n *\n * Every account that participates in a transaction can be read from, but only ones that you mark as\n * writable may be written to, and only ones that you indicate must sign the transaction will gain\n * the privileges associated with signers at runtime.\n *\n * | | `isSigner` | `isWritable` |\n * | ----------------------------- | ---------- | ------------ |\n * | `AccountRole.READONLY` | ❌ | ❌ |\n * | `AccountRole.WRITABLE` | ❌ | ✅ |\n * | `AccountRole.READONLY_SIGNER` | ✅ | ❌ |\n * | `AccountRole.WRITABLE_SIGNER` | ✅ | ✅ |\n */\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\n// Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\n/**\n * @returns An {@link AccountRole} representing the non-signer variant of the supplied role.\n */\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the read-only variant of the supplied role.\n */\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a signer. Also refines the\n * TypeScript type of the supplied role.\n */\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a writable account. Also\n * refines the TypeScript type of the supplied role.\n */\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\n/**\n * Given two {@link AccountRole | AccountRoles}, will return the {@link AccountRole} that grants the\n * highest privileges of both.\n *\n * @example\n * ```ts\n * // Returns `AccountRole.WRITABLE_SIGNER`\n * mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE);\n * ```\n */\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\n/**\n * @returns An {@link AccountRole} representing the signer variant of the supplied role.\n */\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the writable variant of the supplied role.\n */\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { Address, assertIsAddress, getAddressDecoder, getAddressEncoder, isAddress } from '@solana/addresses';\nimport { combineCodec, createEncoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nexport type Blockhash = Brand, 'Blockhash'>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Blockhash} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isBlockhash } from '@solana/rpc-types';\n *\n * if (isBlockhash(blockhash)) {\n * // At this point, `blockhash` has been refined to a\n * // `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsFresh(isValid);\n * } else {\n * setError(`${blockhash} is not a blockhash`);\n * }\n * ```\n */\nexport function isBlockhash(putativeBlockhash: string): putativeBlockhash is Blockhash {\n return isAddress(putativeBlockhash);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as a blockhash, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string is\n * a base58-encoded blockhash.\n *\n * @example\n * ```ts\n * import { assertIsBlockhash } from '@solana/rpc-types';\n *\n * // Imagine a function that determines whether a blockhash is fresh when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const blockhash: string = blockhashInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `blockhash` to `Blockhash`.\n * assertIsBlockhash(blockhash);\n * // At this point, `blockhash` is a `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `blockhash` turned out not to be a base58-encoded blockhash\n * }\n * }\n * ```\n */\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n assertIsAddress(putativeBlockhash);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, error.context);\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, error.context);\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is a blockhash with _coercing_ it to the {@link Blockhash}\n * type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { blockhash } from '@solana/rpc-types';\n *\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash(blockhashFromUserInput)).send();\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good blockhash as a string, it's more efficient to typecast it\n * rather than to use the {@link blockhash} helper, because the helper unconditionally performs\n * validation on its input.\n * >\n * > ```ts\n * > import { Blockhash } from '@solana/rpc-types';\n * >\n * > const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * > ```\n */\nexport function blockhash(putativeBlockhash: string): Blockhash {\n assertIsBlockhash(putativeBlockhash);\n return putativeBlockhash;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded blockhash to a byte array.\n *\n * @example\n * ```ts\n * import { getBlockhashEncoder } from '@solana/rpc-types';\n *\n * const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * const blockhashEncoder = getBlockhashEncoder();\n * const blockhashBytes = blockhashEncoder.encode(blockhash);\n * // Uint8Array(32) [\n * // 136, 123, 44, 249, 43, 19, 60, 14,\n * // 144, 16, 168, 241, 121, 111, 70, 232,\n * // 186, 26, 140, 202, 213, 64, 231, 82,\n * // 179, 66, 103, 237, 52, 117, 217, 93\n * // ]\n * ```\n */\nexport function getBlockhashEncoder(): FixedSizeEncoder {\n const addressEncoder = getAddressEncoder();\n return createEncoder({\n fixedSize: 32,\n write: (value: string, bytes, offset) => {\n assertIsBlockhash(value);\n return addressEncoder.write(value as string as Address, bytes, offset);\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing a blockhash to\n * the base58-encoded representation of that blockhash.\n *\n * @example\n * ```ts\n * import { getBlockhashDecoder } from '@solana/rpc-types';\n *\n * const blockhashBytes = new Uint8Array([\n * 136, 123, 44, 249, 43, 19, 60, 14,\n * 144, 16, 168, 241, 121, 111, 70, 232,\n * 186, 26, 140, 202, 213, 64, 231, 82,\n * 179, 66, 103, 237, 52, 117, 217, 93\n * ]);\n * const blockhashDecoder = getBlockhashDecoder();\n * const blockhash = blockhashDecoder.decode(blockhashBytes); // ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48\n * ```\n */\nexport function getBlockhashDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded blockhash.\n *\n * @see {@link getBlockhashDecoder}\n * @see {@link getBlockhashEncoder}\n */\nexport function getBlockhashCodec(): FixedSizeCodec {\n return combineCodec(getBlockhashEncoder(), getBlockhashDecoder());\n}\n\nexport function getBlockhashComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","export type MainnetUrl = string & { '~cluster': 'mainnet' };\nexport type DevnetUrl = string & { '~cluster': 'devnet' };\nexport type TestnetUrl = string & { '~cluster': 'testnet' };\nexport type ClusterUrl = DevnetUrl | MainnetUrl | TestnetUrl | string;\n\n/** Given a URL casts it to a type that is only accepted where mainnet URLs are expected. */\nexport function mainnet(putativeString: string): MainnetUrl {\n return putativeString as MainnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where devnet URLs are expected. */\nexport function devnet(putativeString: string): DevnetUrl {\n return putativeString as DevnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where testnet URLs are expected. */\nexport function testnet(putativeString: string): TestnetUrl {\n return putativeString as TestnetUrl;\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\n\n/**\n * A union of all possible commitment statuses -- each a measure of the network confirmation and\n * stake levels on a particular block.\n *\n * Read more about the statuses themselves, [here](https://docs.solana.com/cluster/commitments).\n */\nexport type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: commitment satisfies never,\n });\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n} from '@solana/codecs-core';\nimport { getU64Decoder, getU64Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * Represents an integer value denominated in Lamports (ie. $1 \\times 10^{-9}$ ◎).\n *\n * It is represented as a `bigint` in client code and an `u64` in server code.\n */\nexport type Lamports = Brand;\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nlet memoizedU64Encoder: FixedSizeEncoder | undefined;\nlet memoizedU64Decoder: FixedSizeDecoder | undefined;\n\nfunction getMemoizedU64Encoder(): FixedSizeEncoder {\n if (!memoizedU64Encoder) memoizedU64Encoder = getU64Encoder();\n return memoizedU64Encoder;\n}\n\nfunction getMemoizedU64Decoder(): FixedSizeDecoder {\n if (!memoizedU64Decoder) memoizedU64Decoder = getU64Decoder();\n return memoizedU64Decoder;\n}\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link Lamports} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isLamports } from '@solana/rpc-types';\n *\n * if (isLamports(lamports)) {\n * // At this point, `lamports` has been refined to a\n * // `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } else {\n * setError(`${lamports} is not a quantity of Lamports`);\n * }\n * ```\n */\nexport function isLamports(putativeLamports: bigint): putativeLamports is Lamports {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\n/**\n * Lamport values returned from the RPC API conform to the type {@link Lamports}. You can use a\n * value of that type wherever a quantity of Lamports is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a quantity of Lamports, from\n * an untrusted network API or user input. To assert that such an arbitrary number is usable as a\n * quantity of Lamports, use this function.\n *\n * ```ts\n * import { assertIsLamports } from '@solana/rpc-types';\n *\n * // Imagine a function that creates a transfer instruction when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `number` type.\n * const lamports: number = parseInt(quantityInput.value, 10);\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `lamports` to `Lamports`.\n * assertIsLamports(lamports);\n * // At this point, `lamports` is a `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } catch (e) {\n * // `lamports` turned out not to validate as a quantity of Lamports.\n * }\n * }\n * ```\n */\nexport function assertIsLamports(putativeLamports: bigint): asserts putativeLamports is Lamports {\n if (putativeLamports < 0 || putativeLamports > maxU64Value) {\n throw new SolanaError(SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE);\n }\n}\n\n/**\n * This helper combines _asserting_ that a number is a possible number of {@link Lamports} with\n * _coercing_ it to the {@link Lamports} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { lamports } from '@solana/rpc-types';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n */\nexport function lamports(putativeLamports: bigint): Lamports {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n\ntype ExtractAdditionalProps = Omit;\n\n/**\n * Returns an encoder that you can use to encode a 64-bit {@link Lamports} value to 8 bytes in\n * little endian order.\n */\nexport function getDefaultLamportsEncoder(): FixedSizeEncoder {\n return getLamportsEncoder(getMemoizedU64Encoder());\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link Lamports} value to a byte array.\n *\n * You must supply a number decoder that will determine how encode the numeric value.\n *\n * @example\n * ```ts\n * import { getLamportsEncoder } from '@solana/rpc-types';\n * import { getU16Encoder } from '@solana/codecs-numbers';\n *\n * const lamports = lamports(256n);\n * const lamportsEncoder = getLamportsEncoder(getU16Encoder());\n * const lamportsBytes = lamportsEncoder.encode(lamports);\n * // Uint8Array(2) [ 0, 1 ]\n * ```\n */\nexport function getLamportsEncoder(\n innerEncoder: TEncoder,\n): Encoder & ExtractAdditionalProps {\n return innerEncoder;\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a 64-bit little endian\n * number to a {@link Lamports} value.\n */\nexport function getDefaultLamportsDecoder(): FixedSizeDecoder {\n return getLamportsDecoder(getMemoizedU64Decoder());\n}\n\n/**\n * Returns a decoder that you can use to convert an array of bytes representing a number to a\n * {@link Lamports} value.\n *\n * You must supply a number decoder that will determine how many bits to use to decode the numeric\n * value.\n *\n * @example\n * ```ts\n * import { getLamportsDecoder } from '@solana/rpc-types';\n * import { getU16Decoder } from '@solana/codecs-numbers';\n *\n * const lamportsBytes = new Uint8Array([ 0, 1 ]);\n * const lamportsDecoder = getLamportsDecoder(getU16Decoder());\n * const lamports = lamportsDecoder.decode(lamportsBytes); // lamports(256n)\n * ```\n */\nexport function getLamportsDecoder(\n innerDecoder: TDecoder,\n): Decoder & ExtractAdditionalProps {\n return transformDecoder(innerDecoder, value =>\n lamports(typeof value === 'bigint' ? value : BigInt(value)),\n ) as Decoder & ExtractAdditionalProps;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a 64-bit {@link Lamports} value.\n *\n * @see {@link getDefaultLamportsDecoder}\n * @see {@link getDefaultLamportsEncoder}\n */\nexport function getDefaultLamportsCodec(): FixedSizeCodec {\n return combineCodec(getDefaultLamportsEncoder(), getDefaultLamportsDecoder());\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link Lamports} value.\n *\n * @see {@link getLamportsDecoder}\n * @see {@link getLamportsEncoder}\n */\nexport function getLamportsCodec(\n innerCodec: TCodec,\n): Codec & ExtractAdditionalProps {\n return combineCodec(getLamportsEncoder(innerCodec), getLamportsDecoder(innerCodec)) as Codec &\n ExtractAdditionalProps;\n}\n","import { SOLANA_ERROR__MALFORMED_BIGINT_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a `bigint` which has been encoded as a string for transit over a transport\n * that does not support `bigint` values natively. The JSON-RPC is such a transport.\n */\nexport type StringifiedBigInt = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `BigInt`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedBigInt } from '@solana/rpc-types';\n *\n * if (isStringifiedBigInt(bigintString)) {\n * // At this point, `bigintString` has been refined to a `StringifiedBigInt`\n * bigintString satisfies StringifiedBigInt; // OK\n * } else {\n * setError(`${bigintString} does not represent a BigInt`);\n * }\n * ```\n */\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `BigInt`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `BigInt`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedBigInt } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents the supply of some token.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `supplyString` to `StringifiedBigInt`.\n * assertIsStringifiedBigInt(supplyString);\n * // At this point, `supplyString` is a `StringifiedBigInt`.\n * supplyString satisfies StringifiedBigInt;\n * } catch (e) {\n * // `supplyString` turned out not to parse as a `BigInt`\n * }\n * ```\n */\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_BIGINT_STRING, {\n value: putativeBigInt,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `BigInt` with _coercing_ it to the\n * {@link StringifiedBigInt} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedBigInt } from '@solana/rpc-types';\n *\n * const supplyString = stringifiedBigInt('1000000000');\n * ```\n */\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","import { SOLANA_ERROR__MALFORMED_NUMBER_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a number which has been encoded as a string for transit over a transport\n * where loss of precision when using the native number type is a concern. The JSON-RPC is such a\n * transport.\n */\nexport type StringifiedNumber = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `Number`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedNumber } from '@solana/rpc-types';\n *\n * if (isStringifiedNumber(numericString)) {\n * // At this point, `numericString` has been refined to a `StringifiedNumber`\n * numericString satisfies StringifiedNumber; // OK\n * } else {\n * setError(`${numericString} does not represent a number`);\n * }\n * ```\n */\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `Number`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `Number`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedNumber } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents some decimal number.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `decimalNumberString` to `StringifiedNumber`.\n * assertIsStringifiedNumber(decimalNumberString);\n * // At this point, `decimalNumberString` is a `StringifiedNumber`.\n * decimalNumberString satisfies StringifiedNumber;\n * } catch (e) {\n * // `decimalNumberString` turned out not to parse as a number.\n * }\n * ```\n */\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_NUMBER_STRING, {\n value: putativeNumber,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `Number` with _coercing_ it to the\n * {@link StringifiedNumber} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedNumber } from '@solana/rpc-types';\n *\n * const decimalNumberString = stringifiedNumber('-42.1');\n * ```\n */\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","import { SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a Unix timestamp in _seconds_.\n *\n * It is represented as a `bigint` in client code and an `i64` in server code.\n */\nexport type UnixTimestamp = Brand;\n\n// Largest possible value to be represented by an i64\nconst maxI64Value = 9223372036854775807n; // 2n ** 63n - 1n\nconst minI64Value = -9223372036854775808n; // -(2n ** 63n)\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link UnixTimestamp} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isUnixTimestamp } from '@solana/rpc-types';\n *\n * if (isUnixTimestamp(timestamp)) {\n * // At this point, `timestamp` has been refined to a\n * // `UnixTimestamp` that can be used anywhere timestamps are expected.\n * timestamp satisfies UnixTimestamp;\n * } else {\n * setError(`${timestamp} is not a Unix timestamp`);\n * }\n * ```\n */\n\nexport function isUnixTimestamp(putativeTimestamp: bigint): putativeTimestamp is UnixTimestamp {\n return putativeTimestamp >= minI64Value && putativeTimestamp <= maxI64Value;\n}\n\n/**\n * Timestamp values returned from the RPC API conform to the type {@link UnixTimestamp}. You can use\n * a value of that type wherever a timestamp is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a timestamp, from an untrusted\n * network API or user input. To assert that such an arbitrary number is usable as a Unix timestamp,\n * use this function.\n *\n * ```ts\n * import { assertIsUnixTimestamp } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents a timestamp.\n * // At this point we know only that it conforms to the `bigint` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `timestamp` to `UnixTimestamp`.\n * assertIsUnixTimestamp(timestamp);\n * // At this point, `timestamp` is a `UnixTimestamp`.\n * timestamp satisfies UnixTimestamp;\n * } catch (e) {\n * // `timestamp` turned out not to be a valid Unix timestamp\n * }\n * ```\n */\nexport function assertIsUnixTimestamp(putativeTimestamp: bigint): asserts putativeTimestamp is UnixTimestamp {\n if (putativeTimestamp < minI64Value || putativeTimestamp > maxI64Value) {\n throw new SolanaError(SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, {\n value: putativeTimestamp,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a `bigint` represents a Unix timestamp with _coercing_ it\n * to the {@link UnixTimestamp} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { unixTimestamp } from '@solana/rpc-types';\n *\n * const timestamp = unixTimestamp(-42n); // Wednesday, December 31, 1969 3:59:18 PM GMT-08:00\n * ```\n */\nexport function unixTimestamp(putativeTimestamp: bigint): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SolanaError } from '@solana/errors';\nimport { type Blockhash, isBlockhash } from '@solana/rpc-types';\n\nimport { ExcludeTransactionMessageLifetime, TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network. The transaction message will continue to be eligible to land\n * until the network considers the `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type BlockhashLifetimeConstraint = Readonly<{\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction message will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction message eligible to land.\n */\n lastValidBlockHeight: bigint;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the age of the blockhash it\n * includes.\n *\n * Such a transaction can only be landed on the network if the current block height of the network\n * is less than or equal to the value of\n * `TransactionMessageWithBlockhashLifetime['lifetimeConstraint']['lastValidBlockHeight']`.\n */\nexport interface TransactionMessageWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * if (isTransactionMessageWithBlockhashLifetime(message)) {\n * // At this point, `message` has been refined to a `TransactionMessageWithBlockhashLifetime`.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.blockhash === 'string' &&\n typeof transactionMessage.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transactionMessage.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * blockhash-based lifetime, from an untrusted network API or user input. Use this function to\n * assert that such a transaction message actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithBlockhashLifetime`.\n * assertIsTransactionMessageWithBlockhashLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `message` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n if (!isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * Given a blockhash and the last block height at which that blockhash is considered usable to land\n * transactions, this method will return a new transaction message having the same type as the one\n * supplied plus the `TransactionMessageWithBlockhashLifetime` type.\n *\n * @example\n * ```ts\n * import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages';\n *\n * const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n * const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, txMessage);\n * ```\n */\nexport function setTransactionMessageLifetimeUsingBlockhash<\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime {\n type ReturnType = ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime;\n\n if (\n 'lifetimeConstraint' in transactionMessage &&\n transactionMessage.lifetimeConstraint &&\n 'blockhash' in transactionMessage.lifetimeConstraint &&\n transactionMessage.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transactionMessage.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transactionMessage as ReturnType;\n }\n\n return Object.freeze({\n ...transactionMessage,\n lifetimeConstraint: Object.freeze(blockhashLifetimeConstraint),\n }) as ReturnType;\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n type Encoder,\n type VariableSizeCodec,\n type VariableSizeDecoder,\n type VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\n\ntype AddressTableLookup = ReturnType[number];\n\nlet memoizedAddressTableLookupEncoder: VariableSizeEncoder | undefined;\nexport function getAddressTableLookupEncoder(): VariableSizeEncoder {\n if (!memoizedAddressTableLookupEncoder) {\n const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<\n readonly number[]\n >;\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder {\n if (!memoizedAddressTableLookupDecoder) {\n const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): VariableSizeCodec {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile/header';\n\ntype MessageHeader = ReturnType;\n\nlet memoizedU8Encoder: FixedSizeEncoder | undefined;\nfunction getMemoizedU8Encoder(): FixedSizeEncoder {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nlet memoizedU8Decoder: FixedSizeDecoder | undefined;\nfunction getMemoizedU8Decoder(): FixedSizeDecoder {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nlet memoizedU8Codec: FixedSizeCodec | undefined;\nfunction getMemoizedU8Codec(): FixedSizeCodec {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nexport function getMessageHeaderEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['numSignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Encoder()],\n ]) as FixedSizeEncoder;\n}\n\nexport function getMessageHeaderDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['numSignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Decoder()],\n ]) as FixedSizeDecoder;\n}\n\nexport function getMessageHeaderCodec(): FixedSizeCodec {\n return getStructCodec([\n ['numSignerAccounts', getMemoizedU8Codec()],\n ['numReadonlySignerAccounts', getMemoizedU8Codec()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Codec()],\n ]) as FixedSizeCodec;\n}\n","import {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile/instructions';\n\ntype Instruction = ReturnType[number];\n\nlet memoizedGetInstructionEncoder: VariableSizeEncoder | undefined;\nexport function getInstructionEncoder(): VariableSizeEncoder {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = transformEncoder, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', addEncoderSizePrefix(getBytesEncoder(), getShortU16Encoder())],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required;\n },\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: VariableSizeDecoder | undefined;\nexport function getInstructionDecoder(): VariableSizeDecoder {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = transformDecoder, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\n 'data',\n addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder()) as VariableSizeDecoder,\n ],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n },\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): VariableSizeCodec {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { AccountMeta, Instruction } from '@solana/instructions';\n\n/**\n * @deprecated Use `TransactionMessage` instead.\n */\n// TODO(#1147) Stop exporting this in a future major version.\nexport type BaseTransactionMessage<\n TVersion extends TransactionVersion = TransactionVersion,\n TInstruction extends Instruction = Instruction,\n> = Readonly<{\n instructions: readonly TInstruction[];\n version: TVersion;\n}>;\n\nexport const MAX_SUPPORTED_TRANSACTION_VERSION = 0;\n\ntype LegacyInstruction = Instruction;\ntype LegacyTransactionMessage = BaseTransactionMessage<'legacy', LegacyInstruction>;\ntype V0TransactionMessage = BaseTransactionMessage<0, Instruction>;\n\nexport type TransactionMessage = LegacyTransactionMessage | V0TransactionMessage;\nexport type TransactionVersion = 'legacy' | 0;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { MAX_SUPPORTED_TRANSACTION_VERSION, TransactionVersion } from '../transaction-message';\n\nconst VERSION_FLAG_MASK = 0x80;\n\n/**\n * Returns an encoder that you can use to encode a {@link TransactionVersion} to a byte array.\n *\n * Legacy messages will produce an empty array and will not advance the offset. Versioned messages\n * will produce an array with a single byte.\n */\nexport function getTransactionVersionEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => (value === 'legacy' ? 0 : 1),\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === 'legacy') {\n return offset;\n }\n if (value < 0 || value > 127) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {\n actualVersion: value,\n });\n }\n\n if (value > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: value,\n });\n }\n bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link TransactionVersion}.\n *\n * When the byte at the current offset is determined to represent a legacy transaction, this decoder\n * will return `'legacy'` and will not advance the offset.\n */\nexport function getTransactionVersionDecoder(): VariableSizeDecoder {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n if (version > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n return [version as TransactionVersion, offset + 1];\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link TransactionVersion}\n *\n * @see {@link getTransactionVersionDecoder}\n * @see {@link getTransactionVersionEncoder}\n */\nexport function getTransactionVersionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n createEncoder,\n Decoder,\n fixDecoderSize,\n fixEncoderSize,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getConstantEncoder,\n getStructDecoder,\n getStructEncoder,\n getUnionEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from '../compile/message';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nfunction getCompiledMessageLegacyEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return getStructEncoder(getPreludeStructEncoderTuple()) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >;\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return transformEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ]) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >,\n value => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n };\n },\n );\n}\n\nfunction getPreludeStructEncoderTuple() {\n const lifetimeTokenEncoder = getUnionEncoder(\n [\n // Use a 32-byte constant encoder for a missing lifetime token (index 0).\n getConstantEncoder(new Uint8Array(32)),\n // Use a 32-byte base58 encoder for a valid lifetime token (index 1).\n fixEncoderSize(getBase58Encoder(), 32),\n ],\n value => (value === undefined ? 0 : 1),\n );\n\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', lifetimeTokenEncoder],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\n ] as const;\n}\n\nfunction getPreludeStructDecoderTuple() {\n return [\n ['version', getTransactionVersionDecoder() as Decoder],\n ['header', getMessageHeaderDecoder()],\n ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', fixDecoderSize(getBase58Decoder(), 32)],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ] as const;\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link CompiledTransactionMessage} to a byte\n * array.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. The byte array produced by this encoder is the message part.\n */\nexport function getCompiledTransactionMessageEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return createEncoder({\n getSizeFromValue: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link CompiledTransactionMessage}.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. You can use this decoder to decode the message part.\n */\nexport function getCompiledTransactionMessageDecoder(): VariableSizeDecoder<\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return transformDecoder(\n getStructDecoder(getPreludeStructDecoderTuple()) as VariableSizeDecoder<\n CompiledTransactionMessage &\n CompiledTransactionMessageWithLifetime & {\n addressTableLookups?: ReturnType;\n }\n >,\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups };\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link CompiledTransactionMessage}\n *\n * @see {@link getCompiledTransactionMessageDecoder}\n * @see {@link getCompiledTransactionMessageEncoder}\n */\nexport function getCompiledTransactionMessageCodec(): VariableSizeCodec<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime),\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return combineCodec(getCompiledTransactionMessageEncoder(), getCompiledTransactionMessageDecoder());\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SolanaError,\n} from '@solana/errors';\nimport {\n AccountLookupMeta,\n AccountMeta,\n AccountRole,\n Instruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = Brand<(AccountLookupMeta | AccountMeta)[], 'OrderedAccounts'>;\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | Record | StaticAccountEntry,\n ) => AddressMap[Address],\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(feePayer: Address, instructions: readonly Instruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set
();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {\n programAddress: instruction.programAddress,\n });\n default:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {\n programAddress: instruction.programAddress,\n });\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress,\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n {\n programAddress: account.address,\n },\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType;\n const orderedAccounts: (AccountLookupMeta | AccountMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Address,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype AddressTableLookup = Readonly<{\n /** The address of the address lookup table account. */\n lookupTableAddress: Address;\n /** Indexes of accounts in a lookup table to load as read-only. */\n readonlyIndexes: readonly number[];\n /** Indexes of accounts in a lookup table to load as writable. */\n writableIndexes: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Address,\n Readonly<{\n [K in keyof Omit]: number[];\n }>\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readonlyIndexes: [],\n writableIndexes: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndexes.push(account.addressIndex);\n } else {\n entry.readonlyIndexes.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype MessageHeader = Readonly<{\n /**\n * The number of accounts in the static accounts list that are neither writable nor\n * signers.\n *\n * Adding this number to `numSignerAccounts` yields the index of the first read-only non-signer\n * account in the static accounts list.\n */\n numReadonlyNonSignerAccounts: number;\n /**\n * The number of read-only accounts in the static accounts list that must sign this\n * transaction.\n *\n * Subtracting this number from `numSignerAccounts` yields the index of the first read-only\n * signer account in the static accounts list.\n */\n numReadonlySignerAccounts: number;\n /**\n * The number of accounts in the static accounts list that must sign this transaction.\n *\n * Subtracting `numReadonlySignerAccounts` from this number yields the number of\n * writable signer accounts in the static accounts list. Writable signer accounts always\n * begin at index zero in the static accounts list.\n *\n * This number itself is the index of the first non-signer account in the static\n * accounts list.\n */\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { Instruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n /**\n * An ordered list of indices that indicate which accounts in the transaction message's\n * accounts list are loaded by this instruction.\n */\n accountIndices?: number[];\n /** The input to the invoked program */\n data?: ReadonlyUint8Array;\n /**\n * The index of the address in the transaction message's accounts list associated with the\n * program to invoke.\n */\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly Instruction[],\n orderedAccounts: OrderedAccounts,\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { TransactionMessageWithBlockhashLifetime, TransactionMessageWithDurableNonceLifetime } from '../index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (\n | TransactionMessageWithBlockhashLifetime\n | TransactionMessageWithDurableNonceLifetime\n )['lifetimeConstraint'],\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { TransactionMessageWithFeePayer } from '../fee-payer';\nimport { TransactionMessageWithLifetime } from '../lifetime';\nimport { BaseTransactionMessage } from '../transaction-message';\nimport { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { getCompiledAddressTableLookups } from './address-table-lookups';\nimport { getCompiledMessageHeader } from './header';\nimport { getCompiledInstructions } from './instructions';\nimport { getCompiledLifetimeToken } from './lifetime-token';\nimport { getCompiledStaticAccounts } from './static-accounts';\n\ntype BaseCompiledTransactionMessage = Readonly<{\n /**\n * Information about the version of the transaction message and the role of the accounts it\n * loads.\n */\n header: ReturnType;\n instructions: ReturnType;\n /** A list of addresses indicating which accounts to load */\n staticAccounts: ReturnType;\n}>;\n\n/**\n * A transaction message in a form suitable for encoding for execution on the network.\n *\n * You can not fully reconstruct a source message from a compiled message without extra information.\n * In particular, supporting details about the lifetime constraint and the concrete addresses of\n * accounts sourced from account lookup tables are lost to compilation.\n */\nexport type CompiledTransactionMessage = LegacyCompiledTransactionMessage | VersionedCompiledTransactionMessage;\n\nexport type CompiledTransactionMessageWithLifetime = Readonly<{\n /**\n * 32 bytes of data observed by the transaction proposed that makes a transaction eligible to\n * land on the network.\n *\n * In the case of a transaction message with a nonce lifetime constraint, this will be the value\n * of the nonce itself. In all other cases this will be a recent blockhash.\n */\n lifetimeToken: ReturnType;\n}>;\n\ntype LegacyCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n /** A list of address tables and the accounts that this transaction loads from them */\n addressTableLookups?: ReturnType;\n version: 0;\n }>;\n\n/**\n * Converts the type of transaction message data structure that you create in your application to\n * the type of transaction message data structure that can be encoded for execution on the network.\n *\n * This is a lossy process; you can not fully reconstruct a source message from a compiled message\n * without extra information. In particular, supporting details about the lifetime constraint and\n * the concrete addresses of accounts sourced from account lookup tables will be lost to\n * compilation.\n *\n * @see {@link decompileTransactionMessage}\n */\nexport function compileTransactionMessage<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): CompiledTransactionMessageFromTransactionMessage {\n type ReturnType = CompiledTransactionMessageFromTransactionMessage;\n\n const addressMap = getAddressMapFromInstructions(\n transactionMessage.feePayer.address,\n transactionMessage.instructions,\n );\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n const lifetimeConstraint = (transactionMessage as Partial).lifetimeConstraint;\n\n return {\n ...(transactionMessage.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n ...(lifetimeConstraint ? { lifetimeToken: getCompiledLifetimeToken(lifetimeConstraint) } : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transactionMessage.instructions, orderedAccounts),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transactionMessage.version,\n } as ReturnType;\n}\n\ntype CompiledTransactionMessageFromTransactionMessage =\n ForwardTransactionMessageLifetime, TTransactionMessage>;\n\ntype ForwardTransactionMessageVersion =\n TTransactionMessage extends Readonly<{ version: 'legacy' }>\n ? LegacyCompiledTransactionMessage\n : VersionedCompiledTransactionMessage;\n\ntype ForwardTransactionMessageLifetime<\n TCompiledTransactionMessage extends CompiledTransactionMessage,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithLifetime\n ? CompiledTransactionMessageWithLifetime & TCompiledTransactionMessage\n : TCompiledTransactionMessage;\n","import { Address } from '@solana/addresses';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction, isSignerRole } from '@solana/instructions';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BaseTransactionMessage, TransactionMessage } from './transaction-message';\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n// Look up the address in lookup tables, return a lookup meta if it is found in any of them\nfunction findAddressInLookupTables(\n address: Address,\n role: AccountRole.READONLY | AccountRole.WRITABLE,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta | undefined {\n for (const [lookupTableAddress, addresses] of Object.entries(addressesByLookupTableAddress)) {\n for (let i = 0; i < addresses.length; i++) {\n if (address === addresses[i]) {\n return {\n address,\n addressIndex: i,\n lookupTableAddress: lookupTableAddress as Address,\n role,\n };\n }\n }\n }\n}\n\ntype TransactionMessageNotLegacy = Exclude;\n\n// Each account can be AccountLookupMeta | AccountMeta\ntype WidenInstructionAccounts =\n TInstruction extends Instruction\n ? Instruction<\n TProgramAddress,\n {\n [K in keyof TAccounts]: TAccounts[K] extends AccountMeta\n ? AccountLookupMeta | AccountMeta\n : TAccounts[K];\n }\n >\n : TInstruction;\n\ntype ExtractAdditionalProps = Omit;\n\ntype WidenTransactionMessageInstructions =\n TTransactionMessage extends BaseTransactionMessage\n ? BaseTransactionMessage> &\n ExtractAdditionalProps<\n TTransactionMessage,\n BaseTransactionMessage>\n >\n : TTransactionMessage;\n\n/**\n * Given a transaction message and a mapping of lookup tables to the addresses stored in them, this\n * function will return a new transaction message with the same instructions but with all non-signer\n * accounts that are found in the given lookup tables represented by an {@link AccountLookupMeta}\n * instead of an {@link AccountMeta}.\n *\n * This means that these accounts will take up less space in the compiled transaction message. This\n * size reduction is most significant when the transaction includes many accounts from the same\n * lookup table.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import {\n * AddressesByLookupTableAddress,\n * compressTransactionMessageUsingAddressLookupTables,\n * } from '@solana/transaction-messages';\n * import { fetchAddressLookupTable } from '@solana-program/address-lookup-table';\n *\n * const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW');\n * const {\n * data: { addresses },\n * } = await fetchAddressLookupTable(rpc, lookupTableAddress);\n * const addressesByAddressLookupTable: AddressesByLookupTableAddress = {\n * [lookupTableAddress]: addresses,\n * };\n *\n * const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables(\n * transactionMessage,\n * addressesByAddressLookupTable,\n * );\n * ```\n */\nexport function compressTransactionMessageUsingAddressLookupTables<\n TTransactionMessage extends TransactionMessageNotLegacy = TransactionMessageNotLegacy,\n>(\n transactionMessage: TTransactionMessage,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): TTransactionMessage | WidenTransactionMessageInstructions {\n const programAddresses = new Set(transactionMessage.instructions.map(ix => ix.programAddress));\n const eligibleLookupAddresses = new Set(\n Object.values(addressesByLookupTableAddress)\n .flatMap(a => a)\n .filter(address => !programAddresses.has(address)),\n );\n const newInstructions: Instruction[] = [];\n let updatedAnyInstructions = false;\n for (const instruction of transactionMessage.instructions) {\n if (!instruction.accounts) {\n newInstructions.push(instruction);\n continue;\n }\n\n const newAccounts: Mutable> = [];\n let updatedAnyAccounts = false;\n for (const account of instruction.accounts) {\n // If the address is already a lookup, is not in any lookup tables, or is a signer role, return as-is\n if (\n 'lookupTableAddress' in account ||\n !eligibleLookupAddresses.has(account.address) ||\n isSignerRole(account.role)\n ) {\n newAccounts.push(account);\n continue;\n }\n\n // We already checked it's in one of the lookup tables\n const lookupMetaAccount = findAddressInLookupTables(\n account.address,\n account.role,\n addressesByLookupTableAddress,\n )!;\n newAccounts.push(Object.freeze(lookupMetaAccount));\n updatedAnyAccounts = true;\n updatedAnyInstructions = true;\n }\n\n newInstructions.push(\n Object.freeze(updatedAnyAccounts ? { ...instruction, accounts: newAccounts } : instruction),\n );\n }\n\n return Object.freeze(\n updatedAnyInstructions ? { ...transactionMessage, instructions: newInstructions } : transactionMessage,\n );\n}\n","import { TransactionMessage, TransactionVersion } from './transaction-message';\nimport { TransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype TransactionConfig = Readonly<{\n version: TVersion;\n}>;\n\ntype EmptyTransactionMessage = Omit<\n Extract,\n 'instructions'\n> &\n TransactionMessageWithinSizeLimit & { instructions: readonly [] };\n\n/**\n * Given a {@link TransactionVersion} this method will return an empty transaction having the\n * capabilities of that version.\n *\n * @example\n * ```ts\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const message = createTransactionMessage({ version: 0 });\n * ```\n */\nexport function createTransactionMessage(\n config: TransactionConfig,\n): EmptyTransactionMessage {\n return Object.freeze({\n instructions: Object.freeze([]),\n version: config.version,\n }) as EmptyTransactionMessage;\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n AccountRole,\n Instruction,\n InstructionWithAccounts,\n InstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport type AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n> = Instruction<'11111111111111111111111111111111'> &\n InstructionWithAccounts<\n readonly [\n WritableAccount,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount | WritableSignerAccount,\n ]\n > &\n InstructionWithData;\n\ntype AdvanceNonceAccountInstructionData = Brand;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\n/**\n * Creates an instruction for the System program to advance a nonce.\n *\n * This instruction is a prerequisite for a transaction with a nonce-based lifetime to be landed on\n * the network. In order to be considered valid, the transaction must meet all of these criteria.\n *\n * 1. Its lifetime constraint must be a {@link NonceLifetimeConstraint}.\n * 2. The value contained in the on-chain account at the address `nonceAccountAddress` must be equal\n * to {@link NonceLifetimeConstraint.nonce} at the time the transaction is landed.\n * 3. The first instruction in that transaction message must be the one returned by this function.\n *\n * You could also use the `getAdvanceNonceAccountInstruction` method of `@solana-program/system`.\n */\nexport function createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n>(\n nonceAccountAddress: Address,\n nonceAuthorityAddress: Address,\n): AdvanceNonceAccountInstruction {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\n/**\n * A type guard that returns `true` if the instruction conforms to the\n * {@link AdvanceNonceAccountInstruction} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAdvanceNonceAccountInstruction } from '@solana/transaction-messages';\n *\n * if (isAdvanceNonceAccountInstruction(message.instructions[0])) {\n * // At this point, the first instruction in the message has been refined to a\n * // `AdvanceNonceAccountInstruction`.\n * setNonceAccountAddress(message.instructions[0].accounts[0].address);\n * } else {\n * setError('The first instruction is not an `AdvanceNonce` instruction');\n * }\n * ```\n */\nexport function isAdvanceNonceAccountInstruction(\n instruction: Instruction,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SolanaError } from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nimport {\n AdvanceNonceAccountInstruction,\n createAdvanceNonceAccountInstruction,\n isAdvanceNonceAccountInstruction,\n} from './durable-nonce-instruction';\nimport { ExcludeTransactionMessageLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = Readonly<{\n readonly nonce: Nonce;\n readonly nonceAccountAddress: Address;\n readonly nonceAuthorityAddress: Address;\n}>;\n\n/** Represents a string that is particularly known to be the base58-encoded value of a nonce. */\nexport type Nonce = Brand;\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network.\n *\n * The transaction message will continue to be eligible to land until the network considers the\n * `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is\n * destroyed, or the nonce value within changes.\n */\nexport type NonceLifetimeConstraint = Readonly<{\n /**\n * A value contained in the related nonce account at the time the transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the value of a nonce it includes.\n *\n * Such a transaction can only be landed on the network if the nonce is known to the network and has\n * not already been used to land a different transaction.\n */\nexport interface TransactionMessageWithDurableNonceLifetime<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n}\n\n/**\n * A helper type to exclude the durable nonce lifetime constraint from a transaction message.\n */\nexport type ExcludeTransactionMessageDurableNonceLifetime =\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? ExcludeTransactionMessageLifetime\n : TTransactionMessage;\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionMessageWithDurableNonceLifetime(message)) {\n * // At this point, `message` has been refined to a\n * // `TransactionMessageWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.nonce === 'string' &&\n transactionMessage.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transactionMessage.instructions[0])\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * nonce-based lifetime, from an untrusted network API or user input. Use this function to assert\n * that such a transaction message actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithDurableNonceLifetime`.\n * assertIsTransactionMessageWithDurableNonceLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `message` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n if (!isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address,\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\n/**\n * Given a nonce, the account where the value of the nonce is stored, and the address of the account\n * authorized to consume that nonce, this method will return a new transaction having the same type\n * as the one supplied plus the {@link TransactionMessageWithDurableNonceLifetime} type.\n *\n * In particular, this method _prepends_ an instruction to the transaction message designed to\n * consume (or 'advance') the nonce in the same transaction whose lifetime is defined by it.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/transaction-messages';\n * import { fetchNonce } from '@solana-program/system';\n *\n * const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ');\n * const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT');\n *\n * const {\n * data: { blockhash },\n * } = await fetchNonce(rpc, nonceAccountAddress);\n * const nonce = blockhash as string as Nonce;\n *\n * const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce(\n * { nonce, nonceAccountAddress, nonceAuthorityAddress },\n * tx,\n * );\n * ```\n */\nexport function setTransactionMessageLifetimeUsingDurableNonce<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig,\n transactionMessage: TTransactionMessage,\n): SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n> {\n type ReturnType = SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n >;\n\n let newInstructions: [\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n\n const firstInstruction = transactionMessage.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (\n isTransactionMessageWithDurableNonceLifetime(transactionMessage) &&\n transactionMessage.lifetimeConstraint.nonce === nonce\n ) {\n return transactionMessage as unknown as ReturnType;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transactionMessage.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions,\n ];\n }\n\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze(newInstructions),\n lifetimeConstraint: Object.freeze({ nonce }),\n }) as unknown as ReturnType;\n}\n\n/**\n * Helper type that transforms a given transaction message type into a new one that has the\n * `AdvanceNonceAccount` instruction as the first instruction and a lifetime constraint\n * representing the nonce value.\n */\ntype SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = TTransactionMessage extends unknown\n ? Omit<\n // 1. The transaction message only grows in size if it currently has a different (or no) lifetime.\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? TTransactionMessage\n : ExcludeTransactionMessageWithinSizeLimit,\n // 2. Remove the instructions array as we are going to replace it with a new one.\n 'instructions'\n > & {\n // 3. Replace or prepend the first instruction with the advance nonce account instruction.\n readonly instructions: TTransactionMessage['instructions'] extends readonly [\n AdvanceNonceAccountInstruction,\n ...infer TTail extends readonly Instruction[],\n ]\n ? readonly [AdvanceNonceAccountInstruction, ...TTail]\n : readonly [\n AdvanceNonceAccountInstruction,\n ...TTransactionMessage['instructions'],\n ];\n // 4. Set the lifetime constraint to the nonce value.\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n }\n : never;\n","import { Address } from '@solana/addresses';\n\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * Represents a transaction message for which a fee payer has been declared. A transaction must\n * conform to this type to be compiled and landed on the network.\n */\nexport interface TransactionMessageWithFeePayer {\n readonly feePayer: Readonly<{ address: Address }>;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Given a base58-encoded address of a system account, this method will return a new transaction\n * message having the same type as the one supplied plus the {@link TransactionMessageWithFeePayer}\n * type.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const myAddress = address('mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu');\n * const txPaidByMe = setTransactionMessageFeePayer(myAddress, tx);\n * ```\n */\nexport function setTransactionMessageFeePayer<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n feePayer: Address,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayer {\n if (\n 'feePayer' in transactionMessage &&\n feePayer === transactionMessage.feePayer?.address &&\n isAddressOnlyFeePayer(transactionMessage.feePayer)\n ) {\n return transactionMessage as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n }\n const out = {\n ...transactionMessage,\n feePayer: Object.freeze({ address: feePayer }),\n };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n}\n\nfunction isAddressOnlyFeePayer(\n feePayer: Partial['feePayer'],\n): feePayer is { address: Address } {\n return (\n !!feePayer &&\n 'address' in feePayer &&\n typeof feePayer.address === 'string' &&\n Object.keys(feePayer).length === 1\n );\n}\n","import { Instruction } from '@solana/instructions';\n\nimport { ExcludeTransactionMessageDurableNonceLifetime } from './durable-nonce';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype AppendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit, 'instructions'> & {\n readonly instructions: readonly [...TTransactionMessage['instructions'], ...TInstructions];\n }\n : never;\n\n/**\n * A helper type to prepend instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype PrependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit<\n ExcludeTransactionMessageWithinSizeLimit>,\n 'instructions'\n > & {\n readonly instructions: readonly [...TInstructions, ...TTransactionMessage['instructions']];\n }\n : never;\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstructions} if you need to append multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { appendTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransactionMessage = appendTransactionMessageInstruction(\n * {\n * data: getUtf8Encoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * transactionMessage,\n * );\n * ```\n */\nexport function appendTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return appendTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstruction} if you only need to append one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { appendTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = appendTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function appendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze([\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ...instructions,\n ] as readonly [...TTransactionMessage['instructions'], ...TInstructions]),\n }) as AppendTransactionMessageInstructions;\n}\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstructions} if you need to prepend multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstruction(\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return prependTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstruction} if you only need to prepend one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return Object.freeze({\n ...(transactionMessage as ExcludeTransactionMessageDurableNonceLifetime),\n instructions: Object.freeze([\n ...instructions,\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ] as readonly [...TInstructions, ...TTransactionMessage['instructions']]),\n }) as unknown as PrependTransactionMessageInstructions;\n}\n","import { Address, assertIsAddress } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\nimport { pipe } from '@solana/functional';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport type { Blockhash } from '@solana/rpc-types';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BlockhashLifetimeConstraint, setTransactionMessageLifetimeUsingBlockhash } from './blockhash';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from './compile';\nimport type { getCompiledAddressTableLookups } from './compile/address-table-lookups';\nimport { createTransactionMessage } from './create-transaction-message';\nimport { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from './durable-nonce';\nimport { isAdvanceNonceAccountInstruction } from './durable-nonce-instruction';\nimport { setTransactionMessageFeePayer, TransactionMessageWithFeePayer } from './fee-payer';\nimport { appendTransactionMessageInstruction } from './instructions';\nimport { TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage, TransactionVersion } from './transaction-message';\n\nfunction getAccountMetas(message: CompiledTransactionMessage): AccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: AccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction getAddressLookupMetas(\n compiledAddressTableLookups: ReturnType,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta[] {\n // check that all message lookups are known\n const compiledAddressTableLookupAddresses = compiledAddressTableLookups.map(l => l.lookupTableAddress);\n const missing = compiledAddressTableLookupAddresses.filter(a => addressesByLookupTableAddress[a] === undefined);\n if (missing.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, {\n lookupTableAddresses: missing,\n });\n }\n\n const readOnlyMetas: AccountLookupMeta[] = [];\n const writableMetas: AccountLookupMeta[] = [];\n\n // we know that for each lookup, knownLookups[lookup.lookupTableAddress] is defined\n for (const lookup of compiledAddressTableLookups) {\n const addresses = addressesByLookupTableAddress[lookup.lookupTableAddress];\n const readonlyIndexes = lookup.readonlyIndexes;\n const writableIndexes = lookup.writableIndexes;\n\n const highestIndex = Math.max(...readonlyIndexes, ...writableIndexes);\n if (highestIndex >= addresses.length) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n {\n highestKnownIndex: addresses.length - 1,\n highestRequestedIndex: highestIndex,\n lookupTableAddress: lookup.lookupTableAddress,\n },\n );\n }\n\n const readOnlyForLookup: AccountLookupMeta[] = readonlyIndexes.map(r => ({\n address: addresses[r],\n addressIndex: r,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.READONLY,\n }));\n readOnlyMetas.push(...readOnlyForLookup);\n\n const writableForLookup: AccountLookupMeta[] = writableIndexes.map(w => ({\n address: addresses[w],\n addressIndex: w,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.WRITABLE,\n }));\n writableMetas.push(...writableForLookup);\n }\n\n return [...writableMetas, ...readOnlyMetas];\n}\n\nfunction convertInstruction(\n instruction: CompiledTransactionMessage['instructions'][0],\n accountMetas: AccountMeta[],\n): Instruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, {\n index: instruction.programAddressIndex,\n });\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return Object.freeze({\n programAddress,\n ...(accounts && accounts.length ? { accounts: Object.freeze(accounts) } : {}),\n ...(data && data.length ? { data } : {}),\n });\n}\n\ntype LifetimeConstraint =\n | BlockhashLifetimeConstraint\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: Instruction,\n lastValidBlockHeight?: bigint,\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts[0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts[2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nexport type DecompileTransactionMessageConfig = {\n /**\n * If the compiled message loads addresses from one or more address lookup tables, you will have\n * to supply a map of those tables to an array of the addresses they contained at the time that\n * the transaction message was constructed.\n *\n * @see {@link decompileTransactionMessageFetchingLookupTables} if you do not already have this.\n */\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n /**\n * If the compiled message has a blockhash-based lifetime constraint, you will have to supply\n * the block height after which that blockhash is no longer valid for use as a lifetime\n * constraint.\n */\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Converts the type of transaction message data structure appropriate for execution on the network\n * to the type of transaction message data structure designed for use in your application.\n *\n * Because compilation is a lossy process, you can not fully reconstruct a source message from a\n * compiled message without extra information. In order to faithfully reconstruct the original\n * source message you will need to supply supporting details about the lifetime constraint and the\n * concrete addresses of any accounts sourced from account lookup tables.\n *\n * @see {@link compileTransactionMessage}\n */\nexport function decompileTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n config?: DecompileTransactionMessageConfig,\n): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime {\n const feePayer = compiledTransactionMessage.staticAccounts[0];\n if (!feePayer) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING);\n }\n\n const accountMetas = getAccountMetas(compiledTransactionMessage);\n const accountLookupMetas =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? getAddressLookupMetas(\n compiledTransactionMessage.addressTableLookups,\n config?.addressesByLookupTableAddress ?? {},\n )\n : [];\n const transactionMetas = [...accountMetas, ...accountLookupMetas];\n\n const instructions: Instruction[] = compiledTransactionMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, transactionMetas),\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledTransactionMessage.lifetimeToken,\n firstInstruction,\n config?.lastValidBlockHeight,\n );\n\n return pipe(\n createTransactionMessage({ version: compiledTransactionMessage.version as TransactionVersion }),\n m => setTransactionMessageFeePayer(feePayer, m),\n m =>\n instructions.reduce(\n (acc, instruction) => appendTransactionMessageInstruction(instruction, acc),\n m as TransactionMessage,\n ),\n m =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionMessageLifetimeUsingBlockhash(lifetimeConstraint, m)\n : setTransactionMessageLifetimeUsingDurableNonce(lifetimeConstraint, m),\n ) as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime;\n}\n","export const ED25519_ALGORITHM_IDENTIFIER =\n // Resist the temptation to convert this to a simple string; As of version 133.0.3, Firefox\n // requires the object form of `AlgorithmIdentifier` and will throw a `DOMException` otherwise.\n Object.freeze({ name: 'Ed25519' });\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\nfunction addPkcs8Header(bytes: ReadonlyUint8Array): ReadonlyUint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 private key for use\n * with other methods in this package that accept\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]));\n * const extractablePrivateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n * ```\n */\nexport async function createPrivateKeyFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const actualLength = bytes.byteLength;\n if (actualLength !== 32) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, {\n actualLength,\n });\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, ED25519_ALGORITHM_IDENTIFIER, extractable, [\n 'sign',\n ]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SolanaError } from '@solana/errors';\n\n/**\n * Given an extractable [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * private key, gets the corresponding public key as a\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey).\n *\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the public\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes, getPublicKeyFromPrivateKey } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n *\n * const publicKey = await getPublicKeyFromPrivateKey(privateKey);\n * const extractablePublicKey = await getPublicKeyFromPrivateKey(privateKey, true);\n * ```\n */\nexport async function getPublicKeyFromPrivateKey(\n privateKey: CryptoKey,\n extractable: boolean = false,\n): Promise {\n assertKeyExporterIsAvailable();\n\n if (privateKey.extractable === false) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, { key: privateKey });\n }\n\n // Export private key.\n const jwk = await crypto.subtle.exportKey('jwk', privateKey);\n\n // Import public key.\n return await crypto.subtle.importKey(\n 'jwk',\n {\n crv /* curve */: 'Ed25519',\n ext /* extractable */: extractable,\n key_ops /* key operations */: ['verify'],\n kty /* key type */: 'OKP' /* octet key pair */,\n x /* public key x-coordinate */: jwk.x,\n },\n 'Ed25519',\n extractable,\n ['verify'],\n );\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder, ReadonlyUint8Array, toArrayBuffer } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\n/**\n * A 64-byte Ed25519 signature as a base58-encoded string.\n */\nexport type Signature = Brand, 'Signature'>;\n/**\n * A 64-byte Ed25519 signature.\n *\n * Whenever you need to verify that a particular signature is, in fact, the one that would have been\n * produced by signing some known bytes using the private key associated with some known public key,\n * use the {@link verifySignature} function in this package.\n */\nexport type SignatureBytes = Brand;\n\nlet base58Encoder: Encoder | undefined;\n\n/**\n * Asserts that an arbitrary string is a base58-encoded Ed25519 signature.\n *\n * Useful when you receive a string from user input or an untrusted network API that you expect to\n * represent an Ed25519 signature (eg. of a transaction).\n *\n * @example\n * ```ts\n * import { assertIsSignature } from '@solana/keys';\n *\n * // Imagine a function that asserts whether a user-supplied signature is valid or not.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const signature: string = signatureInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signature` to `Signature`.\n * assertIsSignature(signature);\n * // At this point, `signature` is a `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * } catch (e) {\n * // `signature` turned out not to be a base58-encoded signature\n * }\n * }\n * ```\n */\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeSignature.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n assertIsSignatureBytes(bytes);\n}\n\n/**\n * Asserts that an arbitrary `ReadonlyUint8Array` is an Ed25519 signature.\n *\n * Useful when you receive a `ReadonlyUint8Array` from an external interface (like the browser wallets' `signMessage` API) that you expect to\n * represent an Ed25519 signature.\n *\n * @example\n * ```ts\n * import { assertIsSignatureBytes } from '@solana/keys';\n *\n * // Imagine a function that verifies a signature.\n * function verifySignature() {\n * // We know only that the input conforms to the `ReadonlyUint8Array` type.\n * const signatureBytes: ReadonlyUint8Array = signatureBytesInput;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signatureBytes` to `SignatureBytes`.\n * assertIsSignatureBytes(signatureBytes);\n * // At this point, `signatureBytes` is a `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } catch (e) {\n * // `signatureBytes` turned out not to be a 64-byte Ed25519 signature\n * }\n * }\n * ```\n */\nexport function assertIsSignatureBytes(\n putativeSignatureBytes: ReadonlyUint8Array,\n): asserts putativeSignatureBytes is SignatureBytes {\n const numBytes = putativeSignatureBytes.byteLength;\n if (numBytes !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * A type guard that accepts a string as input. It will both return `true` if the string conforms to\n * the {@link Signature} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignature } from '@solana/keys';\n *\n * if (isSignature(signature)) {\n * // At this point, `signature` has been refined to a\n * // `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * setSignatureStatus(status);\n * } else {\n * setError(`${signature} is not a transaction signature`);\n * }\n * ```\n */\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n return isSignatureBytes(bytes);\n}\n\n/**\n * A type guard that accepts a `ReadonlyUint8Array` as input. It will both return `true` if the `ReadonlyUint8Array` conforms to\n * the {@link SignatureBytes} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignatureBytes } from '@solana/keys';\n *\n * if (isSignatureBytes(signatureBytes)) {\n * // At this point, `signatureBytes` has been refined to a\n * // `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } else {\n * setError(`${signatureBytes} is not a 64-byte Ed25519 signature`);\n * }\n * ```\n */\nexport function isSignatureBytes(putativeSignatureBytes: ReadonlyUint8Array): putativeSignatureBytes is SignatureBytes {\n return putativeSignatureBytes.byteLength === 64;\n}\n\n/**\n * Given a private [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and a\n * `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a\n * `Uint8Array`.\n *\n * @example\n * ```ts\n * import { signBytes } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * const signature = await signBytes(privateKey, data);\n * ```\n */\nexport async function signBytes(key: CryptoKey, data: ReadonlyUint8Array): Promise {\n assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(data));\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\n/**\n * This helper combines _asserting_ that a string is an Ed25519 signature with _coercing_ it to the\n * {@link Signature} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signature } from '@solana/keys';\n *\n * const signature = signature(userSuppliedSignature);\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * ```\n */\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\n/**\n * This helper combines _asserting_ that a `ReadonlyUint8Array` is an Ed25519 signature with _coercing_ it to the\n * {@link SignatureBytes} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signatureBytes } from '@solana/keys';\n *\n * const signature = signatureBytes(userSuppliedSignatureBytes);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport function signatureBytes(putativeSignatureBytes: ReadonlyUint8Array): SignatureBytes {\n assertIsSignatureBytes(putativeSignatureBytes);\n return putativeSignatureBytes;\n}\n\n/**\n * Given a public [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), some\n * {@link SignatureBytes}, and a `Uint8Array` of data, this method will return `true` if the\n * signature was produced by signing the data using the private key associated with the public key,\n * and `false` otherwise.\n *\n * @example\n * ```ts\n * import { verifySignature } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport async function verifySignature(\n key: CryptoKey,\n signature: SignatureBytes,\n data: ReadonlyUint8Array,\n): Promise {\n assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(signature), toArrayBuffer(data));\n}\n","import { assertKeyGenerationIsAvailable, assertPRNGIsAvailable } from '@solana/assertions';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SolanaError,\n} from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\nimport { createPrivateKeyFromBytes } from './private-key';\nimport { getPublicKeyFromPrivateKey } from './public-key';\nimport { signBytes, verifySignature } from './signatures';\n\n/**\n * Generates an Ed25519 public/private key pair for use with other methods in this package that\n * accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await generateKeyPair();\n * ```\n */\nexport async function generateKeyPair(): Promise {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ ED25519_ALGORITHM_IDENTIFIER, // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify'],\n );\n return keyPair;\n}\n\n/**\n * Given a 64-byte `Uint8Array` secret key, creates an Ed25519 public/private key pair for use with\n * other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 64 bytes, the first 32 of which represent the private key and the last 32 of which\n * represent its associated public key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairFromBytes } from '@solana/keys';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a CryptoKeyPair from the bytes.\n * const { privateKey, publicKey } = await createKeyPairFromBytes(keypairBytes);\n * ```\n */\nexport async function createKeyPairFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n assertPRNGIsAvailable();\n\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), ED25519_ALGORITHM_IDENTIFIER, /* extractable */ true, [\n 'verify',\n ]),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n\n // Verify the key pair\n const randomBytes = new Uint8Array(32);\n crypto.getRandomValues(randomBytes);\n const signedData = await signBytes(privateKey, randomBytes);\n const isValid = await verifySignature(publicKey, signedData, randomBytes);\n if (!isValid) {\n throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);\n }\n\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 public/private key\n * pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await createKeyPairFromPrivateKeyBytes(new Uint8Array([...]));\n * ```\n *\n * This can be useful when you have a private key but not the corresponding public key or when you\n * need to derive key pairs from seeds. For instance, the following code snippet derives a key pair\n * from the hash of a message.\n *\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedKeypair = await createKeyPairFromPrivateKeyBytes(seed);\n * ```\n */\nexport async function createKeyPairFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const privateKeyPromise = createPrivateKeyFromBytes(bytes, extractable);\n\n // Here we need the private key to be extractable in order to export\n // it as a public key. Therefore, if the `extractable` parameter\n // is `false`, we need to create two private keys such that:\n // - The extractable one is used to create the public key and\n // - The non-extractable one is the one we will return.\n const [publicKey, privateKey] = await Promise.all([\n // This nested promise makes things efficient by\n // creating the public key in parallel with the\n // second private key creation, if it is needed.\n (extractable ? privateKeyPromise : createPrivateKeyFromBytes(bytes, true /* extractable */)).then(\n async privateKey => await getPublicKeyFromPrivateKey(privateKey, true /* extractable */),\n ),\n privateKeyPromise,\n ]);\n\n return { privateKey, publicKey };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { SignaturesMap } from '../transaction';\n\nfunction getSignaturesToEncode(signaturesMap: SignaturesMap): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { getAddressDecoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n padRightDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { getTransactionVersionDecoder } from '@solana/transaction-messages';\n\nimport { SignaturesMap, Transaction, TransactionMessageBytes } from '../transaction';\nimport { getSignaturesEncoder } from './signatures-encoder';\n\n/**\n * Returns an encoder that you can use to encode a {@link Transaction} to a byte array in a wire\n * format appropriate for sending to the Solana network for execution.\n */\nexport function getTransactionEncoder(): VariableSizeEncoder {\n return getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['messageBytes', getBytesEncoder()],\n ]);\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana transaction wire format\n * to a {@link Transaction} object.\n *\n * @example\n * ```ts\n * import { getTransactionDecoder } from '@solana/transactions';\n *\n * const transactionDecoder = getTransactionDecoder();\n * const transaction = transactionDecoder.decode(wireTransactionBytes);\n * for (const [address, signature] in Object.entries(transaction.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\n\nexport function getTransactionDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getShortU16Decoder() })],\n ['messageBytes', getBytesDecoder()],\n ]),\n decodePartiallyDecodedTransaction,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a {@link Transaction}\n *\n * @see {@link getTransactionDecoder}\n * @see {@link getTransactionEncoder}\n */\nexport function getTransactionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder());\n}\n\ntype PartiallyDecodedTransaction = {\n messageBytes: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedTransaction(transaction: PartiallyDecodedTransaction): Transaction {\n const { messageBytes, signatures } = transaction;\n\n /*\n Relevant message structure is at the start:\n - transaction version (0 bytes for legacy transactions, 1 byte for versioned transactions)\n - `numRequiredSignatures` (1 byte, we verify this matches the length of signatures)\n - `numReadOnlySignedAccounts` (1 byte, not used here)\n - `numReadOnlyUnsignedAccounts` (1 byte, not used here)\n - static addresses, with signers first. This is an array of addresses, prefixed with a short-u16 length\n */\n\n const signerAddressesDecoder = getTupleDecoder([\n // read transaction version\n getTransactionVersionDecoder(),\n // read first byte of header, `numSignerAccounts`\n // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need\n padRightDecoder(getU8Decoder(), 2),\n // read static addresses\n getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() }),\n ]);\n const [_txVersion, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);\n\n const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);\n\n // signer addresses and signatures must be the same length\n // we encode an all-zero signature when the signature is missing\n if (signerAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, {\n numRequiredSignatures,\n signaturesLength: signatures.length,\n signerAddresses,\n });\n }\n\n // combine the signer addresses + signatures into the signatures map\n const signaturesMap: SignaturesMap = {};\n signerAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return {\n messageBytes: messageBytes as TransactionMessageBytes,\n signatures: Object.freeze(signaturesMap),\n };\n}\n","import { type Address, isAddress } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SolanaError,\n} from '@solana/errors';\nimport { type Blockhash, isBlockhash, type Slot } from '@solana/rpc-types';\nimport type {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n Nonce,\n TransactionMessage,\n TransactionMessageWithBlockhashLifetime,\n TransactionMessageWithDurableNonceLifetime,\n} from '@solana/transaction-messages';\n\nimport type { Transaction } from './transaction';\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network. The transaction will continue to be eligible to land until the network considers the\n * `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type TransactionBlockhashLifetime = {\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction eligible to land.\n */\n lastValidBlockHeight: Slot;\n};\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionDurableNonceLifetime = {\n /**\n * A value contained in the account with address `nonceAccountAddress` at the time the\n * transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n /** The account that contains the `nonce` value */\n nonceAccountAddress: Address;\n};\n\n/**\n * A transaction whose ability to land on the network is determined by some evanescent criteria.\n *\n * This describes a window of time after which a transaction is constructed and before which it will\n * no longer be accepted by the network.\n *\n * No transaction can land on Solana without having a `lifetimeConstraint` set.\n */\nexport type TransactionWithLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime | TransactionDurableNonceLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by the age of a blockhash observed on the network.\n *\n * The transaction will continue to be eligible to land until the network considers the `blockhash`\n * to be expired.\n */\nexport type TransactionWithBlockhashLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by a nonce.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionWithDurableNonceLifetime = {\n readonly lifetimeConstraint: TransactionDurableNonceLifetime;\n};\n\n/**\n * Helper type that sets the lifetime constraint of a transaction to be the same as the\n * lifetime constraint of the provided transaction message.\n *\n * If the transaction message has no explicit lifetime constraint, neither will the transaction.\n */\nexport type SetTransactionLifetimeFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends TransactionMessage,\n> = TTransactionMessage extends { lifetimeConstraint: unknown }\n ? TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithBlockhashLifetime['lifetimeConstraint']\n ? TransactionWithBlockhashLifetime & TTransaction\n : TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithDurableNonceLifetime['lifetimeConstraint']\n ? TransactionWithDurableNonceLifetime & TTransaction\n : TransactionWithLifetime & TTransaction\n : TTransaction;\n\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address;\n\nfunction compiledInstructionIsAdvanceNonceInstruction(\n instruction: CompiledTransactionMessage['instructions'][number],\n staticAddresses: Address[],\n): instruction is typeof instruction & { accountIndices: [number, number, number] } {\n return (\n staticAddresses[instruction.programAddressIndex] === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accountIndices?.length === 3\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): boolean {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\n/**\n * Get the lifetime constraint for a transaction from a compiled transaction message that includes a lifetime token.\n * @param compiledTransactionMessage A compiled transaction message that includes a lifetime token\n * @returns A lifetime constraint for the transaction\n * Note that this is less precise than checking a decompiled instruction, as we can't inspect\n * the address or role of input accounts (which may be in lookup tables). However, this is\n * sufficient for all valid advance durable nonce instructions.\n * Note that the program address must not be in a lookup table, see [this answer on StackExchange](https://solana.stackexchange.com/a/16224/289)\n * @see {@link isAdvanceNonceAccountInstruction}\n * Note that this function is async to allow for future implementations that may fetch `lastValidBlockHeight` using an RPC\n */\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function getTransactionLifetimeConstraintFromCompiledTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n): Promise {\n const firstInstruction = compiledTransactionMessage.instructions[0];\n const { staticAccounts } = compiledTransactionMessage;\n\n // We need to check if the first instruction is an AdvanceNonceAccount instruction\n if (firstInstruction && compiledInstructionIsAdvanceNonceInstruction(firstInstruction, staticAccounts)) {\n const nonceAccountAddress = staticAccounts[firstInstruction.accountIndices[0]];\n if (!nonceAccountAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, {\n nonce: compiledTransactionMessage.lifetimeToken,\n });\n }\n return {\n nonce: compiledTransactionMessage.lifetimeToken as Nonce,\n nonceAccountAddress,\n };\n } else {\n return {\n blockhash: compiledTransactionMessage.lifetimeToken as Blockhash,\n // This is not known from the compiled message, so we set it to the maximum possible value\n lastValidBlockHeight: 0xffffffffffffffffn,\n };\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * if (isTransactionWithBlockhashLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a `TransactionWithBlockhashLifetime`.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'blockhash' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.blockhash === 'string' &&\n typeof transaction.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transaction.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * blockhash-based lifetime, from for example a wallet. Use this function to\n * assert that such a transaction actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithBlockhashLifetime`.\n * assertIsTransactionWithBlockhashLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `transaction` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithBlockhashLifetime {\n if (!isTransactionWithBlockhashLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithDurableNonceLifetime } from '@solana/transactions';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionWithDurableNonceLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a\n * // `TransactionWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'nonce' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n typeof transaction.lifetimeConstraint.nonceAccountAddress === 'string' &&\n isAddress(transaction.lifetimeConstraint.nonceAccountAddress)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * nonce-based lifetime, from for example a wallet. Use this function to assert\n * that such a transaction actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithDurableNonceLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithDurableNonceLifetime`.\n * assertIsTransactionWithDurableNonceLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `transaction` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithDurableNonceLifetime {\n if (!isTransactionWithDurableNonceLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n","import {\n compileTransactionMessage,\n getCompiledTransactionMessageEncoder,\n isTransactionMessageWithBlockhashLifetime,\n isTransactionMessageWithDurableNonceLifetime,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport type { TransactionWithLifetime } from './lifetime';\nimport type { SignaturesMap, TransactionFromTransactionMessage, TransactionMessageBytes } from './transaction';\n\n/**\n * Returns a {@link Transaction} object for a given {@link TransactionMessage}.\n *\n * This includes the compiled bytes of the transaction message, and a map of signatures. This map\n * will have a key for each address that is required to sign the transaction. The transaction will\n * not yet have signatures for any of these addresses.\n *\n * Whether a transaction message is ready to be compiled or not is enforced for you at the type\n * level. In order to be signable, a transaction message must:\n *\n * - have a version and a list of zero or more instructions (ie. conform to\n * {@link TransactionMessage})\n * - have a fee payer set (ie. conform to {@link TransactionMessageWithFeePayer})\n * - have a lifetime specified (ie. conform to {@link TransactionMessageWithBlockhashLifetime} or\n * {@link TransactionMessageWithDurableNonceLifetime})\n */\nexport function compileTransaction(\n transactionMessage: TTransactionMessage,\n): Readonly> {\n type ReturnType = Readonly>;\n\n const compiledMessage = compileTransactionMessage(transactionMessage);\n const messageBytes = getCompiledTransactionMessageEncoder().encode(compiledMessage) as TransactionMessageBytes;\n\n const transactionSigners = compiledMessage.staticAccounts.slice(0, compiledMessage.header.numSignerAccounts);\n const signatures: SignaturesMap = {};\n for (const signerAddress of transactionSigners) {\n signatures[signerAddress] = null;\n }\n\n let lifetimeConstraint: TransactionWithLifetime['lifetimeConstraint'] | undefined;\n if (isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n lifetimeConstraint = {\n blockhash: transactionMessage.lifetimeConstraint.blockhash,\n lastValidBlockHeight: transactionMessage.lifetimeConstraint.lastValidBlockHeight,\n };\n } else if (isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n lifetimeConstraint = {\n nonce: transactionMessage.lifetimeConstraint.nonce,\n nonceAccountAddress: transactionMessage.instructions[0].accounts[0].address,\n };\n }\n\n return Object.freeze({\n ...(lifetimeConstraint ? { lifetimeConstraint } : undefined),\n messageBytes: messageBytes,\n signatures: Object.freeze(signatures),\n }) as ReturnType;\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { bytesEqual, Decoder } from '@solana/codecs-core';\nimport { getBase58Decoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Signature, SignatureBytes, signBytes } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { Transaction } from './transaction';\n\n/**\n * Represents a transaction that is signed by all of its required signers. Being fully signed is a\n * prerequisite of functions designed to land transactions on the network.\n */\nexport type FullySignedTransaction = NominalType<'transactionSignedness', 'fullySigned'>;\n\nlet base58Decoder: Decoder | undefined;\n\n/**\n * Given a transaction signed by its fee payer, this method will return the {@link Signature} that\n * uniquely identifies it. This string can be used to look up transactions at a later date, for\n * example on a Solana block explorer.\n *\n * @example\n * ```ts\n * import { getSignatureFromTransaction } from '@solana/transactions';\n *\n * const signature = getSignatureFromTransaction(tx);\n * console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`);\n * ```\n */\nexport function getSignatureFromTransaction(transaction: Transaction): Signature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n // We have ordered signatures from the compiled message accounts\n // first signature is the fee payer\n const signatureBytes = Object.values(transaction.signatures)[0];\n if (!signatureBytes) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);\n }\n const transactionSignature = base58Decoder.decode(signatureBytes);\n return transactionSignature as Signature;\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link Transaction}.\n *\n * Though the resulting transaction might have every signature it needs to land on the network, this\n * function will not assert that it does. A partially signed transaction cannot be landed on the\n * network, but can be serialized and deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignTransaction } from '@solana/transactions';\n *\n * const partiallySignedTransaction = await partiallySignTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link signTransaction} if you want to assert that the transaction has all of its required\n * signatures after signing.\n */\nexport async function partiallySignTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const existingSignature = transaction.signatures[address];\n\n // Check if the address is expected to sign the transaction\n if (existingSignature === undefined) {\n // address is not an expected signer for this transaction\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);\n\n if (existingSignature !== null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n const expectedSigners = Object.keys(transaction.signatures);\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {\n expectedAddresses: expectedSigners,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return transaction;\n }\n\n return Object.freeze({\n ...transaction,\n signatures: Object.freeze({\n ...transaction.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link FullySignedTransaction}.\n *\n * This function will throw unless the resulting transaction is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signTransaction } from '@solana/transactions';\n *\n * const signedTransaction = await signTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link partiallySignTransaction} if you want to sign the transaction without asserting that\n * the resulting transaction is fully signed.\n */\nexport async function signTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertIsFullySignedTransaction(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * Checks whether a given {@link Transaction} is fully signed.\n *\n * @example\n * ```ts\n * import { isFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isFullySignedTransaction(transaction)) {\n * // At this point we know that the transaction is signed and can be sent to the network.\n * }\n * ```\n */\nexport function isFullySignedTransaction(\n transaction: TTransaction,\n): transaction is FullySignedTransaction & TTransaction {\n return Object.entries(transaction.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link Transaction}, that you expect to be fully signed,\n * from an untrusted network API or user input. Use this function to assert that such a transaction\n * is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `FullySignedTransaction`.\n * assertIsFullySignedTransaction(transaction);\n * // At this point we know that the transaction is signed and can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsFullySignedTransaction(\n transaction: TTransaction,\n): asserts transaction is FullySignedTransaction & TTransaction {\n const missingSigs: Address[] = [];\n Object.entries(transaction.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n","import { getBase64Decoder } from '@solana/codecs-strings';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/** Represents the wire format of a transaction as a base64-encoded string. */\nexport type Base64EncodedWireTransaction = Brand, 'Base64EncodedWireTransaction'>;\n\n/**\n * Given a signed transaction, this method returns the transaction as a string that conforms to the\n * {@link Base64EncodedWireTransaction} type.\n *\n * @example\n * ```ts\n * import { getBase64EncodedWireTransaction, signTransaction } from '@solana/transactions';\n *\n * const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send();\n * ```\n */\nexport function getBase64EncodedWireTransaction(transaction: Transaction): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes) as Base64EncodedWireTransaction;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type { NominalType } from '@solana/nominal-types';\nimport type { BaseTransactionMessage, TransactionMessageWithinSizeLimit } from '@solana/transaction-messages';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/**\n * The maximum size of a transaction packet in bytes.\n */\nexport const TRANSACTION_PACKET_SIZE = 1280;\n\n/**\n * The size of the transaction packet header in bytes.\n * This includes the IPv6 header and the fragment header.\n */\nexport const TRANSACTION_PACKET_HEADER =\n 40 /* 40 bytes is the size of the IPv6 header. */ + 8; /* 8 bytes is the size of the fragment header. */\n\n/**\n * The maximum size of a transaction in bytes.\n *\n * Note that this excludes the transaction packet header.\n * In other words, this is how much content we can fit in a transaction packet.\n */\nexport const TRANSACTION_SIZE_LIMIT = TRANSACTION_PACKET_SIZE - TRANSACTION_PACKET_HEADER;\n\n/**\n * Gets the size of a given transaction in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionSize(transaction);\n * ```\n */\nexport function getTransactionSize(transaction: Transaction): number {\n return getTransactionEncoder().getSizeFromValue(transaction);\n}\n\n/**\n * A type guard that checks if a transaction is within the size limit.\n */\nexport type TransactionWithinSizeLimit = NominalType<'transactionSize', 'withinLimit'>;\n\n/**\n * Helper type that adds the `TransactionWithinSizeLimit` flag to\n * a transaction if and only if the provided transaction message\n * is also within the size limit.\n */\nexport type SetTransactionWithinSizeLimitFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithinSizeLimit\n ? TransactionWithinSizeLimit & TTransaction\n : TTransaction;\n\n/**\n * Checks if a transaction is within the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * if (isTransactionWithinSizeLimit(transaction)) {\n * transaction satisfies TransactionWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionWithinSizeLimit(\n transaction: TTransaction,\n): transaction is TransactionWithinSizeLimit & TTransaction {\n return getTransactionSize(transaction) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction is within the size limit.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction exceeds the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * assertIsTransactionWithinSizeLimit(transaction);\n * transaction satisfies TransactionWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionWithinSizeLimit(\n transaction: TTransaction,\n): asserts transaction is TransactionWithinSizeLimit & TTransaction {\n const transactionSize = getTransactionSize(transaction);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","import { assertIsFullySignedTransaction, FullySignedTransaction, isFullySignedTransaction } from './signatures';\nimport { Transaction } from './transaction';\nimport {\n assertIsTransactionWithinSizeLimit,\n isTransactionWithinSizeLimit,\n TransactionWithinSizeLimit,\n} from './transaction-size';\n\n/**\n * Helper type that includes all transaction types required\n * for the transaction to be sent to the network.\n *\n * @see {@link isSendableTransaction}\n * @see {@link assertIsSendableTransaction}\n */\nexport type SendableTransaction = FullySignedTransaction & TransactionWithinSizeLimit;\n\n/**\n * Checks if a transaction has all the required\n * conditions to be sent to the network.\n *\n * @example\n * ```ts\n * import { isSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isSendableTransaction(transaction)) {\n * // At this point we know that the transaction can be sent to the network.\n * }\n * ```\n *\n * @see {@link assertIsSendableTransaction}\n */\nexport function isSendableTransaction(\n transaction: TTransaction,\n): transaction is SendableTransaction & TTransaction {\n return isFullySignedTransaction(transaction) && isTransactionWithinSizeLimit(transaction);\n}\n\n/**\n * Asserts that a given transaction has all the\n * required conditions to be sent to the network.\n *\n * From time to time you might acquire a {@link Transaction}\n * from an untrusted network API or user input and you are not sure\n * that it has all the required conditions to be sent to the network\n * — such as being fully signed and within the size limit.\n * This function can be used to assert that such a transaction\n * is in fact sendable.\n *\n * @example\n * ```ts\n * import { assertIsSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `SendableTransaction`.\n * assertIsSendableTransaction(transaction);\n * // At this point we know that the transaction can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT)) {\n * setError(`Transaction exceeds size limit of ${e.context.transactionSizeLimit} bytes`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsSendableTransaction(\n transaction: TTransaction,\n): asserts transaction is SendableTransaction & TTransaction {\n assertIsFullySignedTransaction(transaction);\n assertIsTransactionWithinSizeLimit(transaction);\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithinSizeLimit,\n} from '@solana/transaction-messages';\n\nimport { compileTransaction } from './compile-transaction';\nimport { getTransactionSize, TRANSACTION_SIZE_LIMIT } from './transaction-size';\n\n/**\n * Gets the compiled transaction size of a given transaction message in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionMessageSize(transactionMessage);\n * ```\n */\nexport function getTransactionMessageSize(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n): number {\n return getTransactionSize(compileTransaction(transactionMessage));\n}\n\n/**\n * Checks if a transaction message is within the size limit\n * when compiled into a transaction.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * if (isTransactionMessageWithinSizeLimit(transactionMessage)) {\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n return getTransactionMessageSize(transactionMessage) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction message is within the size limit\n * when compiled into a transaction.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction message exceeds the size limit.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * assertIsTransactionMessageWithinSizeLimit(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): asserts transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n const transactionSize = getTransactionMessageSize(transactionMessage);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","/**\n * Forked from https://github.com/digitalloggers/race-as-promised/tree/master\n *\n * Authored by Brian Kim:\n * https://github.com/nodejs/node/issues/17469#issuecomment-685216777\n *\n * Adapted to module structure.\n *\n * This is free and unencumbered software released into the public domain.\n *\n * Anyone is free to copy, modify, publish, use, compile, sell, or\n * distribute this software, either in source code form or as a compiled\n * binary, for any purpose, commercial or non-commercial, and by any\n * means.\n *\n * In jurisdictions that recognize copyright laws, the author or authors\n * of this software dedicate any and all copyright interest in the\n * software to the public domain. We make this dedication for the benefit\n * of the public at large and to the detriment of our heirs and\n * successors. We intend this dedication to be an overt act of\n * relinquishment in perpetuity of all present and future rights to this\n * software under copyright law.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * For more information, please refer to \n */\n\ntype Deferred = Readonly<{\n reject: (reason?: unknown) => void;\n resolve: (value: unknown) => void;\n}>;\n\nfunction isObject(value: unknown): value is object {\n return value !== null && (typeof value === 'object' || typeof value === 'function');\n}\n\nfunction addRaceContender(contender: object) {\n const deferreds = new Set();\n const record = { deferreds, settled: false };\n\n // This call to `then` happens once for the lifetime of the value.\n Promise.resolve(contender).then(\n value => {\n for (const { resolve } of deferreds) {\n resolve(value);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n err => {\n for (const { reject } of deferreds) {\n reject(err);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n );\n return record;\n}\n\n// Keys are the values passed to race, values are a record of data containing a\n// set of deferreds and whether the value has settled.\nconst wm = new WeakMap; settled: boolean }>();\n/**\n * An implementation of [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)\n * that causes all of the losing promises to settle. This allows them to be released and garbage\n * collected, preventing memory leaks.\n *\n * Read more here: https://github.com/nodejs/node/issues/17469\n */\nexport async function safeRace(contenders: T): Promise> {\n let deferred: Deferred;\n const result = new Promise((resolve, reject) => {\n deferred = { reject, resolve };\n for (const contender of contenders) {\n if (!isObject(contender)) {\n // If the contender is a primitive, attempting to use it as a key in the\n // weakmap would throw an error. Luckily, it is safe to call\n // `Promise.resolve(contender).then` on a primitive value multiple times\n // because the promise fulfills immediately.\n Promise.resolve(contender).then(resolve, reject);\n continue;\n }\n\n let record = wm.get(contender);\n if (record === undefined) {\n record = addRaceContender(contender);\n record.deferreds.add(deferred);\n wm.set(contender, record);\n } else if (record.settled) {\n // If the value has settled, it is safe to call\n // `Promise.resolve(contender).then` on it.\n Promise.resolve(contender).then(resolve, reject);\n } else {\n record.deferreds.add(deferred);\n }\n }\n });\n\n // The finally callback executes when any value settles, preventing any of\n // the unresolved values from retaining a reference to the resolved value.\n return await (result.finally(() => {\n for (const contender of contenders) {\n if (isObject(contender)) {\n const record = wm.get(contender)!;\n record.deferreds.delete(deferred);\n }\n }\n }) as Promise>);\n}\n","import { safeRace } from './race';\n\n/**\n * Returns a new promise that will reject if the abort signal fires before the original promise\n * settles. Resolves or rejects with the value of the original promise otherwise.\n *\n * @example\n * ```ts\n * const result = await getAbortablePromise(\n * // Resolves or rejects when `fetch` settles.\n * fetch('https://example.com/json').then(r => r.json()),\n * // ...unless it takes longer than 5 seconds, after which the `AbortSignal` is triggered.\n * AbortSignal.timeout(5000),\n * );\n * ```\n */\nexport function getAbortablePromise(promise: Promise, abortSignal?: AbortSignal): Promise {\n if (!abortSignal) {\n return promise;\n } else {\n return safeRace([\n // This promise only ever rejects if the signal is aborted. Otherwise it idles forever.\n // It's important that this come before the input promise; in the event of an abort, we\n // want to throw even if the input promise's result is ready\n new Promise((_, reject) => {\n if (abortSignal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(abortSignal.reason);\n } else {\n abortSignal.addEventListener('abort', function () {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n });\n }\n }),\n promise,\n ]);\n }\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SolanaError,\n} from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\n/**\n * A set of instructions with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans in order to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely the following plans are supported:\n * - {@link SingleInstructionPlan} - A plan that contains a single instruction.\n * This is a simple instruction wrapper and the simplest leaf in this tree.\n * - {@link ParallelInstructionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialInstructionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that instructions inside it can be split into separate transactions.\n * - {@link MessagePackerInstructionPlan} - A plan that can dynamically pack\n * instructions into transaction messages.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myInstructionPlan: InstructionPlan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * instructionC,\n * instructionD,\n * ]);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link ParallelInstructionPlan}\n * @see {@link SequentialInstructionPlan}\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type InstructionPlan =\n | MessagePackerInstructionPlan\n | ParallelInstructionPlan\n | SequentialInstructionPlan\n | SingleInstructionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the instructions inside them can be split into separate transactions.\n * When `divisible` is `false`, the instructions inside the plan should\n * all be executed atomically — either in a single transaction or in a\n * transaction bundle.\n *\n * You may use the {@link sequentialInstructionPlan} and {@link nonDivisibleSequentialInstructionPlan}\n * helpers to create objects of this type.\n *\n * @example Simple sequential plan with two instructions.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan;\n * ```\n *\n * @example Non-divisible sequential plan with two instructions.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @example Sequential plan with nested parallel plans.\n * Here, instructions A and B can be executed in parallel, but they must both be finalized\n * before instructions C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * parallelInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @see {@link sequentialInstructionPlan}\n * @see {@link nonDivisibleSequentialInstructionPlan}\n */\nexport type SequentialInstructionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without consequence.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialInstructionPlan}.\n *\n * You may use the {@link parallelInstructionPlan} helper to create objects of this type.\n *\n * @example Simple parallel plan with two instructions.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @example Parallel plan with nested sequential plans.\n * Here, instructions A and B must be executed sequentially and so must instructions C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @see {@link parallelInstructionPlan}\n */\nexport type ParallelInstructionPlan = Readonly<{\n kind: 'parallel';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan that contains a single instruction.\n *\n * This is a simple instruction wrapper that transforms an instruction into a plan.\n *\n * You may use the {@link singleInstructionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * plan satisfies SingleInstructionPlan;\n * ```\n *\n * @see {@link singleInstructionPlan}\n */\nexport type SingleInstructionPlan = Readonly<{\n instruction: TInstruction;\n kind: 'single';\n}>;\n\n/**\n * A plan that can dynamically pack instructions into transaction messages.\n *\n * This plan provides a {@link MessagePacker} via the `getMessagePacker`\n * method, which enables instructions to be dynamically packed into the\n * provided transaction message until there are no more instructions to pack.\n * The returned {@link MessagePacker} offers a `packMessageToCapacity(message)`\n * method that packs the provided message — when possible — and a `done()` method\n * that checks whether there are more instructions to pack.\n *\n * Several helper functions are provided to create objects of this type such as\n * {@link getLinearMessagePackerInstructionPlan} or {@link getMessagePackerInstructionPlanFromInstructions}.\n *\n * @example An message packer plan for a write instruction that uses as many bytes as possible.\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example A message packer plan for multiple realloc instructions.\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example Using a message packer plan.\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link getLinearMessagePackerInstructionPlan}\n * @see {@link getMessagePackerInstructionPlanFromInstructions}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport type MessagePackerInstructionPlan = Readonly<{\n getMessagePacker: () => MessagePacker;\n kind: 'messagePacker';\n}>;\n\n/**\n * The message packer returned by the {@link MessagePackerInstructionPlan}.\n *\n * It offers a `packMessageToCapacity(transactionMessage)` method that packs as many instructions\n * as possible into the provided transaction message, while still being able to fit into the\n * transaction size limit. It returns the updated transaction message with the packed instructions\n * or throws an error if the current transaction message cannot accommodate this plan.\n *\n * The `done()` method checks whether there are more instructions to pack into\n * transaction messages.\n *\n * @example\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type MessagePacker = Readonly<{\n /** Checks whether the message packer has more instructions to pack into transaction messages. */\n done: () => boolean;\n /**\n * Packs the provided transaction message with instructions or throws if not possible.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN}\n * if the provided transaction message cannot be used to fill the next instructions.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE}\n * if the message packer is already done and no more instructions can be packed.\n */\n packMessageToCapacity: (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer;\n}>;\n\n/**\n * Creates a {@link ParallelInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = parallelInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n */\nexport function parallelInstructionPlan(plans: (Instruction | InstructionPlan)[]): ParallelInstructionPlan {\n return Object.freeze({\n kind: 'parallel',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function sequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: true } {\n return Object.freeze({\n divisible: true,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a non-divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function nonDivisibleSequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: false } {\n return Object.freeze({\n divisible: false,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a {@link SingleInstructionPlan} from an {@link Instruction} object.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n */\nexport function singleInstructionPlan(instruction: Instruction): SingleInstructionPlan {\n return Object.freeze({ instruction, kind: 'single' });\n}\n\nfunction parseSingleInstructionPlans(plans: (Instruction | InstructionPlan)[]): InstructionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleInstructionPlan(plan)));\n}\n\n/**\n * Checks if the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a single instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * if (isSingleInstructionPlan(plan)) {\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * }\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link assertIsSingleInstructionPlan}\n */\nexport function isSingleInstructionPlan(plan: InstructionPlan): plan is SingleInstructionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a single instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * assertIsSingleInstructionPlan(plan);\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link isSingleInstructionPlan}\n */\nexport function assertIsSingleInstructionPlan(plan: InstructionPlan): asserts plan is SingleInstructionPlan {\n if (!isSingleInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a message packer instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * if (isMessagePackerInstructionPlan(plan)) {\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link assertIsMessagePackerInstructionPlan}\n */\nexport function isMessagePackerInstructionPlan(plan: InstructionPlan): plan is MessagePackerInstructionPlan {\n return plan.kind === 'messagePacker';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a message packer instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * assertIsMessagePackerInstructionPlan(plan);\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link isMessagePackerInstructionPlan}\n */\nexport function assertIsMessagePackerInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is MessagePackerInstructionPlan {\n if (!isMessagePackerInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'messagePacker',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isSequentialInstructionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsSequentialInstructionPlan}\n */\nexport function isSequentialInstructionPlan(plan: InstructionPlan): plan is SequentialInstructionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsSequentialInstructionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isSequentialInstructionPlan}\n */\nexport function assertIsSequentialInstructionPlan(plan: InstructionPlan): asserts plan is SequentialInstructionPlan {\n if (!isSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a non-divisible sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isNonDivisibleSequentialInstructionPlan(plan)) {\n * // All instructions must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsNonDivisibleSequentialInstructionPlan}\n */\nexport function isNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): plan is SequentialInstructionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a non-divisible sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsNonDivisibleSequentialInstructionPlan(plan);\n * // All instructions must be executed atomically.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isNonDivisibleSequentialInstructionPlan}\n */\nexport function assertIsNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is SequentialInstructionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a parallel instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * if (isParallelInstructionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * }\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link assertIsParallelInstructionPlan}\n */\nexport function isParallelInstructionPlan(plan: InstructionPlan): plan is ParallelInstructionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a parallel instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * assertIsParallelInstructionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link isParallelInstructionPlan}\n */\nexport function assertIsParallelInstructionPlan(plan: InstructionPlan): asserts plan is ParallelInstructionPlan {\n if (!isParallelInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Finds the first instruction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the instruction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param instructionPlan - The instruction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @returns The first matching instruction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const nonDivisible = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing instructionC and instructionD.\n * ```\n *\n * @example\n * Finding a specific single instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const found = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.instruction === instructionB,\n * );\n * // Returns the SingleInstructionPlan wrapping instructionB.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function findInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): InstructionPlan | undefined {\n if (predicate(instructionPlan)) {\n return instructionPlan;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return undefined;\n }\n for (const subPlan of instructionPlan.plans) {\n const foundPlan = findInstructionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every instruction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the instruction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param instructionPlan - The instruction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const allDivisible = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single instructions use a specific program.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const allUseSameProgram = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.instruction.programAddress === myProgramAddress,\n * );\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function everyInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): boolean {\n if (!predicate(instructionPlan)) {\n return false;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return true;\n }\n return instructionPlan.plans.every(p => everyInstructionPlan(p, predicate));\n}\n\n/**\n * Transforms an instruction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the instruction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param instructionPlan - The instruction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed instruction plan tree.\n *\n * @example\n * Making all sequential plans non-divisible to ensure atomicity.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' && p.divisible) {\n * return nonDivisibleSequentialInstructionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Filtering out debug instructions before production execution.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, debugInstruction, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' || p.kind === 'parallel') {\n * return { ...p, plans: p.plans.filter((p) => !isDebugInstruction(p)) };\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function transformInstructionPlan(\n instructionPlan: InstructionPlan,\n fn: (plan: InstructionPlan) => InstructionPlan,\n): InstructionPlan {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return Object.freeze(fn(instructionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...instructionPlan,\n plans: instructionPlan.plans.map(p => transformInstructionPlan(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleInstructionPlan} and {@link MessagePackerInstructionPlan}\n * instances from an instruction plan tree.\n *\n * This function recursively traverses any nested structure of instruction plans and extracts\n * all the leaf plans they contain. It's useful when you need to access all the individual\n * instructions or message packers that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param instructionPlan - The instruction plan to extract leaf plans from\n * @returns An array of all single and message packer instruction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * instructionE,\n * ]);\n *\n * const leafPlans = flattenInstructionPlan(plan);\n * // Array of `SingleInstructionPlan` containing:\n * // instructionA, instructionB, instructionC, instructionD and instructionE.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n */\nexport function flattenInstructionPlan(\n instructionPlan: InstructionPlan,\n): (MessagePackerInstructionPlan | SingleInstructionPlan)[] {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return [instructionPlan];\n }\n return instructionPlan.plans.flatMap(flattenInstructionPlan);\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs instructions\n * such that each instruction consumes as many bytes as possible from the given\n * `totalLength` while still being able to fit into the given transaction messages.\n *\n * This is particularly useful for instructions that write data to accounts and must\n * span multiple transactions due to their size limit.\n *\n * This message packer will first call `getInstruction` with a length of zero to\n * determine the base size of the instruction before figuring out how many\n * additional bytes can be packed into the transaction message. That remaining space\n * will then be used to call `getInstruction` again with the appropriate length.\n *\n * @param getInstruction - A function that returns an instruction for a given offset and length.\n * @param totalLength - The total length of the data to write, in bytes.\n *\n * @example\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getLinearMessagePackerInstructionPlan({\n getInstruction,\n totalLength: totalBytes,\n}: {\n getInstruction: (offset: number, length: number) => Instruction;\n totalLength: number;\n}): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let offset = 0;\n return Object.freeze({\n done: () => offset >= totalBytes,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (offset >= totalBytes) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const messageSizeWithBaseInstruction = getTransactionMessageSize(\n appendTransactionMessageInstruction(getInstruction(offset, 0), message),\n );\n const freeSpace =\n TRANSACTION_SIZE_LIMIT -\n messageSizeWithBaseInstruction /* Includes the base instruction (length: 0). */ -\n 1; /* Leeway for shortU16 numbers in transaction headers. */\n\n if (freeSpace <= 0) {\n const messageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n // (+1) We need to pack at least one byte of data otherwise\n // there is no point packing the base instruction alone.\n numBytesRequired: messageSizeWithBaseInstruction - messageSize + 1,\n // (-1) Leeway for shortU16 numbers in transaction headers.\n numFreeBytes: TRANSACTION_SIZE_LIMIT - messageSize - 1,\n });\n }\n\n const length = Math.min(totalBytes - offset, freeSpace);\n const instruction = getInstruction(offset, length);\n offset += length;\n return appendTransactionMessageInstruction(instruction, message);\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} from a list of instructions.\n *\n * This can be useful to prepare a set of instructions that can be iterated over\n * — e.g. to pack a list of instructions that gradually reallocate the size of an account\n * one `REALLOC_LIMIT` (10'240 bytes) at a time.\n *\n * @example\n * ```ts\n * const plan = getMessagePackerInstructionPlanFromInstructions([\n * instructionA,\n * instructionB,\n * instructionC,\n * ]);\n *\n * const messagePacker = plan.getMessagePacker();\n * firstTransactionMessage = messagePacker.packMessageToCapacity(firstTransactionMessage);\n * // Contains instruction A and instruction B.\n * secondTransactionMessage = messagePacker.packMessageToCapacity(secondTransactionMessage);\n * // Contains instruction C.\n * messagePacker.done(); // true\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport function getMessagePackerInstructionPlanFromInstructions(\n instructions: TInstruction[],\n): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let instructionIndex = 0;\n return Object.freeze({\n done: () => instructionIndex >= instructions.length,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (instructionIndex >= instructions.length) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const originalMessageSize = getTransactionMessageSize(message);\n\n for (let index = instructionIndex; index < instructions.length; index++) {\n message = appendTransactionMessageInstruction(instructions[index], message);\n const messageSize = getTransactionMessageSize(message);\n\n if (messageSize > TRANSACTION_SIZE_LIMIT) {\n if (index === instructionIndex) {\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n {\n numBytesRequired: messageSize - originalMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - originalMessageSize,\n },\n );\n }\n instructionIndex = index;\n return message;\n }\n }\n\n instructionIndex = instructions.length;\n return message;\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\nconst REALLOC_LIMIT = 10_240;\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs a list of realloc instructions.\n *\n * That is, it splits instruction by chunks of `REALLOC_LIMIT` (10'240) bytes until\n * the given total size is reached.\n *\n * @example\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getReallocMessagePackerInstructionPlan({\n getInstruction,\n totalSize,\n}: {\n getInstruction: (size: number) => Instruction;\n totalSize: number;\n}): MessagePackerInstructionPlan {\n const numberOfInstructions = Math.ceil(totalSize / REALLOC_LIMIT);\n const lastInstructionSize = totalSize % REALLOC_LIMIT;\n const instructions = new Array(numberOfInstructions)\n .fill(0)\n .map((_, i) => getInstruction(i === numberOfInstructions - 1 ? lastInstructionSize : REALLOC_LIMIT));\n\n return getMessagePackerInstructionPlanFromInstructions(instructions);\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, SolanaError } from '@solana/errors';\nimport { type Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport { flattenInstructionPlan, InstructionPlan } from './instruction-plan';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\n\ntype AppendTransactionMessageInstructions = ReturnType<\n typeof appendTransactionMessageInstructions\n>;\n\n/**\n * Appends all instructions from an instruction plan to a transaction message.\n *\n * This function flattens the instruction plan into its leaf plans and sequentially\n * appends each instruction to the provided transaction message. It handles both\n * single instructions and message packer plans.\n *\n * Note that any {@link MessagePackerInstructionPlan} is assumed to only append\n * instructions. If it modifies other properties of the transaction message, the\n * type of the returned transaction message may not accurately reflect those changes.\n *\n * @typeParam TTransactionMessage - The type of transaction message being modified.\n *\n * @param transactionMessage - The transaction message to append instructions to.\n * @param instructionPlan - The instruction plan containing the instructions to append.\n * @returns The transaction message with all instructions from the plan appended.\n *\n * @example\n * Appending a simple instruction plan to a transaction message.\n * ```ts\n * import { appendTransactionMessageInstructionPlan } from '@solana/instruction-plans';\n * import { createTransactionMessage, setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const message = setTransactionMessageFeePayer(feePayer, createTransactionMessage({ version: 0 }));\n * const plan = singleInstructionPlan(myInstruction);\n *\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @example\n * Appending a sequential instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function appendTransactionMessageInstructionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer,\n>(\n instructionPlan: InstructionPlan,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n type Out = AppendTransactionMessageInstructions;\n\n const leafInstructionPlans = flattenInstructionPlan(instructionPlan);\n\n return leafInstructionPlans.reduce(\n (messageSoFar, plan) => {\n const kind = plan.kind;\n if (kind === 'single') {\n return appendTransactionMessageInstruction(plan.instruction, messageSoFar) as unknown as Out;\n }\n if (kind === 'messagePacker') {\n const messagerPacker = plan.getMessagePacker();\n let nextMessage: Out = messageSoFar;\n while (!messagerPacker.done()) {\n nextMessage = messagerPacker.packMessageToCapacity(nextMessage) as Out;\n }\n return nextMessage;\n }\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, {\n kind,\n });\n },\n transactionMessage as unknown as Out,\n );\n}\n","import { SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, SolanaError } from '@solana/errors';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\n/**\n * A set of transaction messages with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely, the following plans are supported:\n * - {@link SingleTransactionPlan} - A plan that contains a single transaction message.\n * This is the simplest leaf in this tree.\n * - {@link ParallelTransactionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialTransactionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that transaction messages inside it can be split into separate batches.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myTransactionPlan: TransactionPlan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * messageC,\n * ]);\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link ParallelTransactionPlan}\n * @see {@link SequentialTransactionPlan}\n */\nexport type TransactionPlan = ParallelTransactionPlan | SequentialTransactionPlan | SingleTransactionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the transaction messages inside them can be split into separate batches.\n * When `divisible` is `false`, the transaction messages inside the plan should\n * all be executed atomically — usually in a transaction bundle.\n *\n * You may use the {@link sequentialTransactionPlan} and {@link nonDivisibleSequentialTransactionPlan}\n * helpers to create objects of this type.\n *\n * @example\n * Simple sequential plan with two transaction messages.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan;\n * ```\n *\n * @example\n * Non-divisible sequential plan with two transaction messages.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan & { divisible: false };\n * ```\n *\n * @example\n * Sequential plan with nested parallel plans.\n * Here, messages A and B can be executed in parallel, but they must both be finalized\n * before messages C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * parallelTransactionPlan([messageC, messageD]),\n * ]);\n * ```\n *\n * @see {@link sequentialTransactionPlan}\n * @see {@link nonDivisibleSequentialTransactionPlan}\n */\nexport type SequentialTransactionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without causing any side effects.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialTransactionPlan}.\n *\n * You may use the {@link parallelTransactionPlan} helper to create objects of this type.\n *\n * @example\n * Simple parallel plan with two transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @example\n * Parallel plan with nested sequential plans.\n * Here, messages A and B must be executed sequentially and so must messages C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @see {@link parallelTransactionPlan}\n */\nexport type ParallelTransactionPlan = Readonly<{\n kind: 'parallel';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan that contains a single transaction message.\n *\n * This is a simple transaction message wrapper that transforms a message into a plan.\n *\n * You may use the {@link singleTransactionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link singleTransactionPlan}\n */\nexport type SingleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n}>;\n\n/**\n * Creates a {@link ParallelTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = parallelTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n */\nexport function parallelTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): ParallelTransactionPlan {\n return Object.freeze({ kind: 'parallel', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function sequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function nonDivisibleSequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a {@link SingleTransactionPlan} from a {@link TransactionMessage} object.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link SingleTransactionPlan}\n */\nexport function singleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlan {\n return Object.freeze({ kind: 'single', message: transactionMessage });\n}\n\nfunction parseSingleTransactionPlans(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): TransactionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleTransactionPlan(plan)));\n}\n\n/**\n * Checks if the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a single transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * if (isSingleTransactionPlan(plan)) {\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link assertIsSingleTransactionPlan}\n */\nexport function isSingleTransactionPlan(plan: TransactionPlan): plan is SingleTransactionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a single transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * assertIsSingleTransactionPlan(plan);\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link isSingleTransactionPlan}\n */\nexport function assertIsSingleTransactionPlan(plan: TransactionPlan): asserts plan is SingleTransactionPlan {\n if (!isSingleTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * if (isSequentialTransactionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsSequentialTransactionPlan}\n */\nexport function isSequentialTransactionPlan(plan: TransactionPlan): plan is SequentialTransactionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsSequentialTransactionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isSequentialTransactionPlan}\n */\nexport function assertIsSequentialTransactionPlan(plan: TransactionPlan): asserts plan is SequentialTransactionPlan {\n if (!isSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a non-divisible sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * if (isNonDivisibleSequentialTransactionPlan(plan)) {\n * // All transaction messages must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlan}\n */\nexport function isNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): plan is SequentialTransactionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a non-divisible sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlan(plan);\n * // All transaction messages must be executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isNonDivisibleSequentialTransactionPlan}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): asserts plan is SequentialTransactionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a parallel transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * if (isParallelTransactionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link assertIsParallelTransactionPlan}\n */\nexport function isParallelTransactionPlan(plan: TransactionPlan): plan is ParallelTransactionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a parallel transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * assertIsParallelTransactionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link isParallelTransactionPlan}\n */\nexport function assertIsParallelTransactionPlan(plan: TransactionPlan): asserts plan is ParallelTransactionPlan {\n if (!isParallelTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * @deprecated Use {@link flattenTransactionPlan} instead.\n */\nexport const getAllSingleTransactionPlans = flattenTransactionPlan;\n\n/**\n * Retrieves all individual {@link SingleTransactionPlan} instances from a transaction plan tree.\n *\n * This function recursively traverses any nested structure of transaction plans and extracts\n * all the single transaction plans they contain. It's useful when you need to access all\n * the actual transaction messages that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param transactionPlan - The transaction plan to extract single plans from\n * @returns An array of all single transaction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * messageE,\n * ]);\n *\n * const singlePlans = flattenTransactionPlan(plan);\n * // Array of `SingleTransactionPlan` containing:\n * // messageA, messageB, messageC and messageD.\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * ```\n */\nexport function flattenTransactionPlan(transactionPlan: TransactionPlan): SingleTransactionPlan[] {\n if (transactionPlan.kind === 'single') {\n return [transactionPlan];\n }\n return transactionPlan.plans.flatMap(flattenTransactionPlan);\n}\n\n/**\n * Finds the first transaction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param transactionPlan - The transaction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @return The first matching transaction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const nonDivisible = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing messageC and messageD.\n * ```\n *\n * @example\n * Finding a specific single transaction plan.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB, messageC]);\n *\n * const found = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.message === messageB,\n * );\n * // Returns the SingleTransactionPlan wrapping messageB.\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function findTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): TransactionPlan | undefined {\n if (predicate(transactionPlan)) {\n return transactionPlan;\n }\n if (transactionPlan.kind === 'single') {\n return undefined;\n }\n for (const subPlan of transactionPlan.plans) {\n const foundPlan = findTransactionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every transaction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param transactionPlan - The transaction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const allDivisible = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single plans have a specific fee payer.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const allUseSameFeePayer = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.message.feePayer.address === myFeePayer,\n * );\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function everyTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): boolean {\n if (!predicate(transactionPlan)) {\n return false;\n }\n if (transactionPlan.kind === 'single') {\n return true;\n }\n return transactionPlan.plans.every(p => everyTransactionPlan(p, predicate));\n}\n\n/**\n * Transforms a transaction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlan - The transaction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed transaction plan tree.\n *\n * @example\n * Removing parallelism by converting parallel plans to sequential.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'parallel') {\n * return sequentialTransactionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Updating the fee payer on all transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'single') {\n * return singleTransactionPlan({ ...p.message, feePayer: newFeePayer });\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function transformTransactionPlan(\n transactionPlan: TransactionPlan,\n fn: (plan: TransactionPlan) => TransactionPlan,\n): TransactionPlan {\n if (transactionPlan.kind === 'single') {\n return Object.freeze(fn(transactionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlan,\n plans: transactionPlan.plans.map(p => transformTransactionPlan(p, fn)),\n }),\n ),\n );\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { getSignatureFromTransaction, Transaction } from '@solana/transactions';\n\n/**\n * The result of executing a transaction plan.\n *\n * This is structured as a recursive tree of results that mirrors the structure\n * of the original transaction plan, capturing the execution status at each level.\n *\n * Namely, the following result types are supported:\n * - {@link SingleTransactionPlanResult} - A result for a single transaction message\n * containing its execution status.\n * - {@link ParallelTransactionPlanResult} - A result containing other results that\n * were executed in parallel.\n * - {@link SequentialTransactionPlanResult} - A result containing other results that\n * were executed sequentially. It also retains the divisibility property from the\n * original plan.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link TransactionPlanResultStatus}\n */\nexport type TransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = ParallelTransactionPlanResult | SequentialTransactionPlanResult | TSingle;\n\n/**\n * A {@link TransactionPlanResult} where all single transaction results are successful.\n *\n * This type represents a transaction plan result tree where every\n * {@link SingleTransactionPlanResult} has a 'successful' status. It can be used\n * to ensure that an entire execution completed without any failures or cancellations.\n *\n * Note: This is different from {@link SuccessfulSingleTransactionPlanResult} which\n * represents a single successful transaction, whereas this type represents an entire\n * plan result tree (which may contain parallel/sequential structures) where all\n * leaf nodes are successful.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n *\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link SuccessfulSingleTransactionPlanResult}\n */\nexport type SuccessfulTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = TransactionPlanResult>;\n\n/** A context object that may be passed along with successful results. */\nexport type TransactionPlanResultContext = Record;\n\n/**\n * A result for a sequential transaction plan.\n *\n * This represents the execution result of a {@link SequentialTransactionPlan} and\n * contains child results that were executed sequentially. It also retains the\n * divisibility property from the original plan.\n *\n * You may use the {@link sequentialTransactionPlanResult} and\n * {@link nonDivisibleSequentialTransactionPlanResult} helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult;\n * ```\n *\n * @example\n * Non-divisible sequential result.\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link sequentialTransactionPlanResult}\n * @see {@link nonDivisibleSequentialTransactionPlanResult}\n */\nexport type SequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a parallel transaction plan.\n *\n * This represents the execution result of a {@link ParallelTransactionPlan} and\n * contains child results that were executed in parallel.\n *\n * You may use the {@link parallelTransactionPlanResult} helper to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link parallelTransactionPlanResult}\n */\nexport type ParallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n kind: 'parallel';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a single transaction plan.\n *\n * This represents the execution result of a {@link SingleTransactionPlan} and\n * contains the original transaction message along with its execution status.\n *\n * You may use the {@link successfulSingleTransactionPlanResult},\n * {@link failedSingleTransactionPlanResult}, or {@link canceledSingleTransactionPlanResult}\n * helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TTransactionMessage - The type of the transaction message\n *\n * @example\n * Successful result with a transaction and context.\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Failed result with an error.\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError(SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Canceled result.\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link successfulSingleTransactionPlanResult}\n * @see {@link failedSingleTransactionPlanResult}\n * @see {@link canceledSingleTransactionPlanResult}\n */\nexport type SingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n status: TransactionPlanResultStatus;\n}>;\n\n/**\n * The status of a single transaction plan execution.\n *\n * This represents the outcome of executing a single transaction message and can be one of:\n * - `successful` - The transaction was successfully executed. Contains the transaction\n * and an optional context object.\n * - `failed` - The transaction execution failed. Contains the error that caused the failure.\n * - `canceled` - The transaction execution was canceled.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n */\nexport type TransactionPlanResultStatus =\n | Readonly<{ context: TContext; kind: 'successful'; signature: Signature; transaction?: Transaction }>\n | Readonly<{ error: Error; kind: 'failed' }>\n | Readonly<{ kind: 'canceled' }>;\n\n/**\n * Creates a divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `true`,\n * indicating that the nested plans were executed sequentially but could have been\n * split into separate transactions or batches.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: true };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function sequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `false`,\n * indicating that the nested plans were executed sequentially and could not have been\n * split into separate transactions or batches (e.g., they were executed as a transaction bundle).\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function nonDivisibleSequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans });\n}\n\n/**\n * Creates a {@link ParallelTransactionPlanResult} from an array of nested results.\n *\n * This function creates a parallel result indicating that the nested plans\n * were executed in parallel.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed in parallel\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n */\nexport function parallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): ParallelTransactionPlanResult {\n return Object.freeze({ kind: 'parallel', plans });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and transaction.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param transaction - The successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n transaction: Transaction,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({\n context: context ?? ({} as TContext),\n kind: 'successful',\n signature: getSignatureFromTransaction(transaction),\n transaction,\n }),\n });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and signature.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the signature of the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param signature - The signature of the successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * signature\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResultFromSignature<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n signature: Signature,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ context: context ?? ({} as TContext), kind: 'successful', signature }),\n });\n}\n\n/**\n * Creates a failed {@link SingleTransactionPlanResult} from a transaction message and error.\n *\n * This function creates a single result with a 'failed' status, indicating that\n * the transaction execution failed. It includes the original transaction message\n * and the error that caused the failure.\n *\n * @template TContext - The type of the context object (not used in failed results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param error - The error that caused the transaction to fail\n *\n * @example\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError({\n * code: 123,\n * message: 'Transaction simulation failed',\n * }),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function failedSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage, error: Error): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ error, kind: 'failed' }),\n });\n}\n\n/**\n * Creates a canceled {@link SingleTransactionPlanResult} from a transaction message.\n *\n * This function creates a single result with a 'canceled' status, indicating that\n * the transaction execution was canceled. It includes the original transaction message.\n *\n * @template TContext - The type of the context object (not used in canceled results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n *\n * @example\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function canceledSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ kind: 'canceled' }),\n });\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSingleTransactionPlanResult(result)) {\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link assertIsSingleTransactionPlanResult}\n */\nexport function isSingleTransactionPlanResult(plan: TransactionPlanResult): plan is SingleTransactionPlanResult {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSingleTransactionPlanResult(result);\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link isSingleTransactionPlanResult}\n */\nexport function assertIsSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SingleTransactionPlanResult {\n if (!isSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a successful single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSuccessfulSingleTransactionPlanResult(result)) {\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * }\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'successful';\n}\n\n/**\n * Asserts that the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a successful single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSuccessfulSingleTransactionPlanResult(result);\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulSingleTransactionPlanResult {\n if (!isSuccessfulSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'successful single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a failed single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * if (isFailedSingleTransactionPlanResult(result)) {\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * }\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link assertIsFailedSingleTransactionPlanResult}\n */\nexport function isFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is FailedSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'failed';\n}\n\n/**\n * Asserts that the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a failed single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * assertIsFailedSingleTransactionPlanResult(result);\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link isFailedSingleTransactionPlanResult}\n */\nexport function assertIsFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is FailedSingleTransactionPlanResult {\n if (!isFailedSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'failed single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a canceled single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * if (isCanceledSingleTransactionPlanResult(result)) {\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * }\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link assertIsCanceledSingleTransactionPlanResult}\n */\nexport function isCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is CanceledSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'canceled';\n}\n\n/**\n * Asserts that the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a canceled single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * assertIsCanceledSingleTransactionPlanResult(result);\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link isCanceledSingleTransactionPlanResult}\n */\nexport function assertIsCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is CanceledSingleTransactionPlanResult {\n if (!isCanceledSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'canceled single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isSequentialTransactionPlanResult(result)) {\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsSequentialTransactionPlanResult}\n */\nexport function isSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsSequentialTransactionPlanResult(result);\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isSequentialTransactionPlanResult}\n */\nexport function assertIsSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult {\n if (!isSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a non-divisible sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isNonDivisibleSequentialTransactionPlanResult(result)) {\n * // Transactions were executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlanResult}\n */\nexport function isNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a non-divisible sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlanResult(result);\n * // Transactions were executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isNonDivisibleSequentialTransactionPlanResult}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a parallel transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * if (isParallelTransactionPlanResult(result)) {\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link assertIsParallelTransactionPlanResult}\n */\nexport function isParallelTransactionPlanResult(plan: TransactionPlanResult): plan is ParallelTransactionPlanResult {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a parallel transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * assertIsParallelTransactionPlanResult(result);\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link isParallelTransactionPlanResult}\n */\nexport function assertIsParallelTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is ParallelTransactionPlanResult {\n if (!isParallelTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It recursively checks all nested results\n * to ensure every {@link SingleTransactionPlanResult} has a 'successful' status.\n *\n * Note: This is different from {@link isSuccessfulSingleTransactionPlanResult} which\n * checks if a single result is successful. This function checks that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if all single transaction results in the tree are successful, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * if (isSuccessfulTransactionPlanResult(result)) {\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * }\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulTransactionPlanResult {\n return everyTransactionPlanResult(\n plan,\n r => !isSingleTransactionPlanResult(r) || isSuccessfulSingleTransactionPlanResult(r),\n );\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It throws if any {@link SingleTransactionPlanResult}\n * in the tree has a 'failed' or 'canceled' status.\n *\n * Note: This is different from {@link assertIsSuccessfulSingleTransactionPlanResult} which\n * asserts that a single result is successful. This function asserts that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT` if\n * any single transaction result in the tree is not successful.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * assertIsSuccessfulTransactionPlanResult(result);\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulTransactionPlanResult {\n if (!isSuccessfulTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT, {\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Finds the first transaction plan result in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan result tree,\n * returning the first result that satisfies the predicate. It checks the root result\n * first, then recursively searches through nested results.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @param predicate - A function that returns `true` for the result to find.\n * @returns The first matching transaction plan result, or `undefined` if no match is found.\n *\n * @example\n * Finding a failed transaction result.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * ]);\n *\n * const failed = findTransactionPlanResult(\n * result,\n * (r) => r.kind === 'single' && r.status.kind === 'failed',\n * );\n * // Returns the failed single transaction plan result for messageB.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function findTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (result: TransactionPlanResult) => boolean,\n): TransactionPlanResult | undefined {\n if (predicate(transactionPlanResult)) {\n return transactionPlanResult;\n }\n if (transactionPlanResult.kind === 'single') {\n return undefined;\n }\n for (const subResult of transactionPlanResult.plans) {\n const foundResult = findTransactionPlanResult(subResult, predicate);\n if (foundResult) {\n return foundResult;\n }\n }\n return undefined;\n}\n\n/**\n * Retrieves the first failed transaction plan result from a transaction plan result tree.\n *\n * This function searches the transaction plan result tree using a depth-first traversal\n * and returns the first single transaction result with a 'failed' status. If no failed\n * result is found, it throws a {@link SolanaError}.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @return The first failed single transaction plan result.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND` if no\n * failed transaction plan result is found. The error context contains a non-enumerable\n * `transactionPlanResult` property for recovery purposes.\n *\n * @example\n * Retrieving the first failed result from a parallel execution.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * failedSingleTransactionPlanResult(messageC, anotherError),\n * ]);\n *\n * const firstFailed = getFirstFailedSingleTransactionPlanResult(result);\n * // Returns the failed result for messageB.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n */\nexport function getFirstFailedSingleTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n): FailedSingleTransactionPlanResult {\n const result = findTransactionPlanResult(\n transactionPlanResult,\n r => r.kind === 'single' && r.status.kind === 'failed',\n );\n\n if (!result) {\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can recover but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n const context = {};\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n context,\n );\n }\n\n return result as FailedSingleTransactionPlanResult;\n}\n\n/**\n * Checks if every transaction plan result in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan result tree,\n * returning `true` only if the predicate returns `true` for every result in the tree\n * (including the root result and all nested results).\n *\n * @param transactionPlanResult - The transaction plan result tree to check.\n * @param predicate - A function that returns `true` if the result satisfies the condition.\n * @return `true` if every result in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all transactions were successful.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * const allSuccessful = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind === 'successful',\n * );\n * // Returns true because all single results are successful.\n * ```\n *\n * @example\n * Checking if no transactions were canceled.\n * ```ts\n * const result = sequentialTransactionPlanResult([resultA, resultB, resultC]);\n *\n * const noCanceled = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind !== 'canceled',\n * );\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function everyTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (plan: TransactionPlanResult) => boolean,\n): boolean {\n if (!predicate(transactionPlanResult)) {\n return false;\n }\n if (transactionPlanResult.kind === 'single') {\n return true;\n }\n return transactionPlanResult.plans.every(p => everyTransactionPlanResult(p, predicate));\n}\n\n/**\n * Transforms a transaction plan result tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan result tree, applying the\n * transformation function to each result. The transformation is applied bottom-up,\n * meaning nested results are transformed first, then the parent results receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed results are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlanResult - The transaction plan result tree to transform.\n * @param fn - A function that transforms each result and returns a new result.\n * @return A new transformed transaction plan result tree.\n *\n * @example\n * Converting all canceled results to failed results.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * canceledSingleTransactionPlanResult(messageB),\n * ]);\n *\n * const transformed = transformTransactionPlanResult(result, (r) => {\n * if (r.kind === 'single' && r.status.kind === 'canceled') {\n * return failedSingleTransactionPlanResult(r.message, new Error('Execution canceled'));\n * }\n * return r;\n * });\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function transformTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n fn: (plan: TransactionPlanResult) => TransactionPlanResult,\n): TransactionPlanResult {\n if (transactionPlanResult.kind === 'single') {\n return Object.freeze(fn(transactionPlanResult));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlanResult,\n plans: transactionPlanResult.plans.map(p => transformTransactionPlanResult(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleTransactionPlanResult} instances from a transaction plan result tree.\n *\n * This function recursively traverses any nested structure of transaction plan results and extracts\n * all the single results they contain. It's useful when you need to access all the individual\n * transaction results, regardless of their organization in the result tree (parallel or sequential).\n *\n * @param result - The transaction plan result to extract single results from\n * @returns An array of all single transaction plan results contained in the tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * sequentialTransactionPlanResult([resultA, resultB]),\n * nonDivisibleSequentialTransactionPlanResult([resultC, resultD]),\n * resultE,\n * ]);\n *\n * const singleResults = flattenTransactionPlanResult(result);\n * // Array of `SingleTransactionPlanResult` containing:\n * // resultA, resultB, resultC, resultD and resultE.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n */\nexport function flattenTransactionPlanResult(result: TransactionPlanResult): SingleTransactionPlanResult[] {\n if (result.kind === 'single') {\n return [result];\n }\n return result.plans.flatMap(flattenTransactionPlanResult);\n}\n\n/**\n * A {@link SingleTransactionPlanResult} with 'successful' status.\n */\nexport type SuccessfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = SingleTransactionPlanResult & { status: { kind: 'successful' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'failed' status.\n */\nexport type FailedSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'failed' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'canceled' status.\n */\nexport type CanceledSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'canceled' } };\n\n/**\n * A summary of a {@link TransactionPlanResult}, categorizing transactions by their execution status.\n * - `successful`: Indicates whether all transactions were successful (i.e., no failed or canceled transactions).\n * - `successfulTransactions`: An array of successful transactions, each including its signature.\n * - `failedTransactions`: An array of failed transactions, each including the error that caused the failure.\n * - `canceledTransactions`: An array of canceled transactions.\n */\nexport type TransactionPlanResultSummary = Readonly<{\n canceledTransactions: CanceledSingleTransactionPlanResult[];\n failedTransactions: FailedSingleTransactionPlanResult[];\n successful: boolean;\n successfulTransactions: SuccessfulSingleTransactionPlanResult[];\n}>;\n\n/**\n * Summarize a {@link TransactionPlanResult} into a {@link TransactionPlanResultSummary}.\n * @param result The transaction plan result to summarize\n * @returns A summary of the transaction plan result\n */\nexport function summarizeTransactionPlanResult(result: TransactionPlanResult): TransactionPlanResultSummary {\n const successfulTransactions: TransactionPlanResultSummary['successfulTransactions'] = [];\n const failedTransactions: TransactionPlanResultSummary['failedTransactions'] = [];\n const canceledTransactions: TransactionPlanResultSummary['canceledTransactions'] = [];\n\n const flattenedResults = flattenTransactionPlanResult(result);\n\n for (const singleResult of flattenedResults) {\n switch (singleResult.status.kind) {\n case 'successful': {\n successfulTransactions.push(singleResult as SuccessfulSingleTransactionPlanResult);\n break;\n }\n case 'failed': {\n failedTransactions.push(singleResult as FailedSingleTransactionPlanResult);\n break;\n }\n case 'canceled': {\n canceledTransactions.push(singleResult as CanceledSingleTransactionPlanResult);\n break;\n }\n }\n }\n\n return Object.freeze({\n canceledTransactions,\n failedTransactions,\n successful: failedTransactions.length === 0 && canceledTransactions.length === 0,\n successfulTransactions,\n });\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { getAbortablePromise } from '@solana/promises';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { Transaction } from '@solana/transactions';\n\nimport type {\n ParallelTransactionPlan,\n SequentialTransactionPlan,\n SingleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\nimport {\n canceledSingleTransactionPlanResult,\n failedSingleTransactionPlanResult,\n parallelTransactionPlanResult,\n sequentialTransactionPlanResult,\n SingleTransactionPlanResult,\n successfulSingleTransactionPlanResult,\n successfulSingleTransactionPlanResultFromSignature,\n type TransactionPlanResult,\n type TransactionPlanResultContext,\n} from './transaction-plan-result';\n\n/**\n * Executes a transaction plan and returns the execution results.\n *\n * This function traverses the transaction plan tree, executing each transaction\n * message and collecting results that mirror the structure of the original plan.\n *\n * @typeParam TContext - The type of the context object that may be passed along with successful results.\n * @param transactionPlan - The transaction plan to execute.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel execution.\n * @return A promise that resolves to the execution results.\n *\n * @see {@link TransactionPlan}\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutor = (\n transactionPlan: TransactionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\ntype ExecuteResult = {\n context?: TContext;\n} & ({ signature: Signature } | { transaction: Transaction });\n\ntype ExecuteTransactionMessage = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\n/**\n * Configuration object for creating a new transaction plan executor.\n *\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutorConfig = {\n /** Called whenever a transaction message must be sent to the blockchain. */\n executeTransactionMessage: ExecuteTransactionMessage;\n};\n\n/**\n * Creates a new transaction plan executor based on the provided configuration.\n *\n * The executor will traverse the provided `TransactionPlan` sequentially or in parallel,\n * executing each transaction message using the `executeTransactionMessage` function.\n *\n * - If that function is successful, the executor will return a successful `TransactionPlanResult`\n * for that message including the transaction and any custom context.\n * - If that function throws an error, the executor will stop processing and cancel all\n * remaining transaction messages in the plan.\n * - If the `abortSignal` is triggered, the executor will immediately stop processing the plan and\n * return a `TransactionPlanResult` with the status set to `canceled`.\n *\n * @param config - Configuration object containing the transaction message executor function.\n * @return A {@link TransactionPlanExecutor} function that can execute transaction plans.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * if any transaction in the plan fails to execute. The error context contains a\n * `transactionPlanResult` property with the partial results up to the point of failure.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED}\n * if the transaction plan contains non-divisible sequential plans, which are not\n * supported by this executor.\n *\n * @example\n * ```ts\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * const transactionPlanExecutor = createTransactionPlanExecutor({\n * executeTransactionMessage: async (message) => {\n * const transaction = await signTransactionMessageWithSigners(message);\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * return { transaction };\n * }\n * });\n * ```\n *\n * @see {@link TransactionPlanExecutorConfig}\n */\nexport function createTransactionPlanExecutor(config: TransactionPlanExecutorConfig): TransactionPlanExecutor {\n return async (plan, { abortSignal } = {}): Promise => {\n const context: TraverseContext = {\n ...config,\n abortSignal: abortSignal,\n canceled: abortSignal?.aborted ?? false,\n };\n\n // Fail early if there are non-divisible sequential plans in the\n // transaction plan as they are not supported by this executor.\n assertDivisibleSequentialPlansOnly(plan);\n\n const cancelHandler = () => {\n context.canceled = true;\n };\n abortSignal?.addEventListener('abort', cancelHandler);\n const transactionPlanResult = await traverse(plan, context);\n abortSignal?.removeEventListener('abort', cancelHandler);\n\n if (context.canceled) {\n const abortReason = abortSignal?.aborted ? abortSignal.reason : undefined;\n const context = { cause: findErrorFromTransactionPlanResult(transactionPlanResult) ?? abortReason };\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can create recovery plans but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, context);\n }\n\n return transactionPlanResult;\n };\n}\n\ntype TraverseContext = TransactionPlanExecutorConfig & {\n abortSignal?: AbortSignal;\n canceled: boolean;\n};\n\nasync function traverse(transactionPlan: TransactionPlan, context: TraverseContext): Promise {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(transactionPlan, context);\n case 'parallel':\n return await traverseParallel(transactionPlan, context);\n case 'single':\n return await traverseSingle(transactionPlan, context);\n default:\n transactionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n transactionPlan: SequentialTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n\n const results: TransactionPlanResult[] = [];\n\n for (const subPlan of transactionPlan.plans) {\n const result = await traverse(subPlan, context);\n results.push(result);\n }\n\n return sequentialTransactionPlanResult(results);\n}\n\nasync function traverseParallel(\n transactionPlan: ParallelTransactionPlan,\n context: TraverseContext,\n): Promise {\n const results = await Promise.all(transactionPlan.plans.map(plan => traverse(plan, context)));\n return parallelTransactionPlanResult(results);\n}\n\nasync function traverseSingle(\n transactionPlan: SingleTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (context.canceled) {\n return canceledSingleTransactionPlanResult(transactionPlan.message);\n }\n\n try {\n const result = await getAbortablePromise(\n context.executeTransactionMessage(transactionPlan.message, { abortSignal: context.abortSignal }),\n context.abortSignal,\n );\n if ('transaction' in result) {\n return successfulSingleTransactionPlanResult(transactionPlan.message, result.transaction, result.context);\n } else {\n return successfulSingleTransactionPlanResultFromSignature(\n transactionPlan.message,\n result.signature,\n result.context,\n );\n }\n } catch (error) {\n context.canceled = true;\n return failedSingleTransactionPlanResult(transactionPlan.message, error as Error);\n }\n}\n\nfunction findErrorFromTransactionPlanResult(result: TransactionPlanResult): Error | undefined {\n if (result.kind === 'single') {\n return result.status.kind === 'failed' ? result.status.error : undefined;\n }\n for (const plan of result.plans) {\n const error = findErrorFromTransactionPlanResult(plan);\n if (error) {\n return error;\n }\n }\n}\n\nfunction assertDivisibleSequentialPlansOnly(transactionPlan: TransactionPlan): void {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'parallel':\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'single':\n default:\n return;\n }\n}\n\n/**\n * Wraps a transaction plan execution promise to return a\n * {@link TransactionPlanResult} even on execution failure.\n *\n * When a transaction plan executor throws a\n * {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * error, this helper catches it and returns the `TransactionPlanResult`\n * from the error context instead of throwing.\n *\n * This allows us to handle the result of an execution in a single unified way\n * instead of using try/catch and examine the `TransactionPlanResult` in both\n * success and failure cases.\n *\n * Any other errors are re-thrown as normal.\n *\n * @param promise - A promise returned by a transaction plan executor.\n * @return A promise that resolves to the transaction plan result, even if some transactions failed.\n *\n * @example\n * Handling failures using a single result object:\n * ```ts\n * const result = await passthroughFailedTransactionPlanExecution(\n * transactionPlanExecutor(transactionPlan)\n * );\n *\n * const summary = summarizeTransactionPlanResult(result);\n * if (summary.successful) {\n * console.log('All transactions executed successfully');\n * } else {\n * console.log(`${summary.successfulTransactions.length} succeeded`);\n * console.log(`${summary.failedTransactions.length} failed`);\n * console.log(`${summary.canceledTransactions.length} canceled`);\n * }\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n * @see {@link summarizeTransactionPlanResult}\n */\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise {\n try {\n return await promise;\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN)) {\n return error.context.transactionPlanResult as TransactionPlanResult;\n }\n throw error;\n }\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { getAbortablePromise } from '@solana/promises';\nimport {\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\nimport {\n InstructionPlan,\n MessagePackerInstructionPlan,\n ParallelInstructionPlan,\n SequentialInstructionPlan,\n SingleInstructionPlan,\n} from './instruction-plan';\nimport {\n flattenTransactionPlan,\n nonDivisibleSequentialTransactionPlan,\n parallelTransactionPlan,\n sequentialTransactionPlan,\n SingleTransactionPlan,\n singleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\n\n/**\n * Plans one or more transactions according to the provided instruction plan.\n *\n * @param instructionPlan - The instruction plan to be planned and executed.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel the planning process.\n *\n * @see {@link InstructionPlan}\n * @see {@link TransactionPlan}\n */\nexport type TransactionPlanner = (\n instructionPlan: InstructionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise;\n\ntype Mutable = { -readonly [P in keyof T]: T[P] };\n\ntype CreateTransactionMessage = (config?: {\n abortSignal?: AbortSignal;\n}) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\ntype OnTransactionMessageUpdated = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\n/**\n * Configuration object for creating a new transaction planner.\n *\n * @see {@link createTransactionPlanner}\n */\nexport type TransactionPlannerConfig = {\n /** Called whenever a new transaction message is needed. */\n createTransactionMessage: CreateTransactionMessage;\n /**\n * Called whenever a transaction message is updated — e.g. new instructions were added.\n * This function must return the updated transaction message back — even if no changes were made.\n */\n onTransactionMessageUpdated?: OnTransactionMessageUpdated;\n};\n\n/**\n * Creates a new transaction planner based on the provided configuration.\n *\n * At the very least, the `createTransactionMessage` function must be provided.\n * This function is used to create new transaction messages whenever needed.\n *\n * Additionally, the `onTransactionMessageUpdated` function can be provided\n * to update transaction messages during the planning process. This function will\n * be called whenever a transaction message is updated, e.g. when new instructions\n * are added to a transaction message. It accepts the updated transaction message\n * and must return a transaction message back, even if no changes were made.\n *\n * @example\n * ```ts\n * const transactionPlanner = createTransactionPlanner({\n * createTransactionMessage: () => pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(mySigner, message),\n * )\n * });\n * ```\n *\n * @see {@link TransactionPlannerConfig}\n */\nexport function createTransactionPlanner(config: TransactionPlannerConfig): TransactionPlanner {\n return async (instructionPlan, { abortSignal } = {}): Promise => {\n const plan = await traverse(instructionPlan, {\n abortSignal,\n createTransactionMessage: config.createTransactionMessage,\n onTransactionMessageUpdated: config.onTransactionMessageUpdated ?? (msg => msg),\n parent: null,\n parentCandidates: [],\n });\n\n if (!plan) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN);\n }\n\n return freezeTransactionPlan(plan);\n };\n}\n\ntype MutableTransactionPlan = Mutable;\ntype MutableSingleTransactionPlan = Mutable;\n\ntype TraverseContext = {\n abortSignal?: AbortSignal;\n createTransactionMessage: CreateTransactionMessage;\n onTransactionMessageUpdated: OnTransactionMessageUpdated;\n parent: InstructionPlan | null;\n parentCandidates: MutableSingleTransactionPlan[];\n};\n\nasync function traverse(\n instructionPlan: InstructionPlan,\n context: TraverseContext,\n): Promise {\n context.abortSignal?.throwIfAborted();\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(instructionPlan, context);\n case 'parallel':\n return await traverseParallel(instructionPlan, context);\n case 'single':\n return await traverseSingle(instructionPlan, context);\n case 'messagePacker':\n return await traverseMessagePacker(instructionPlan, context);\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n instructionPlan: SequentialInstructionPlan,\n context: TraverseContext,\n): Promise {\n let candidate: MutableSingleTransactionPlan | null = null;\n\n // Check if the sequential plan must fit entirely in its parent candidates\n // due to constraints like being inside a parallel plan or not being divisible.\n const mustEntirelyFitInParentCandidate =\n context.parent && (context.parent.kind === 'parallel' || !instructionPlan.divisible);\n\n // If so, try to fit the entire plan inside one of the parent candidates.\n if (mustEntirelyFitInParentCandidate) {\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, message =>\n fitEntirePlanInsideMessage(instructionPlan, message),\n );\n // If that's possible, we the candidate is mutated and we can return null.\n // Otherwise, we proceed with the normal traversal and no parent candidate.\n if (candidate) {\n return null;\n }\n } else {\n // Otherwise, we can use the first parent candidate, if any,\n // since we know it must be a divisible sequential plan.\n candidate = context.parentCandidates.length > 0 ? context.parentCandidates[0] : null;\n }\n\n const transactionPlans: TransactionPlan[] = [];\n for (const plan of instructionPlan.plans) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidate ? [candidate] : [],\n });\n if (transactionPlan) {\n candidate = getSequentialCandidate(transactionPlan);\n const newPlans =\n transactionPlan.kind === 'sequential' && (transactionPlan.divisible || !instructionPlan.divisible)\n ? transactionPlan.plans\n : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a sequential plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return {\n divisible: instructionPlan.divisible,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nasync function traverseParallel(\n instructionPlan: ParallelInstructionPlan,\n context: TraverseContext,\n): Promise {\n const candidates: MutableSingleTransactionPlan[] = [...context.parentCandidates];\n const transactionPlans: TransactionPlan[] = [];\n\n // Reorder children so message packer plans are last.\n const sortedChildren = Array.from(instructionPlan.plans).sort(\n (a, b) => Number(a.kind === 'messagePacker') - Number(b.kind === 'messagePacker'),\n );\n\n for (const plan of sortedChildren) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidates,\n });\n if (transactionPlan) {\n candidates.push(...getParallelCandidates(transactionPlan));\n const newPlans = transactionPlan.kind === 'parallel' ? transactionPlan.plans : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a parallel plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return { kind: 'parallel', plans: transactionPlans };\n}\n\nasync function traverseSingle(\n instructionPlan: SingleInstructionPlan,\n context: TraverseContext,\n): Promise {\n const predicate = (message: TransactionMessage & TransactionMessageWithFeePayer) =>\n appendTransactionMessageInstructions([instructionPlan.instruction], message);\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, predicate);\n if (candidate) {\n return null;\n }\n const message = await createNewMessage(context, predicate);\n return { kind: 'single', message };\n}\n\nasync function traverseMessagePacker(\n instructionPlan: MessagePackerInstructionPlan,\n context: TraverseContext,\n): Promise {\n const messagePacker = instructionPlan.getMessagePacker();\n const transactionPlans: SingleTransactionPlan[] = [];\n const candidates = [...context.parentCandidates];\n\n while (!messagePacker.done()) {\n const candidate = await selectAndMutateCandidate(context, candidates, messagePacker.packMessageToCapacity);\n if (!candidate) {\n const message = await createNewMessage(context, messagePacker.packMessageToCapacity);\n const newPlan: MutableSingleTransactionPlan = { kind: 'single', message };\n transactionPlans.push(newPlan);\n }\n }\n\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n if (context.parent?.kind === 'parallel') {\n return { kind: 'parallel', plans: transactionPlans };\n }\n return {\n divisible: context.parent?.kind === 'sequential' ? context.parent.divisible : true,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nfunction getSequentialCandidate(latestPlan: MutableTransactionPlan): MutableSingleTransactionPlan | null {\n if (latestPlan.kind === 'single') {\n return latestPlan;\n }\n if (latestPlan.kind === 'sequential' && latestPlan.plans.length > 0) {\n return getSequentialCandidate(latestPlan.plans[latestPlan.plans.length - 1]);\n }\n return null;\n}\n\nfunction getParallelCandidates(latestPlan: TransactionPlan): MutableSingleTransactionPlan[] {\n return flattenTransactionPlan(latestPlan);\n}\n\nasync function selectAndMutateCandidate(\n context: Pick,\n candidates: MutableSingleTransactionPlan[],\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n for (const candidate of candidates) {\n try {\n const message = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(candidate.message), {\n abortSignal: context.abortSignal,\n }),\n ),\n context.abortSignal,\n );\n if (getTransactionMessageSize(message) <= TRANSACTION_SIZE_LIMIT) {\n candidate.message = message;\n return candidate;\n }\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN)) {\n // Try the next candidate.\n } else {\n throw error;\n }\n }\n }\n return null;\n}\n\nasync function createNewMessage(\n context: Pick,\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n const newMessage = await getAbortablePromise(\n Promise.resolve(context.createTransactionMessage({ abortSignal: context.abortSignal })),\n context.abortSignal,\n );\n const updatedMessage = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(newMessage), { abortSignal: context.abortSignal }),\n ),\n context.abortSignal,\n );\n const updatedMessageSize = getTransactionMessageSize(updatedMessage);\n if (updatedMessageSize > TRANSACTION_SIZE_LIMIT) {\n const newMessageSize = getTransactionMessageSize(newMessage);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: updatedMessageSize - newMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - newMessageSize,\n });\n }\n return updatedMessage;\n}\n\nfunction freezeTransactionPlan(plan: MutableTransactionPlan): TransactionPlan {\n const kind = plan.kind;\n switch (kind) {\n case 'single':\n return singleTransactionPlan(plan.message);\n case 'sequential':\n return plan.divisible\n ? sequentialTransactionPlan(plan.plans.map(freezeTransactionPlan))\n : nonDivisibleSequentialTransactionPlan(plan.plans.map(freezeTransactionPlan));\n case 'parallel':\n return parallelTransactionPlan(plan.plans.map(freezeTransactionPlan));\n default:\n plan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nfunction fitEntirePlanInsideMessage(\n instructionPlan: InstructionPlan,\n message: TransactionMessage & TransactionMessageWithFeePayer,\n): TransactionMessage & TransactionMessageWithFeePayer {\n let newMessage: TransactionMessage & TransactionMessageWithFeePayer = message;\n\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n case 'parallel':\n for (const plan of instructionPlan.plans) {\n newMessage = fitEntirePlanInsideMessage(plan, newMessage);\n }\n return newMessage;\n case 'single':\n newMessage = appendTransactionMessageInstructions([instructionPlan.instruction], message);\n // eslint-disable-next-line no-case-declarations\n const newMessageSize = getTransactionMessageSize(newMessage);\n if (newMessageSize > TRANSACTION_SIZE_LIMIT) {\n const baseMessageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: newMessageSize - baseMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - baseMessageSize,\n });\n }\n return newMessage;\n case 'messagePacker':\n // eslint-disable-next-line no-case-declarations\n const messagePacker = instructionPlan.getMessagePacker();\n while (!messagePacker.done()) {\n newMessage = messagePacker.packMessageToCapacity(newMessage);\n }\n return newMessage;\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n","import { assertIsAddress, isAddress } from '@solana/addresses';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * A 32-byte array identifying the application requesting off-chain message signing.\n *\n * This may be any arbitrary bytes. For instance the on-chain address of a program, DAO instance,\n * Candy Machine, et cetera.\n *\n * This field SHOULD be displayed to users as a base58-encoded ASCII string rather than interpreted\n * otherwise.\n */\nexport type OffchainMessageApplicationDomain = Brand<\n EncodedString,\n 'OffchainMessageApplicationDomain'\n>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the\n * {@link OffchainMessageApplicationDomain} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * if (isOffchainMessageApplicationDomain(applicationDomain)) {\n * // At this point, `applicationDomain` has been refined to an\n * // `OffchainMessageApplcationDomain` that can be used to craft a message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } else {\n * setError(`${applicationDomain} is not a valid application domain for an offchain message`);\n * }\n * ```\n */\nexport function isOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): putativeApplicationDomain is OffchainMessageApplicationDomain {\n return isAddress(putativeApplicationDomain);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an offchain message\n * application domain, from an untrusted network API or user input. Use this function to assert that\n * such an arbitrary string is a base58-encoded application domain.\n *\n * @example\n * ```ts\n * import { assertIsOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * // Imagine a function that determines whether an application domain is valid.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const applicationDomain: string = applicationDomainInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `applicationDomain` to `OffchainMessageApplicationDomain`.\n * assertIsOffchainMessageApplicationDomain(applicationDomain);\n * // At this point, `applicationDomain` is a `OffchainMessageApplicationDomain` that can be\n * // used to craft an offchain message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } catch (e) {\n * // `applicationDomain` turned out not to be a base58-encoded application domain\n * }\n * }\n * ```\n */\nexport function assertIsOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): asserts putativeApplicationDomain is OffchainMessageApplicationDomain {\n try {\n assertIsAddress(putativeApplicationDomain);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n error.context,\n );\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n error.context,\n );\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is an offchain message application domain with _coercing_ it\n * to the {@link OffchainMessageApplicationDomain} type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good application domain as a string, it's more efficient to typecast\n * > it rather than to use the {@link offchainMessageApplicationDomain} helper, because the helper\n * > unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageApplicationDomain } from '@solana/offchain-messages';\n * >\n * > const applicationDomain =\n * > 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * > ```\n */\nexport function offchainMessageApplicationDomain(putativeApplicationDomain: string): OffchainMessageApplicationDomain {\n assertIsOffchainMessageApplicationDomain(putativeApplicationDomain);\n return putativeApplicationDomain;\n}\n","import { Address, getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformEncoder,\n} from '@solana/codecs-core';\n\nimport { OffchainMessageApplicationDomain, offchainMessageApplicationDomain } from '../application-domain';\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded offchain message application\n * domain to a byte array.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainEncoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomain =\n * 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * const offchainMessageApplicationDomainEncoder = getOffchainMessageApplicationDomainEncoder();\n * const offchainMessageApplicationDomainBytes =\n * offchainMessageApplicationDomainEncoder.encode(offchainMessageApplicationDomain);\n * // Uint8Array(32) [\n * // 247, 203, 28, 80, 52, 240, 169, 19,\n * // 21, 103, 107, 119, 91, 235, 13, 48,\n * // 194, 169, 148, 160, 78, 105, 235, 37,\n * // 232, 160, 49, 47, 64, 89, 18, 153,\n * // ]\n * ```\n */\nexport function getOffchainMessageApplicationDomainEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getAddressEncoder(),\n putativeApplicationDomain => offchainMessageApplicationDomain(putativeApplicationDomain) as string as Address,\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an offchain\n * message application domain to the base58-encoded representation of that application domain.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomainBytes = new Uint8Array([\n * 247, 203, 28, 80, 52, 240, 169, 19,\n * 21, 103, 107, 119, 91, 235, 13, 48,\n * 194, 169, 148, 160, 78, 105, 235, 37,\n * 232, 160, 49, 47, 64, 89, 18, 153,\n * ]);\n * const offchainMessageApplicationDomainDecoder = getOffchainMessageApplicationDomainDecoder();\n * const offchainMessageApplicationDomain =\n * offchainMessageApplicationDomainDecoder.decode(offchainMessageApplicationDomainBytes);\n * // HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx\n * ```\n */\nexport function getOffchainMessageApplicationDomainDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder<\n OffchainMessageApplicationDomain,\n 32\n >;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded offchain message\n * application domain.\n *\n * @see {@link getOffchainMessageApplicationDomainDecoder}\n * @see {@link getOffchainMessageApplicationDomainEncoder}\n */\nexport function getOffchainMessageApplicationDomainCodec(): FixedSizeCodec<\n OffchainMessageApplicationDomain,\n OffchainMessageApplicationDomain,\n 32\n> {\n return combineCodec(getOffchainMessageApplicationDomainEncoder(), getOffchainMessageApplicationDomainDecoder());\n}\n","import {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getConstantDecoder, getConstantEncoder } from '@solana/codecs-data-structures';\n\n// The string `'\\xffsolana offchain'`\nconst OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES: ReadonlyUint8Array = new Uint8Array([\n 0xff, 0x73, 0x6f, 0x6c, 0x61, 0x6e, 0x61, 0x20, 0x6f, 0x66, 0x66, 0x63, 0x68, 0x61, 0x69, 0x6e,\n]);\n\nexport function getOffchainMessageSigningDomainDecoder(): FixedSizeDecoder {\n return getConstantDecoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeDecoder;\n}\n\nexport function getOffchainMessageSigningDomainEncoder(): FixedSizeEncoder {\n return getConstantEncoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeEncoder;\n}\n\nexport function getOffchainMessageSigningDomainCodec(): FixedSizeCodec {\n return combineCodec(getOffchainMessageSigningDomainEncoder(), getOffchainMessageSigningDomainDecoder());\n}\n","import { Address, getAddressDecoder } from '@solana/addresses';\nimport {\n FixedSizeDecoder,\n FixedSizeEncoder,\n offsetDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageVersion } from '../version';\nimport { getOffchainMessageSigningDomainDecoder, getOffchainMessageSigningDomainEncoder } from './signing-domain';\n\ntype TDecoderFields = Parameters[0];\ntype TEncoderFields = Parameters[0];\n\nfunction getSigningDomainPrefixedDecoder(...fields: T) {\n return getHiddenPrefixDecoder(getStructDecoder(fields), [getOffchainMessageSigningDomainDecoder()]);\n}\n\nfunction getSigningDomainPrefixedEncoder(...fields: T) {\n return getHiddenPrefixEncoder(getStructEncoder(fields), [getOffchainMessageSigningDomainEncoder()]);\n}\n\nfunction getVersionTransformer(fixedVersion?: OffchainMessageVersion) {\n return (version: number) => {\n if (version > 1) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n if (fixedVersion != null && version !== fixedVersion) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION, {\n actualVersion: version,\n expectedVersion: fixedVersion,\n });\n }\n return version;\n };\n}\n\nexport function createOffchainMessagePreambleDecoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TDecoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer(version)) as FixedSizeDecoder],\n ...fields,\n );\n}\n\nexport function createOffchainMessagePreambleEncoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TEncoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedEncoder(\n ['version', transformEncoder(getU8Encoder(), getVersionTransformer(version)) as FixedSizeEncoder],\n ...fields,\n );\n}\n\nexport function decodeRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const { version, bytesAfterVersion } = getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer())],\n ['bytesAfterVersion', getBytesDecoder()],\n ).decode(bytes);\n return offsetDecoder(\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses;\n }),\n {\n preOffset: ({ preOffset }) =>\n preOffset +\n (version === 0\n ? 32 + 1 // skip the application domain and message format of v0 messages\n : 0),\n },\n ).decode(bytesAfterVersion);\n}\n\nexport function getSignatoriesComparator(): (a: ReadonlyUint8Array, b: ReadonlyUint8Array) => -1 | 0 | 1 {\n return (x, y) => {\n if (x.length !== y.length) {\n return x.length < y.length ? -1 : 1;\n }\n for (let ii = 0; ii < x.length; ii++) {\n if (x[ii] === y[ii]) {\n continue;\n } else {\n return x[ii] < y[ii] ? -1 : 1;\n }\n }\n return 0;\n };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\n\nfunction getSignaturesToEncode(signaturesMap: OffchainMessageEnvelope['signatures']): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getU8Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { Address, address } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\nimport { OffchainMessageBytes } from '../message';\nimport { decodeRequiredSignatoryAddresses } from './preamble-common';\nimport { getSignaturesEncoder } from './signatures';\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageEnvelope} to a byte array\n * appropriate for sharing with a third party for validation.\n */\nexport function getOffchainMessageEnvelopeEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['content', getBytesEncoder()],\n ]),\n envelope => {\n const signaturesMapAddresses = Object.keys(envelope.signatures).map(address);\n if (signaturesMapAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(envelope.content);\n const missingRequiredSigners = [];\n const unexpectedSigners = [];\n for (const address of signatoryAddresses) {\n if (!signaturesMapAddresses.includes(address)) {\n missingRequiredSigners.push(address);\n }\n }\n for (const address of signaturesMapAddresses) {\n if (!signatoryAddresses.includes(address)) {\n unexpectedSigners.push(address);\n }\n }\n if (missingRequiredSigners.length || unexpectedSigners.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH, {\n missingRequiredSigners,\n unexpectedSigners,\n });\n }\n const orderedSignatureMap: OffchainMessageEnvelope['signatures'] = {};\n for (const address of signatoryAddresses) {\n orderedSignatureMap[address] = envelope.signatures[address];\n }\n return {\n ...envelope,\n signatures: orderedSignatureMap,\n };\n },\n );\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana offchain message format\n * to a {@link OffchainMessageEnvelope} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageEnvelopeDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelopeDecoder = getOffchainMessageEnvelopeDecoder();\n * const offchainMessageEnvelope = offchainMessageEnvelopeDecoder.decode(offchainMessageEnvelopeBytes);\n * for (const [address, signature] in Object.entries(offchainMessageEnvelope.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\nexport function getOffchainMessageEnvelopeDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getU8Decoder() })],\n ['content', getBytesDecoder()],\n ]),\n decodePartiallyDecodedOffchainMessageEnvelope,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageEnvelope}\n *\n * @see {@link getOffchainMessageEnvelopeDecoder}\n * @see {@link getOffchainMessageEnvelopeEncoder}\n */\nexport function getOffchainMessageEnvelopeCodec() {\n return combineCodec(getOffchainMessageEnvelopeEncoder(), getOffchainMessageEnvelopeDecoder());\n}\n\ntype PartiallyDecodedOffchainMessageEnvelope = {\n content: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedOffchainMessageEnvelope(\n offchainMessageEnvelope: PartiallyDecodedOffchainMessageEnvelope,\n): OffchainMessageEnvelope {\n const { content, signatures } = offchainMessageEnvelope;\n\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(content);\n\n // Signer addresses and signatures must be the same length\n // We encode an all-zero signature when the signature is missing\n if (signatoryAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH, {\n numRequiredSignatures: signatoryAddresses.length,\n signatoryAddresses,\n signaturesLength: signatures.length,\n });\n }\n\n // Combine the signer addresses + signatures into the signatures map\n const signaturesMap: OffchainMessageEnvelope['signatures'] = {};\n signatoryAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return Object.freeze({\n content: content as OffchainMessageBytes,\n signatures: Object.freeze(signaturesMap),\n });\n}\n\nfunction decodeAndValidateRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const signatoryAddresses = decodeRequiredSignatoryAddresses(bytes);\n\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n\n return signatoryAddresses;\n}\n","import { getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nconst MAX_BODY_BYTES =\n // Largest 16-bit unsigned integer\n 0xffff;\nconst MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE =\n // Space remaining in the mininum IPv6 MTU after network header overhead\n 1232;\n\n/**\n * A restriction on what characters the message text can contain and how long it can be.\n *\n * The aim of this restriction is to make a message more likely to be signable by a hardware wallet\n * that imposes limits on message size. In the case of wanting a message to be clear-signable,\n * restricting the character set to ASCII may ensure that certain models of hardware wallet without\n * extended character sets can display it onscreen.\n *\n * @remarks This only applies to v0 messages.\n */\nexport enum OffchainMessageContentFormat {\n RESTRICTED_ASCII_1232_BYTES_MAX = 0,\n UTF8_1232_BYTES_MAX = 1,\n UTF8_65535_BYTES_MAX = 2,\n}\n\n/**\n * Describes message text that is no more than 1232 bytes long and made up of characters with ASCII\n * character codes in the range [0x20, 0x7e].\n *\n * @remarks This type aims to restrict text to that which can be clear-signed by hardware wallets\n * that can only display ASCII characters onscreen.\n */\nexport type OffchainMessageContentRestrictedAsciiOf1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 1232 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 65535 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of65535BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX;\n text: Brand;\n}>;\n\nexport type OffchainMessageContent =\n | OffchainMessageContentRestrictedAsciiOf1232BytesMax\n | OffchainMessageContentUtf8Of1232BytesMax\n | OffchainMessageContentUtf8Of65535BytesMax;\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (isTextRestrictedAscii(putativeContent.text) === false) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX ||\n putativeContent.text.length === 0 ||\n isTextRestrictedAscii(putativeContent.text) === false\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is restricted ASCII with\n * _coercing_ it to the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type. It's most\n * useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageContentRestrictedAsciiOf1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: offchainMessageContentRestrictedAsciiOf1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentRestrictedAsciiOf1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good ASCII content as a string, it's more efficient to typecast it\n * > rather than to use the {@link offchainMessageContentRestrictedAsciiOf1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n * > text: 'Hello world',\n * > } as OffchainMessageContentRestrictedAsciiOf1232BytesMax<'Hello world'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentRestrictedAsciiOf1232BytesMax(\n text: TText,\n): OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n });\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 1232 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of1232BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 1232 bytes, it's more efficient\n * > to typecast it rather than to use the {@link offchainMessageContentUtf8Of1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of1232BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of1232BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of65535BytesMax}\n * type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of65535BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 65535 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of65535BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of65535BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of65535BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of65535BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 65535 bytes, it's more efficient\n * > to typecast it rather than to use the {@link OffchainMessageContentUtf8Of65535BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of65535BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of65535BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of65535BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent);\n return putativeContent;\n}\n\nfunction isTextRestrictedAscii(putativeRestrictedAsciiString: string): boolean {\n return /^[\\x20-\\x7e]+$/.test(putativeRestrictedAsciiString);\n}\n","import {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageContentUtf8Of1232BytesMax,\n assertIsOffchainMessageContentUtf8Of65535BytesMax,\n OffchainMessageContentFormat,\n OffchainMessageContentRestrictedAsciiOf1232BytesMax,\n OffchainMessageContentUtf8Of1232BytesMax,\n OffchainMessageContentUtf8Of65535BytesMax,\n} from './content';\nimport { OffchainMessagePreambleV0 } from './preamble-v0';\nimport { OffchainMessageWithRequiredSignatories } from './signatures';\n\nexport type BaseOffchainMessageV0 = Omit<\n OffchainMessagePreambleV0,\n 'messageFormat' | 'messageLength' | 'requiredSignatories'\n>;\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax}\n */\nexport interface OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent {\n readonly content: OffchainMessageContentRestrictedAsciiOf1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link offchainMessageContentUtf8Of1232BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of1232BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentUtf8Of65535BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of65535BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of65535BytesMax;\n}\n\n/**\n * A union of the formats a v0 message's contents can take.\n *\n * @remarks From v1 and onward, an offchain message has only one format: UTF-8 text of arbitrary\n * length.\n */\nexport type OffchainMessageWithContent =\n | OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent\n | OffchainMessageWithUtf8Of1232BytesMaxContent\n | OffchainMessageWithUtf8Of65535BytesMaxContent;\n\nexport type OffchainMessageV0 = BaseOffchainMessageV0 &\n OffchainMessageWithContent &\n OffchainMessageWithRequiredSignatories;\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }>,\n): asserts putativeMessage is OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link offchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link offchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentUtf8Of65535BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of65535BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of65535BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeMessage.content);\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getEnumDecoder, getEnumEncoder } from '@solana/codecs-data-structures';\n\nimport { OffchainMessageContentFormat } from '../content';\n\nexport function getOffchainMessageContentFormatDecoder(): FixedSizeDecoder {\n return getEnumDecoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatEncoder(): FixedSizeEncoder {\n return getEnumEncoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatCodec(): FixedSizeCodec<\n OffchainMessageContentFormat,\n OffchainMessageContentFormat,\n 1\n> {\n return combineCodec(getOffchainMessageContentFormatEncoder(), getOffchainMessageContentFormatDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder, getU16Decoder, getU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\n\nimport { OffchainMessagePreambleV0 } from '../preamble-v0';\nimport {\n getOffchainMessageApplicationDomainDecoder,\n getOffchainMessageApplicationDomainEncoder,\n} from './application-domain';\nimport { getOffchainMessageContentFormatDecoder, getOffchainMessageContentFormatEncoder } from './content';\nimport { createOffchainMessagePreambleDecoder, createOffchainMessagePreambleEncoder } from './preamble-common';\n\nexport function getOffchainMessageV0PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainDecoder()],\n ['messageFormat', getOffchainMessageContentFormatDecoder()],\n [\n 'requiredSignatories',\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(address => Object.freeze({ address }));\n }),\n ],\n ['messageLength', getU16Decoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainEncoder()],\n ['messageFormat', getOffchainMessageContentFormatEncoder()],\n [\n 'requiredSignatories',\n transformEncoder(\n getArrayEncoder(getAddressEncoder(), { size: getU8Encoder() }),\n (signatoryAddresses: OffchainMessagePreambleV0['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(({ address }) => address);\n },\n ),\n ],\n ['messageLength', getU16Encoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0PreambleEncoder(), getOffchainMessageV0PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageContentFormat } from '../content';\nimport {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageUtf8Of1232BytesMax,\n assertIsOffchainMessageUtf8Of65535BytesMax,\n OffchainMessageV0,\n} from '../message-v0';\nimport { getOffchainMessageV0PreambleDecoder, getOffchainMessageV0PreambleEncoder } from './preamble-v0';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV0} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV0Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV0Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v0 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 0.\n */\nexport function getOffchainMessageV0Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV0PreambleDecoder(), getUtf8Decoder()]),\n ([{ messageLength, messageFormat, requiredSignatories, ...preambleRest }, text]) => {\n const actualLength = getUtf8Encoder().getSizeFromValue(text);\n if (messageLength !== actualLength) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH, {\n actualLength: actualLength,\n specifiedLength: messageLength,\n });\n }\n const offchainMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }> = Object.freeze({\n ...preambleRest,\n content: Object.freeze({\n format: messageFormat,\n text,\n }),\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n switch (messageFormat) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n return offchainMessage;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: messageFormat satisfies never,\n });\n }\n }\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV0} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV0Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV0PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...preamble } = offchainMessage;\n switch (offchainMessage.content.format) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n break;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: offchainMessage.content satisfies never,\n });\n }\n }\n const messageLength = getUtf8Encoder().getSizeFromValue(content.text);\n const compiledPreamble = {\n ...preamble,\n messageFormat: content.format,\n messageLength,\n };\n return [compiledPreamble, content.text] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV0}\n *\n * @see {@link getOffchainMessageV0Decoder}\n * @see {@link getOffchainMessageV0Encoder}\n */\nexport function getOffchainMessageV0Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0Encoder(), getOffchainMessageV0Decoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getBytesDecoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessagePreambleV1 } from '../preamble-v1';\nimport {\n createOffchainMessagePreambleDecoder,\n createOffchainMessagePreambleEncoder,\n getSignatoriesComparator,\n} from './preamble-common';\n\nexport function getOffchainMessageV1PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(/* version */ 1, [\n 'requiredSignatories',\n transformDecoder(\n getArrayDecoder(fixDecoderSize(getBytesDecoder(), 32), { size: getU8Decoder() }),\n signatoryAddressesBytes => {\n if (signatoryAddressesBytes.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const comparator = getSignatoriesComparator();\n for (let ii = 0; ii < signatoryAddressesBytes.length - 1; ii++) {\n switch (comparator(signatoryAddressesBytes[ii], signatoryAddressesBytes[ii + 1])) {\n case 0:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n case 1:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED);\n }\n }\n const addressDecoder = getAddressDecoder();\n return signatoryAddressesBytes.map(addressBytes =>\n Object.freeze({\n address: addressDecoder.decode(addressBytes),\n }),\n );\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(/* version */ 1, [\n 'requiredSignatories',\n transformEncoder(\n transformEncoder(\n getArrayEncoder(getBytesEncoder(), { size: getU8Encoder() }),\n (signatoryAddressesBytes: readonly ReadonlyUint8Array[]) => {\n return signatoryAddressesBytes.toSorted(getSignatoriesComparator());\n },\n ),\n (signatoryAddresses: OffchainMessagePreambleV1['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const seenSignatories = new Set();\n for (const { address } of signatoryAddresses) {\n if (seenSignatories.has(address)) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n }\n seenSignatories.add(address);\n }\n const addressEncoder = getAddressEncoder();\n return signatoryAddresses.map(({ address }) => addressEncoder.encode(address));\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1PreambleEncoder(), getOffchainMessageV1PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY, SolanaError } from '@solana/errors';\n\nimport { OffchainMessageV1 } from '../message-v1';\nimport { getOffchainMessageV1PreambleDecoder, getOffchainMessageV1PreambleEncoder } from './preamble-v1';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV1} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV1Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV1Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v1 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 1.\n */\nexport function getOffchainMessageV1Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV1PreambleDecoder(), getUtf8Decoder()]),\n ([{ requiredSignatories, ...preambleRest }, text]) => {\n if (text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return Object.freeze({\n ...preambleRest,\n content: text,\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV1} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV1Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV1PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...compiledPreamble } = offchainMessage;\n if (content.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return [compiledPreamble, content] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV1}\n *\n * @see {@link getOffchainMessageV1Decoder}\n * @see {@link getOffchainMessageV1Encoder}\n */\nexport function getOffchainMessageV1Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1Encoder(), getOffchainMessageV1Decoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getHiddenPrefixDecoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, SolanaError } from '@solana/errors';\n\nimport { OffchainMessage } from '../message';\nimport { getOffchainMessageV0Decoder, getOffchainMessageV0Encoder } from './message-v0';\nimport { getOffchainMessageV1Decoder, getOffchainMessageV1Encoder } from './message-v1';\nimport { getOffchainMessageSigningDomainDecoder } from './signing-domain';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessage} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageDecoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded an offchain message (version: ${offchainMessage.version}`);\n * ```\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the decoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageDecoder(): VariableSizeDecoder {\n return createDecoder({\n read(bytes, offset): [OffchainMessage, number] {\n const version = getHiddenPrefixDecoder(getU8Decoder(), [\n // Discard the signing domain\n getOffchainMessageSigningDomainDecoder(),\n ]).decode(bytes, offset);\n switch (version) {\n case 0:\n return getOffchainMessageV0Decoder().read(bytes, offset);\n case 1:\n return getOffchainMessageV1Decoder().read(bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n },\n });\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessage} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the encoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: offchainMessage => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().getSizeFromValue(offchainMessage);\n case 1:\n return getOffchainMessageV1Encoder().getSizeFromValue(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n write: (offchainMessage, bytes, offset) => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().write(offchainMessage, bytes, offset);\n case 1:\n return getOffchainMessageV1Encoder().write(offchainMessage, bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessage}\n *\n * @see {@link getOffchainMessageDecoder}\n * @see {@link getOffchainMessageEncoder}\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the codecs specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageEncoder(), getOffchainMessageDecoder());\n}\n","import { VariableSizeEncoder } from '@solana/codecs-core';\n\nimport { OffchainMessageEnvelope } from './envelope';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\nexport function compileOffchainMessageEnvelopeUsingEncoder(\n offchainMessage: T,\n encoder: VariableSizeEncoder,\n) {\n const offchainMessageBytes = encoder.encode(offchainMessage) as OffchainMessageBytes;\n const signatures: OffchainMessageEnvelope['signatures'] = {};\n for (const { address } of offchainMessage.requiredSignatories) {\n signatures[address] = null;\n }\n return Object.freeze({\n content: offchainMessageBytes,\n signatures: Object.freeze(signatures),\n });\n}\n","import { getOffchainMessageV0Encoder } from './codecs/message-v0';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV0 } from './message-v0';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV0}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV0Envelope(offchainMessage: OffchainMessageV0): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV0Encoder());\n}\n","import { getOffchainMessageV1Encoder } from './codecs/message-v1';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV1 } from './message-v1';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV1}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV1Envelope(offchainMessage: OffchainMessageV1): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV1Encoder());\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { compileOffchainMessageV0Envelope } from './envelope-v0';\nimport { compileOffchainMessageV1Envelope } from './envelope-v1';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\ntype OrderedMap = Record;\ntype OffchainMessageSignaturesMap = OrderedMap;\n\nexport interface OffchainMessageEnvelope {\n /** The bytes of the combined offchain message preamble and content */\n readonly content: OffchainMessageBytes;\n /**\n * A map between the addresses of an offchain message's signers, and the 64-byte Ed25519\n * signature of the combined message preamble and message content by the private key associated\n * with each.\n */\n readonly signatures: OffchainMessageSignaturesMap;\n}\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessage}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the compile functions\n * specific to that version so as not to bundle more code than you need.\n */\nexport function compileOffchainMessageEnvelope(offchainMessage: OffchainMessage): OffchainMessageEnvelope {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return compileOffchainMessageV0Envelope(offchainMessage);\n case 1:\n return compileOffchainMessageV1Envelope(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: version satisfies never,\n });\n }\n}\n","import { Address, getAddressFromPublicKey, getPublicKeyFromAddress } from '@solana/addresses';\nimport { bytesEqual } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes, signBytes, verifySignature } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { decodeRequiredSignatoryAddresses } from './codecs/preamble-common';\nimport { OffchainMessageEnvelope } from './envelope';\n\n/**\n * Represents an offchain message envelope that is signed by all of its required signers.\n */\nexport type FullySignedOffchainMessageEnvelope = NominalType<'offchainMessageEnvelopeSignedness', 'fullySigned'>;\n\n/**\n * Represents an address that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatory = Readonly<{\n address: Address;\n}>;\n\n/**\n * An offchain message having a list of accounts that must sign it in order for it to be valid.\n */\nexport interface OffchainMessageWithRequiredSignatories<\n TSignatory extends OffchainMessageSignatory = OffchainMessageSignatory,\n> {\n requiredSignatories: readonly TSignatory[];\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message, this method will return a new signed offchain message\n * envelope of type {@link OffchainMessageEnvelope}.\n *\n * Though the resulting message might be signed by all required signers, this function will not\n * assert that it is. A partially signed message is not complete, but can be serialized and\n * deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const partiallySignedOffchainMessage = await partiallySignOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link signOffchainMessageEnvelope} if you want to assert that the message is signed by all\n * its required signers after signing.\n */\nexport async function partiallySignOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n const requiredSignatoryAddresses = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n\n // Check if the address is expected to sign the message\n if (!requiredSignatoryAddresses.includes(address)) {\n // address is not an expected signer for this message\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const existingSignature = offchainMessageEnvelope.signatures[address];\n const newSignature = await signBytes(keyPair.privateKey, offchainMessageEnvelope.content);\n\n if (existingSignature != null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE, {\n expectedAddresses: requiredSignatoryAddresses,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return offchainMessageEnvelope;\n }\n\n return Object.freeze({\n ...offchainMessageEnvelope,\n signatures: Object.freeze({\n ...offchainMessageEnvelope.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message envelope, this method will return a new signed envelope of\n * type {@link FullySignedOffchainMessageEnvelope}.\n *\n * This function will throw unless the resulting message is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const signedOffchainMessage = await signOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link partiallySignOffchainMessageEnvelope} if you want to sign the message without\n * asserting that the resulting message envelope is fully signed.\n */\nexport async function signOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n const out = await partiallySignOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope);\n assertIsFullySignedOffchainMessageEnvelope(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * A type guard that returns `true` if the input {@link OffchainMessageEnvelope} is fully signed,\n * and refines its type for use in your program, adding the\n * {@link FullySignedOffchainMessageEnvelope} type.\n *\n * @example\n * ```ts\n * import { isFullySignedOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * if (isFullySignedOffchainMessageEnvelope(offchainMessageEnvelope)) {\n * // At this point we know that the offchain message is fully signed.\n * }\n * ```\n */\nexport function isFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n return Object.entries(offchainMessage.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link OffchainMessageEnvelope}, that you expect to be\n * fully signed, from an untrusted network API or user input. Use this function to assert that such\n * an offchain message is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedOffchainMessage } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast\n * // `offchainMessageEnvelope` to `FullySignedOffchainMessageEnvelope`.\n * assertIsFullySignedOffchainMessageEnvelope(offchainMessage);\n * // At this point we know that the offchain message is signed by all required signers.\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function assertIsFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): asserts offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n const missingSigs: Address[] = [];\n Object.entries(offchainMessage.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n\n/**\n * Asserts that there are signatures present for all of an offchain message's required signatories,\n * and that those signatures are valid given the message.\n *\n * @example\n * ```ts\n * import { isSolanaError, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE } from '@solana/errors';\n * import { verifyOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * try {\n * await verifyOffchainMessageEnvelope(offchainMessageEnvelope);\n * // At this point the message is valid and signed by all of the required signatories.\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) {\n * if (e.context.signatoriesWithMissingSignatures.length) {\n * console.error(\n * 'Missing signatures for the following addresses',\n * e.context.signatoriesWithMissingSignatures,\n * );\n * }\n * if (e.context.signatoriesWithInvalidSignatures.length) {\n * console.error(\n * 'Signatures for the following addresses are invalid',\n * e.context.signatoriesWithInvalidSignatures,\n * );\n * }\n * }\n * throw e;\n * }\n */\nexport async function verifyOffchainMessageEnvelope(offchainMessageEnvelope: OffchainMessageEnvelope): Promise {\n let errorContext;\n const requiredSignatories = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n await Promise.all(\n requiredSignatories.map(async address => {\n const signature = offchainMessageEnvelope.signatures[address];\n if (signature == null) {\n errorContext ||= {};\n errorContext.signatoriesWithMissingSignatures ||= [];\n errorContext.signatoriesWithMissingSignatures.push(address);\n } else {\n const publicKey = await getPublicKeyFromAddress(address);\n if (await verifySignature(publicKey, signature, offchainMessageEnvelope.content)) {\n return true;\n } else {\n errorContext ||= {};\n errorContext.signatoriesWithInvalidSignatures ||= [];\n errorContext.signatoriesWithInvalidSignatures.push(address);\n }\n }\n }),\n );\n if (errorContext) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, errorContext);\n }\n}\n","/**\n * Defines a plugin that transforms or extends a client with additional functionality.\n *\n * For instance, plugins may add RPC capabilities, wallet integration, transaction building,\n * or other features necessary for interacting with the Solana blockchain.\n *\n * Plugins are functions that take a client object as input and return a new client object\n * or a promise that resolves to a new client object. This allows for both synchronous\n * and asynchronous transformations and extensions of the client.\n *\n * Plugins are usually applied using the `use` method on a {@link Client} or {@link AsyncClient}\n * instance, which {@link createEmptyClient} provides as a starting point.\n *\n * @typeParam TInput - The input client object type that this plugin accepts.\n * @typeParam TOutput - The output type. Either a new client object or a promise resolving to one.\n *\n * @example Basic RPC plugin\n * Given an RPC endpoint, this plugin adds an `rpc` property to the client.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc } from '@solana/kit';\n *\n * // Define a simple RPC plugin.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n *\n * // Use the plugin.\n * const client = createEmptyClient().use(rpcPlugin('https://api.mainnet-beta.solana.com'));\n * await client.rpc.getLatestBlockhash().send();\n * ```\n *\n * @example Async plugin that generates a payer wallet\n * The following plugin shows how to create an asynchronous plugin that generates a new keypair signer.\n *\n * ```ts\n * import { createEmptyClient, generateKeypairSigner } from '@solana/kit';\n *\n * // Define a plugin that generates a new keypair signer.\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n *\n * // Use the plugin.\n * const client = await createEmptyClient().use(generatedPayerPlugin());\n * console.log(client.payer.address);\n * ```\n *\n * @example Plugins with input requirements\n * A plugin can specify required properties on the input client. The example below requires the\n * client to already have a `payer` signer attached to the client in order to perform an airdrop.\n *\n * ```ts\n * import { createEmptyClient, TransactionSigner, Lamports, lamports } from '@solana/kit';\n *\n * // Define a plugin that airdrops lamports to the payer set on the client.\n * function airdropPayerPlugin(lamports: Lamports) {\n * return async (client: T) => {\n * await myAirdropFunction(client.payer, lamports);\n * return client;\n * };\n * }\n *\n * // Use the plugins.\n * const client = await createEmptyClient()\n * .use(generatedPayerPlugin()) // This is required before using the airdrop plugin.\n * .use(airdropPayerPlugin(lamports(1_000_000_000n)));\n * ```\n *\n * @example Chaining plugins\n * Multiple plugins — asynchronous or not — can be chained together to build up complex clients.\n * The example below demonstrates how to gradually build a client with multiple plugins.\n * Notice how, despite having multiple asynchronous plugins, we only need to `await` the final result.\n * This is because the `use` method on `AsyncClient` returns another `AsyncClient`, allowing for seamless chaining.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc, createSolanaRpcSubscriptions, generateKeypairSigner } from '@solana/kit';\n *\n * // Define multiple plugins.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n * function rpcSubscriptionsPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpcSubscriptions(endpoint) });\n * }\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n * function generatedAuthorityPlugin() {\n * return async (client: T) => ({...client, authority: await generateKeypairSigner() });\n * }\n *\n * // Chain plugins together.\n * const client = await createEmptyClient()\n * .use(rpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(rpcSubscriptionsPlugin('wss://api.mainnet-beta.solana.com'))\n * .use(generatedPayerPlugin())\n * .use(generatedAuthorityPlugin());\n * ```\n */\nexport type ClientPlugin | object> = (input: TInput) => TOutput;\n\n/**\n * A client that can be extended with plugins.\n *\n * The `Client` type represents a client object that can be built up through\n * the application of one or more plugins. It provides a `use` method to\n * apply plugins, either synchronously (returning a new `Client`) or\n * asynchronously (returning an {@link AsyncClient}).\n *\n * @typeParam TSelf - The current shape of the client object including all applied plugins.\n */\nexport type Client = TSelf & {\n /**\n * Applies a plugin to extend or transform the client.\n *\n * @param plugin The plugin function to apply to this client.\n * @returns Either a new `Client` (for sync plugins) or {@link AsyncClient} (for async plugins).\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => TOutput extends Promise ? AsyncClient : Client;\n};\n\n/**\n * An asynchronous wrapper that represents a promise of a client.\n *\n * The `AsyncClient` type is returned when an async plugin is applied to a client.\n * It behaves like a `Promise>` but with an additional `use` method\n * that allows chaining more plugins before the promise resolves.\n *\n * This enables fluent chaining of both synchronous and asynchronous plugins\n * without having to await intermediate promises.\n *\n * @typeParam TSelf - The shape of the client object that this async client will resolve to.\n */\nexport type AsyncClient = Promise> & {\n /**\n * Applies a plugin to the client once it resolves.\n *\n * @param plugin The plugin function to apply to the resolved client.\n * @returns A new `AsyncClient` representing the result of applying the plugin.\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => AsyncClient ? (U extends object ? U : never) : TOutput>;\n};\n\n// TODO(loris): Add examples in this docblock using real plugins once they have been published.\n\n/**\n * Creates a new empty client that can be extended with plugins.\n *\n * This serves as an entry point for building Solana clients.\n * Start with an empty client and chain the `.use()` method\n * to apply plugins that add various functionalities such as RPC\n * connectivity, wallet integration, transaction building, and more.\n *\n * See {@link ClientPlugin} for detailed examples on creating and using plugins.\n *\n * @returns An empty client object with only the `use` method available.\n *\n * @example Basic client setup\n * ```ts\n * import { createEmptyClient } from '@solana/client';\n *\n * const client = createEmptyClient()\n * .use(myRpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(myWalletPlugin());\n * ```\n */\nexport function createEmptyClient(): Client {\n return addUse({});\n}\n\nfunction addUse(value: TSelf): Client {\n return Object.freeze({\n ...value,\n use | object>(plugin: ClientPlugin) {\n const result = plugin(value);\n return result instanceof Promise ? createAsyncClient(result) : addUse(result);\n },\n } as Client);\n}\n\nfunction createAsyncClient(promise: Promise): AsyncClient {\n return Object.freeze({\n catch(onrejected) {\n return promise.then(v => addUse(v)).catch(onrejected);\n },\n finally(onfinally) {\n return promise.then(v => addUse(v)).finally(onfinally);\n },\n then(onfulfilled, onrejected) {\n return promise.then(v => addUse(v)).then(onfulfilled, onrejected);\n },\n use | object>(plugin: ClientPlugin) {\n return createAsyncClient(promise.then(plugin));\n },\n } as AsyncClient);\n}\n","import type { Address } from '@solana/addresses';\nimport { isSolanaError, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SolanaError } from '@solana/errors';\n\n/**\n * Identifies whether an error -- typically caused by a transaction failure -- is a custom program\n * error from the provided program address.\n *\n * @param transactionMessage The transaction message that failed to execute. Since the RPC response\n * only provides the index of the failed instruction, the transaction message is required to\n * determine its program address\n * @param programAddress The address of the program from which the error is expected to have\n * originated\n * @param code The expected error code of the custom program error. When provided, the function will\n * check that the custom program error code matches the given value.\n *\n * @example\n * ```ts\n * try {\n * // Send and confirm your transaction.\n * } catch (error) {\n * if (isProgramError(error, transactionMessage, myProgramAddress, 42)) {\n * // Handle custom program error 42 from this program.\n * } else if (isProgramError(error, transactionMessage, myProgramAddress)) {\n * // Handle all other custom program errors from this program.\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isProgramError(\n error: unknown,\n transactionMessage: { instructions: Record },\n programAddress: Address,\n code?: TProgramErrorCode,\n): error is Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> &\n SolanaError {\n if (!isSolanaError(error, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM)) {\n return false;\n }\n const instructionProgramAddress = transactionMessage.instructions[error.context.index]?.programAddress;\n if (!instructionProgramAddress || instructionProgramAddress !== programAddress) {\n return false;\n }\n return typeof code === 'undefined' || error.context.code === code;\n}\n","/**\n * This function is a replacement for `JSON.parse` that can handle large\n * unsafe integers by parsing them as BigInts. It transforms every\n * numerical value into a BigInt without loss of precision.\n */\nexport function parseJsonWithBigInts(json: string): unknown {\n return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {\n return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;\n });\n}\n\nfunction wrapIntegersInBigIntValueObject(json: string): string {\n const out = [];\n let inQuote = false;\n for (let ii = 0; ii < json.length; ii++) {\n let isEscaped = false;\n if (json[ii] === '\\\\') {\n out.push(json[ii++]);\n isEscaped = !isEscaped;\n }\n if (json[ii] === '\"') {\n out.push(json[ii]);\n if (!isEscaped) {\n inQuote = !inQuote;\n }\n continue;\n }\n if (!inQuote) {\n const consumedNumber = consumeNumber(json, ii);\n if (consumedNumber?.length) {\n ii += consumedNumber.length - 1;\n // Don't wrap numbers that contain a decimal point or a negative exponent.\n if (consumedNumber.match(/\\.|[eE]-/)) {\n out.push(consumedNumber);\n } else {\n out.push(wrapBigIntValueObject(consumedNumber));\n }\n continue;\n }\n }\n out.push(json[ii]);\n }\n\n return out.join('');\n}\n\nfunction consumeNumber(json: string, ii: number): string | null {\n /** @see https://stackoverflow.com/a/13340826/11440277 */\n const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/;\n\n // Stop early if the first character isn't a digit or a minus sign.\n if (!json[ii]?.match(/[-\\d]/)) {\n return null;\n }\n\n // Otherwise, check if the next characters form a valid JSON number.\n const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);\n return numberMatch ? numberMatch[0] : null;\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: string): string {\n return `{\"$n\":\"${value}\"}`;\n}\n\nfunction unwrapBigIntValueObject({ $n }: BigIntValueObject): bigint {\n if ($n.match(/[eE]/)) {\n const [units, exponent] = $n.split(/[eE]/);\n return BigInt(units) * BigInt(10) ** BigInt(exponent);\n }\n return BigInt($n);\n}\n\nfunction isBigIntValueObject(value: unknown): value is BigIntValueObject {\n return !!value && typeof value === 'object' && '$n' in value && typeof value.$n === 'string';\n}\n","import { RpcRequest } from './rpc-request';\n\nlet _nextMessageId = 0n;\nfunction getNextMessageId(): string {\n const id = _nextMessageId;\n _nextMessageId++;\n return id.toString();\n}\n\n/**\n * Returns a spec-compliant JSON RPC 2.0 message, given a method name and some params.\n *\n * Generates a new `id` on each call by incrementing a `bigint` and casting it to a string.\n */\nexport function createRpcMessage(request: RpcRequest) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method: request.methodName,\n params: request.params,\n };\n}\n","/**\n * Transforms a value into a JSON string, whilst rendering bigints as large unsafe integers.\n */\nexport function stringifyJsonWithBigInts(value: unknown, space?: number | string): string {\n return unwrapBigIntValueObject(\n JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? wrapBigIntValueObject(v) : v), space),\n );\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: bigint): BigIntValueObject {\n return { $n: `${value}` };\n}\n\nfunction unwrapBigIntValueObject(value: string): string {\n return value.replace(/\\{\\s*\"\\$n\"\\s*:\\s*\"(-?\\d+)\"\\s*\\}/g, '$1');\n}\n","import { SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\n\nimport { RpcApi, RpcPlan } from './rpc-api';\nimport { RpcTransport } from './rpc-transport';\n\nexport type RpcConfig = Readonly<{\n api: RpcApi;\n transport: TRpcTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcMethods`.\n *\n * Calling each method returns a {@link PendingRpcRequest | PendingRpcRequest} where\n * `TResponse` is that method's response type.\n */\nexport type Rpc = {\n [TMethodName in keyof TRpcMethods]: PendingRpcRequestBuilder>;\n};\n\n/**\n * Pending requests are the result of calling a supported method on a {@link Rpc} object. They\n * encapsulate all of the information necessary to make the request without actually making it.\n *\n * Calling the {@link PendingRpcRequest.send | `send(options)`} method on a\n * {@link PendingRpcRequest | PendingRpcRequest} will trigger the request and return a\n * promise for `TResponse`.\n */\nexport type PendingRpcRequest = {\n send(options?: RpcSendOptions): Promise;\n};\n\nexport type RpcSendOptions = Readonly<{\n /**\n * An optional signal that you can supply when triggering a {@link PendingRpcRequest} that you\n * might later need to abort.\n */\n abortSignal?: AbortSignal;\n}>;\n\ntype PendingRpcRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TMethodImplementations]: PendingRpcRequestReturnTypeMapper;\n }>\n>;\n\ntype PendingRpcRequestReturnTypeMapper =\n // Check that this property of the TRpcMethods interface is, in fact, a function.\n TMethodImplementation extends Callable\n ? (...args: Parameters) => PendingRpcRequest>\n : never;\n\n/**\n * Creates a {@link Rpc} instance given a {@link RpcApi | RpcApi} and a\n * {@link RpcTransport} capable of fulfilling them.\n */\nexport function createRpc(\n rpcConfig: RpcConfig,\n): Rpc {\n return makeProxy(rpcConfig);\n}\n\nfunction makeProxy(\n rpcConfig: RpcConfig,\n): Rpc {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const getApiPlan = Reflect.get(target, methodName, receiver);\n if (!getApiPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {\n method: methodName,\n params: rawParams,\n });\n }\n const apiPlan = getApiPlan(...rawParams);\n return createPendingRpcRequest(rpcConfig, apiPlan);\n };\n },\n }) as Rpc;\n}\n\nfunction createPendingRpcRequest(\n { transport }: RpcConfig,\n plan: RpcPlan,\n): PendingRpcRequest {\n return {\n async send(options?: RpcSendOptions): Promise {\n return await plan.execute({ signal: options?.abortSignal, transport });\n },\n };\n}\n","import {\n Callable,\n createRpcMessage,\n RpcRequestTransformer,\n RpcResponse,\n RpcResponseTransformer,\n} from '@solana/rpc-spec-types';\n\nimport type { RpcTransport } from './rpc-transport';\n\nexport type RpcApiConfig = Readonly<{\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n /**\n * An optional function that transforms the {@link RpcResponse} before it is returned to the\n * caller.\n *\n * Use cases for this include constructing complex data types from serialized data, and throwing\n * exceptions.\n */\n responseTransformer?: RpcResponseTransformer;\n}>;\n\n/**\n * This type allows an {@link RpcApi} to describe how a particular request should be issued to the\n * JSON RPC server.\n *\n * Given a function that was called on a {@link Rpc}, this object exposes an `execute` function that\n * dictates which request will be sent, how the underlying transport will be used, and how the\n * responses will be transformed.\n *\n * This function accepts a {@link RpcTransport} and an `AbortSignal` and asynchronously returns a\n * {@link RpcResponse}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * transport.\n * - call the underlying transport zero, one or multiple times depending on the use-case (e.g.\n * caching or aggregating multiple responses).\n * - transform the response from the JSON RPC server, in case it does not match the `TResponse`\n * specified by the {@link PendingRpcRequest | PendingRpcRequest} returned from that\n * function.\n */\nexport type RpcPlan = {\n execute: (\n config: Readonly<{\n signal?: AbortSignal;\n transport: RpcTransport;\n }>,\n ) => Promise>;\n};\n\n/**\n * For each of `TRpcMethods`, this object exposes a method with the same name that maps between its\n * input arguments and a {@link RpcPlan | RpcPlan} that implements the execution of a\n * JSON RPC request to fetch `TResponse`.\n */\nexport type RpcApi = {\n [MethodName in keyof TRpcMethods]: RpcReturnTypeMapper;\n};\n\ntype RpcReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcApiMethod = (...args: any) => any;\ninterface RpcApiMethods {\n [methodName: string]: RpcApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a {@link RpcPlan} by\n * creating an `execute` function that:\n *\n * - sets the transport payload to a JSON RPC v2 payload object with the requested `methodName` and\n * `params` properties, optionally transformed by {@link RpcApiConfig.requestTransformer}.\n * - transforms the transport's response using the {@link RpcApiConfig.responseTransformer}\n * function, if provided.\n *\n * @example\n * ```ts\n * // For example, given this `RpcApi`:\n * const rpcApi = createJsonRpcApi({\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * responseTransformer: response => response.result,\n * });\n *\n * // ...the following function call:\n * rpcApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Returns the \"result\" property of the RPC response.\n * ```\n */\nexport function createJsonRpcApi(config?: RpcApiConfig): RpcApi {\n return new Proxy({} as RpcApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcMethods as string;\n return function (\n ...rawParams: Parameters<\n TRpcMethods[TMethodName] extends CallableFunction ? TRpcMethods[TMethodName] : never\n >\n ): RpcPlan> {\n const rawRequest = Object.freeze({ methodName, params: rawParams });\n const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;\n return Object.freeze(>>{\n execute: async ({ signal, transport }) => {\n const payload = createRpcMessage(request);\n const response = await transport({ payload, signal });\n if (!config?.responseTransformer) {\n return response;\n }\n return config.responseTransformer(response, request);\n },\n });\n };\n },\n });\n}\n","import { RpcResponse } from '@solana/rpc-spec-types';\n\ntype Config = Readonly<{\n /** A value of arbitrary type to be sent to a RPC server */\n payload: unknown;\n /**\n * An optional `AbortSignal` on which the `'abort'` event will be fired if the request should be\n * cancelled.\n */\n signal?: AbortSignal;\n}>;\n\n/**\n * A function that can act as a transport for a {@link Rpc}. It need only return a promise for a\n * response given the supplied config.\n */\nexport type RpcTransport = {\n (config: Config): Promise>;\n};\n\n/**\n * Returns `true` if the given payload is a JSON RPC v2 payload.\n *\n * This means, the payload is an object such that:\n *\n * - It has a `jsonrpc` property with a value of `'2.0'`.\n * - It has a `method` property that is a string.\n * - It has a `params` property of any type.\n *\n * @example\n * ```ts\n * import { isJsonRpcPayload } from '@solana/rpc-spec';\n *\n * if (isJsonRpcPayload(payload)) {\n * const payloadMethod: string = payload.method;\n * const payloadParams: unknown = payload.params;\n * }\n * ```\n */\nexport function isJsonRpcPayload(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: string;\n params: unknown;\n}> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n","export function downcastNodeToNumberIfBigint(value: bigint): number;\nexport function downcastNodeToNumberIfBigint(value: T): T;\nexport function downcastNodeToNumberIfBigint(value: unknown): unknown {\n return typeof value === 'bigint'\n ? // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n Number(value)\n : value;\n}\n","import { RpcRequest, RpcRequestTransformer, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nexport type KeyPathWildcard = { readonly ['__keyPathWildcard:@solana/kit']: unique symbol };\nexport type KeyPath = ReadonlyArray;\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n\ntype NodeVisitor = (value: unknown, state: TState) => unknown;\nexport type TraversalState = Readonly<{\n keyPath: KeyPath;\n}>;\n\nfunction getTreeWalker(visitors: NodeVisitor[]) {\n return function traverse(node: unknown, state: TState): unknown {\n if (Array.isArray(node)) {\n return node.map((element, ii) => {\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, ii],\n };\n return traverse(element, nextState);\n });\n } else if (typeof node === 'object' && node !== null) {\n const out: Record = {};\n for (const propName in node) {\n if (!Object.prototype.hasOwnProperty.call(node, propName)) {\n continue;\n }\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, propName],\n };\n out[propName] = traverse(node[propName as keyof typeof node], nextState);\n }\n return out;\n } else {\n return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);\n }\n };\n}\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided visitors at\n * each node. A custom initial state can be provided but must at least provide `{ keyPath: [] }`.\n *\n * @example\n * ```ts\n * import { getTreeWalkerRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getTreeWalkerRequestTransformer(\n * [\n * // Replaces foo.bar with \"baz\".\n * (node, state) => (state.keyPath === ['foo', 'bar'] ? 'baz' : node),\n * // Increments all numbers by 1.\n * node => (typeof node === number ? node + 1 : node),\n * ],\n * { keyPath: [] },\n * );\n * ```\n */\nexport function getTreeWalkerRequestTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const traverse = getTreeWalker(visitors);\n return Object.freeze({\n ...request,\n params: traverse(request.params, initialState),\n });\n };\n}\n\nexport function getTreeWalkerResponseTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcResponseTransformer {\n return json => getTreeWalker(visitors)(json, initialState);\n}\n","import { downcastNodeToNumberIfBigint } from './request-transformer-bigint-downcast-internal';\nimport { getTreeWalkerRequestTransformer } from './tree-traversal';\n\n/**\n * Creates a transformer that downcasts all `BigInt` values to `Number`.\n *\n * @example\n * ```ts\n * import { getBigIntDowncastRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getBigIntDowncastRequestTransformer();\n * ```\n *\n */\nexport function getBigIntDowncastRequestTransformer() {\n return getTreeWalkerRequestTransformer([downcastNodeToNumberIfBigint], { keyPath: [] });\n}\n","import { Commitment } from '@solana/rpc-types';\n\nexport function applyDefaultCommitment({\n commitmentPropertyName,\n params,\n optionsObjectPositionInParams,\n overrideCommitment,\n}: Readonly<{\n commitmentPropertyName: string;\n optionsObjectPositionInParams: number;\n overrideCommitment?: Commitment;\n params: unknown[];\n}>) {\n const paramInTargetPosition = params[optionsObjectPositionInParams];\n if (\n // There's no config.\n paramInTargetPosition === undefined ||\n // There is a config object.\n (paramInTargetPosition && typeof paramInTargetPosition === 'object' && !Array.isArray(paramInTargetPosition))\n ) {\n if (\n // The config object already has a commitment set.\n paramInTargetPosition &&\n commitmentPropertyName in paramInTargetPosition\n ) {\n if (\n !paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] ||\n paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] === 'finalized'\n ) {\n // Delete the commitment property; `finalized` is already the server default.\n const nextParams = [...params];\n const {\n [commitmentPropertyName as keyof typeof paramInTargetPosition]: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...rest\n } = paramInTargetPosition;\n if (Object.keys(rest).length > 0) {\n nextParams[optionsObjectPositionInParams] = rest;\n } else {\n if (optionsObjectPositionInParams === nextParams.length - 1) {\n nextParams.length--;\n } else {\n nextParams[optionsObjectPositionInParams] = undefined;\n }\n }\n return nextParams;\n }\n } else if (overrideCommitment !== 'finalized') {\n // Apply the default commitment.\n const nextParams = [...params];\n nextParams[optionsObjectPositionInParams] = {\n ...paramInTargetPosition,\n [commitmentPropertyName]: overrideCommitment,\n };\n return nextParams;\n }\n }\n return params;\n}\n","import type { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { applyDefaultCommitment } from './request-transformer-default-commitment-internal';\n\n/**\n * Creates a transformer that adds the provided default commitment to the configuration object of the request when applicable.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getDefaultCommitmentRequestTransformer, OPTIONS_OBJECT_POSITION_BY_METHOD } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultCommitmentRequestTransformer({\n * defaultCommitment: 'confirmed',\n * optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n * });\n */\nexport function getDefaultCommitmentRequestTransformer({\n defaultCommitment,\n optionsObjectPositionByMethod,\n}: Readonly<{\n defaultCommitment?: Commitment;\n optionsObjectPositionByMethod: Record;\n}>): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const { params, methodName } = request;\n\n // We only apply default commitment to array parameters.\n if (!Array.isArray(params)) {\n return request;\n }\n\n // Find the position of the options object in the parameters and abort if not found.\n const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];\n if (optionsObjectPositionInParams == null) {\n return request;\n }\n\n return Object.freeze({\n methodName,\n params: applyDefaultCommitment({\n commitmentPropertyName: methodName === 'sendTransaction' ? 'preflightCommitment' : 'commitment',\n optionsObjectPositionInParams,\n overrideCommitment: defaultCommitment,\n params,\n }),\n });\n };\n}\n","import { KeyPath, TraversalState } from './tree-traversal';\n\nexport function getIntegerOverflowNodeVisitor(onIntegerOverflow: (keyPath: KeyPath, value: bigint) => void) {\n return (value: T, { keyPath }: TraversalState): T => {\n if (typeof value === 'bigint') {\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath as (number | string)[], value);\n }\n }\n return value;\n };\n}\n","import { RpcRequest } from '@solana/rpc-spec-types';\n\nimport { getIntegerOverflowNodeVisitor } from './request-transformer-integer-overflow-internal';\nimport { getTreeWalkerRequestTransformer, KeyPath } from './tree-traversal';\n\nexport type IntegerOverflowHandler = (request: RpcRequest, keyPath: KeyPath, value: bigint) => void;\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided handler\n * when an integer overflow is detected.\n *\n * @example\n * ```ts\n * import { getIntegerOverflowRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getIntegerOverflowRequestTransformer((request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * });\n * ```\n */\nexport function getIntegerOverflowRequestTransformer(onIntegerOverflow: IntegerOverflowHandler) {\n return (request: RpcRequest): RpcRequest => {\n const transformer = getTreeWalkerRequestTransformer(\n [getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))],\n { keyPath: [] },\n );\n return transformer(request);\n };\n}\n","export const OPTIONS_OBJECT_POSITION_BY_METHOD: Record = {\n accountNotifications: 1,\n blockNotifications: 1,\n getAccountInfo: 1,\n getBalance: 1,\n getBlock: 1,\n getBlockHeight: 0,\n getBlockProduction: 0,\n getBlocks: 2,\n getBlocksWithLimit: 2,\n getEpochInfo: 0,\n getFeeForMessage: 1,\n getInflationGovernor: 0,\n getInflationReward: 1,\n getLargestAccounts: 0,\n getLatestBlockhash: 0,\n getLeaderSchedule: 1,\n getMinimumBalanceForRentExemption: 1,\n getMultipleAccounts: 1,\n getProgramAccounts: 1,\n getSignaturesForAddress: 1,\n getSlot: 0,\n getSlotLeader: 0,\n getStakeMinimumDelegation: 0,\n getSupply: 0,\n getTokenAccountBalance: 1,\n getTokenAccountsByDelegate: 2,\n getTokenAccountsByOwner: 2,\n getTokenLargestAccounts: 1,\n getTokenSupply: 1,\n getTransaction: 1,\n getTransactionCount: 0,\n getVoteAccounts: 0,\n isBlockhashValid: 1,\n logsNotifications: 1,\n programNotifications: 1,\n requestAirdrop: 2,\n sendTransaction: 1,\n signatureNotifications: 1,\n simulateTransaction: 1,\n};\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { getBigIntDowncastRequestTransformer } from './request-transformer-bigint-downcast';\nimport { getDefaultCommitmentRequestTransformer } from './request-transformer-default-commitment';\nimport { getIntegerOverflowRequestTransformer, IntegerOverflowHandler } from './request-transformer-integer-overflow';\nimport { OPTIONS_OBJECT_POSITION_BY_METHOD } from './request-transformer-options-object-position-config';\n\nexport type RequestTransformerConfig = Readonly<{\n /**\n * An optional {@link Commitment} value to use as the default when none is supplied by the\n * caller.\n */\n defaultCommitment?: Commitment;\n /**\n * An optional function that will be called whenever a `bigint` input exceeds that which can be\n * expressed using JavaScript numbers.\n *\n * This is used in the default {@link SolanaRpcSubscriptionsApi} to throw an exception rather\n * than to allow truncated values to propagate through a program.\n */\n onIntegerOverflow?: IntegerOverflowHandler;\n}>;\n\n/**\n * Returns the default request transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcRequestTransformer | RpcRequestTransformers} together such as the\n * {@link getDefaultCommitmentTransformer}, the {@link getIntegerOverflowRequestTransformer} and the\n * {@link getBigIntDowncastRequestTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultRequestTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultRequestTransformerForSolanaRpc({\n * defaultCommitment: 'confirmed',\n * onIntegerOverflow: (request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * },\n * });\n * ```\n */\nexport function getDefaultRequestTransformerForSolanaRpc(config?: RequestTransformerConfig): RpcRequestTransformer {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n return (request: RpcRequest): RpcRequest => {\n return pipe(\n request,\n handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : r => r,\n getBigIntDowncastRequestTransformer(),\n getDefaultCommitmentRequestTransformer({\n defaultCommitment: config?.defaultCommitment,\n optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n }),\n );\n };\n}\n","import { KeyPath, KEYPATH_WILDCARD, TraversalState } from './tree-traversal';\n\nexport function getBigIntUpcastVisitor(allowedNumericKeyPaths: readonly KeyPath[]) {\n return function upcastNodeToBigIntIfNumber(value: unknown, { keyPath }: TraversalState) {\n const isInteger = (typeof value === 'number' && Number.isInteger(value)) || typeof value === 'bigint';\n if (!isInteger) return value;\n if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {\n return Number(value);\n } else {\n return BigInt(value);\n }\n };\n}\n\nfunction keyPathIsAllowedToBeNumeric(keyPath: KeyPath, allowedNumericKeyPaths: readonly KeyPath[]) {\n return allowedNumericKeyPaths.some(prohibitedKeyPath => {\n if (prohibitedKeyPath.length !== keyPath.length) {\n return false;\n }\n for (let ii = keyPath.length - 1; ii >= 0; ii--) {\n const keyPathPart = keyPath[ii];\n const prohibitedKeyPathPart = prohibitedKeyPath[ii];\n if (\n prohibitedKeyPathPart !== keyPathPart &&\n (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== 'number')\n ) {\n return false;\n }\n }\n return true;\n });\n}\n","import { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath } from './tree-traversal';\n\n/**\n * Returns a transformer that upcasts all `Number` values to `BigInts` unless they match within the\n * provided {@link KeyPath | KeyPaths}. In other words, the provided {@link KeyPath | KeyPaths} will\n * remain as `Number` values, any other numeric value will be upcasted to a `BigInt`.\n *\n * Note that you can use {@link KEYPATH_WILDCARD} to match any key within a {@link KeyPath}.\n *\n * @example\n * ```ts\n * import { getBigIntUpcastResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getBigIntUpcastResponseTransformer([\n * ['index'],\n * ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n * ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n * ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n * ]);\n * ```\n */\nexport function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths: readonly KeyPath[]) {\n return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });\n}\n","import { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\ntype JsonRpcResponse = { result: unknown };\n\n/**\n * Returns a transformer that extracts the `result` field from the body of the RPC response.\n *\n * For instance, we go from `{ jsonrpc: '2.0', result: 'foo', id: 1 }` to `'foo'`.\n *\n * @example\n * ```ts\n * import { getResultResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getResultResponseTransformer();\n * ```\n */\nexport function getResultResponseTransformer(): RpcResponseTransformer {\n return json => (json as JsonRpcResponse).result;\n}\n","import { KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\nexport type AllowedNumericKeypaths = Partial>;\n\n// Numeric values nested in `jsonParsed` accounts\nexport const jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nexport const jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n];\nexport const innerInstructionsConfigs = [\n ['index'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n];\nexport const messageConfig = [\n ['addressTableLookups', KEYPATH_WILDCARD, 'writableIndexes', KEYPATH_WILDCARD],\n ['addressTableLookups', KEYPATH_WILDCARD, 'readonlyIndexes', KEYPATH_WILDCARD],\n ['header', 'numReadonlySignedAccounts'],\n ['header', 'numReadonlyUnsignedAccounts'],\n ['header', 'numRequiredSignatures'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n] as const;\n","import { getSolanaErrorFromJsonRpcError } from '@solana/errors';\nimport { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { innerInstructionsConfigs, jsonParsedAccountsConfigs } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\ntype JsonRpcResponse = { error: Parameters[0] } | { result: unknown };\n\n// Keypaths for simulateTransaction result that should remain as Number (not BigInt)\n// Note: These are relative to the error.data root, not result.value like in success responses\nfunction getSimulateTransactionAllowedNumericKeypaths(): readonly KeyPath[] {\n return [\n ['loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['innerInstructions', KEYPATH_WILDCARD, ...c]),\n ];\n}\n\n/**\n * Returns a transformer that throws a {@link SolanaError} with the appropriate RPC error code if\n * the body of the RPC response contains an error.\n *\n * @example\n * ```ts\n * import { getThrowSolanaErrorResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getThrowSolanaErrorResponseTransformer();\n * ```\n */\nexport function getThrowSolanaErrorResponseTransformer(): RpcResponseTransformer {\n return (json, request) => {\n const jsonRpcResponse = json as JsonRpcResponse;\n if ('error' in jsonRpcResponse) {\n const { error } = jsonRpcResponse;\n\n // Check if this is a sendTransaction preflight failure (error code -32002)\n // These errors contain RpcSimulateTransactionResult in error.data which needs\n // BigInt values downcast to Number for fields that should be numbers\n const isSendTransactionPreflightFailure =\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n (error.code === -32002 || error.code === -32002n);\n\n if (isSendTransactionPreflightFailure && 'data' in error && error.data) {\n // Apply BigInt downcast transformation to error.data\n const treeWalker = getTreeWalkerResponseTransformer(\n [getBigIntUpcastVisitor(getSimulateTransactionAllowedNumericKeypaths())],\n { keyPath: [] },\n );\n const transformedData = treeWalker(error.data, request);\n\n // Reconstruct error with transformed data\n const transformedError = { ...error, data: transformedData };\n throw getSolanaErrorFromJsonRpcError(transformedError);\n }\n\n throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);\n }\n return jsonRpcResponse;\n };\n}\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcResponse, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { AllowedNumericKeypaths } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastResponseTransformer } from './response-transformer-bigint-upcast';\nimport { getResultResponseTransformer } from './response-transformer-result';\nimport { getThrowSolanaErrorResponseTransformer } from './response-transformer-throw-solana-error';\n\nexport type ResponseTransformerConfig = Readonly<{\n /**\n * An optional map from the name of an API method to an array of {@link KeyPath | KeyPaths}\n * pointing to values in the response that should materialize in the application as `Number`\n * instead of `BigInt`.\n */\n allowedNumericKeyPaths?: AllowedNumericKeypaths;\n}>;\n\n/**\n * Returns the default response transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcResponseTransformer | RpcResponseTransformers} together such as the\n * {@link getThrowSolanaErrorResponseTransformer}, the {@link getResultResponseTransformer} and the\n * {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpc({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpc(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(\n response,\n r => getThrowSolanaErrorResponseTransformer()(r, request),\n r => getResultResponseTransformer()(r, request),\n r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request),\n );\n };\n}\n\n/**\n * Returns the default response transformer for the Solana RPC Subscriptions API.\n *\n * Under the hood, this function composes the {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpcSubscriptions } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpcSubscriptions(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(response, r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));\n };\n}\n","/**\n * This package contains types that describe the [methods](https://solana.com/docs/rpc/http) of the\n * Solana JSON RPC API, and utilities for creating a {@link RpcApi} implementation with sensible\n * defaults. It can be used standalone, but it is also exported as part of Kit\n * [`@solana/kit`](https://github.com/anza-xyz/kit/tree/main/packages/kit).\n *\n * @example\n * Each RPC method is described in terms of a TypeScript type of the following form:\n *\n * ```ts\n * type ExampleApi = {\n * getSomething(address: Address): Something;\n * };\n * ```\n *\n * A {@link RpcApi} that implements `ExampleApi` will ultimately expose its defined methods on any\n * {@link Rpc} that uses it.\n *\n * ```ts\n * const rpc: Rpc = createExampleRpc(/* ... *\\/);\n * const something: Something = await rpc.getSomething(address('95DpK3y3GF7U8s1k4EvZ7xqyeCkhsHeZaE97iZpHUGMN')).send();\n * ```\n *\n * @packageDocumentation\n */\nimport { createJsonRpcApi, RpcApi } from '@solana/rpc-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpc,\n innerInstructionsConfigs,\n jsonParsedAccountsConfigs,\n jsonParsedTokenAccountsConfigs,\n KEYPATH_WILDCARD,\n messageConfig,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype SolanaRpcApiForAllClusters = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n SendTransactionApi &\n SimulateTransactionApi;\ntype SolanaRpcApiForTestClusters = RequestAirdropApi & SolanaRpcApiForAllClusters;\n/**\n * Represents the RPC methods available on test clusters.\n *\n * For instance, the test clusters support the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApi = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the devnet cluster.\n *\n * For instance, the devnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiDevnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the testnet cluster.\n *\n * For instance, the testnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiTestnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the mainnet cluster.\n *\n * For instance, the mainnet cluster does not support the {@link RequestAirdropApi} whereas test\n * clusters do.\n */\nexport type SolanaRpcApiMainnet = SolanaRpcApiForAllClusters;\n\nexport type {\n GetAccountInfoApi,\n GetBalanceApi,\n GetBlockApi,\n GetBlockCommitmentApi,\n GetBlockHeightApi,\n GetBlockProductionApi,\n GetBlocksApi,\n GetBlocksWithLimitApi,\n GetBlockTimeApi,\n GetClusterNodesApi,\n GetEpochInfoApi,\n GetEpochScheduleApi,\n GetFeeForMessageApi,\n GetFirstAvailableBlockApi,\n GetGenesisHashApi,\n GetHealthApi,\n GetHighestSnapshotSlotApi,\n GetIdentityApi,\n GetInflationGovernorApi,\n GetInflationRateApi,\n GetInflationRewardApi,\n GetLargestAccountsApi,\n GetLatestBlockhashApi,\n GetLeaderScheduleApi,\n GetMaxRetransmitSlotApi,\n GetMaxShredInsertSlotApi,\n GetMinimumBalanceForRentExemptionApi,\n GetMultipleAccountsApi,\n GetProgramAccountsApi,\n GetRecentPerformanceSamplesApi,\n GetRecentPrioritizationFeesApi,\n GetSignaturesForAddressApi,\n GetSignatureStatusesApi,\n GetSlotApi,\n GetSlotLeaderApi,\n GetSlotLeadersApi,\n GetStakeMinimumDelegationApi,\n GetSupplyApi,\n GetTokenAccountBalanceApi,\n GetTokenAccountsByDelegateApi,\n GetTokenAccountsByOwnerApi,\n GetTokenLargestAccountsApi,\n GetTokenSupplyApi,\n GetTransactionApi,\n GetTransactionCountApi,\n GetVersionApi,\n GetVoteAccountsApi,\n IsBlockhashValidApi,\n MinimumLedgerSlotApi,\n RequestAirdropApi,\n SendTransactionApi,\n SimulateTransactionApi,\n};\n\ntype Config = RequestTransformerConfig;\n\n/**\n * Creates a {@link RpcApi} implementation of the Solana JSON RPC API with some default behaviours.\n *\n * The default behaviours include:\n * - A transform that converts `bigint` inputs to `number` for compatibility with version 1.0 of the\n * Solana JSON RPC.\n * - A transform that calls the config's {@link Config.onIntegerOverflow | onIntegerOverflow}\n * handler whenever a `bigint` input would overflow a JavaScript IEEE 754 number. See\n * [this](https://github.com/solana-labs/solana-web3.js/issues/1116) GitHub issue for more\n * information.\n * - A transform that applies a default commitment wherever not specified\n */\nexport function createSolanaRpcApi<\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n TRpcMethods extends SolanaRpcApi | SolanaRpcApiDevnet | SolanaRpcApiMainnet | SolanaRpcApiTestnet = SolanaRpcApi,\n>(config?: Config): RpcApi {\n return createJsonRpcApi({\n requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),\n responseTransformer: getDefaultResponseTransformerForSolanaRpc({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n }),\n });\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n ...c,\n ]),\n ...messageConfig.map(c => ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', ...c] as const),\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => ['meta', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ...messageConfig.map(c => ['transaction', 'message', ...c] as const),\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: [\n ['value', 'loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['value', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ],\n };\n }\n return memoizedKeypaths;\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SolanaError } from '@solana/errors';\n\nexport type AllowedHttpRequestHeaders = Readonly<\n {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | Capitalize> // `Foo-bar`\n | K // `Foo-Bar`\n | Lowercase // `foo-bar`\n | Uncapitalize // `foo-Bar`\n // `FOO-BAR`\n | Uppercase]?: never;\n } & { [headerName: string]: string }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n // Though technically forbidden in non-Node environments, we don't have a way to target\n // TypeScript types depending on which platform you are authoring for. `Accept-Encoding` is\n // therefore omitted from the forbidden headers type, but is still a runtime error in dev mode\n // when supplied in a non-Node context.\n // | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n // Similar to `Accept-Encoding`, we don't have a way to target TypeScript types depending on\n // which platform you are authoring for. `Origin` is therefore omitted from the forbidden\n // headers type, but is still a runtime error in dev mode when supplied in a browser context.\n // | 'Origin'\n | 'Permissions-Policy'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via'\n | `Proxy-${string}`\n | `Sec-${string}`;\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record = /* @__PURE__ */ Object.assign(\n {\n 'accept-charset': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n 'permissions-policy': true,\n // Prefix matching is implemented in code, below.\n // 'proxy-': true,\n // 'sec-': true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n },\n __NODEJS__ ? undefined : { 'accept-encoding': true },\n __BROWSER__ ? { origin: true } : undefined,\n);\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record,\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, {\n headers: badHeaders,\n });\n }\n}\n\n// Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n// in the `DisallowedHeaders` type.\nexport function normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError } from '@solana/errors';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\nimport type Dispatcher from 'undici-types/dispatcher';\n\nimport { HttpTransportConfig as Config } from './http-transport-config';\nimport { assertIsAllowedHttpRequestHeaders, normalizeHeaders } from './http-transport-headers';\n\nlet didWarnDispatcherWasSuppliedInNonNodeEnvironment = false;\nfunction warnDispatcherWasSuppliedInNonNodeEnvironment() {\n if (didWarnDispatcherWasSuppliedInNonNodeEnvironment) {\n return;\n }\n didWarnDispatcherWasSuppliedInNonNodeEnvironment = true;\n console.warn(\n 'You have supplied a `Dispatcher` to `createHttpTransport()`. It has been ignored ' +\n 'because Undici dispatchers only work in Node environments. To eliminate this ' +\n 'warning, omit the `dispatcher_NODE_ONLY` property from your config when running in ' +\n 'a non-Node environment.',\n );\n}\n\n/**\n * Creates a function you can use to make `POST` requests with headers suitable for sending JSON\n * data to a server.\n *\n * @example\n * ```ts\n * import { createHttpTransport } from '@solana/rpc-transport-http';\n *\n * const transport = createHttpTransport({ url: 'https://api.mainnet-beta.solana.com' });\n * const response = await transport({\n * payload: { id: 1, jsonrpc: '2.0', method: 'getSlot' },\n * });\n * const data = await response.json();\n * ```\n */\nexport function createHttpTransport(config: Config): RpcTransport {\n if (process.env.NODE_ENV !== \"production\" && !__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n warnDispatcherWasSuppliedInNonNodeEnvironment();\n }\n const { fromJson, headers, toJson, url } = config;\n if (process.env.NODE_ENV !== \"production\" && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n let dispatcherConfig: { dispatcher: Dispatcher | undefined } | undefined;\n if (__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n dispatcherConfig = { dispatcher: config.dispatcher_NODE_ONLY };\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest({\n payload,\n signal,\n }: Parameters[0]): Promise> {\n const body = toJson ? toJson(payload) : JSON.stringify(payload);\n const requestInfo = {\n ...dispatcherConfig,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetch(url, requestInfo);\n if (!response.ok) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {\n headers: response.headers,\n message: response.statusText,\n statusCode: response.status,\n });\n }\n if (fromJson) {\n return fromJson(await response.text(), payload) as TResponse;\n }\n return await response.json();\n };\n}\n","import { isJsonRpcPayload } from '@solana/rpc-spec';\n\nconst SOLANA_RPC_METHODS = [\n 'getAccountInfo',\n 'getBalance',\n 'getBlock',\n 'getBlockCommitment',\n 'getBlockHeight',\n 'getBlockProduction',\n 'getBlocks',\n 'getBlocksWithLimit',\n 'getBlockTime',\n 'getClusterNodes',\n 'getEpochInfo',\n 'getEpochSchedule',\n 'getFeeForMessage',\n 'getFirstAvailableBlock',\n 'getGenesisHash',\n 'getHealth',\n 'getHighestSnapshotSlot',\n 'getIdentity',\n 'getInflationGovernor',\n 'getInflationRate',\n 'getInflationReward',\n 'getLargestAccounts',\n 'getLatestBlockhash',\n 'getLeaderSchedule',\n 'getMaxRetransmitSlot',\n 'getMaxShredInsertSlot',\n 'getMinimumBalanceForRentExemption',\n 'getMultipleAccounts',\n 'getProgramAccounts',\n 'getRecentPerformanceSamples',\n 'getRecentPrioritizationFees',\n 'getSignaturesForAddress',\n 'getSignatureStatuses',\n 'getSlot',\n 'getSlotLeader',\n 'getSlotLeaders',\n 'getStakeMinimumDelegation',\n 'getSupply',\n 'getTokenAccountBalance',\n 'getTokenAccountsByDelegate',\n 'getTokenAccountsByOwner',\n 'getTokenLargestAccounts',\n 'getTokenSupply',\n 'getTransaction',\n 'getTransactionCount',\n 'getVersion',\n 'getVoteAccounts',\n 'index',\n 'isBlockhashValid',\n 'minimumLedgerSlot',\n 'requestAirdrop',\n 'sendTransaction',\n 'simulateTransaction',\n] as const;\n\n/**\n * Helper function that checks if a given `RpcRequest` comes from the Solana RPC API.\n */\nexport function isSolanaRequest(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: (typeof SOLANA_RPC_METHODS)[number];\n params: unknown;\n}> {\n return isJsonRpcPayload(payload) && (SOLANA_RPC_METHODS as readonly string[]).includes(payload.method);\n}\n","import { RpcTransport } from '@solana/rpc-spec';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\n\nimport { createHttpTransport } from './http-transport';\nimport { HttpTransportConfig } from './http-transport-config';\nimport { isSolanaRequest } from './is-solana-request';\n\ntype Config = Pick;\n\n/**\n * Creates a {@link RpcTransport} that uses JSON HTTP requests — much like the\n * {@link createHttpTransport} function - except that it also uses custom `toJson` and `fromJson`\n * functions in order to allow `bigint` values to be serialized and deserialized correctly over the\n * wire.\n *\n * Since this is something specific to the Solana RPC API, these custom JSON functions are only\n * triggered when the request is recognized as a Solana RPC request. Normal RPC APIs should aim to\n * wrap their `bigint` values — e.g. `u64` or `i64` — in special value objects that represent the\n * number as a string to avoid numerical values going above `Number.MAX_SAFE_INTEGER`.\n *\n * It has the same configuration options as {@link createHttpTransport}, but without the `fromJson`\n * and `toJson` options.\n */\nexport function createHttpTransportForSolanaRpc(config: Config): RpcTransport {\n return createHttpTransport({\n ...config,\n fromJson: (rawResponse: string, payload: unknown) =>\n isSolanaRequest(payload) ? parseJsonWithBigInts(rawResponse) : JSON.parse(rawResponse),\n toJson: (payload: unknown) =>\n isSolanaRequest(payload) ? stringifyJsonWithBigInts(payload) : JSON.stringify(payload),\n });\n}\n","/**\n * This project is a fork of [nickyout/fast-stable-stringify](https://github.com/nickyout/fast-stable-stringify)\n *\n * The most popular repository providing this feature is [substack's json-stable-stringify](https://www.npmjs.com/package/json-stable-stringify). The intent of this library is to provide a faster alternative for when performance is more important than features. It assumes you provide basic javascript values without circular references, and returns a non-indented string.\n *\n * Just like substack's, it:\n *\n * - handles all variations of all basic javascript values (number, string, boolean, array, object, null, Date, BigInt)\n * - handles undefined _and_ function in the same way as `JSON.stringify`\n * - **does not support ie8 (and below) with complete certainty**.\n *\n * Unlike substack's, it:\n *\n * - does not implement the 'replacer' or 'space' arguments of the JSON.stringify method\n * - does not check for circular references\n *\n * @example\n * ```js\n * import stringify from '@solana/fast-stable-stringify';\n * stringify({ d: 0, c: 1, a: 2, b: 3, e: 4 }); // '{\"a\":2,\"b\":3,\"c\":1,\"d\":0,\"e\":4}'\n * ```\n *\n * @packageDocumentation\n */\nconst objToString = Object.prototype.toString;\nconst objKeys =\n Object.keys ||\n function (obj) {\n const keys = [];\n for (const name in obj) {\n keys.push(name);\n }\n return keys;\n };\n\nfunction stringify(val: unknown, isArrayProp: boolean) {\n let i, max, str, keys, key, propVal, toStr;\n if (val === true) {\n return 'true';\n }\n if (val === false) {\n return 'false';\n }\n switch (typeof val) {\n case 'object':\n if (val === null) {\n return null;\n } else if ('toJSON' in val && typeof val.toJSON === 'function') {\n return stringify(val.toJSON(), isArrayProp);\n } else {\n toStr = objToString.call(val);\n if (toStr === '[object Array]') {\n str = '[';\n max = (val as unknown[]).length - 1;\n for (i = 0; i < max; i++) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true) + ',';\n }\n if (max > -1) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true);\n }\n return str + ']';\n } else if (toStr === '[object Object]') {\n // only object is left\n keys = objKeys(val).sort();\n max = keys.length;\n str = '';\n i = 0;\n while (i < max) {\n key = keys[i];\n propVal = stringify((val as Record)[key], false);\n if (propVal !== undefined) {\n if (str) {\n str += ',';\n }\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += JSON.stringify(key) + ':' + propVal;\n }\n i++;\n }\n return '{' + str + '}';\n } else {\n return JSON.stringify(val);\n }\n }\n case 'function':\n case 'undefined':\n return isArrayProp ? null : undefined;\n case 'bigint':\n return `${val.toString()}n`;\n case 'string':\n return JSON.stringify(val);\n default:\n return isFinite(val as number) ? val : null;\n }\n}\n\nexport default function (\n val:\n | Function // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n | undefined,\n): undefined;\nexport default function (val: unknown): string;\nexport default function (val: unknown): string | undefined {\n const returnVal = stringify(val, false);\n if (returnVal !== undefined) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n return '' + returnVal;\n }\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcApi } from '@solana/rpc-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\n/**\n * When you create {@link Rpc} instances with custom transports but otherwise the default RPC API\n * behaviours, use this.\n *\n * @example\n * ```ts\n * const myCustomRpc = createRpc({\n * api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n * transport: myCustomTransport,\n * });\n * ```\n */\nexport const DEFAULT_RPC_CONFIG: Partial[0]>> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { AbortController } from '@solana/event-target-impl';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\n// This used to be a `Symbol()`, but there's a bug in Node <21 where the `undici` library passes\n// the `reason` property of the `AbortSignal` straight to `Error.captureStackTrace()` without first\n// typechecking it. `Error.captureStackTrace()` fatals when given a `Symbol`.\n// See https://github.com/nodejs/undici/pull/2597\nlet EXPLICIT_ABORT_TOKEN: ReturnType;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return process.env.NODE_ENV !== \"production\"\n ? {\n EXPLICIT_ABORT_TOKEN:\n 'This object is thrown from the request that underlies a series of coalesced ' +\n 'requests when the last request in that series aborts',\n }\n : {};\n}\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: TTransport,\n getDeduplicationKey: GetDeduplicationKeyFn,\n): TTransport {\n let coalescedRequestsByDeduplicationKey: Record | undefined;\n return async function makeCoalescedHttpRequest(\n request: Parameters[0],\n ): Promise> {\n const { payload, signal } = request;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(request);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n queueMicrotask(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n const responsePromise = (async () => {\n try {\n return await transport({\n ...request,\n signal: abortController.signal,\n });\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n // We triggered this error when the last subscriber aborted. Letting this\n // error bubble up from here would cause runtime fatals where there should\n // be none.\n return;\n }\n throw e;\n }\n })();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise,\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise>;\n return await new Promise>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n queueMicrotask(() => {\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n }\n });\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject((e.target as AbortSignal).reason);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise\n .then(resolve)\n .catch(reject)\n .finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as RpcResponse;\n }\n } as TTransport;\n}\n","import fastStableStringify from '@solana/fast-stable-stringify';\nimport { isJsonRpcPayload } from '@solana/rpc-spec';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport, createHttpTransportForSolanaRpc } from '@solana/rpc-transport-http';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { RpcTransportFromClusterUrl } from './rpc-clusters';\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\ntype RpcTransportConfig = Parameters[0];\ninterface DefaultRpcTransportConfig extends RpcTransportConfig {\n url: TClusterUrl;\n}\n\nfunction normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n // Lowercasing header names makes it easier to override user-supplied headers.\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n\n/**\n * Creates a {@link RpcTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - An automatically-set `Solana-Client` request header, containing the version of `@solana/kit`\n * - Logic that coalesces multiple calls in the same runloop, for the same methods with the same\n * arguments, into a single network request.\n * - [node-only] An automatically-set `Accept-Encoding` request header asking the server to compress\n * responses\n *\n * @param config\n */\nexport function createDefaultRpcTransport(\n config: DefaultRpcTransportConfig,\n): RpcTransportFromClusterUrl {\n return pipe(\n createHttpTransportForSolanaRpc({\n ...config,\n headers: {\n ...(__NODEJS__ &&\n ({\n // Keep these headers lowercase so they will be overridden by any user-supplied headers below.\n 'accept-encoding':\n // Natively supported by Node LTS v20.18.0 and above.\n 'br,gzip,deflate', // Brotli, gzip, and Deflate, in that order.\n } as { [overrideHeader: string]: string })),\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': __VERSION__ ? `js/${__VERSION__}` : 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }) as RpcTransportFromClusterUrl,\n transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey),\n );\n}\n","import { createSolanaRpcApi } from '@solana/rpc-api';\nimport { createRpc, RpcTransport } from '@solana/rpc-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport type { RpcFromTransport, SolanaRpcApiFromTransport } from './rpc-clusters';\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { createDefaultRpcTransport } from './rpc-transport';\n\ntype DefaultRpcTransportConfig = Parameters<\n typeof createDefaultRpcTransport\n>[0];\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given a cluster URL and some\n * optional transport config. See {@link createDefaultRpcTransport} for the shape of the transport\n * config.\n */\nexport function createSolanaRpc(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcFromTransport(createDefaultRpcTransport({ url: clusterUrl, ...config }));\n}\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given the supplied\n * {@link RpcTransport}.\n */\nexport function createSolanaRpcFromTransport(transport: TTransport) {\n return createRpc({\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n transport,\n }) as RpcFromTransport, TTransport>;\n}\n","\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable {\n const iteratorState: Map> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher = Record> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter>(\n eventEmitter: TypedEventEmitter | TypedEventTarget,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\nimport { createAsyncIterableFromDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsApi, RpcSubscriptionsPlan } from './rpc-subscriptions-api';\nimport { PendingRpcSubscriptionsRequest, RpcSubscribeOptions } from './rpc-subscriptions-request';\nimport { RpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsConfig = Readonly<{\n api: RpcSubscriptionsApi;\n transport: RpcSubscriptionsTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcSubscriptionsMethods`.\n *\n * Calling each method returns a\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} where\n * `TNotification` is that method's notification type.\n */\nexport type RpcSubscriptions = {\n [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder<\n OverloadImplementations\n >;\n};\n\ntype PendingRpcSubscriptionsRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TSubscriptionMethodImplementations]: PendingRpcSubscriptionsRequestReturnTypeMapper<\n TSubscriptionMethodImplementations[P]\n >;\n }>\n>;\n\ntype PendingRpcSubscriptionsRequestReturnTypeMapper =\n // Check that this property of the TRpcSubscriptionMethods interface is, in fact, a function.\n TSubscriptionMethodImplementation extends Callable\n ? (\n ...args: Parameters\n ) => PendingRpcSubscriptionsRequest>\n : never;\n\n/**\n * Creates a {@link RpcSubscriptions} instance given a\n * {@link RpcSubscriptionsApi | RpcSubscriptionsApi} and a\n * {@link RpcSubscriptionsTransport} capable of fulfilling them.\n */\nexport function createSubscriptionRpc(\n rpcConfig: RpcSubscriptionsConfig,\n): RpcSubscriptions {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const notificationName = p.toString();\n const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);\n if (!createRpcSubscriptionPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {\n notificationName,\n });\n }\n const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);\n return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);\n };\n },\n }) as RpcSubscriptions;\n}\n\nfunction createPendingRpcSubscription(\n transport: RpcSubscriptionsTransport,\n subscriptionsPlan: RpcSubscriptionsPlan,\n): PendingRpcSubscriptionsRequest {\n return {\n async subscribe({ abortSignal }: RpcSubscribeOptions): Promise> {\n const notificationsDataPublisher = await transport({\n signal: abortSignal,\n ...subscriptionsPlan,\n });\n return createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName: 'notification',\n dataPublisher: notificationsDataPublisher,\n errorChannelName: 'error',\n });\n },\n };\n}\n","import { Callable, RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsTransportDataEvents } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsApiConfig = Readonly<{\n planExecutor: RpcSubscriptionsPlanExecutor>;\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n}>;\n\n/**\n * A function that implements a protocol for subscribing and unsubscribing from notifications given\n * a {@link RpcSubscriptionsChannel}, a {@link RpcRequest}, and an `AbortSignal`.\n *\n * @returns A {@link DataPublisher} that emits {@link RpcSubscriptionsTransportDataEvents}\n */\ntype RpcSubscriptionsPlanExecutor = (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n request: RpcRequest;\n signal: AbortSignal;\n }>,\n) => Promise>>;\n\n/**\n * This type allows an {@link RpcSubscriptionsApi} to describe how a particular subscription should\n * be issued to the JSON RPC server.\n *\n * Given a function that was called on a {@link RpcSubscriptions}, this object exposes an `execute`\n * function that dictates which subscription request will be sent, how the underlying transport will\n * be used, and how the notifications will be transformed.\n *\n * This function accepts a {@link RpcSubscriptionsChannel} and an `AbortSignal` and asynchronously\n * returns a {@link DataPublisher}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * channel.\n * - call the underlying channel zero, one or multiple times depending on the use-case (e.g.\n * caching or coalescing multiple subscriptions).\n * - transform the notification from the JSON RPC server, in case it does not match the\n * `TNotification` specified by the\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} emitted\n * from the publisher returned.\n */\nexport type RpcSubscriptionsPlan = Readonly<{\n /**\n * This method may be called with a newly-opened channel or a pre-established channel.\n */\n execute: (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n signal: AbortSignal;\n }>,\n ) => Promise>>;\n /**\n * This request is used to uniquely identify the subscription.\n * It typically comes from the method name and parameters of the subscription call,\n * after potentially being transformed by the RPC Subscriptions API.\n */\n request: RpcRequest;\n}>;\n\n/**\n * For each of `TRpcSubscriptionsMethods`, this object exposes a method with the same name that maps\n * between its input arguments and a\n * {@link RpcSubscriptionsPlan | RpcSubscriptionsPlan} that implements the execution\n * of a JSON RPC subscription for `TNotifications`.\n */\nexport type RpcSubscriptionsApi = {\n [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper<\n TRpcSubscriptionMethods[MethodName]\n >;\n};\n\ntype RpcSubscriptionsReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcSubscriptionsPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcSubscriptionsApiMethod = (...args: any) => any;\nexport interface RpcSubscriptionsApiMethods {\n [methodName: string]: RpcSubscriptionsApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a\n * {@link RpcSubscriptionsPlan} by creating an `execute` function that:\n *\n * - calls the supplied {@link RpcSubscriptionsApiConfig.planExecutor} with a JSON RPC v2 payload\n * object with the requested `methodName` and `params` properties, optionally transformed by\n * {@link RpcSubscriptionsApiConfig.requestTransformer}.\n *\n * @example\n * ```ts\n * // For example, given this `RpcSubscriptionsApi`:\n * const rpcSubscriptionsApi = createJsonRpcSubscriptionsApi({\n * async planExecutor({ channel, request }) {\n * await channel.send(request);\n * return {\n * ...channel,\n * on(type, listener, options) {\n * if (type !== 'message') {\n * return channel.on(type, listener, options);\n * }\n * return channel.on(\n * 'message',\n * function resultGettingListener(message) {\n * listener(message.result);\n * },\n * options,\n * );\n * }\n * }\n * },\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * });\n *\n * // ...the following function call:\n * rpcSubscriptionsApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcSubscriptionsPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Emits the \"result\" property of each RPC Subscriptions message.\n * ```\n */\nexport function createRpcSubscriptionsApi(\n config: RpcSubscriptionsApiConfig,\n): RpcSubscriptionsApi {\n return new Proxy({} as RpcSubscriptionsApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcSubscriptionsApiMethods as string;\n return function (\n ...params: Parameters<\n TRpcSubscriptionsApiMethods[TNotificationName] extends CallableFunction\n ? TRpcSubscriptionsApiMethods[TNotificationName]\n : never\n >\n ): RpcSubscriptionsPlan> {\n const rawRequest = { methodName, params };\n const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;\n return {\n execute(planConfig) {\n return config.planExecutor({ ...planConfig, request });\n },\n request,\n };\n };\n },\n });\n}\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype RpcSubscriptionsChannelSolanaErrorCode =\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT;\n\nexport type RpcSubscriptionChannelEvents = {\n /**\n * Fires when the channel closes unexpectedly.\n * @eventProperty\n */\n error: SolanaError;\n /**\n * Fires on every message received from the remote end.\n * @eventProperty\n */\n message: TInboundMessage;\n};\n\n/**\n * A {@link DataPublisher} on which you can subscribe to events of type\n * {@link RpcSubscriptionChannelEvents | RpcSubscriptionChannelEvents}.\n * Additionally, you can use this object to send messages of type `TOutboundMessage` back to the\n * remote end by calling its {@link RpcSubscriptionsChannel.send | `send(message)`} method.\n */\nexport interface RpcSubscriptionsChannel extends DataPublisher<\n RpcSubscriptionChannelEvents\n> {\n send(message: TOutboundMessage): Promise;\n}\n\n/**\n * A channel creator is a function that accepts an `AbortSignal`, returns a new\n * {@link RpcSubscriptionsChannel}, and tears down the channel when the abort signal fires.\n */\nexport type RpcSubscriptionsChannelCreator = (\n config: Readonly<{\n abortSignal: AbortSignal;\n }>,\n) => Promise>;\n\n/**\n * Given a channel with inbound messages of type `T` and a function of type `T => U`, returns a new\n * channel with inbound messages of type `U`.\n *\n * Note that this only affects messages of type `\"message\"` and thus, does not affect incoming error\n * messages.\n *\n * @example Parsing incoming JSON messages\n * ```ts\n * const transformedChannel = transformChannelInboundMessages(channel, JSON.parse);\n * ```\n */\nexport function transformChannelInboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TInboundMessage) => TNewInboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n on(type, subscriber, options) {\n if (type !== 'message') {\n return channel.on(\n type,\n subscriber as (data: RpcSubscriptionChannelEvents[typeof type]) => void,\n options,\n );\n }\n return channel.on(\n 'message',\n message => (subscriber as (data: TNewInboundMessage) => void)(transform(message)),\n options,\n );\n },\n });\n}\n\n/**\n * Given a channel with outbound messages of type `T` and a function of type `U => T`, returns a new\n * channel with outbound messages of type `U`.\n *\n * @example Stringifying JSON messages before sending them over the wire\n * ```ts\n * const transformedChannel = transformChannelOutboundMessages(channel, JSON.stringify);\n * ```\n */\nexport function transformChannelOutboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TNewOutboundMessage) => TOutboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n send: message => channel.send(transform(message)),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n getSolanaErrorFromJsonRpcError,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport { createRpcMessage, RpcRequest, RpcResponseData, RpcResponseTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\nimport { demultiplexDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionChannelEvents } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\n\ntype Config = Readonly<{\n channel: RpcSubscriptionsChannel | RpcResponseData>;\n responseTransformer?: RpcResponseTransformer;\n signal: AbortSignal;\n subscribeRequest: RpcRequest;\n unsubscribeMethodName: string;\n}>;\n\ntype RpcNotification = Readonly<{\n method: string;\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\n\ntype RpcSubscriptionId = number;\n\ntype RpcSubscriptionNotificationEvents = Omit, 'message'> & {\n notification: TNotification;\n};\n\nconst subscriberCountBySubscriptionIdByChannel = new WeakMap>();\nfunction decrementSubscriberCountAndReturnNewCount(channel: WeakKey, subscriptionId?: number): number | undefined {\n return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);\n}\nfunction incrementSubscriberCount(channel: WeakKey, subscriptionId?: number): void {\n augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);\n}\nfunction getSubscriberCountBySubscriptionIdForChannel(channel: WeakKey): Record {\n let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);\n if (!subscriberCountBySubscriptionId) {\n subscriberCountBySubscriptionIdByChannel.set(channel, (subscriberCountBySubscriptionId = {}));\n }\n return subscriberCountBySubscriptionId;\n}\nfunction augmentSubscriberCountAndReturnNewCount(\n amount: -1 | 1,\n channel: WeakKey,\n subscriptionId?: number,\n): number | undefined {\n if (subscriptionId === undefined) {\n return;\n }\n const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);\n if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) {\n subscriberCountBySubscriptionId[subscriptionId] = 0;\n }\n const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];\n if (newCount <= 0) {\n delete subscriberCountBySubscriptionId[subscriptionId];\n } else {\n subscriberCountBySubscriptionId[subscriptionId] = newCount;\n }\n return newCount;\n}\n\nconst cache = new WeakMap();\nfunction getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel: RpcSubscriptionsChannel>,\n subscribeRequest: RpcRequest,\n responseTransformer?: RpcResponseTransformer,\n): DataPublisher<{\n [channelName: `notification:${number}`]: TNotification;\n}> {\n let publisherByResponseTransformer = cache.get(channel);\n if (!publisherByResponseTransformer) {\n cache.set(channel, (publisherByResponseTransformer = new WeakMap()));\n }\n const responseTransformerKey = responseTransformer ?? channel;\n let publisher = publisherByResponseTransformer.get(responseTransformerKey);\n if (!publisher) {\n publisherByResponseTransformer.set(\n responseTransformerKey,\n (publisher = demultiplexDataPublisher(channel, 'message', rawMessage => {\n const message = rawMessage as RpcNotification | RpcResponseData;\n if (!('method' in message)) {\n return;\n }\n const transformedNotification = responseTransformer\n ? responseTransformer(message.params.result, subscribeRequest)\n : message.params.result;\n return [`notification:${message.params.subscription}`, transformedNotification];\n })),\n );\n }\n return publisher;\n}\n\n/**\n * Given a channel, this function executes the particular subscription plan required by the Solana\n * JSON RPC Subscriptions API.\n *\n * @param config\n *\n * 1. Calls the `subscribeRequest` on the remote RPC\n * 2. Waits for a response containing the subscription id\n * 3. Returns a {@link DataPublisher} that publishes notifications related to that subscriptions id,\n * filtering out all others\n * 4. Calls the `unsubscribeMethodName` on the remote RPC when the abort signal is fired.\n */\nexport async function executeRpcPubSubSubscriptionPlan({\n channel,\n responseTransformer,\n signal,\n subscribeRequest,\n unsubscribeMethodName,\n}: Config): Promise>> {\n let subscriptionId: number | undefined;\n channel.on(\n 'error',\n () => {\n // An error on the channel indicates that the subscriptions are dead.\n // There is no longer any sense hanging on to subscription ids.\n // Erasing it here will prevent the unsubscribe code from running.\n subscriptionId = undefined;\n subscriberCountBySubscriptionIdByChannel.delete(channel);\n },\n { signal },\n );\n /**\n * STEP 1\n * Create a promise that rejects if this subscription is aborted and sends\n * the unsubscribe message if the subscription is active at that time.\n */\n const abortPromise = new Promise((_, reject) => {\n function handleAbort(this: AbortSignal) {\n /**\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they\n * will be assigned the same subscription id, and will occupy one subscription slot. We\n * must be careful not to send the unsubscribe message until the last subscriber aborts.\n */\n if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {\n const unsubscribePayload = createRpcMessage({\n methodName: unsubscribeMethodName,\n params: [subscriptionId],\n });\n subscriptionId = undefined;\n channel.send(unsubscribePayload).catch(() => {});\n }\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n }\n if (signal.aborted) {\n handleAbort.call(signal);\n } else {\n signal.addEventListener('abort', handleAbort);\n }\n });\n /**\n * STEP 2\n * Send the subscription request.\n */\n const subscribePayload = createRpcMessage(subscribeRequest);\n await channel.send(subscribePayload);\n /**\n * STEP 3\n * Wait for the acknowledgement from the server with the subscription id.\n */\n const subscriptionIdPromise = new Promise((resolve, reject) => {\n const abortController = new AbortController();\n signal.addEventListener('abort', abortController.abort.bind(abortController));\n const options = { signal: abortController.signal } as const;\n channel.on(\n 'error',\n err => {\n abortController.abort();\n reject(err);\n },\n options,\n );\n channel.on(\n 'message',\n message => {\n if (message && typeof message === 'object' && 'id' in message && message.id === subscribePayload.id) {\n abortController.abort();\n if ('error' in message) {\n reject(getSolanaErrorFromJsonRpcError(message.error));\n } else {\n resolve(message.result);\n }\n }\n },\n options,\n );\n });\n subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);\n if (subscriptionId == null) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);\n }\n incrementSubscriberCount(channel, subscriptionId);\n /**\n * STEP 4\n * Filter out notifications unrelated to this subscription.\n */\n const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel,\n subscribeRequest,\n responseTransformer,\n );\n const notificationKey = `notification:${subscriptionId}` as const;\n return {\n on(type, listener, options) {\n switch (type) {\n case 'notification':\n return notificationPublisher.on(\n notificationKey,\n listener as (data: RpcSubscriptionNotificationEvents['notification']) => void,\n options,\n );\n case 'error':\n return channel.on(\n 'error',\n listener as (data: RpcSubscriptionNotificationEvents['error']) => void,\n options,\n );\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {\n channelName: type,\n supportedChannelNames: ['notification', 'error'],\n });\n }\n },\n };\n}\n","import {\n createRpcSubscriptionsApi,\n executeRpcPubSubSubscriptionPlan,\n RpcSubscriptionsApi,\n RpcSubscriptionsApiMethods,\n} from '@solana/rpc-subscriptions-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpcSubscriptions,\n jsonParsedAccountsConfigs,\n KEYPATH_WILDCARD,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\nexport type SolanaRpcSubscriptionsApi = AccountNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsApiUnstable = BlockNotificationsApi &\n SlotsUpdatesNotificationsApi &\n VoteNotificationsApi;\n\nexport type {\n AccountNotificationsApi,\n BlockNotificationsApi,\n LogsNotificationsApi,\n ProgramNotificationsApi,\n RootNotificationsApi,\n SignatureNotificationsApi,\n SlotNotificationsApi,\n SlotsUpdatesNotificationsApi,\n VoteNotificationsApi,\n};\n\ntype Config = RequestTransformerConfig;\n\nfunction createSolanaRpcSubscriptionsApi_INTERNAL(\n config?: Config,\n): RpcSubscriptionsApi {\n const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);\n const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n });\n return createRpcSubscriptionsApi({\n planExecutor({ request, ...rest }) {\n return executeRpcPubSubSubscriptionPlan({\n ...rest,\n responseTransformer,\n subscribeRequest: { ...request, methodName: request.methodName.replace(/Notifications$/, 'Subscribe') },\n unsubscribeMethodName: request.methodName.replace(/Notifications$/, 'Unsubscribe'),\n });\n },\n requestTransformer,\n });\n}\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config,\n): RpcSubscriptionsApi {\n return createSolanaRpcSubscriptionsApi_INTERNAL(config);\n}\n\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(config?: Config) {\n return createSolanaRpcSubscriptionsApi_INTERNAL(\n config,\n );\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths<\n RpcSubscriptionsApi\n>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths<\n RpcSubscriptionsApi\n> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\n }\n return memoizedKeypaths;\n}\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 CLOSE_TIMEOUT: 30000,\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","'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\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\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\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\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 | String)[]} 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 CLOSE_TIMEOUT,\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 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._closeTimeout = options.closeTimeout;\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 {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\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 closeTimeout: CLOSE_TIMEOUT,\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 websocket._closeTimeout = opts.closeTimeout;\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 websocket._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 //\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. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\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","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\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 { 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 { CLOSE_TIMEOUT, 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 {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\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 closeTimeout: CLOSE_TIMEOUT,\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 !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\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 * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\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, headers);\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","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","// When building the browser bundle, this import gets replaced by `globalThis.WebSocket`.\nimport WebSocketImpl from 'ws';\n\nexport default globalThis.WebSocket\n ? globalThis.WebSocket // Use native `WebSocket` in runtimes that support it (eg. Deno)\n : WebSocketImpl;\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { EventTarget } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport { getDataPublisherFromEventEmitter } from '@solana/subscribable';\nimport WebSocket from '@solana/ws-impl';\n\nexport type Config = Readonly<{\n /**\n * The number of bytes to admit into the WebSocket's send buffer before queueing messages on the\n * client.\n *\n * When you call {@link RpcSubscriptionsChannel.send | `send()`} on a `WebSocket` the runtime\n * might add the message to a buffer rather than send it right away. In the event that\n * `socket.bufferedAmount` exceeds the value configured here, messages will be added to a queue\n * in your application code instead of being sent to the WebSocket, until such time as the\n * `bufferedAmount` falls back below the high watermark.\n */\n sendBufferHighWatermark: number;\n /**\n * An `AbortSignal` to fire when you want to explicitly close the `WebSocket`.\n *\n * If the channel is open it will be closed with a normal closure code\n * (https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1) If the channel has not been\n * established yet, firing this signal will result in the `AbortError` being thrown to the\n * caller who was trying to open the channel.\n */\n signal: AbortSignal;\n /**\n * A string representing the target endpoint.\n *\n * In Node, it must be an absolute URL using the `ws` or `wss` protocol.\n */\n url: string;\n}>;\n\ntype WebSocketMessage = ArrayBufferLike | ArrayBufferView | Blob | string;\n\nconst NORMAL_CLOSURE_CODE = 1000; // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n\n/**\n * Creates an object that represents an open channel to a `WebSocket` server.\n *\n * You can use it to send messages by calling its\n * {@link RpcSubscriptionsChannel.send | `send()`} function and you can receive them by subscribing\n * to the {@link RpcSubscriptionChannelEvents} it emits.\n */\nexport function createWebSocketChannel({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise> {\n if (signal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(signal.reason);\n }\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise }> | undefined;\n let hasConnected = false;\n const listenerRemovers = new Set<() => void>();\n function cleanupListeners() {\n listenerRemovers.forEach(r => {\n r();\n });\n listenerRemovers.clear();\n }\n function handleAbort() {\n cleanupListeners();\n if (!hasConnected) {\n rejectOpen(signal.reason);\n }\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(NORMAL_CLOSURE_CODE);\n }\n }\n function handleClose(ev: CloseEvent) {\n cleanupListeners();\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('message', handleMessage);\n webSocket.removeEventListener('open', handleOpen);\n if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) {\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, {\n cause: ev,\n }),\n }),\n );\n }\n }\n function handleError(ev: Event) {\n if (signal.aborted) {\n return;\n }\n if (!hasConnected) {\n const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, {\n errorEvent: ev,\n });\n rejectOpen(failedToConnectError);\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: failedToConnectError,\n }),\n );\n }\n }\n function handleMessage(ev: MessageEvent) {\n if (signal.aborted) {\n return;\n }\n eventTarget.dispatchEvent(new CustomEvent('message', { detail: ev.data }));\n }\n const eventTarget = new EventTarget();\n const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n function handleOpen() {\n hasConnected = true;\n resolveOpen({\n ...dataPublisher,\n async send(message) {\n if (webSocket.readyState !== WebSocket.OPEN) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);\n }\n if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {\n let onCancel!: () => void;\n const promise = new Promise((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n new SolanaError(\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n ),\n );\n };\n });\n bufferDrainWatcher = {\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {\n const TypedArrayConstructor = message.constructor as {\n new (...args: [typeof message]): typeof message;\n };\n // Clone the message to prevent mutation while queued.\n message = new TypedArrayConstructor(message);\n }\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n });\n }\n const webSocket = new WebSocket(url);\n signal.addEventListener('abort', handleAbort);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('message', handleMessage);\n webSocket.addEventListener('open', handleOpen);\n let rejectOpen!: (e: SolanaError) => void;\n let resolveOpen!: (value: RpcSubscriptionsChannel) => void;\n return new Promise>((resolve, reject) => {\n rejectOpen = reject;\n resolveOpen = resolve;\n });\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_SUBSCRIPTIONS_CONFIG: Partial<\n NonNullable[0]>\n> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { isSolanaError, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\ntype Config> = Readonly<{\n abortSignal: AbortSignal;\n channel: TChannel;\n intervalMs: number;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that sends a ping message to\n * the inner channel if a message has not been sent or received in the last `intervalMs`. In web\n * browsers, this implementation sends no ping when the network is down, and sends a ping\n * immediately upon the network coming back up.\n */\nexport function getRpcSubscriptionsChannelWithAutoping>({\n abortSignal: callerAbortSignal,\n channel,\n intervalMs,\n}: Config): TChannel {\n let intervalId: ReturnType | undefined;\n function sendPing() {\n channel.send(PING_PAYLOAD).catch((e: unknown) => {\n if (isSolanaError(e, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED)) {\n pingerAbortController.abort();\n }\n });\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, intervalMs);\n }\n const pingerAbortController = new AbortController();\n pingerAbortController.signal.addEventListener('abort', () => {\n clearInterval(intervalId);\n });\n callerAbortSignal.addEventListener('abort', () => {\n pingerAbortController.abort();\n });\n channel.on(\n 'error',\n () => {\n pingerAbortController.abort();\n },\n { signal: pingerAbortController.signal },\n );\n channel.on('message', restartPingTimer, { signal: pingerAbortController.signal });\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n if (__BROWSER__) {\n globalThis.addEventListener(\n 'offline',\n function handleOffline() {\n clearInterval(intervalId);\n },\n { signal: pingerAbortController.signal },\n );\n globalThis.addEventListener(\n 'online',\n function handleOnline() {\n sendPing();\n restartPingTimer();\n },\n { signal: pingerAbortController.signal },\n );\n }\n return {\n ...channel,\n send(...args) {\n if (!pingerAbortController.signal.aborted) {\n restartPingTimer();\n }\n return channel.send(...args);\n },\n };\n}\n","import { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\nexport type ChannelPoolEntry = {\n channel: PromiseLike> | RpcSubscriptionsChannel;\n readonly dispose: () => void;\n subscriptionCount: number;\n};\n\ntype ChannelPool = { readonly entries: ChannelPoolEntry[]; freeChannelIndex: number };\n\nexport function createChannelPool(): ChannelPool {\n return {\n entries: [],\n freeChannelIndex: -1,\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannelCreator } from '@solana/rpc-subscriptions-spec';\n\nimport { ChannelPoolEntry, createChannelPool } from './rpc-subscriptions-channel-pool-internal';\n\ntype Config = Readonly<{\n maxSubscriptionsPerChannel: number;\n minChannels: number;\n}>;\n\n/**\n * Given a channel creator, will return a new channel creator with the following behavior.\n *\n * 1. When called, returns a {@link RpcSubscriptionsChannel}. Adds that channel to a pool.\n * 2. When called again, creates and returns new\n * {@link RpcSubscriptionChannel | RpcSubscriptionChannels} up to the number specified by\n * `minChannels`.\n * 3. When `minChannels` channels have been created, subsequent calls vend whichever existing\n * channel from the pool has the fewest subscribers, or the next one in rotation in the event of\n * a tie.\n * 4. Once all channels carry the number of subscribers specified by the number\n * `maxSubscriptionsPerChannel`, new channels in excess of `minChannel` will be created,\n * returned, and added to the pool.\n * 5. A channel will be destroyed once all of its subscribers' abort signals fire.\n */\nexport function getChannelPoolingChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n>(createChannel: TChannelCreator, { maxSubscriptionsPerChannel, minChannels }: Config): TChannelCreator {\n const pool = createChannelPool();\n /**\n * This function advances the free channel index to the pool entry with the most capacity. It\n * sets the index to `-1` if all channels are full.\n */\n function recomputeFreeChannelIndex() {\n if (pool.entries.length < minChannels) {\n // Don't set the free channel index until the pool fills up; we want to keep creating\n // channels before we start rotating among them.\n pool.freeChannelIndex = -1;\n return;\n }\n let mostFreeChannel: Readonly<{ poolIndex: number; subscriptionCount: number }> | undefined;\n for (let ii = 0; ii < pool.entries.length; ii++) {\n const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;\n const nextPoolEntry =\n // Start from the item two positions after the current item. This way, the\n // search will finish on the item after the current one. This ensures that, if\n // any channels tie for having the most capacity, the one that will be chosen is\n // the one immediately to the current one's right (wrapping around).\n pool.entries[nextPoolIndex];\n if (\n nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel &&\n (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)\n ) {\n mostFreeChannel = {\n poolIndex: nextPoolIndex,\n subscriptionCount: nextPoolEntry.subscriptionCount,\n };\n }\n }\n pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;\n }\n return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {\n let poolEntry: ChannelPoolEntry;\n function destroyPoolEntry() {\n const index = pool.entries.findIndex(entry => entry === poolEntry);\n pool.entries.splice(index, 1);\n poolEntry.dispose();\n recomputeFreeChannelIndex();\n }\n if (pool.freeChannelIndex === -1) {\n const abortController = new AbortController();\n const newChannelPromise = createChannel({ abortSignal: abortController.signal });\n newChannelPromise\n .then(newChannel => {\n newChannel.on('error', destroyPoolEntry, { signal: abortController.signal });\n })\n .catch(destroyPoolEntry);\n poolEntry = {\n channel: newChannelPromise,\n dispose() {\n abortController.abort();\n },\n subscriptionCount: 0,\n };\n pool.entries.push(poolEntry);\n } else {\n poolEntry = pool.entries[pool.freeChannelIndex];\n }\n /**\n * A note about subscription counts.\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they will be\n * assigned the same subscription id, and will occupy one subscription slot. We can't tell,\n * from here, whether a subscription will be treated in this way or not, so we\n * unconditionally increment the subscription count every time a subscription request is\n * made. This may result in subscription channels being treated as out-of-capacity when in\n * fact they are not.\n */\n poolEntry.subscriptionCount++;\n abortSignal.addEventListener('abort', function destroyConsumer() {\n poolEntry.subscriptionCount--;\n if (poolEntry.subscriptionCount === 0) {\n destroyPoolEntry();\n } else if (pool.freeChannelIndex !== -1) {\n // Back the free channel index up one position, and recompute it.\n pool.freeChannelIndex--;\n recomputeFreeChannelIndex();\n }\n });\n recomputeFreeChannelIndex();\n return poolEntry.channel;\n } as TChannelCreator;\n}\n","import { pipe } from '@solana/functional';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that parses data published to\n * the `'message'` channel as JSON, and JSON-stringifies messages sent via the\n * {@link RpcSubscriptionsChannel.send | send(message)} method.\n */\nexport function getRpcSubscriptionsChannelWithJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, JSON.parse),\n c => transformChannelOutboundMessages(c, JSON.stringify),\n );\n}\n","import { pipe } from '@solana/functional';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Similarly, to {@link getRpcSubscriptionsChannelWithJSONSerialization}, this function will\n * stringify and parse JSON message to and from the given `string` channel. However, this function\n * parses any integer value as a `BigInt` in order to safely handle numbers that exceed the\n * JavaScript [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\n * value.\n */\nexport function getRpcSubscriptionsChannelWithBigIntJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, parseJsonWithBigInts),\n c => transformChannelOutboundMessages(c, stringifyJsonWithBigInts),\n );\n}\n","import { createWebSocketChannel } from '@solana/rpc-subscriptions-channel-websocket';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { getRpcSubscriptionsChannelWithAutoping } from './rpc-subscriptions-autopinger';\nimport { getChannelPoolingChannelCreator } from './rpc-subscriptions-channel-pool';\nimport { RpcSubscriptionsChannelCreatorFromClusterUrl } from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsChannelWithJSONSerialization } from './rpc-subscriptions-json';\nimport { getRpcSubscriptionsChannelWithBigIntJSONSerialization } from './rpc-subscriptions-json-bigint';\n\nexport type DefaultRpcSubscriptionsChannelConfig = Readonly<{\n /**\n * The number of milliseconds to wait since the last message sent or received over the channel\n * before sending a ping message to keep the channel open.\n */\n intervalMs?: number;\n /**\n * The number of subscribers that may share a channel before a new channel must be created.\n *\n * It is important that you set this to the maximum number of subscriptions that your RPC\n * provider recommends making over a single connection; the default is set deliberately low, so\n * as to comply with the restrictive limits of the public mainnet RPC node.\n *\n * @defaultValue 100\n */\n maxSubscriptionsPerChannel?: number;\n /** The number of channels to create before reusing a channel for a new subscription. */\n minChannels?: number;\n /**\n * The number of bytes of data to admit into the\n * [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) buffer before\n * buffering data on the client.\n */\n sendBufferHighWatermark?: number;\n /** The URL of the web socket server. Must use the `ws` or `wss` protocols. */\n url: TClusterUrl;\n}>;\n\n/**\n * Similar to {@link createDefaultRpcSubscriptionsChannelCreator} with some Solana-specific\n * defaults.\n *\n * For instance, it safely handles `BigInt` values in JSON messages since Solana RPC servers accept\n * and return integers larger than [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER).\n */\nexport function createDefaultSolanaRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization,\n });\n}\n\n/**\n * Creates a function that returns new subscription channels when called.\n */\nexport function createDefaultRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithJSONSerialization,\n });\n}\n\nfunction createDefaultRpcSubscriptionsChannelCreatorImpl(\n config: DefaultRpcSubscriptionsChannelConfig & {\n jsonSerializer: (channel: RpcSubscriptionsChannel) => RpcSubscriptionsChannel;\n },\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n if (/^wss?:/i.test(config.url) === false) {\n const protocolMatch = config.url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? \"Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or \" +\n `'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`,\n );\n }\n const { intervalMs, ...rest } = config;\n const createDefaultRpcSubscriptionsChannel = (({ abortSignal }) => {\n return createWebSocketChannel({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n signal: abortSignal,\n })\n .then(config.jsonSerializer)\n .then(channel =>\n getRpcSubscriptionsChannelWithAutoping({\n abortSignal,\n channel,\n intervalMs: intervalMs ?? 5_000,\n }),\n );\n }) as RpcSubscriptionsChannelCreatorFromClusterUrl;\n return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {\n maxSubscriptionsPerChannel:\n config.maxSubscriptionsPerChannel ??\n /**\n * A note about this default. The idea here is that, because some RPC providers impose\n * an upper limit on the number of subscriptions you can make per channel, we must\n * choose a number low enough to avoid hitting that limit. Without knowing what provider\n * a given person is using, or what their limit is, we have to choose the lowest of all\n * known limits. As of this writing (October 2024) that is the public mainnet RPC node\n * (api.mainnet-beta.solana.com) at 100 subscriptions.\n */\n 100,\n minChannels: config.minChannels ?? 1,\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport fastStableStringify from '@solana/fast-stable-stringify';\nimport { RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype CacheEntry = {\n readonly abortController: AbortController;\n readonly dataPublisherPromise: Promise;\n numSubscribers: number;\n};\n\n/**\n * Given a {@link RpcSubscriptionsTransport}, will return a new transport that coalesces identical\n * subscriptions into a single subscription request to the server. The determination of whether a\n * subscription is the same as another is based on the `rpcRequest` returned by its\n * {@link RpcSubscriptionsPlan}. The subscription will only be aborted once all subscribers abort,\n * or there is an error.\n */\nexport function getRpcSubscriptionsTransportWithSubscriptionCoalescing(\n transport: TTransport,\n): TTransport {\n const cache = new Map();\n return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {\n const { request, signal } = config;\n const subscriptionConfigurationHash = fastStableStringify([request.methodName, request.params]);\n\n let cachedDataPublisherPromise = cache.get(subscriptionConfigurationHash);\n if (!cachedDataPublisherPromise) {\n const abortController = new AbortController();\n const dataPublisherPromise = transport({\n ...config,\n signal: abortController.signal,\n });\n dataPublisherPromise\n .then(dataPublisher => {\n dataPublisher.on(\n 'error',\n () => {\n cache.delete(subscriptionConfigurationHash);\n abortController.abort();\n },\n { signal: abortController.signal },\n );\n })\n .catch(() => {});\n cache.set(\n subscriptionConfigurationHash,\n (cachedDataPublisherPromise = {\n abortController,\n dataPublisherPromise,\n numSubscribers: 0,\n }),\n );\n }\n cachedDataPublisherPromise.numSubscribers++;\n signal.addEventListener(\n 'abort',\n () => {\n cachedDataPublisherPromise.numSubscribers--;\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n queueMicrotask(() => {\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n cache.delete(subscriptionConfigurationHash);\n cachedDataPublisherPromise.abortController.abort();\n }\n });\n }\n },\n { signal: cachedDataPublisherPromise.abortController.signal },\n );\n return cachedDataPublisherPromise.dataPublisherPromise;\n } as TTransport;\n}\n","import { pipe } from '@solana/functional';\nimport { RpcSubscriptionsChannelCreator, RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport {\n RpcSubscriptionsChannelCreatorDevnet,\n RpcSubscriptionsChannelCreatorFromClusterUrl,\n RpcSubscriptionsChannelCreatorMainnet,\n RpcSubscriptionsChannelCreatorTestnet,\n RpcSubscriptionsTransportDevnet,\n RpcSubscriptionsTransportFromClusterUrl,\n RpcSubscriptionsTransportMainnet,\n RpcSubscriptionsTransportTestnet,\n} from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsTransportWithSubscriptionCoalescing } from './rpc-subscriptions-coalescer';\n\nexport type DefaultRpcSubscriptionsTransportConfig = Readonly<{\n createChannel: RpcSubscriptionsChannelCreatorFromClusterUrl;\n}>;\n\n/**\n * Creates a {@link RpcSubscriptionsTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - Logic that coalesces multiple subscriptions for the same notifications with the same arguments\n * into a single subscription.\n *\n * @param config\n */\nexport function createDefaultRpcSubscriptionsTransport({\n createChannel,\n}: DefaultRpcSubscriptionsTransportConfig) {\n return pipe(\n createRpcSubscriptionsTransportFromChannelCreator(\n createChannel,\n ) as RpcSubscriptionsTransport as RpcSubscriptionsTransportFromClusterUrl,\n transport => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport),\n );\n}\n\nexport function createRpcSubscriptionsTransportFromChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n TInboundMessage,\n TOutboundMessage,\n>(createChannel: TChannelCreator) {\n return (async ({ execute, signal }) => {\n const channel = await createChannel({ abortSignal: signal });\n return await execute({ channel, signal });\n }) as TChannelCreator extends RpcSubscriptionsChannelCreatorDevnet\n ? RpcSubscriptionsTransportDevnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorTestnet\n ? RpcSubscriptionsTransportTestnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorMainnet\n ? RpcSubscriptionsTransportMainnet\n : RpcSubscriptionsTransport;\n}\n","import type { SolanaRpcSubscriptionsApi, SolanaRpcSubscriptionsApiUnstable } from '@solana/rpc-subscriptions-api';\nimport { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\nimport {\n createSubscriptionRpc,\n RpcSubscriptionsApiMethods,\n type RpcSubscriptionsTransport,\n} from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport { DEFAULT_RPC_SUBSCRIPTIONS_CONFIG } from './rpc-default-config';\nimport {\n createDefaultSolanaRpcSubscriptionsChannelCreator,\n DefaultRpcSubscriptionsChannelConfig,\n} from './rpc-subscriptions-channel';\nimport type { RpcSubscriptionsFromTransport } from './rpc-subscriptions-clusters';\nimport { createDefaultRpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\ntype Config = DefaultRpcSubscriptionsChannelConfig;\n\nfunction createSolanaRpcSubscriptionsImpl(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n const transport = createDefaultRpcSubscriptionsTransport({\n createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ ...config, url: clusterUrl }),\n });\n return createSolanaRpcSubscriptionsFromTransport(transport);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(clusterUrl, config);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API,\n * including its unstable methods, given a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(\n clusterUrl,\n config,\n );\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * the supplied {@link RpcSubscriptionsTransport}.\n */\nexport function createSolanaRpcSubscriptionsFromTransport<\n TTransport extends RpcSubscriptionsTransport,\n TApi extends RpcSubscriptionsApiMethods = SolanaRpcSubscriptionsApi,\n>(transport: TTransport) {\n return createSubscriptionRpc({\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_SUBSCRIPTIONS_CONFIG),\n transport,\n }) as RpcSubscriptionsFromTransport;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SolanaError } from '@solana/errors';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Removes all duplicated {@link MessageSigner | MessageSigners} and\n * {@link TransactionSigner | TransactionSigners} from a provided array\n * by comparing their {@link Address | addresses}.\n *\n * @internal\n */\nexport function deduplicateSigners(\n signers: readonly TSigner[],\n): readonly TSigner[] {\n const deduplicated: Record = {};\n signers.forEach(signer => {\n if (!deduplicated[signer.address]) {\n deduplicated[signer.address] = signer;\n } else if (deduplicated[signer.address] !== signer) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, {\n address: signer.address,\n });\n }\n });\n return Object.values(deduplicated);\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionModifyingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that potentially modifies the provided {@link Transaction | Transactions}\n * before signing them.\n *\n * For instance, this enables wallets to inject additional instructions into the\n * transaction before signing them. For each transaction, instead of returning a\n * {@link SignatureDictionary}, its\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} function\n * returns an updated {@link Transaction} with a potentially modified set of instructions and\n * signature dictionary. The returned transaction must be within the transaction size limit,\n * and include a `lifetimeConstraint`.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignTransactions: async (\n * transactions: Transaction[]\n * ): Promise<(Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the provided transactions.\n * - **First signers**. For a given transaction, a modifying signer must always\n * be used before a partial signer as the former will likely modify the\n * transaction and thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided,\n * the second signer may invalidate the signature of the first one. However,\n * modifying signers may decide not to modify a transaction based on the\n * existence of signatures for that transaction.\n *\n * @see {@link isTransactionModifyingSigner}\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport type TransactionModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport function isTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionModifyingSigner {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionModifyingSigner}\n */\nexport function assertIsTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionModifyingSigner {\n if (!isTransactionModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionPartialSigner#signTransactions | signTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionPartialSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link Transaction | Transactions}\n * without modifying their content. It defines a\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * function that returns a {@link SignatureDictionary} for each provided transaction.\n *\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionPartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signTransactions: async (\n * transactions: Transaction[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. It returns a signature dictionary for each provided\n * transaction without modifying them, making it possible for multiple\n * partial signers to sign the same transaction in parallel.\n * - **Flexible order**. The order in which we use these signers for\n * a given transaction doesn’t matter.\n *\n * @see {@link isTransactionPartialSigner}\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport type TransactionPartialSigner = Readonly<{\n address: Address;\n signTransactions(\n transactions: readonly (Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[],\n config?: TransactionPartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionPartialSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionPartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport function isTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionPartialSigner {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionPartialSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionPartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionPartialSigner}\n */\nexport function assertIsTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionPartialSigner {\n if (!isTransactionPartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { Transaction, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionSendingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs one or multiple transactions\n * before sending them immediately to the blockchain.\n *\n * It defines a {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions}\n * function that returns the transaction signature (i.e. its identifier) for each provided\n * {@link Transaction}.\n *\n * This interface is required for PDA wallets and other types of wallets that don't provide an\n * interface for signing transactions without sending them.\n *\n * Note that it is also possible for such signers to modify the provided transactions\n * before signing and sending them. This enables use cases where the modified transactions\n * cannot be shared with the app and thus must be sent directly.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signAndSendTransactions: async (transactions: Transaction[]): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Single signer**. Since this signer also sends the provided transactions,\n * we can only use a single {@link TransactionSendingSigner} for a given set of transactions.\n * - **Last signer**. Trivially, that signer must also be the last one used.\n * - **Potential conflicts**. Since signers may decide to modify the given\n * transactions before sending them, they may invalidate previous signatures.\n * However, signers may decide not to modify a transaction based\n * on the existence of signatures for that transaction.\n * - **Potential confirmation**. Whilst this is not required by this interface,\n * it is also worth noting that most wallets will also wait for the transaction\n * to be confirmed (typically with a `confirmed` commitment)\n * before notifying the app that they are done.\n *\n * @see {@link isTransactionSendingSigner}\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport type TransactionSendingSigner = Readonly<{\n address: Address;\n signAndSendTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionSendingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSendingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport function isTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSendingSigner {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSendingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSendingSigner}\n */\nexport function assertIsTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSendingSigner {\n if (!isTransactionSendingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a signer capable of signing transactions.\n *\n * @see {@link TransactionModifyingSigner} For signers that can modify transactions before signing them.\n * @see {@link TransactionPartialSigner} For signers that can be used in parallel.\n * @see {@link TransactionSendingSigner} For signers that send transactions after signing them.\n * @see {@link isTransactionSigner}\n * @see {@link assertIsTransactionSigner}\n */\nexport type TransactionSigner =\n | TransactionModifyingSigner\n | TransactionPartialSigner\n | TransactionSendingSigner;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSigner}\n */\nexport function isTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSigner {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSigner}\n */\nexport function assertIsTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSigner {\n if (!isTransactionSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionVersion,\n} from '@solana/transaction-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionMessageWithFeePayerSigner } from './fee-payer-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * An extension of the {@link AccountMeta} type that allows us to store {@link TransactionSigner | TransactionSigners} inside it.\n *\n * Note that, because this type represents a signer, it must use one the following two roles:\n * - {@link AccountRole.READONLY_SIGNER}\n * - {@link AccountRole.WRITABLE_SIGNER}\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner} to use within the account meta.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole } from '@solana/instructions';\n * import { generateKeyPairSigner, AccountSignerMeta } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const account: AccountSignerMeta = {\n * address: signer.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer,\n * };\n * ```\n */\nexport interface AccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> extends AccountMeta {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\n/**\n * A union type that supports base account metas as well as {@link AccountSignerMeta | signer account metas}.\n */\ntype AccountMetaWithSigner =\n | AccountLookupMeta\n | AccountMeta\n | AccountSignerMeta;\n\n/**\n * Composable type that allows {@link AccountSignerMeta | AccountSignerMetas} to be used inside the instruction's `accounts` array\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { generateKeyPairSigner, InstructionWithSigners } from '@solana/signers';\n *\n * const [authority, buffer] = await Promise.all([\n * generateKeyPairSigner(),\n * generateKeyPairSigner(),\n * ]);\n * const instruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [\n * // The authority is a signer account.\n * {\n * address: authority.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer: authority,\n * },\n * // The buffer is a writable account.\n * { address: buffer.address, role: AccountRole.WRITABLE },\n * ],\n * };\n * ```\n */\nexport type InstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Pick, 'accounts'>;\n\n/**\n * A {@link BaseTransactionMessage} type extension that accept {@link TransactionSigner | TransactionSigners}.\n *\n * Namely, it allows:\n * - a {@link TransactionSigner} to be used as the fee payer and\n * - {@link InstructionWithSigners} to be used in its instructions.\n *\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, InstructionWithSigners, TransactionMessageWithSigners } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const firstInstruction: Instruction = { ... };\n * const secondInstruction: InstructionWithSigners = { ... };\n * const transactionMessage: BaseTransactionMessage & TransactionMessageWithSigners = {\n * feePayer: signer,\n * instructions: [firstInstruction, secondInstruction],\n * }\n * ```\n */\nexport type TransactionMessageWithSigners<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Partial | TransactionMessageWithFeePayerSigner> &\n Pick<\n BaseTransactionMessage>,\n 'instructions'\n >;\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside the account metas of an {@link InstructionWithSigners | instruction}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n *\n * @example\n * ```ts\n * import { InstructionWithSigners, getSignersFromInstruction } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const instructionWithSigners: InstructionWithSigners = {\n * accounts: [\n * { address: signerA.address, signer: signerA, ... },\n * { address: signerB.address, signer: signerB, ... },\n * { address: signerA.address, signer: signerA, ... },\n * ],\n * };\n *\n * const instructionSigners = getSignersFromInstruction(instructionWithSigners);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromInstruction(\n instruction: InstructionWithSigners,\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : [])),\n );\n}\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside a given {@link TransactionMessageWithSigners | transaction message}.\n *\n * This includes any {@link TransactionSigner | TransactionSigners} stored\n * as the fee payer or in the instructions of the transaction message.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { InstructionWithSigners, TransactionMessageWithSigners, getSignersFromTransactionMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const firstInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerA.address, signer: signerA, ... }],\n * };\n * const secondInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerB.address, signer: signerB, ... }],\n * };\n * const transactionMessage: TransactionMessageWithSigners = {\n * feePayer: signerA,\n * instructions: [firstInstruction, secondInstruction],\n * }\n *\n * const transactionSigners = getSignersFromTransactionMessage(transactionMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromTransactionMessage<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TTransactionMessage extends TransactionMessageWithSigners = TransactionMessageWithSigners<\n TAddress,\n TSigner\n >,\n>(transaction: TTransactionMessage): readonly TSigner[] {\n return deduplicateSigners([\n ...(transaction.feePayer && isTransactionSigner(transaction.feePayer) ? [transaction.feePayer as TSigner] : []),\n ...transaction.instructions.flatMap(getSignersFromInstruction),\n ]);\n}\n","import { Address } from '@solana/addresses';\nimport { Instruction, isSignerRole } from '@solana/instructions';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { AccountSignerMeta, InstructionWithSigners, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of an instruction when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TInstruction - The inferred type of the instruction provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { addSignersToInstruction, TransactionSigner } from '@solana/signers';\n *\n * const instruction: Instruction = {\n * accounts: [\n * { address: '1111' as Address, role: AccountRole.READONLY_SIGNER },\n * { address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER },\n * ],\n * // ...\n * };\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const instructionWithSigners = addSignersToInstruction(\n * [signerA, signerB],\n * instruction\n * );\n *\n * // instructionWithSigners.accounts[0].signer === signerA\n * // instructionWithSigners.accounts[1].signer === signerB\n * ```\n */\nexport function addSignersToInstruction(\n signers: TransactionSigner[],\n instruction: TInstruction | (InstructionWithSigners & TInstruction),\n): InstructionWithSigners & TInstruction {\n if (!instruction.accounts || instruction.accounts.length === 0) {\n return instruction as InstructionWithSigners & TInstruction;\n }\n\n const signerByAddress = new Map(deduplicateSigners(signers).map(signer => [signer.address, signer]));\n return Object.freeze({\n ...instruction,\n accounts: instruction.accounts.map(account => {\n const signer = signerByAddress.get(account.address);\n if (!isSignerRole(account.role) || 'signer' in account || !signer) {\n return account;\n }\n return Object.freeze({ ...account, signer } as AccountSignerMeta);\n }),\n });\n}\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of all instructions inside a transaction message and/or\n * the transaction message fee payer, when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { addSignersToTransactionMessage, TransactionSigner } from '@solana/signers';\n *\n * const instructionA: Instruction = {\n * accounts: [{ address: '1111' as Address, role: AccountRole.READONLY_SIGNER }],\n * // ...\n * };\n * const instructionB: Instruction = {\n * accounts: [{ address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER }],\n * // ...\n * };\n * const transactionMessage: BaseTransactionMessage = {\n * instructions: [instructionA, instructionB],\n * // ...\n * }\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const transactionMessageWithSigners = addSignersToTransactionMessage(\n * [signerA, signerB],\n * transactionMessage\n * );\n *\n * // transactionMessageWithSigners.instructions[0].accounts[0].signer === signerA\n * // transactionMessageWithSigners.instructions[1].accounts[0].signer === signerB\n * ```\n */\nexport function addSignersToTransactionMessage(\n signers: TransactionSigner[],\n transactionMessage: TTransactionMessage | (TransactionMessageWithSigners & TTransactionMessage),\n): TransactionMessageWithSigners & TTransactionMessage {\n const feePayerSigner = hasAddressOnlyFeePayer(transactionMessage)\n ? signers.find(signer => signer.address === transactionMessage.feePayer.address)\n : undefined;\n\n if (!feePayerSigner && transactionMessage.instructions.length === 0) {\n return transactionMessage as TransactionMessageWithSigners & TTransactionMessage;\n }\n\n return Object.freeze({\n ...transactionMessage,\n ...(feePayerSigner ? { feePayer: feePayerSigner } : null),\n instructions: transactionMessage.instructions.map(instruction => addSignersToInstruction(signers, instruction)),\n });\n}\n\nfunction hasAddressOnlyFeePayer(\n message: BaseTransactionMessage & Partial,\n): message is BaseTransactionMessage & { feePayer: { address: Address } } {\n return (\n !!message &&\n 'feePayer' in message &&\n !!message.feePayer &&\n typeof message.feePayer.address === 'string' &&\n !isTransactionSigner(message.feePayer)\n );\n}\n","import { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Alternative to {@link TransactionMessageWithFeePayer} that uses a {@link TransactionSigner} for the fee payer.\n *\n * @typeParam TAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner}.\n *\n * @example\n * ```ts\n * import { TransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, TransactionMessageWithFeePayerSigner } from '@solana/signers';\n *\n * const transactionMessage: TransactionMessage & TransactionMessageWithFeePayerSigner = {\n * feePayer: await generateKeyPairSigner(),\n * instructions: [],\n * version: 0,\n * };\n * ```\n */\nexport interface TransactionMessageWithFeePayerSigner<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> {\n readonly feePayer: TSigner;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Sets the fee payer of a {@link TransactionMessage | transaction message}\n * using a {@link TransactionSigner}.\n *\n * @typeParam TFeePayerAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { pipe } from '@solana/functional';\n * import { generateKeyPairSigner, setTransactionMessageFeePayerSigner } from '@solana/signers';\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const feePayer = await generateKeyPairSigner();\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(signer, message),\n * );\n * ```\n */\nexport function setTransactionMessageFeePayerSigner<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial &\n TransactionMessage,\n>(\n feePayer: TransactionSigner,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayerSigner {\n Object.freeze(feePayer);\n const out = { ...transactionMessage, feePayer };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayerSigner;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessagePartialSigner#signMessages | signMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessagePartialSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link SignableMessage | SignableMessages}\n * without modifying their content.\n *\n * It defines a {@link MessagePartialSigner#signMessages | signMessages} function\n * that returns a {@link SignatureDictionary} for each provided message.\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessagePartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. When multiple signers sign the same message, we can\n * perform this operation in parallel to obtain all their signatures.\n * - **Flexible order**. The order in which we use these signers\n * for a given message doesn’t matter.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessagePartialSigner}\n * @see {@link assertIsMessagePartialSigner}\n */\nexport type MessagePartialSigner = Readonly<{\n address: Address;\n signMessages(\n messages: readonly SignableMessage[],\n config?: MessagePartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessagePartialSigner({ address, signMessages: async () => {} }); // true\n * isMessagePartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessagePartialSigner}\n */\nexport function isMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessagePartialSigner {\n return 'signMessages' in value && typeof value.signMessages === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessagePartialSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessagePartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessagePartialSigner}\n */\nexport function assertIsMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessagePartialSigner {\n if (!isMessagePartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SolanaError } from '@solana/errors';\nimport { createKeyPairFromBytes, createKeyPairFromPrivateKeyBytes, generateKeyPair, signBytes } from '@solana/keys';\nimport { partiallySignTransaction } from '@solana/transactions';\n\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a signer that uses a {@link CryptoKeyPair} to sign messages and transactions.\n *\n * It implements both the {@link MessagePartialSigner} and {@link TransactionPartialSigner}\n * interfaces and keeps track of the {@link CryptoKeyPair} instance used\n * to sign messages and transactions.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = generateKeyPairSigner();\n * signer.address; // Address;\n * signer.keyPair; // CryptoKeyPair;\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * ```\n *\n * @see {@link generateKeyPairSigner}\n * @see {@link createSignerFromKeyPair}\n * @see {@link createKeyPairSignerFromBytes}\n * @see {@link createKeyPairSignerFromPrivateKeyBytes}\n * @see {@link isKeyPairSigner}\n * @see {@link assertIsKeyPairSigner}\n */\nexport type KeyPairSigner = MessagePartialSigner &\n TransactionPartialSigner & { keyPair: CryptoKeyPair };\n\n/**\n * Checks whether the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, isKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * isKeyPairSigner(signer); // true\n * isKeyPairSigner({ address: address('1234..5678') }); // false\n * ```\n */\nexport function isKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is KeyPairSigner {\n return (\n 'keyPair' in value &&\n typeof value.keyPair === 'object' &&\n isMessagePartialSigner(value) &&\n isTransactionPartialSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, assertIsKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * assertIsKeyPairSigner(signer); // void\n * assertIsKeyPairSigner({ address: address('1234..5678') }); // Throws an error.\n * ```\n */\nexport function assertIsKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is KeyPairSigner {\n if (!isKeyPairSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, {\n address: value.address,\n });\n }\n}\n\n/**\n * Creates a {@link KeyPairSigner} from a provided {@link CryptoKeyPair}.\n *\n * The {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * functions of the returned signer will use the private key of the provided\n * key pair to sign messages and transactions.\n *\n * Note that both the {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions} implementations\n * are parallelized, meaning that they will sign all provided messages and transactions in parallel.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { createSignerFromKeyPair, KeyPairSigner } from '@solana/signers';\n *\n * const keyPair: CryptoKeyPair = await generateKeyPair();\n * const signer: KeyPairSigner = await createSignerFromKeyPair(keyPair);\n * ```\n */\nexport async function createSignerFromKeyPair(keyPair: CryptoKeyPair): Promise {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const out: KeyPairSigner = {\n address,\n keyPair,\n signMessages: messages =>\n Promise.all(\n messages.map(async message =>\n Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) }),\n ),\n ),\n signTransactions: transactions =>\n Promise.all(\n transactions.map(async transaction => {\n const signedTransaction = await partiallySignTransaction([keyPair], transaction);\n // we know that the address has signed `signedTransaction` because it comes from the keypair\n return Object.freeze({ [address]: signedTransaction.signatures[address]! });\n }),\n ),\n };\n\n return Object.freeze(out);\n}\n\n/**\n * Generates a signer capable of signing messages and transactions by generating\n * a {@link CryptoKeyPair} and creating a {@link KeyPairSigner} from it.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * ```\n *\n * @see {@link createSignerFromKeyPair}\n */\nexport async function generateKeyPairSigner(): Promise {\n return await createSignerFromKeyPair(await generateKeyPair());\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 64-bytes `Uint8Array` secret key (private key and public key).\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairSignerFromBytes } from '@solana/signers';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a KeyPairSigner from the bytes.\n * const signer = await createKeyPairSignerFromBytes(keypairBytes);\n * ```\n *\n * @see {@link createKeyPairSignerFromPrivateKeyBytes} if you only have the 32-bytes private key instead.\n */\nexport async function createKeyPairSignerFromBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromBytes(bytes, extractable));\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 32-bytes `Uint8Array` private key.\n *\n * @example\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairSignerFromPrivateKeyBytes } from '@solana/signers';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedSigner = await createKeyPairSignerFromPrivateKeyBytes(seed);\n * ```\n *\n * @see {@link createKeyPairSignerFromBytes} if you have the 64-bytes secret key instead (private key and public key).\n */\nexport async function createKeyPairSignerFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromPrivateKeyBytes(bytes, extractable));\n}\n","import { Address, isAddress } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessageModifyingSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that _potentially_ modifies the content\n * of the provided {@link SignableMessage | SignableMessages} before signing them.\n *\n * For instance, this enables wallets to prefix or suffix nonces to the messages they sign.\n * For each message, instead of returning a {@link SignatureDictionary}, the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} function\n * returns an updated {@link SignableMessage} with a potentially modified content and signature dictionary.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessageModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the content of the message.\n * - **First signers**. For a given message, a modifying signer must always be used\n * before a partial signer as the former will likely modify the message and\n * thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided, the second\n * signer may invalidate the signature of the first one. However, modifying signers\n * may decide not to modify a message based on the existence of signatures for that message.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessageModifyingSigner}\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport type MessageModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignMessages(\n messages: readonly SignableMessage[],\n config?: MessageModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport function isMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageModifyingSigner {\n return (\n isAddress(value.address) &&\n 'modifyAndSignMessages' in value &&\n typeof value.modifyAndSignMessages === 'function'\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageModifyingSigner}\n */\nexport function assertIsMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageModifyingSigner {\n if (!isMessageModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isMessageModifyingSigner, MessageModifyingSigner } from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\n\n/**\n * Defines a signer capable of signing messages.\n *\n * @see {@link MessageModifyingSigner} For signers that can modify messages before signing them.\n * @see {@link MessagePartialSigner} For signers that can be used in parallel.\n * @see {@link isMessageSigner}\n * @see {@link assertIsMessageSigner}\n */\nexport type MessageSigner =\n | MessageModifyingSigner\n | MessagePartialSigner;\n\n/**\n * Checks whether the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageSigner({ address, signMessages: async () => {} }); // true\n * isMessageSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageSigner}\n */\nexport function isMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageSigner {\n return isMessagePartialSigner(value) || isMessageModifyingSigner(value);\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessageSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageSigner}\n */\nexport function assertIsMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageSigner {\n if (!isMessageSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { MessagePartialSigner } from './message-partial-signer';\nimport { TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a Noop (No-Operation) signer that pretends to partially sign messages and transactions.\n *\n * For a given {@link Address}, a Noop Signer can be created to offer an implementation of both\n * the {@link MessagePartialSigner} and {@link TransactionPartialSigner} interfaces such that\n * they do not sign anything. Namely, signing a transaction or a message with a `NoopSigner`\n * will return an empty `SignatureDictionary`.\n *\n * @typeParam TAddress - Supply a string literal to define a Noop signer having a particular address.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * // ^ Both messageSignatures and transactionSignatures are empty.\n * ```\n *\n * @remarks\n * This signer may be useful:\n *\n * - For testing purposes.\n * - For indicating that a given account is a signer and taking the responsibility to provide\n * the signature for that account ourselves. For instance, if we need to send the transaction\n * to a server that will sign it and send it for us.\n *\n * @see {@link createNoopSigner}\n */\nexport type NoopSigner = MessagePartialSigner &\n TransactionPartialSigner;\n\n/**\n * Creates a {@link NoopSigner} from the provided {@link Address}.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * ```\n */\nexport function createNoopSigner(address: Address): NoopSigner {\n const out: NoopSigner = {\n address,\n signMessages: messages => Promise.resolve(messages.map(() => Object.freeze({}))),\n signTransactions: transactions => Promise.resolve(transactions.map(() => Object.freeze({}))),\n };\n\n return Object.freeze(out);\n}\n","import { OffchainMessageWithRequiredSignatories } from '@solana/offchain-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isMessageSigner, MessageSigner } from './message-signer';\n\n/**\n * Represents a {@link Signer} that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatorySigner = MessageSigner;\n\n/**\n * Extracts and deduplicates all {@link MessageSigner | MessageSigners} stored inside a given\n * {@link OffchainMessageWithSigners | offchain message}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link MessageSigner | MessageSigners}.\n * @typeParam TOffchainMessage - The inferred type of the offchain message provided.\n *\n * @example\n * ```ts\n * import { OffchainMessageWithSigners, getSignersFromOffchainMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signMessages: async () => {} };\n * const signerB = { address: address('2222..2222'), modifyAndSignMessages: async () => {} };\n * const OffchainMessage: OffchainMessageWithSigners = {\n * /* ... *\\/\n * requiredSignatories: [signerA, signerB],\n * };\n *\n * const messageSigners = getSignersFromOffchainMessage(offchainMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromOffchainMessage({\n requiredSignatories,\n}: OffchainMessageWithRequiredSignatories): readonly MessageSigner[] {\n const messageSigners = requiredSignatories.filter(isMessageSigner);\n return deduplicateSigners(messageSigners);\n}\n","import {\n assertIsFullySignedOffchainMessageEnvelope,\n compileOffchainMessageEnvelope,\n FullySignedOffchainMessageEnvelope,\n OffchainMessage,\n OffchainMessageEnvelope,\n OffchainMessageSignatory,\n OffchainMessageWithRequiredSignatories,\n} from '@solana/offchain-messages';\n\nimport {\n isMessageModifyingSigner,\n MessageModifyingSigner,\n MessageModifyingSignerConfig,\n} from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner, MessagePartialSignerConfig } from './message-partial-signer';\nimport { MessageSigner } from './message-signer';\nimport { getSignersFromOffchainMessage, OffchainMessageSignatorySigner } from './offchain-message-signer';\nimport { SignableMessage } from './signable-message';\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope.\n *\n * It first uses all {@link MessageModifyingSigner | MessageModifyingSigners} sequentially before\n * using all {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link MessageModifyingSigner} if no other signer implements that interface. Otherwise, it will\n * be used as a {@link MessagePartialSigner}.\n *\n * @example\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @see {@link signOffchainMessageWithSigners}\n */\nexport async function partiallySignOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeMessageSigners(\n getSignersFromOffchainMessage(offchainMessage),\n );\n return await signModifyingAndPartialMessageSigners(offchainMessage, modifyingSigners, partialSigners, config);\n}\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope before asserting that all signatures required\n * by the message are present.\n *\n * This function delegates to the {@link partiallySignOffchainMessageWithSigners} function\n * in order to extract signers from the offchain message and sign it.\n *\n * @example\n * ```ts\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage);\n *\n * // With additional config.\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the offchain message is fully signed.\n * mySignedOffchainMessageEnvelope satisfies FullySignedOffchainMessageEnvelope;\n * ```\n *\n * @see {@link partiallySignOffchainMessageWithSigners}\n */\nexport async function signOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, config);\n assertIsFullySignedOffchainMessageEnvelope(signedOffchainMessageEnvelope);\n return signedOffchainMessageEnvelope;\n}\n\n/**\n * Identifies each provided {@link MessageSigner} and categorizes them into their respective types.\n * When a signer implements multiple interfaces, it will try to used to most powerful interface but\n * fall back to the least powerful interface when necessary.\n *\n * For instance, if a signer implements {@link MessageSigner} and {@link MessageModifyingSigner},\n * it will be categorized as a `MessageModifyingSigner`.\n */\nfunction categorizeMessageSigners(signers: readonly MessageSigner[]): Readonly<{\n modifyingSigners: readonly MessageModifyingSigner[];\n partialSigners: readonly MessagePartialSigner[];\n}> {\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyMessageModifyingSigners(signers);\n\n // Use any remaining signers as partial signers.\n const partialSigners = signers\n .filter(isMessagePartialSigner)\n .filter(signer => !(modifyingSigners as typeof signers).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners });\n}\n\n/** Identifies the best signers to use as MessageModifyingSigners, if any */\nfunction identifyMessageModifyingSigners(\n signers: readonly (MessageModifyingSigner | MessagePartialSigner)[],\n): readonly MessageModifyingSigner[] {\n // Ensure there are any MessageModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isMessageModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isMessagePartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs an offchain message using the provided\n * {@link MessageModifyingSigner | MessageModifyingSigners} sequentially followed by the\n * {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n */\nasync function signModifyingAndPartialMessageSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n modifyingSigners: readonly MessageModifyingSigner[] = [],\n partialSigners: readonly MessagePartialSigner[] = [],\n config?: MessageModifyingSignerConfig,\n): Promise {\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n const offchainMessageEnvelope: SignableMessage = compileOffchainMessageEnvelope(offchainMessage);\n\n // Handle modifying signers sequentially.\n const modifiedOffchainMessage = await modifyingSigners.reduce(async (offchainMessageEnvelope, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [message] = await modifyingSigner.modifyAndSignMessages([await offchainMessageEnvelope], config);\n return Object.freeze(message);\n }, Promise.resolve(offchainMessageEnvelope));\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signMessages([modifiedOffchainMessage], config);\n return signatures;\n }),\n );\n\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n return Object.freeze({\n ...modifiedOffchainMessage,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedOffchainMessage.signatures ?? {}),\n ),\n } as OffchainMessageEnvelope);\n}\n","import {\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { isTransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a transaction message with exactly one {@link TransactionSendingSigner}.\n *\n * This type is used to narrow the type of transaction messages that have been\n * checked to have exactly one sending signer.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithSingleSendingSigner } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithSingleSendingSigner;\n * ```\n *\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport type TransactionMessageWithSingleSendingSigner = Brand<\n TransactionMessageWithSigners,\n 'TransactionMessageWithSingleSendingSigner'\n>;\n\n/**\n * Checks whether the provided transaction has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using {@link signAndSendTransactionMessageWithSigners} to provide\n * a fallback strategy in case the transaction message cannot be send using this function.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * isTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners,\n * signTransactionMessageWithSigners,\n * } from '@solana/signers';\n * import { getBase64EncodedWireTransaction } from '@solana/transactions';\n *\n * let transactionSignature: SignatureBytes;\n * if (isTransactionMessageWithSingleSendingSigner(transactionMessage)) {\n * transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * } else {\n * const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);\n * const encodedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * transactionSignature = await rpc.sendTransaction(encodedTransaction).send();\n * }\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport function isTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transaction: TTransactionMessage): transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n try {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Asserts that the provided transaction message has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using the {@link signAndSendTransactionMessageWithSigners} function\n * to ensure it will be able to select the correct signer to send the transaction.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * assertIsTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners\n * } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n */\nexport function assertIsTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transaction: TTransactionMessage,\n): asserts transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n const signers = getSignersFromTransactionMessage(transaction);\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n\n if (sendingSigners.length === 0) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n // When identifying if there are multiple sending signers, we only need to check for\n // sending signers that do not implement other transaction signer interfaces as\n // they will be used as these other signer interfaces in case of a conflict.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer),\n );\n\n if (sendingOnlySigners.length > 1) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS);\n }\n}\n","import { SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport {\n assertIsFullySignedTransaction,\n compileTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithinSizeLimit,\n TransactionWithLifetime,\n} from '@solana/transactions';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport {\n isTransactionModifyingSigner,\n TransactionModifyingSigner,\n TransactionModifyingSignerConfig,\n} from './transaction-modifying-signer';\nimport {\n isTransactionPartialSigner,\n TransactionPartialSigner,\n TransactionPartialSignerConfig,\n} from './transaction-partial-signer';\nimport {\n isTransactionSendingSigner,\n TransactionSendingSigner,\n TransactionSendingSignerConfig,\n} from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { assertIsTransactionMessageWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction.\n *\n * It first uses all {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before\n * using all {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link TransactionModifyingSigner} if no other signer implements that interface.\n * Otherwise, it will be used as a {@link TransactionPartialSigner}.\n *\n * @example\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Finally, note that this function ignores {@link TransactionSendingSigner | TransactionSendingSigners}\n * as it does not send the transaction. Check out the {@link signAndSendTransactionMessageWithSigners}\n * function for more details on how to use sending signers.\n *\n * @see {@link signTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function partiallySignTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transactionMessage).filter(isTransactionSigner)),\n { identifySendingSigner: false },\n );\n\n return await signModifyingAndPartialTransactionSigners(\n transactionMessage,\n modifyingSigners,\n partialSigners,\n config,\n );\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction before asserting\n * that all signatures required by the transaction are present.\n *\n * This function delegates to the {@link partiallySignTransactionMessageWithSigners} function\n * in order to extract signers from the transaction message and sign the transaction.\n *\n * @example\n * ```ts\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage);\n *\n * // With additional config.\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the transaction is fully signed.\n * mySignedTransaction satisfies FullySignedTransaction;\n * ```\n *\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function signTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, config);\n assertIsFullySignedTransaction(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to sign it before sending it immediately to the blockchain.\n *\n * It returns the signature of the sent transaction (i.e. its identifier) as bytes.\n *\n * @example\n * ```ts\n * import { signAndSendTransactionMessageWithSigners } from '@solana/signers';\n *\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n *\n * // With additional config.\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Similarly to the {@link partiallySignTransactionMessageWithSigners} function, it first uses all\n * {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before using all\n * {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n * It then sends the transaction using the {@link TransactionSendingSigner} it identified.\n *\n * Composite transaction signers are treated such that at least one sending signer is used if any.\n * When a {@link TransactionSigner} implements more than one interface, we use it as a:\n *\n * - {@link TransactionSendingSigner}, if no other {@link TransactionSendingSigner} exists.\n * - {@link TransactionModifyingSigner}, if no other {@link TransactionModifyingSigner} exists.\n * - {@link TransactionPartialSigner}, otherwise.\n *\n * The provided transaction must contain exactly one {@link TransactionSendingSigner} inside its account metas.\n * If more than one composite signers implement the {@link TransactionSendingSigner} interface,\n * one of them will be selected as the sending signer. Otherwise, if multiple\n * {@link TransactionSendingSigner | TransactionSendingSigners} must be selected, the function will throw an error.\n *\n * If you'd like to assert that a transaction makes use of exactly one {@link TransactionSendingSigner}\n * _before_ calling this function, you may use the {@link assertIsTransactionMessageWithSingleSendingSigner} function.\n *\n * Alternatively, you may use the {@link isTransactionMessageWithSingleSendingSigner} function to provide a\n * fallback in case the transaction does not contain any sending signer.\n *\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signTransactionMessageWithSigners}\n *\n */\nexport async function signAndSendTransactionMessageWithSigners(\n transaction: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionSendingSignerConfig,\n): Promise {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n\n const abortSignal = config?.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transaction).filter(isTransactionSigner)),\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n config,\n );\n\n if (!sendingSigner) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], config);\n abortSignal?.throwIfAborted();\n\n return signature;\n}\n\n/**\n * Identifies each provided TransactionSigner and categorizes them into their respective types.\n * When a signer implements multiple interface, it will try to used to most powerful interface\n * but fallback to the least powerful interface when necessary.\n * For instance, if a signer implements TransactionSendingSigner and TransactionModifyingSigner,\n * it will be categorized as a TransactionSendingSigner if and only if no other signers implement\n * the TransactionSendingSigner interface.\n */\nfunction categorizeTransactionSigners(\n signers: readonly TransactionSigner[],\n config: { identifySendingSigner?: boolean } = {},\n): Readonly<{\n modifyingSigners: readonly TransactionModifyingSigner[];\n partialSigners: readonly TransactionPartialSigner[];\n sendingSigner: TransactionSendingSigner | null;\n}> {\n // Identify the unique sending signer that should be used.\n const identifySendingSigner = config.identifySendingSigner ?? true;\n const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;\n\n // Now, focus on the other signers.\n // I.e. the modifying or partial signers that are not the identified sending signer.\n // Note that any other sending only signers will be discarded.\n const otherSigners = signers.filter(\n (signer): signer is TransactionModifyingSigner | TransactionPartialSigner =>\n signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer)),\n );\n\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);\n\n // Use any remaining signers as partial signers.\n const partialSigners = otherSigners\n .filter(isTransactionPartialSigner)\n .filter(signer => !(modifyingSigners as typeof otherSigners).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });\n}\n\n/** Identifies the best signer to use as a TransactionSendingSigner, if any */\nfunction identifyTransactionSendingSigner(signers: readonly TransactionSigner[]): TransactionSendingSigner | null {\n // Ensure there are any TransactionSendingSigners in the first place.\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n if (sendingSigners.length === 0) return null;\n\n // Prefer sending signers that do not offer other interfaces.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer),\n );\n if (sendingOnlySigners.length > 0) {\n return sendingOnlySigners[0];\n }\n\n // Otherwise, choose any sending signer.\n return sendingSigners[0];\n}\n\n/** Identifies the best signers to use as TransactionModifyingSigners, if any */\nfunction identifyTransactionModifyingSigners(\n signers: readonly (TransactionModifyingSigner | TransactionPartialSigner)[],\n): readonly TransactionModifyingSigner[] {\n // Ensure there are any TransactionModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isTransactionModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isTransactionPartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs a transaction using the provided TransactionModifyingSigners\n * sequentially followed by the TransactionPartialSigners in parallel.\n */\nasync function signModifyingAndPartialTransactionSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n config?: TransactionModifyingSignerConfig,\n): Promise {\n // serialize the transaction\n const transaction = compileTransaction(transactionMessage);\n\n // Handle modifying signers sequentially.\n const modifiedTransaction = (await modifyingSigners.reduce(\n async (transaction, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], config);\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise>,\n )) as Transaction & TransactionWithinSizeLimit & TransactionWithLifetime;\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], config);\n return signatures;\n }),\n );\n\n return Object.freeze({\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {}),\n ),\n });\n}\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import { TextEncoder } from '@solana/text-encoding-impl';\n\nimport { SignatureDictionary } from './types';\n\n/**\n * Defines a message that needs signing and its current set of signatures if any.\n *\n * This interface allows {@link MessageModifyingSigner | MessageModifyingSigners}\n * to decide on whether or not they should modify the provided message depending\n * on whether or not signatures already exist for such message.\n *\n * It also helps create a more consistent API by providing a structure analogous\n * to transactions which also keep track of their {@link SignatureDictionary}.\n *\n * @example\n * ```ts\n * import { createSignableMessage } from '@solana/signers';\n *\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * message.content; // The content of the message as bytes.\n * message.signatures; // The current set of signatures for this message.\n * ```\n *\n * @see {@link createSignableMessage}\n */\nexport type SignableMessage = Readonly<{\n content: Uint8Array;\n signatures: SignatureDictionary;\n}>;\n\n/**\n * Creates a {@link SignableMessage} from a `Uint8Array` or a UTF-8 string.\n *\n * It optionally accepts a signature dictionary if the message already contains signatures.\n *\n * @example\n * ```ts\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * const messageFromText = createSignableMessage('Hello world!');\n * const messageWithSignatures = createSignableMessage('Hello world!', {\n * [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes,\n * });\n * ```\n */\nexport function createSignableMessage(\n content: Uint8Array | string,\n signatures: SignatureDictionary = {},\n): SignableMessage {\n return Object.freeze({\n content: typeof content === 'string' ? new TextEncoder().encode(content) : content,\n signatures: Object.freeze({ ...signatures }),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { GetEpochInfoApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport type { Commitment } from '@solana/rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the block height as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /** The block height after which to reject the promise */\n lastValidBlockHeight: bigint;\n}) => Promise;\n\ntype CreateBlockHeightExceedencePromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that throws when the network progresses past the block height after which the\n * supplied blockhash is considered expired for use as a transaction lifetime specifier.\n *\n * When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the\n * network until that blockhash expires. All blockhashes have a block height after which they are\n * considered to have expired.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getBlockHeightExceedencePromise({ lastValidBlockHeight });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error(\n * `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` +\n * `It is now ${e.context.currentBlockHeight}`,\n * );\n * // Re-sign and retry the transaction.\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'devnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'testnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'mainnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({\n abortSignal: callerAbortSignal,\n commitment,\n lastValidBlockHeight,\n }): Promise {\n callerAbortSignal.throwIfAborted();\n const abortController = new AbortController();\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {\n const { absoluteSlot, blockHeight } = await rpc\n .getEpochInfo({ commitment })\n .send({ abortSignal: abortController.signal });\n return {\n blockHeight,\n differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight,\n };\n }\n try {\n const [slotNotifications, { blockHeight: initialBlockHeight, differenceBetweenSlotHeightAndBlockHeight }] =\n await Promise.all([\n rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),\n getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight(),\n ]);\n callerAbortSignal.throwIfAborted();\n let currentBlockHeight = initialBlockHeight;\n if (currentBlockHeight <= lastValidBlockHeight) {\n let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;\n for await (const slotNotification of slotNotifications) {\n const { slot } = slotNotification;\n if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {\n // Before making a final decision, recheck the actual block height.\n const {\n blockHeight: recheckedBlockHeight,\n differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight,\n } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();\n currentBlockHeight = recheckedBlockHeight;\n if (currentBlockHeight > lastValidBlockHeight) {\n // Verified; the block height has been exceeded.\n break;\n } else {\n // The block height has not been exceeded, which implies that the\n // difference between the slot height and the block height has grown\n // (ie. some blocks have been skipped since we started). Recalibrate the\n // difference and keep waiting.\n lastKnownDifferenceBetweenSlotHeightAndBlockHeight =\n currentDifferenceBetweenSlotHeightAndBlockHeight;\n }\n }\n }\n }\n callerAbortSignal.throwIfAborted();\n throw new SolanaError(SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, {\n currentBlockHeight,\n lastValidBlockHeight,\n });\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport type { GetAccountInfoApi, Rpc } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions } from '@solana/rpc-subscriptions';\nimport type { Base64EncodedDataResponse, Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transaction-messages';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the nonce account details as of the highest slot that has reached this level of\n * commitment.\n */\n commitment: Commitment;\n /**\n * The value of the nonce that we would expect to see in the nonce account in order for any\n * transaction with that nonce-based lifetime to be considered valid.\n */\n currentNonceValue: Nonce;\n /** The address of the account in which the currently-valid nonce value is stored */\n nonceAccountAddress: Address;\n}) => Promise;\n\ntype CreateNonceInvalidationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\n/**\n * Creates a promise that throws when the value stored in a nonce account is not the expected one.\n *\n * When a transaction's lifetime is tied to the value stored in a nonce account, that transaction\n * can be landed on the network until the nonce is advanced to a new value.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getNonceInvalidationPromise({\n * currentNonceValue,\n * nonceAccountAddress,\n * });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) {\n * console.error(`The nonce has advanced to ${e.context.actualNonceValue}`);\n * // Re-sign and retry the transaction.\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(`No nonce account was found at ${nonceAccountAddress}`);\n * }\n * throw e;\n * }\n * ```\n */\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'devnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'testnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'mainnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue: expectedNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes) as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new SolanaError(SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, {\n nonceAccountAddress,\n });\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { getSolanaErrorFromTransactionError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { GetSignatureStatusesApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { type Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * The level of commitment the transaction must have achieved in order for the promise to\n * resolve.\n */\n commitment: Commitment;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}) => Promise;\n\ntype CreateRecentSignatureConfirmationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that resolves when a recently-landed transaction achieves the target\n * confirmation commitment, and throws when the transaction fails with an error.\n *\n * The status of recently-landed transactions is available in the network's status cache. This\n * confirmation strategy will only yield a result if the signature is still in the status cache. To\n * fetch the status of transactions older than those available in the status cache, use the\n * {@link GetSignatureStatusesApi.getSignatureStatuses} method setting the\n * `searchTransactionHistory` configuration param to `true`.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getRecentSignatureConfirmationPromise({\n * commitment,\n * signature,\n * });\n * console.log(`The transaction with signature \\`${signature}\\` has achieved a commitment level of \\`${commitment}\\``);\n * } catch (e) {\n * console.error(`The transaction with signature \\`${signature}\\` failed`, e.cause);\n * throw e;\n * }\n * ```\n */\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'devnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'testnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'mainnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n throw getSolanaErrorFromTransactionError(signatureStatusNotification.value.err);\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (signatureStatus?.err) {\n throw getSolanaErrorFromTransactionError(signatureStatus.err);\n } else if (\n signatureStatus?.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n /**\n * The timeout promise will throw after 30 seconds when the commitment is `processed`, and 60\n * seconds otherwise.\n */\n commitment: Commitment;\n}>;\n\n/**\n * When no other heuristic exists to infer that a transaction has expired, you can use this promise\n * factory with a commitment level. It throws after 30 seconds when the commitment is `processed`,\n * and 60 seconds otherwise. You would typically race this with another confirmation strategy.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { safeRace } from '@solana/promises';\n * import { getTimeoutPromise } from '@solana/transaction-confirmation';\n *\n * try {\n * await safeRace([getCustomTransactionConfirmationPromise(/* ... *\\/), getTimeoutPromise({ commitment })]);\n * } catch (e) {\n * if (e instanceof DOMException && e.name === 'TimeoutError') {\n * console.log('Could not confirm transaction after a timeout');\n * }\n * throw e;\n * }\n * ```\n */\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType;\n}\n\ntype WithNonNullableAbortSignal = Omit & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal) => readonly Promise[],\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await safeRace([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport {\n getSignatureFromTransaction,\n Transaction,\n TransactionWithBlockhashLifetime,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './confirmation-strategy-racer';\nimport { getTimeoutPromise } from './confirmation-strategy-timeout';\n\nexport type TransactionWithLastValidBlockHeight = Omit & {\n lifetimeConstraint: Omit;\n};\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom nonce\n * transaction confirmation strategy.\n *\n * @example\n * ```ts\n * import { waitForDurableNonceTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForDurableNonceTransactionConfirmation({\n * getNonceInvalidationPromise({ abortSignal, commitment, currentNonceValue, nonceAccountAddress }) {\n * // Return a promise that rejects when a nonce becomes invalid.\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.lifetimeConstraint.nonceAccountAddress,\n }),\n ];\n },\n );\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom confirmation\n * strategy for recently-landed transactions.\n *\n * @example\n * ```ts\n * import { waitForRecentTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForRecentTransactionConfirmation({\n * getBlockHeightExceedencePromise({ abortSignal, commitment, lastValidBlockHeight }) {\n * // Return a promise that rejects when the blockhash's block height has been exceeded\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({\n abortSignal,\n commitment,\n getBlockHeightExceedencePromise,\n transaction,\n }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n commitment,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n },\n );\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n },\n );\n}\n","import type { Address } from '@solana/addresses';\nimport type { Signature } from '@solana/keys';\nimport type { RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { Commitment, Lamports } from '@solana/rpc-types';\nimport { waitForRecentTransactionConfirmationUntilTimeout } from '@solana/transaction-confirmation';\n\ntype RequestAndConfirmAirdropConfig = Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: (\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) => Promise;\n lamports: Lamports;\n recipientAddress: Address;\n rpc: Rpc;\n}>;\n\nexport async function requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: RequestAndConfirmAirdropConfig): Promise {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import type { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createRecentSignatureConfirmationPromiseFactory,\n getTimeoutPromise,\n waitForRecentTransactionConfirmationUntilTimeout,\n} from '@solana/transaction-confirmation';\n\nimport { requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT } from './airdrop-internal';\n\ntype AirdropFunction = (\n config: Omit<\n Parameters[0],\n 'confirmSignatureOnlyTransaction' | 'rpc'\n >,\n) => Promise;\n\ntype AirdropFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link RequestAirdropApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to airdrop a certain amount of {@link Lamports} to a Solana\n * address.\n *\n * > [!NOTE] This only works on test clusters.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit';\n *\n * const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899'));\n * const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900'));\n *\n * const airdrop = airdropFactory({ rpc, rpcSubscriptions });\n *\n * await airdrop({\n * commitment: 'confirmed',\n * recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'),\n * lamports: lamports(10_000_000n),\n * });\n * ```\n */\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'devnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'mainnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'testnet'>): AirdropFunction;\nexport function airdropFactory({\n rpc,\n rpcSubscriptions,\n}: AirdropFactoryConfig): AirdropFunction {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmSignatureOnlyTransaction(\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n }\n return async function airdrop(config) {\n return await requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n","import {\n assertAccountsDecoded,\n assertAccountsExist,\n type FetchAccountsConfig,\n fetchJsonParsedAccounts,\n} from '@solana/accounts';\nimport type { Address } from '@solana/addresses';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport { type AddressesByLookupTableAddress } from '@solana/transaction-messages';\n\ntype FetchedAddressLookup = {\n addresses: Address[];\n};\n\n/**\n * Given a list of addresses belonging to address lookup tables, returns a map of lookup table\n * addresses to an ordered array of the addresses they contain.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function fetchAddressesForLookupTables(\n lookupTableAddresses: Address[],\n rpc: Rpc,\n config?: FetchAccountsConfig,\n): Promise {\n if (lookupTableAddresses.length === 0) {\n return {};\n }\n\n const fetchedLookupTables = await fetchJsonParsedAccounts(\n rpc,\n lookupTableAddresses,\n config,\n );\n\n assertAccountsDecoded(fetchedLookupTables);\n assertAccountsExist(fetchedLookupTables);\n\n return fetchedLookupTables.reduce((acc, lookup) => {\n return {\n ...acc,\n [lookup.address]: lookup.data.addresses,\n };\n }, {});\n}\n","import { type FetchAccountsConfig } from '@solana/accounts';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n decompileTransactionMessage,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithLifetime,\n} from '@solana/transaction-messages';\n\nimport { fetchAddressesForLookupTables } from './fetch-lookup-tables';\n\ntype DecompileTransactionMessageFetchingLookupTablesConfig = FetchAccountsConfig & {\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Returns a {@link TransactionMessage} from a {@link CompiledTransactionMessage}. If any of the\n * accounts in the compiled message require an address lookup table to find their address, this\n * function will use the supplied RPC instance to fetch the contents of the address lookup table\n * from the network.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function decompileTransactionMessageFetchingLookupTables(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n rpc: Rpc,\n config?: DecompileTransactionMessageFetchingLookupTablesConfig,\n): Promise {\n const lookupTables =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? compiledTransactionMessage.addressTableLookups\n : [];\n const lookupTableAddresses = lookupTables.map(l => l.lookupTableAddress);\n\n const { lastValidBlockHeight, ...fetchAccountsConfig } = config ?? {};\n const addressesByLookupTableAddress =\n lookupTableAddresses.length > 0\n ? await fetchAddressesForLookupTables(lookupTableAddresses, rpc, fetchAccountsConfig)\n : {};\n\n return decompileTransactionMessage(compiledTransactionMessage, {\n addressesByLookupTableAddress,\n lastValidBlockHeight,\n });\n}\n","import type { Lamports } from '@solana/rpc-types';\n\n/**\n * Calculates the minimum {@link Lamports | lamports} required to make an account rent exempt for a\n * given data size, without performing an RPC call.\n *\n * Values are sourced from the on-chain rent parameters in the Solana runtime:\n * https://github.com/anza-xyz/solana-sdk/blob/c07f692e41d757057c8700211a9300cdcd6d33b1/rent/src/lib.rs#L93-L97\n *\n * Note that this logic may change, or be incorrect depending on the cluster you are connected to.\n * You can always use the RPC method `getMinimumBalanceForRentExemption` to get the current value.\n *\n * @param space The number of bytes of account data.\n */\nexport function getMinimumBalanceForRentExemption(space: bigint): Lamports {\n const RENT = {\n ACCOUNT_STORAGE_OVERHEAD: 128n,\n DEFAULT_EXEMPTION_THRESHOLD: 2n,\n DEFAULT_LAMPORTS_PER_BYTE_YEAR: 3_480n,\n } as const;\n const requiredLamports =\n (RENT.ACCOUNT_STORAGE_OVERHEAD + space) *\n RENT.DEFAULT_LAMPORTS_PER_BYTE_YEAR *\n RENT.DEFAULT_EXEMPTION_THRESHOLD;\n return requiredLamports as Lamports;\n}\n","import type { Signature } from '@solana/keys';\nimport type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n TransactionWithLastValidBlockHeight,\n waitForDurableNonceTransactionConfirmation,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getBase64EncodedWireTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: (\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: (\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight;\n}\n\ninterface SendTransactionBaseConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc;\n transaction: SendableTransaction & Transaction;\n}\n\ntype SendTransactionConfigWithoutEncoding = Omit<\n NonNullable[1]>,\n 'encoding'\n>;\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding,\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nexport async function sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionBaseConfig): Promise {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport async function sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { getSolanaErrorFromTransactionError, isSolanaError, SOLANA_ERROR__INVALID_NONCE } from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport type { GetAccountInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { commitmentComparator } from '@solana/rpc-types';\nimport {\n createNonceInvalidationPromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n waitForDurableNonceTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getSignatureFromTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmDurableNonceTransactionFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime,\n config: Omit<\n Parameters[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmDurableNonceTransactionFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link AccountNotificationsApi} and the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a nonce-based transaction to the network and to wait\n * until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * isSolanaError,\n * sendAndConfirmDurableNonceTransactionFactory,\n * SOLANA_ERROR__INVALID_NONCE,\n * SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n * } from '@solana/kit';\n *\n * const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(\n * 'The lifetime specified by this transaction refers to a nonce account ' +\n * `\\`${e.context.nonceAccountAddress}\\` that does not exist`,\n * );\n * } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n * console.error('This transaction depends on a nonce that is no longer valid');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'devnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'testnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'mainnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig): SendAndConfirmDurableNonceTransactionFunction {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions } as Parameters<\n typeof createNonceInvalidationPromiseFactory\n >[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n\n /**\n * Creates a wrapped version of getNonceInvalidationPromise that handles the race condition\n * where the nonce account update notification arrives before the signature confirmation.\n *\n * When the nonce changes, we check if our transaction actually landed on-chain.\n * If it did, we don't throw - letting the signature confirmation promise continue.\n */\n function createNonceInvalidationPromiseHandlingRaceCondition(\n signature: Signature,\n ): typeof getNonceInvalidationPromise {\n return async function wrappedGetNonceInvalidationPromise(config) {\n try {\n return await getNonceInvalidationPromise(config);\n } catch (e) {\n // If nonce became invalid, check if our transaction actually landed\n if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n let status;\n try {\n const { value: statuses } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: config.abortSignal });\n status = statuses[0];\n } catch {\n // RPC failed - propagate the original nonce error\n throw e;\n }\n\n if (status === null || status === undefined) {\n // Transaction doesn't exist - nonce was truly invalid\n throw e;\n }\n\n // Check if status meets required commitment\n if (\n status.confirmationStatus !== null &&\n commitmentComparator(status.confirmationStatus, config.commitment) >= 0\n ) {\n // Transaction failed on-chain, throw the error from the transaction\n if (status.err !== null) {\n throw getSolanaErrorFromTransactionError(status.err);\n }\n // Transaction succeeded, resolve the promise successfully\n return;\n }\n\n // Commitment not met yet - return a never-resolving promise\n // This lets the signature confirmation promise continue\n return await new Promise(() => {});\n }\n throw e;\n }\n };\n }\n\n async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n const wrappedGetNonceInvalidationPromise = createNonceInvalidationPromiseHandlingRaceCondition(\n getSignatureFromTransaction(config.transaction),\n );\n\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise: wrappedGetNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmDurableNonceTransaction(transaction, config) {\n await sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { GetEpochInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createBlockHeightExceedencePromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n TransactionWithLastValidBlockHeight,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight,\n config: Omit<\n Parameters[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} and the {@link SlotNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a blockhash-based transaction to the network and to\n * wait until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit';\n *\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error('This transaction depends on a blockhash that has expired');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'devnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'testnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'mainnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig): SendAndConfirmTransactionWithBlockhashLifetimeFunction {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmRecentTransaction(\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmTransaction(transaction, config) {\n await sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendTransactionWithoutConfirmingFunction = (\n transaction: SendableTransaction & Transaction,\n config: Omit[0], 'rpc' | 'transaction'>,\n) => Promise;\n\ninterface SendTransactionWithoutConfirmingFactoryConfig {\n /** An object that supports the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}\n\n/**\n * Returns a function that you can call to send a transaction with any kind of lifetime to the\n * network without waiting for it to be confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * sendTransactionWithoutConfirmingFactory,\n * SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n * } from '@solana/kit';\n *\n * const sendTransaction = sendTransactionWithoutConfirmingFactory({ rpc });\n *\n * try {\n * await sendTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) {\n * console.error('The transaction failed in simulation', e.cause);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendTransactionWithoutConfirmingFactory({\n rpc,\n}: SendTransactionWithoutConfirmingFactoryConfig): SendTransactionWithoutConfirmingFunction {\n return async function sendTransactionWithoutConfirming(transaction, config) {\n await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n rpc,\n transaction,\n });\n };\n}\n","/**\n * Solana USDC Balance Monitor\n *\n * Checks USDC balance on Solana mainnet with caching.\n * Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).\n */\n\nimport { address as solAddress, createSolanaRpc } from \"@solana/kit\";\n\nconst SOLANA_USDC_MINT = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nconst SOLANA_DEFAULT_RPC = \"https://api.mainnet-beta.solana.com\";\nconst BALANCE_TIMEOUT_MS = 10_000;\nconst CACHE_TTL_MS = 30_000;\n\nexport type SolanaBalanceInfo = {\n balance: bigint;\n balanceUSD: string;\n isLow: boolean;\n isEmpty: boolean;\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SolanaSufficiencyResult = {\n sufficient: boolean;\n info: SolanaBalanceInfo;\n shortfall?: string;\n};\n\nexport class SolanaBalanceMonitor {\n private readonly rpc: ReturnType;\n private readonly walletAddress: string;\n private cachedBalance: bigint | null = null;\n private cachedAt = 0;\n\n constructor(walletAddress: string, rpcUrl?: string) {\n this.walletAddress = walletAddress;\n const url = rpcUrl || process[\"env\"].CLAWROUTER_SOLANA_RPC_URL || SOLANA_DEFAULT_RPC;\n this.rpc = createSolanaRpc(url);\n }\n\n async checkBalance(): Promise {\n const now = Date.now();\n if (\n this.cachedBalance !== null &&\n this.cachedBalance > 0n &&\n now - this.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(this.cachedBalance);\n }\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n const balance = await this.fetchBalance();\n if (balance > 0n) {\n this.cachedBalance = balance;\n this.cachedAt = now;\n }\n return this.buildInfo(balance);\n }\n\n deductEstimated(amountMicros: bigint): void {\n if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {\n this.cachedBalance -= amountMicros;\n }\n }\n\n invalidate(): void {\n this.cachedBalance = null;\n this.cachedAt = 0;\n }\n\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSDC(shortfall),\n };\n }\n\n /**\n * Format USDC amount (in micros) as \"$X.XX\".\n */\n formatUSDC(amountMicros: bigint): string {\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n /**\n * Check native SOL balance (in lamports). Useful for detecting users who\n * funded with SOL instead of USDC.\n */\n async checkSolBalance(): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n try {\n const owner = solAddress(this.walletAddress);\n const response = await this.rpc.getBalance(owner).send({ abortSignal: controller.signal });\n return BigInt(response.value);\n } catch {\n return 0n;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async fetchBalance(): Promise {\n const owner = solAddress(this.walletAddress);\n const mint = solAddress(SOLANA_USDC_MINT);\n\n // The public Solana RPC frequently returns empty token account lists even\n // for funded wallets. Retry once on empty before accepting $0 as truth.\n for (let attempt = 0; attempt < 2; attempt++) {\n const result = await this.fetchBalanceOnce(owner, mint);\n if (result > 0n || attempt === 1) return result;\n await new Promise((r) => setTimeout(r, 1_000));\n }\n return 0n;\n }\n\n private async fetchBalanceOnce(\n owner: ReturnType,\n mint: ReturnType,\n ): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n\n try {\n const response = await this.rpc\n .getTokenAccountsByOwner(owner, { mint }, { encoding: \"jsonParsed\" })\n .send({ abortSignal: controller.signal });\n\n if (response.value.length === 0) return 0n;\n\n let total = 0n;\n for (const account of response.value) {\n const parsed = account.account.data as {\n parsed: { info: { tokenAmount: { amount: string } } };\n };\n total += BigInt(parsed.parsed.info.tokenAmount.amount);\n }\n return total;\n } catch (err) {\n throw new Error(\n `Failed to fetch Solana USDC balance: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n private buildInfo(balance: bigint): SolanaBalanceInfo {\n const dollars = Number(balance) / 1_000_000;\n return {\n balance,\n balanceUSD: `$${dollars.toFixed(2)}`,\n isLow: balance < 1_000_000n,\n isEmpty: balance < 100n,\n walletAddress: this.walletAddress,\n };\n }\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n};\n\nexport function getMintEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintCodec(): FixedSizeCodec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n\nexport function getMintSize(): number {\n return 82;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getTokenEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenCodec(): FixedSizeCodec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n\nexport function getTokenSize(): number {\n return 165;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n} from '../instructions';\n\nexport const TOKEN_PROGRAM_ADDRESS =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n\nexport enum TokenAccount {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyTokenAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenAccount {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return TokenAccount.Mint;\n }\n if (data.length === 165) {\n return TokenAccount.Token;\n }\n if (data.length === 355) {\n return TokenAccount.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token account.'\n );\n}\n\nexport enum TokenInstruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n}\n\nexport function identifyTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return TokenInstruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return TokenInstruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return TokenInstruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return TokenInstruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return TokenInstruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return TokenInstruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return TokenInstruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return TokenInstruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return TokenInstruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return TokenInstruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return TokenInstruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return TokenInstruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return TokenInstruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return TokenInstruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return TokenInstruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return TokenInstruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return TokenInstruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return TokenInstruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return TokenInstruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return TokenInstruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return TokenInstruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return TokenInstruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return TokenInstruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return TokenInstruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return TokenInstruction.UiAmountToAmount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token instruction.'\n );\n}\n\nexport type ParsedTokenInstruction<\n TProgram extends string = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n> =\n | ({\n instructionType: TokenInstruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: TokenInstruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: TokenInstruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: TokenInstruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: TokenInstruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: TokenInstruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: TokenInstruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: TokenInstruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: TokenInstruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: TokenInstruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: TokenInstruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: TokenInstruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: TokenInstruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: TokenInstruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: TokenInstruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: TokenInstruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: TokenInstruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: TokenInstruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type TokenError =\n | typeof TOKEN_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_ERROR__ALREADY_IN_USE\n | typeof TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__FIXED_SUPPLY\n | typeof TOKEN_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_ERROR__INVALID_MINT\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_STATE\n | typeof TOKEN_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_ERROR__MINT_MISMATCH\n | typeof TOKEN_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_ERROR__OVERFLOW\n | typeof TOKEN_ERROR__OWNER_MISMATCH\n | typeof TOKEN_ERROR__UNINITIALIZED_STATE;\n\nlet tokenErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n tokenErrorMessages = {\n [TOKEN_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getTokenErrorMessage(code: TokenError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (tokenErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isTokenError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU32Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAdvanceNonceAccountInstruction,\n type ParsedAllocateInstruction,\n type ParsedAllocateWithSeedInstruction,\n type ParsedAssignInstruction,\n type ParsedAssignWithSeedInstruction,\n type ParsedAuthorizeNonceAccountInstruction,\n type ParsedCreateAccountInstruction,\n type ParsedCreateAccountWithSeedInstruction,\n type ParsedInitializeNonceAccountInstruction,\n type ParsedTransferSolInstruction,\n type ParsedTransferSolWithSeedInstruction,\n type ParsedUpgradeNonceAccountInstruction,\n type ParsedWithdrawNonceAccountInstruction,\n} from '../instructions';\n\nexport const SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport enum SystemAccount {\n Nonce,\n}\n\nexport enum SystemInstruction {\n CreateAccount,\n Assign,\n TransferSol,\n CreateAccountWithSeed,\n AdvanceNonceAccount,\n WithdrawNonceAccount,\n InitializeNonceAccount,\n AuthorizeNonceAccount,\n Allocate,\n AllocateWithSeed,\n AssignWithSeed,\n TransferSolWithSeed,\n UpgradeNonceAccount,\n}\n\nexport function identifySystemInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): SystemInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU32Encoder().encode(0), 0)) {\n return SystemInstruction.CreateAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(1), 0)) {\n return SystemInstruction.Assign;\n }\n if (containsBytes(data, getU32Encoder().encode(2), 0)) {\n return SystemInstruction.TransferSol;\n }\n if (containsBytes(data, getU32Encoder().encode(3), 0)) {\n return SystemInstruction.CreateAccountWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(4), 0)) {\n return SystemInstruction.AdvanceNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(5), 0)) {\n return SystemInstruction.WithdrawNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(6), 0)) {\n return SystemInstruction.InitializeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(7), 0)) {\n return SystemInstruction.AuthorizeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(8), 0)) {\n return SystemInstruction.Allocate;\n }\n if (containsBytes(data, getU32Encoder().encode(9), 0)) {\n return SystemInstruction.AllocateWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(10), 0)) {\n return SystemInstruction.AssignWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(11), 0)) {\n return SystemInstruction.TransferSolWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(12), 0)) {\n return SystemInstruction.UpgradeNonceAccount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a system instruction.'\n );\n}\n\nexport type ParsedSystemInstruction<\n TProgram extends string = '11111111111111111111111111111111',\n> =\n | ({\n instructionType: SystemInstruction.CreateAccount;\n } & ParsedCreateAccountInstruction)\n | ({\n instructionType: SystemInstruction.Assign;\n } & ParsedAssignInstruction)\n | ({\n instructionType: SystemInstruction.TransferSol;\n } & ParsedTransferSolInstruction)\n | ({\n instructionType: SystemInstruction.CreateAccountWithSeed;\n } & ParsedCreateAccountWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AdvanceNonceAccount;\n } & ParsedAdvanceNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.WithdrawNonceAccount;\n } & ParsedWithdrawNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.InitializeNonceAccount;\n } & ParsedInitializeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.AuthorizeNonceAccount;\n } & ParsedAuthorizeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.Allocate;\n } & ParsedAllocateInstruction)\n | ({\n instructionType: SystemInstruction.AllocateWithSeed;\n } & ParsedAllocateWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AssignWithSeed;\n } & ParsedAssignWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.TransferSolWithSeed;\n } & ParsedTransferSolWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.UpgradeNonceAccount;\n } & ParsedUpgradeNonceAccountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\n\n/** AccountAlreadyInUse: an account with the same address already exists */\nexport const SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE = 0x0; // 0\n/** ResultWithNegativeLamports: account does not have enough SOL to perform the operation */\nexport const SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS = 0x1; // 1\n/** InvalidProgramId: cannot assign account to this program id */\nexport const SYSTEM_ERROR__INVALID_PROGRAM_ID = 0x2; // 2\n/** InvalidAccountDataLength: cannot allocate account data of this length */\nexport const SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH = 0x3; // 3\n/** MaxSeedLengthExceeded: length of requested seed is too long */\nexport const SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED = 0x4; // 4\n/** AddressWithSeedMismatch: provided address does not match addressed derived from seed */\nexport const SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH = 0x5; // 5\n/** NonceNoRecentBlockhashes: advancing stored nonce requires a populated RecentBlockhashes sysvar */\nexport const SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES = 0x6; // 6\n/** NonceBlockhashNotExpired: stored nonce is still in recent_blockhashes */\nexport const SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED = 0x7; // 7\n/** NonceUnexpectedBlockhashValue: specified nonce does not match stored nonce */\nexport const SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE = 0x8; // 8\n\nexport type SystemError =\n | typeof SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE\n | typeof SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH\n | typeof SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH\n | typeof SYSTEM_ERROR__INVALID_PROGRAM_ID\n | typeof SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED\n | typeof SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES\n | typeof SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE\n | typeof SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS;\n\nlet systemErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n systemErrorMessages = {\n [SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE]: `an account with the same address already exists`,\n [SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH]: `provided address does not match addressed derived from seed`,\n [SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH]: `cannot allocate account data of this length`,\n [SYSTEM_ERROR__INVALID_PROGRAM_ID]: `cannot assign account to this program id`,\n [SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED]: `length of requested seed is too long`,\n [SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED]: `stored nonce is still in recent_blockhashes`,\n [SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES]: `advancing stored nonce requires a populated RecentBlockhashes sysvar`,\n [SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE]: `specified nonce does not match stored nonce`,\n [SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS]: `account does not have enough SOL to perform the operation`,\n };\n}\n\nexport function getSystemErrorMessage(code: SystemError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (systemErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isSystemError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n SYSTEM_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n BASE_ACCOUNT_SIZE,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\nimport {\n getAccountMetaFactory,\n type InstructionWithByteDelta,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ACCOUNT_DISCRIMINATOR = 0;\n\nexport function getCreateAccountDiscriminatorBytes() {\n return getU32Encoder().encode(CREATE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNewAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNewAccount extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountNewAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAccountInstructionData = {\n discriminator: number;\n lamports: bigint;\n space: bigint;\n programAddress: Address;\n};\n\nexport type CreateAccountInstructionDataArgs = {\n lamports: number | bigint;\n space: number | bigint;\n programAddress: Address;\n};\n\nexport function getCreateAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU32Encoder()],\n ['lamports', getU64Encoder()],\n ['space', getU64Encoder()],\n ['programAddress', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: CREATE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU32Decoder()],\n ['lamports', getU64Decoder()],\n ['space', getU64Decoder()],\n ['programAddress', getAddressDecoder()],\n ]);\n}\n\nexport function getCreateAccountInstructionDataCodec(): FixedSizeCodec<\n CreateAccountInstructionDataArgs,\n CreateAccountInstructionData\n> {\n return combineCodec(\n getCreateAccountInstructionDataEncoder(),\n getCreateAccountInstructionDataDecoder()\n );\n}\n\nexport type CreateAccountInput<\n TAccountPayer extends string = string,\n TAccountNewAccount extends string = string,\n> = {\n payer: TransactionSigner;\n newAccount: TransactionSigner;\n lamports: CreateAccountInstructionDataArgs['lamports'];\n space: CreateAccountInstructionDataArgs['space'];\n programAddress: CreateAccountInstructionDataArgs['programAddress'];\n};\n\nexport function getCreateAccountInstruction<\n TAccountPayer extends string,\n TAccountNewAccount extends string,\n TProgramAddress extends Address = typeof SYSTEM_PROGRAM_ADDRESS,\n>(\n input: CreateAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n> &\n InstructionWithByteDelta {\n // Program address.\n const programAddress = config?.programAddress ?? SYSTEM_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n newAccount: { value: input.newAccount ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Bytes created or reallocated by the instruction.\n const byteDelta: number = [Number(args.space) + BASE_ACCOUNT_SIZE].reduce(\n (a, b) => a + b,\n 0\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'omitted');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.newAccount),\n ],\n byteDelta,\n data: getCreateAccountInstructionDataEncoder().encode(\n args as CreateAccountInstructionDataArgs\n ),\n programAddress,\n } as CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n > &\n InstructionWithByteDelta);\n}\n\nexport type ParsedCreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n payer: TAccountMetas[0];\n newAccount: TAccountMetas[1];\n };\n data: CreateAccountInstructionData;\n};\n\nexport function parseCreateAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAccountInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { payer: getNextAccount(), newAccount: getNextAccount() },\n data: getCreateAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import { getCreateAccountInstruction } from '@solana-program/system';\nimport {\n Address,\n InstructionPlan,\n OptionOrNullable,\n sequentialInstructionPlan,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n getInitializeMint2Instruction,\n getMintSize,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\n// RPC `getMinimumBalanceForRentExemption` for 82 bytes, which is token mint size\n// Hardcoded to avoid requiring an RPC request each time\nconst MINIMUM_BALANCE_FOR_MINT = 1461600;\n\nexport type CreateMintInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** New mint account to create. */\n newMint: TransactionSigner;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n /**\n * Optional override for the amount of Lamports to fund the mint account with.\n * @default 1461600\n * */\n mintAccountLamports?: number;\n};\n\ntype CreateMintInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n};\n\nexport function getCreateMintInstructionPlan(\n input: CreateMintInstructionPlanInput,\n config?: CreateMintInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAccountInstruction(\n {\n payer: input.payer,\n newAccount: input.newMint,\n lamports: input.mintAccountLamports ?? MINIMUM_BALANCE_FOR_MINT,\n space: getMintSize(),\n programAddress: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n },\n {\n programAddress: config?.systemProgram,\n }\n ),\n getInitializeMint2Instruction(\n {\n mint: input.newMint.address,\n decimals: input.decimals,\n mintAuthority: input.mintAuthority,\n freezeAuthority: input.freezeAuthority,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getMintToCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype MintToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to mint to.\n * Will be created if it does not already exist.\n * Note: Use {@link getMintToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n ata: Address;\n /** Wallet address for the associated token account. */\n owner: Address;\n /** The token mint for the associated token account. */\n mint: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: Address | TransactionSigner;\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype MintToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getMintToATAInstructionPlan(\n input: MintToATAInstructionPlanInput,\n config?: MintToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.ata,\n owner: input.owner,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n // mint to this token account\n getMintToCheckedInstruction(\n {\n mint: input.mint,\n token: input.ata,\n mintAuthority: input.mintAuthority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype MintToATAInstructionPlanAsyncInput = Omit<\n MintToATAInstructionPlanInput,\n 'ata'\n>;\n\nexport async function getMintToATAInstructionPlanAsync(\n input: MintToATAInstructionPlanAsyncInput,\n config?: MintToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.owner,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getMintToATAInstructionPlan(\n {\n ...input,\n ata: ataAddress,\n },\n config\n );\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getTransferCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype TransferToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** The token mint to transfer. */\n mint: Address;\n /** The source account for the transfer. */\n source: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n /** Associated token account address to transfer to.\n * Will be created if it does not already exist.\n * Note: Use {@link getTransferToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n destination: Address;\n /** Wallet address for the destination. */\n recipient: Address;\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype TransferToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getTransferToATAInstructionPlan(\n input: TransferToATAInstructionPlanInput,\n config?: TransferToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.destination,\n owner: input.recipient,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n getTransferCheckedInstruction(\n {\n source: input.source,\n mint: input.mint,\n destination: input.destination,\n authority: input.authority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype TransferToATAInstructionPlanAsyncInput = Omit<\n TransferToATAInstructionPlanInput,\n 'destination'\n>;\n\nexport async function getTransferToATAInstructionPlanAsync(\n input: TransferToATAInstructionPlanAsyncInput,\n config?: TransferToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.recipient,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getTransferToATAInstructionPlan(\n {\n ...input,\n destination: ataAddress,\n },\n config\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n TransferFeeConfig,\n WithheldWithdraw,\n CloseMint,\n InterestRate,\n PermanentDelegate,\n ConfidentialTransferMint,\n TransferHookProgramId,\n ConfidentialTransferFeeConfig,\n MetadataPointer,\n GroupPointer,\n GroupMemberPointer,\n ScaledUiAmount,\n Pause,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** Authenticated encryption containing an account balance. */\nexport type DecryptableBalance = ReadonlyUint8Array;\n\nexport type DecryptableBalanceArgs = DecryptableBalance;\n\nexport function getDecryptableBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 36);\n}\n\nexport function getDecryptableBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 36);\n}\n\nexport function getDecryptableBalanceCodec(): FixedSizeCodec<\n DecryptableBalanceArgs,\n DecryptableBalance\n> {\n return combineCodec(\n getDecryptableBalanceEncoder(),\n getDecryptableBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** ElGamal ciphertext containing an account balance. */\nexport type EncryptedBalance = ReadonlyUint8Array;\n\nexport type EncryptedBalanceArgs = EncryptedBalance;\n\nexport function getEncryptedBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 64);\n}\n\nexport function getEncryptedBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 64);\n}\n\nexport function getEncryptedBalanceCodec(): FixedSizeCodec<\n EncryptedBalanceArgs,\n EncryptedBalance\n> {\n return combineCodec(\n getEncryptedBalanceEncoder(),\n getEncryptedBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getF64Decoder,\n getF64Encoder,\n getI16Decoder,\n getI16Encoder,\n getMapDecoder,\n getMapEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n getEncryptedBalanceDecoder,\n getEncryptedBalanceEncoder,\n getTransferFeeDecoder,\n getTransferFeeEncoder,\n type AccountState,\n type AccountStateArgs,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n type EncryptedBalance,\n type EncryptedBalanceArgs,\n type TransferFee,\n type TransferFeeArgs,\n} from '.';\n\nexport type Extension =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFee;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFee;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: Option
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalance;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalance;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalance;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalance;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountState }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: Option
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: Option
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: Option
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: Option
;\n /** Optional account address that holds the group. */\n groupAddress: Option
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: bigint;\n /** The maximum number of group members. */\n maxSize: bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: Option
;\n /** Optional account address that holds the member. */\n memberAddress: Option
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: bigint;\n newMultiplier: number;\n }\n | { __kind: 'PausableConfig'; authority: Option
; paused: boolean }\n | { __kind: 'PausableAccount' };\n\nexport type ExtensionArgs =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: number | bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFeeArgs;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFeeArgs;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: number | bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: OptionOrNullable
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalanceArgs;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalanceArgs;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalanceArgs;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalanceArgs;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: number | bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: number | bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountStateArgs }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: number | bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: number | bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: OptionOrNullable
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: OptionOrNullable
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the group. */\n groupAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: number | bigint;\n /** The maximum number of group members. */\n maxSize: number | bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the member. */\n memberAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: number | bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: number | bigint;\n newMultiplier: number;\n }\n | {\n __kind: 'PausableConfig';\n authority: OptionOrNullable
;\n paused: boolean;\n }\n | { __kind: 'PausableAccount' };\n\nexport function getExtensionEncoder(): Encoder {\n return getDiscriminatedUnionEncoder(\n [\n ['Uninitialized', getUnitEncoder()],\n [\n 'TransferFeeConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['transferFeeConfigAuthority', getAddressEncoder()],\n ['withdrawWithheldAuthority', getAddressEncoder()],\n ['withheldAmount', getU64Encoder()],\n ['olderTransferFee', getTransferFeeEncoder()],\n ['newerTransferFee', getTransferFeeEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getU64Encoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addEncoderSizePrefix(\n getStructEncoder([['closeAuthority', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addEncoderSizePrefix(\n getStructEncoder([\n ['approved', getBooleanEncoder()],\n ['elgamalPubkey', getAddressEncoder()],\n ['pendingBalanceLow', getEncryptedBalanceEncoder()],\n ['pendingBalanceHigh', getEncryptedBalanceEncoder()],\n ['availableBalance', getEncryptedBalanceEncoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['allowConfidentialCredits', getBooleanEncoder()],\n ['allowNonConfidentialCredits', getBooleanEncoder()],\n ['pendingBalanceCreditCounter', getU64Encoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['actualPendingBalanceCreditCounter', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addEncoderSizePrefix(\n getStructEncoder([['state', getAccountStateEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'MemoTransfer',\n addEncoderSizePrefix(\n getStructEncoder([\n ['requireIncomingTransferMemos', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferable',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'InterestBearingConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['rateAuthority', getAddressEncoder()],\n ['initializationTimestamp', getU64Encoder()],\n ['preUpdateAverageRate', getI16Encoder()],\n ['lastUpdateTimestamp', getU64Encoder()],\n ['currentRate', getI16Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'CpiGuard',\n addEncoderSizePrefix(\n getStructEncoder([['lockCpi', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addEncoderSizePrefix(\n getStructEncoder([['delegate', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'TransferHook',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['programId', getAddressEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addEncoderSizePrefix(\n getStructEncoder([['transferring', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressEncoder()],\n ['harvestToMintEnabled', getBooleanEncoder()],\n ['withheldAmount', getEncryptedBalanceEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getEncryptedBalanceEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MetadataPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenMetadata',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n [\n 'additionalMetadata',\n getMapEncoder(\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())\n ),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroup',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['size', getU64Encoder()],\n ['maxSize', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addEncoderSizePrefix(\n getStructEncoder([\n ['mint', getAddressEncoder()],\n ['group', getAddressEncoder()],\n ['memberNumber', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitEncoder()],\n [\n 'ScaledUiAmountConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['multiplier', getF64Encoder()],\n ['newMultiplierEffectiveTimestamp', getU64Encoder()],\n ['newMultiplier', getF64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'PausableConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['PausableAccount', getUnitEncoder()],\n ],\n { size: getU16Encoder() }\n );\n}\n\nexport function getExtensionDecoder(): Decoder {\n return getDiscriminatedUnionDecoder(\n [\n ['Uninitialized', getUnitDecoder()],\n [\n 'TransferFeeConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['transferFeeConfigAuthority', getAddressDecoder()],\n ['withdrawWithheldAuthority', getAddressDecoder()],\n ['withheldAmount', getU64Decoder()],\n ['olderTransferFee', getTransferFeeDecoder()],\n ['newerTransferFee', getTransferFeeDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getU64Decoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addDecoderSizePrefix(\n getStructDecoder([['closeAuthority', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addDecoderSizePrefix(\n getStructDecoder([\n ['approved', getBooleanDecoder()],\n ['elgamalPubkey', getAddressDecoder()],\n ['pendingBalanceLow', getEncryptedBalanceDecoder()],\n ['pendingBalanceHigh', getEncryptedBalanceDecoder()],\n ['availableBalance', getEncryptedBalanceDecoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['allowConfidentialCredits', getBooleanDecoder()],\n ['allowNonConfidentialCredits', getBooleanDecoder()],\n ['pendingBalanceCreditCounter', getU64Decoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['actualPendingBalanceCreditCounter', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addDecoderSizePrefix(\n getStructDecoder([['state', getAccountStateDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'MemoTransfer',\n addDecoderSizePrefix(\n getStructDecoder([\n ['requireIncomingTransferMemos', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferable',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'InterestBearingConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['rateAuthority', getAddressDecoder()],\n ['initializationTimestamp', getU64Decoder()],\n ['preUpdateAverageRate', getI16Decoder()],\n ['lastUpdateTimestamp', getU64Decoder()],\n ['currentRate', getI16Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'CpiGuard',\n addDecoderSizePrefix(\n getStructDecoder([['lockCpi', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addDecoderSizePrefix(\n getStructDecoder([['delegate', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'TransferHook',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['programId', getAddressDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addDecoderSizePrefix(\n getStructDecoder([['transferring', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressDecoder()],\n ['harvestToMintEnabled', getBooleanDecoder()],\n ['withheldAmount', getEncryptedBalanceDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getEncryptedBalanceDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MetadataPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenMetadata',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n [\n 'additionalMetadata',\n getMapDecoder(\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())\n ),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroup',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['size', getU64Decoder()],\n ['maxSize', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addDecoderSizePrefix(\n getStructDecoder([\n ['mint', getAddressDecoder()],\n ['group', getAddressDecoder()],\n ['memberNumber', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitDecoder()],\n [\n 'ScaledUiAmountConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['multiplier', getF64Decoder()],\n ['newMultiplierEffectiveTimestamp', getU64Decoder()],\n ['newMultiplier', getF64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'PausableConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['PausableAccount', getUnitDecoder()],\n ],\n { size: getU16Decoder() }\n );\n}\n\nexport function getExtensionCodec(): Codec {\n return combineCodec(getExtensionEncoder(), getExtensionDecoder());\n}\n\n// Data Enum Helpers.\nexport function extension(\n kind: 'Uninitialized'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MintCloseAuthority',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MintCloseAuthority'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferMint',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n>;\nexport function extension(\n kind: 'ConfidentialTransferAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n>;\nexport function extension(\n kind: 'DefaultAccountState',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'DefaultAccountState'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ImmutableOwner',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ImmutableOwner'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MemoTransfer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MemoTransfer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferable',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferable'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'InterestBearingConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n>;\nexport function extension(\n kind: 'CpiGuard',\n data: GetDiscriminatedUnionVariantContent\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PermanentDelegate',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PermanentDelegate'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferableAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n>;\nexport function extension(\n kind: 'TransferHook',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHook'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferHookAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHookAccount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferFee',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n>;\nexport function extension(\n kind: 'ConfidentialTransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n>;\nexport function extension(\n kind: 'MetadataPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MetadataPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenMetadata',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenMetadata'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroup',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroup'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupMemberPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupMemberPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroupMember',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroupMember'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialMintBurn'\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialMintBurn'\n>;\nexport function extension(\n kind: 'ScaledUiAmountConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n>;\nexport function extension(\n kind: 'PausableConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PausableConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PausableAccount'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: K,\n data?: Data\n) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isExtension(\n kind: K,\n value: Extension\n): value is Extension & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n getU16Decoder,\n getU16Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\n/**\n * Extensions that can be applied to mints or accounts. Mint extensions must\n * only be applied to mint accounts, and account extensions must only be\n * applied to token holding accounts.\n */\nexport enum ExtensionType {\n Uninitialized,\n TransferFeeConfig,\n TransferFeeAmount,\n MintCloseAuthority,\n ConfidentialTransferMint,\n ConfidentialTransferAccount,\n DefaultAccountState,\n ImmutableOwner,\n MemoTransfer,\n NonTransferable,\n InterestBearingConfig,\n CpiGuard,\n PermanentDelegate,\n NonTransferableAccount,\n TransferHook,\n TransferHookAccount,\n ConfidentialTransferFee,\n ConfidentialTransferFeeAmount,\n ScaledUiAmountConfig,\n PausableConfig,\n PausableAccount,\n MetadataPointer,\n TokenMetadata,\n GroupPointer,\n TokenGroup,\n GroupMemberPointer,\n TokenGroupMember,\n}\n\nexport type ExtensionTypeArgs = ExtensionType;\n\nexport function getExtensionTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(ExtensionType, { size: getU16Encoder() });\n}\n\nexport function getExtensionTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(ExtensionType, { size: getU16Decoder() });\n}\n\nexport function getExtensionTypeCodec(): FixedSizeCodec<\n ExtensionTypeArgs,\n ExtensionType\n> {\n return combineCodec(getExtensionTypeEncoder(), getExtensionTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getU32Decoder,\n getU32Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n} from '@solana/kit';\n\n/** Fields in the metadata account, used for updating. */\nexport type TokenMetadataField =\n | { __kind: 'Name' }\n | { __kind: 'Symbol' }\n | { __kind: 'Uri' }\n | { __kind: 'Key'; fields: readonly [string] };\n\nexport type TokenMetadataFieldArgs = TokenMetadataField;\n\nexport function getTokenMetadataFieldEncoder(): Encoder {\n return getDiscriminatedUnionEncoder([\n ['Name', getUnitEncoder()],\n ['Symbol', getUnitEncoder()],\n ['Uri', getUnitEncoder()],\n [\n 'Key',\n getStructEncoder([\n [\n 'fields',\n getTupleEncoder([\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldDecoder(): Decoder {\n return getDiscriminatedUnionDecoder([\n ['Name', getUnitDecoder()],\n ['Symbol', getUnitDecoder()],\n ['Uri', getUnitDecoder()],\n [\n 'Key',\n getStructDecoder([\n [\n 'fields',\n getTupleDecoder([\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldCodec(): Codec<\n TokenMetadataFieldArgs,\n TokenMetadataField\n> {\n return combineCodec(\n getTokenMetadataFieldEncoder(),\n getTokenMetadataFieldDecoder()\n );\n}\n\n// Data Enum Helpers.\nexport function tokenMetadataField(\n kind: 'Name'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Symbol'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Uri'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Key',\n data: GetDiscriminatedUnionVariantContent<\n TokenMetadataFieldArgs,\n '__kind',\n 'Key'\n >['fields']\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField<\n K extends TokenMetadataFieldArgs['__kind'],\n Data,\n>(kind: K, data?: Data) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isTokenMetadataField(\n kind: K,\n value: TokenMetadataField\n): value is TokenMetadataField & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport type TransferFee = {\n /** First epoch where the transfer fee takes effect. */\n epoch: bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport type TransferFeeArgs = {\n /** First epoch where the transfer fee takes effect. */\n epoch: number | bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: number | bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport function getTransferFeeEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['epoch', getU64Encoder()],\n ['maximumFee', getU64Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ]);\n}\n\nexport function getTransferFeeDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['epoch', getU64Decoder()],\n ['maximumFee', getU64Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ]);\n}\n\nexport function getTransferFeeCodec(): FixedSizeCodec<\n TransferFeeArgs,\n TransferFee\n> {\n return combineCodec(getTransferFeeEncoder(), getTransferFeeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n padLeftEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getExtensionDecoder,\n getExtensionEncoder,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n /** The extensions activated on the mint account. */\n extensions: Option>;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n /** The extensions activated on the mint account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getMintEncoder(): Encoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintDecoder(): Decoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintCodec(): Codec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Encoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getExtensionDecoder,\n getExtensionEncoder,\n type AccountState,\n type AccountStateArgs,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n /** The extensions activated on the token account. */\n extensions: Option>;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n /** The extensions activated on the token account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getTokenEncoder(): Encoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): Decoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenCodec(): Codec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApplyConfidentialPendingBalanceInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveConfidentialTransferAccountInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedConfidentialDepositInstruction,\n type ParsedConfidentialTransferInstruction,\n type ParsedConfidentialTransferWithFeeInstruction,\n type ParsedConfidentialWithdrawInstruction,\n type ParsedConfigureConfidentialTransferAccountInstruction,\n type ParsedCreateNativeMintInstruction,\n type ParsedDisableConfidentialCreditsInstruction,\n type ParsedDisableCpiGuardInstruction,\n type ParsedDisableHarvestToMintInstruction,\n type ParsedDisableMemoTransfersInstruction,\n type ParsedDisableNonConfidentialCreditsInstruction,\n type ParsedEmitTokenMetadataInstruction,\n type ParsedEmptyConfidentialTransferAccountInstruction,\n type ParsedEnableConfidentialCreditsInstruction,\n type ParsedEnableCpiGuardInstruction,\n type ParsedEnableHarvestToMintInstruction,\n type ParsedEnableMemoTransfersInstruction,\n type ParsedEnableNonConfidentialCreditsInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction,\n type ParsedHarvestWithheldTokensToMintInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeConfidentialTransferFeeInstruction,\n type ParsedInitializeConfidentialTransferMintInstruction,\n type ParsedInitializeDefaultAccountStateInstruction,\n type ParsedInitializeGroupMemberPointerInstruction,\n type ParsedInitializeGroupPointerInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeInterestBearingMintInstruction,\n type ParsedInitializeMetadataPointerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintCloseAuthorityInstruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedInitializeNonTransferableMintInstruction,\n type ParsedInitializePausableConfigInstruction,\n type ParsedInitializePermanentDelegateInstruction,\n type ParsedInitializeScaledUiAmountMintInstruction,\n type ParsedInitializeTokenGroupInstruction,\n type ParsedInitializeTokenGroupMemberInstruction,\n type ParsedInitializeTokenMetadataInstruction,\n type ParsedInitializeTransferFeeConfigInstruction,\n type ParsedInitializeTransferHookInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedPauseInstruction,\n type ParsedReallocateInstruction,\n type ParsedRemoveTokenMetadataKeyInstruction,\n type ParsedResumeInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSetTransferFeeInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferCheckedWithFeeInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n type ParsedUpdateConfidentialTransferMintInstruction,\n type ParsedUpdateDefaultAccountStateInstruction,\n type ParsedUpdateGroupMemberPointerInstruction,\n type ParsedUpdateGroupPointerInstruction,\n type ParsedUpdateMetadataPointerInstruction,\n type ParsedUpdateMultiplierScaledUiMintInstruction,\n type ParsedUpdateRateInterestBearingMintInstruction,\n type ParsedUpdateTokenGroupMaxSizeInstruction,\n type ParsedUpdateTokenGroupUpdateAuthorityInstruction,\n type ParsedUpdateTokenMetadataFieldInstruction,\n type ParsedUpdateTokenMetadataUpdateAuthorityInstruction,\n type ParsedUpdateTransferHookInstruction,\n type ParsedWithdrawExcessLamportsInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsInstruction,\n type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromMintInstruction,\n} from '../instructions';\n\nexport const TOKEN_2022_PROGRAM_ADDRESS =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n\nexport enum Token2022Account {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyToken2022Account(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Account {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return Token2022Account.Mint;\n }\n if (data.length === 165) {\n return Token2022Account.Token;\n }\n if (data.length === 355) {\n return Token2022Account.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token-2022 account.'\n );\n}\n\nexport enum Token2022Instruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n InitializeMintCloseAuthority,\n InitializeTransferFeeConfig,\n TransferCheckedWithFee,\n WithdrawWithheldTokensFromMint,\n WithdrawWithheldTokensFromAccounts,\n HarvestWithheldTokensToMint,\n SetTransferFee,\n InitializeConfidentialTransferMint,\n UpdateConfidentialTransferMint,\n ConfigureConfidentialTransferAccount,\n ApproveConfidentialTransferAccount,\n EmptyConfidentialTransferAccount,\n ConfidentialDeposit,\n ConfidentialWithdraw,\n ConfidentialTransfer,\n ApplyConfidentialPendingBalance,\n EnableConfidentialCredits,\n DisableConfidentialCredits,\n EnableNonConfidentialCredits,\n DisableNonConfidentialCredits,\n ConfidentialTransferWithFee,\n InitializeDefaultAccountState,\n UpdateDefaultAccountState,\n Reallocate,\n EnableMemoTransfers,\n DisableMemoTransfers,\n CreateNativeMint,\n InitializeNonTransferableMint,\n InitializeInterestBearingMint,\n UpdateRateInterestBearingMint,\n EnableCpiGuard,\n DisableCpiGuard,\n InitializePermanentDelegate,\n InitializeTransferHook,\n UpdateTransferHook,\n InitializeConfidentialTransferFee,\n WithdrawWithheldTokensFromMintForConfidentialTransferFee,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFee,\n HarvestWithheldTokensToMintForConfidentialTransferFee,\n EnableHarvestToMint,\n DisableHarvestToMint,\n WithdrawExcessLamports,\n InitializeMetadataPointer,\n UpdateMetadataPointer,\n InitializeGroupPointer,\n UpdateGroupPointer,\n InitializeGroupMemberPointer,\n UpdateGroupMemberPointer,\n InitializeScaledUiAmountMint,\n UpdateMultiplierScaledUiMint,\n InitializePausableConfig,\n Pause,\n Resume,\n InitializeTokenMetadata,\n UpdateTokenMetadataField,\n RemoveTokenMetadataKey,\n UpdateTokenMetadataUpdateAuthority,\n EmitTokenMetadata,\n InitializeTokenGroup,\n UpdateTokenGroupMaxSize,\n UpdateTokenGroupUpdateAuthority,\n InitializeTokenGroupMember,\n}\n\nexport function identifyToken2022Instruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Instruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return Token2022Instruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return Token2022Instruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return Token2022Instruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return Token2022Instruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return Token2022Instruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return Token2022Instruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return Token2022Instruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return Token2022Instruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return Token2022Instruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return Token2022Instruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return Token2022Instruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return Token2022Instruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return Token2022Instruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return Token2022Instruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return Token2022Instruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return Token2022Instruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return Token2022Instruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return Token2022Instruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return Token2022Instruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return Token2022Instruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return Token2022Instruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return Token2022Instruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return Token2022Instruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return Token2022Instruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return Token2022Instruction.UiAmountToAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(25), 0)) {\n return Token2022Instruction.InitializeMintCloseAuthority;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferFeeConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.TransferCheckedWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.SetTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.ConfigureConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.ApproveConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EmptyConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.ConfidentialDeposit;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(6), 1)\n ) {\n return Token2022Instruction.ConfidentialWithdraw;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(7), 1)\n ) {\n return Token2022Instruction.ConfidentialTransfer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(8), 1)\n ) {\n return Token2022Instruction.ApplyConfidentialPendingBalance;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(9), 1)\n ) {\n return Token2022Instruction.EnableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(10), 1)\n ) {\n return Token2022Instruction.DisableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(11), 1)\n ) {\n return Token2022Instruction.EnableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(12), 1)\n ) {\n return Token2022Instruction.DisableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(13), 1)\n ) {\n return Token2022Instruction.ConfidentialTransferWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeDefaultAccountState;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateDefaultAccountState;\n }\n if (containsBytes(data, getU8Encoder().encode(29), 0)) {\n return Token2022Instruction.Reallocate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableMemoTransfers;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableMemoTransfers;\n }\n if (containsBytes(data, getU8Encoder().encode(31), 0)) {\n return Token2022Instruction.CreateNativeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(32), 0)) {\n return Token2022Instruction.InitializeNonTransferableMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateRateInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableCpiGuard;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableCpiGuard;\n }\n if (containsBytes(data, getU8Encoder().encode(35), 0)) {\n return Token2022Instruction.InitializePermanentDelegate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EnableHarvestToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.DisableHarvestToMint;\n }\n if (containsBytes(data, getU8Encoder().encode(38), 0)) {\n return Token2022Instruction.WithdrawExcessLamports;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeScaledUiAmountMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMultiplierScaledUiMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializePausableConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.Pause;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.Resume;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([210, 225, 30, 162, 88, 184, 77, 141]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenMetadata;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([221, 233, 49, 45, 181, 202, 220, 200]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataField;\n }\n if (\n containsBytes(data, new Uint8Array([234, 18, 32, 56, 89, 141, 37, 181]), 0)\n ) {\n return Token2022Instruction.RemoveTokenMetadataKey;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([250, 166, 180, 250, 13, 12, 184, 70]),\n 0\n )\n ) {\n return Token2022Instruction.EmitTokenMetadata;\n }\n if (\n containsBytes(data, new Uint8Array([121, 113, 108, 39, 54, 51, 0, 4]), 0)\n ) {\n return Token2022Instruction.InitializeTokenGroup;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([108, 37, 171, 143, 248, 30, 18, 110]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupMaxSize;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([161, 105, 88, 1, 237, 221, 216, 203]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([152, 32, 222, 176, 223, 237, 116, 134]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenGroupMember;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token-2022 instruction.'\n );\n}\n\nexport type ParsedToken2022Instruction<\n TProgram extends string = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n> =\n | ({\n instructionType: Token2022Instruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: Token2022Instruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: Token2022Instruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: Token2022Instruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: Token2022Instruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: Token2022Instruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: Token2022Instruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: Token2022Instruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: Token2022Instruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: Token2022Instruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: Token2022Instruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: Token2022Instruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: Token2022Instruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMintCloseAuthority;\n } & ParsedInitializeMintCloseAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferFeeConfig;\n } & ParsedInitializeTransferFeeConfigInstruction)\n | ({\n instructionType: Token2022Instruction.TransferCheckedWithFee;\n } & ParsedTransferCheckedWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMint;\n } & ParsedWithdrawWithheldTokensFromMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n } & ParsedWithdrawWithheldTokensFromAccountsInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMint;\n } & ParsedHarvestWithheldTokensToMintInstruction)\n | ({\n instructionType: Token2022Instruction.SetTransferFee;\n } & ParsedSetTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferMint;\n } & ParsedInitializeConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateConfidentialTransferMint;\n } & ParsedUpdateConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.ConfigureConfidentialTransferAccount;\n } & ParsedConfigureConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveConfidentialTransferAccount;\n } & ParsedApproveConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.EmptyConfidentialTransferAccount;\n } & ParsedEmptyConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialDeposit;\n } & ParsedConfidentialDepositInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialWithdraw;\n } & ParsedConfidentialWithdrawInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransfer;\n } & ParsedConfidentialTransferInstruction)\n | ({\n instructionType: Token2022Instruction.ApplyConfidentialPendingBalance;\n } & ParsedApplyConfidentialPendingBalanceInstruction)\n | ({\n instructionType: Token2022Instruction.EnableConfidentialCredits;\n } & ParsedEnableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableConfidentialCredits;\n } & ParsedDisableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.EnableNonConfidentialCredits;\n } & ParsedEnableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableNonConfidentialCredits;\n } & ParsedDisableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransferWithFee;\n } & ParsedConfidentialTransferWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeDefaultAccountState;\n } & ParsedInitializeDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateDefaultAccountState;\n } & ParsedUpdateDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.Reallocate;\n } & ParsedReallocateInstruction)\n | ({\n instructionType: Token2022Instruction.EnableMemoTransfers;\n } & ParsedEnableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.DisableMemoTransfers;\n } & ParsedDisableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.CreateNativeMint;\n } & ParsedCreateNativeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeNonTransferableMint;\n } & ParsedInitializeNonTransferableMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeInterestBearingMint;\n } & ParsedInitializeInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateRateInterestBearingMint;\n } & ParsedUpdateRateInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.EnableCpiGuard;\n } & ParsedEnableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.DisableCpiGuard;\n } & ParsedDisableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePermanentDelegate;\n } & ParsedInitializePermanentDelegateInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferHook;\n } & ParsedInitializeTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTransferHook;\n } & ParsedUpdateTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferFee;\n } & ParsedInitializeConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n } & ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.EnableHarvestToMint;\n } & ParsedEnableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.DisableHarvestToMint;\n } & ParsedDisableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawExcessLamports;\n } & ParsedWithdrawExcessLamportsInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMetadataPointer;\n } & ParsedInitializeMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMetadataPointer;\n } & ParsedUpdateMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupPointer;\n } & ParsedInitializeGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupPointer;\n } & ParsedUpdateGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupMemberPointer;\n } & ParsedInitializeGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupMemberPointer;\n } & ParsedUpdateGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeScaledUiAmountMint;\n } & ParsedInitializeScaledUiAmountMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMultiplierScaledUiMint;\n } & ParsedUpdateMultiplierScaledUiMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePausableConfig;\n } & ParsedInitializePausableConfigInstruction)\n | ({\n instructionType: Token2022Instruction.Pause;\n } & ParsedPauseInstruction)\n | ({\n instructionType: Token2022Instruction.Resume;\n } & ParsedResumeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenMetadata;\n } & ParsedInitializeTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataField;\n } & ParsedUpdateTokenMetadataFieldInstruction)\n | ({\n instructionType: Token2022Instruction.RemoveTokenMetadataKey;\n } & ParsedRemoveTokenMetadataKeyInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n } & ParsedUpdateTokenMetadataUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.EmitTokenMetadata;\n } & ParsedEmitTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroup;\n } & ParsedInitializeTokenGroupInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupMaxSize;\n } & ParsedUpdateTokenGroupMaxSizeInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n } & ParsedUpdateTokenGroupUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroupMember;\n } & ParsedInitializeTokenGroupMemberInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_2022_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_2022_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_2022_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_2022_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_2022_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_2022_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_2022_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_2022_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_2022_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_2022_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_2022_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_2022_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_2022_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type Token2022Error =\n | typeof TOKEN_2022_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_2022_ERROR__ALREADY_IN_USE\n | typeof TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__FIXED_SUPPLY\n | typeof TOKEN_2022_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_2022_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_2022_ERROR__INVALID_MINT\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_STATE\n | typeof TOKEN_2022_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_2022_ERROR__MINT_MISMATCH\n | typeof TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_2022_ERROR__OVERFLOW\n | typeof TOKEN_2022_ERROR__OWNER_MISMATCH\n | typeof TOKEN_2022_ERROR__UNINITIALIZED_STATE;\n\nlet token2022ErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n token2022ErrorMessages = {\n [TOKEN_2022_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_2022_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_2022_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_2022_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_2022_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_2022_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_2022_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_2022_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_2022_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_2022_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_2022_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_2022_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_2022_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getToken2022ErrorMessage(code: Token2022Error): string {\n if (process.env.NODE_ENV !== 'production') {\n return (token2022ErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isToken2022Error(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_2022_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR = 27;\n\nexport function getApplyConfidentialPendingBalanceDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR\n );\n}\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 8;\n\nexport function getApplyConfidentialPendingBalanceConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApplyConfidentialPendingBalanceInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalance;\n};\n\nexport type ApplyConfidentialPendingBalanceInstructionDataArgs = {\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n};\n\nexport function getApplyConfidentialPendingBalanceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataCodec(): FixedSizeCodec<\n ApplyConfidentialPendingBalanceInstructionDataArgs,\n ApplyConfidentialPendingBalanceInstructionData\n> {\n return combineCodec(\n getApplyConfidentialPendingBalanceInstructionDataEncoder(),\n getApplyConfidentialPendingBalanceInstructionDataDecoder()\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n expectedPendingBalanceCreditCounter: ApplyConfidentialPendingBalanceInstructionDataArgs['expectedPendingBalanceCreditCounter'];\n newDecryptableAvailableBalance: ApplyConfidentialPendingBalanceInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getApplyConfidentialPendingBalanceInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApplyConfidentialPendingBalanceInput,\n config?: { programAddress?: TProgramAddress }\n): ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getApplyConfidentialPendingBalanceInstructionDataEncoder().encode(\n args as ApplyConfidentialPendingBalanceInstructionDataArgs\n ),\n programAddress,\n } as ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: ApplyConfidentialPendingBalanceInstructionData;\n};\n\nexport function parseApplyConfidentialPendingBalanceInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApplyConfidentialPendingBalanceInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getApplyConfidentialPendingBalanceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getApproveConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 3;\n\nexport function getApproveConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type ApproveConfidentialTransferAccountInstructionDataArgs = {};\n\nexport function getApproveConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ApproveConfidentialTransferAccountInstructionDataArgs,\n ApproveConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getApproveConfidentialTransferAccountInstructionDataEncoder(),\n getApproveConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ApproveConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account to approve. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n};\n\nexport function getApproveConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getApproveConfidentialTransferAccountInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account to approve. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[2];\n };\n data: ApproveConfidentialTransferAccountInstructionData;\n};\n\nexport function parseApproveConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getApproveConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CONFIDENTIAL_DEPOSIT_DISCRIMINATOR = 27;\n\nexport function getConfidentialDepositDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_DEPOSIT_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 5;\n\nexport function getConfidentialDepositConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialDepositInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to deposit. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ConfidentialDepositInstructionDataArgs = {\n /** The amount of tokens to deposit. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getConfidentialDepositInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_DEPOSIT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialDepositInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getConfidentialDepositInstructionDataCodec(): FixedSizeCodec<\n ConfidentialDepositInstructionDataArgs,\n ConfidentialDepositInstructionData\n> {\n return combineCodec(\n getConfidentialDepositInstructionDataEncoder(),\n getConfidentialDepositInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialDepositInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialDepositInstructionDataArgs['amount'];\n decimals: ConfidentialDepositInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialDepositInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialDepositInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialDepositInstructionDataEncoder().encode(\n args as ConfidentialDepositInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: ConfidentialDepositInstructionData;\n};\n\nexport function parseConfidentialDepositInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialDepositInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialDepositInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 7;\n\nexport function getConfidentialTransferConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferInstructionDataArgs,\n ConfidentialTransferInstructionData\n> {\n return combineCodec(\n getConfidentialTransferInstructionDataEncoder(),\n getConfidentialTransferInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['equalityProofInstructionOffset'];\n ciphertextValidityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['ciphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n ciphertextValidityRecord: {\n value: input.ciphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.ciphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferInstructionDataEncoder().encode(\n args as ConfidentialTransferInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[6] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[7];\n };\n data: ConfidentialTransferInstructionData;\n};\n\nexport function parseConfidentialTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferInstruction {\n if (instruction.accounts.length < 8) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n ciphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 13;\n\nexport function getConfidentialTransferWithFeeConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountTransferAmountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountFeeSigmaRecord extends string | AccountMeta = string,\n TAccountFeeCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord extends string\n ? ReadonlyAccount\n : TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferWithFeeInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferWithFeeInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n [\n 'transferAmountCiphertextValidityProofInstructionOffset',\n getI8Encoder(),\n ],\n ['feeSigmaProofInstructionOffset', getI8Encoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['transferAmountCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['feeSigmaProofInstructionOffset', getI8Decoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferWithFeeInstructionDataArgs,\n ConfidentialTransferWithFeeInstructionData\n> {\n return combineCodec(\n getConfidentialTransferWithFeeInstructionDataEncoder(),\n getConfidentialTransferWithFeeInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferWithFeeInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountTransferAmountCiphertextValidityRecord extends string = string,\n TAccountFeeSigmaRecord extends string = string,\n TAccountFeeCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: Address;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: Address;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferWithFeeInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['equalityProofInstructionOffset'];\n transferAmountCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['transferAmountCiphertextValidityProofInstructionOffset'];\n feeSigmaProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeSigmaProofInstructionOffset'];\n feeCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeCiphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferWithFeeInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountTransferAmountCiphertextValidityRecord extends string,\n TAccountFeeSigmaRecord extends string,\n TAccountFeeCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferWithFeeInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n transferAmountCiphertextValidityRecord: {\n value: input.transferAmountCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n feeSigmaRecord: { value: input.feeSigmaRecord ?? null, isWritable: false },\n feeCiphertextValidityRecord: {\n value: input.feeCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.transferAmountCiphertextValidityRecord),\n getAccountMeta(accounts.feeSigmaRecord),\n getAccountMeta(accounts.feeCiphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferWithFeeInstructionDataEncoder().encode(\n args as ConfidentialTransferWithFeeInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: TAccountMetas[6] | undefined;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: TAccountMetas[7] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[8] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[9];\n };\n data: ConfidentialTransferWithFeeInstructionData;\n};\n\nexport function parseConfidentialTransferWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferWithFeeInstruction {\n if (instruction.accounts.length < 10) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n transferAmountCiphertextValidityRecord: getNextOptionalAccount(),\n feeSigmaRecord: getNextOptionalAccount(),\n feeCiphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_WITHDRAW_DISCRIMINATOR = 27;\n\nexport function getConfidentialWithdrawDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_WITHDRAW_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 6;\n\nexport function getConfidentialWithdrawConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialWithdrawInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to withdraw. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialWithdrawInstructionDataArgs = {\n /** The amount of tokens to withdraw. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialWithdrawInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_WITHDRAW_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialWithdrawInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialWithdrawInstructionDataCodec(): FixedSizeCodec<\n ConfidentialWithdrawInstructionDataArgs,\n ConfidentialWithdrawInstructionData\n> {\n return combineCodec(\n getConfidentialWithdrawInstructionDataEncoder(),\n getConfidentialWithdrawInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialWithdrawInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialWithdrawInstructionDataArgs['amount'];\n decimals: ConfidentialWithdrawInstructionDataArgs['decimals'];\n newDecryptableAvailableBalance: ConfidentialWithdrawInstructionDataArgs['newDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['equalityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialWithdrawInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialWithdrawInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialWithdrawInstructionDataEncoder().encode(\n args as ConfidentialWithdrawInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[2] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[3] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[4] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[5];\n };\n data: ConfidentialWithdrawInstructionData;\n};\n\nexport function parseConfidentialWithdrawInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialWithdrawInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialWithdrawInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getConfigureConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 2;\n\nexport function getConfigureConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfigureConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalance;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type ConfigureConfidentialTransferAccountInstructionDataArgs = {\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalanceArgs;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getConfigureConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['decryptableZeroBalance', getDecryptableBalanceEncoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['decryptableZeroBalance', getDecryptableBalanceDecoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ConfigureConfidentialTransferAccountInstructionDataArgs,\n ConfigureConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getConfigureConfidentialTransferAccountInstructionDataEncoder(),\n getConfigureConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n decryptableZeroBalance: ConfigureConfidentialTransferAccountInstructionDataArgs['decryptableZeroBalance'];\n maximumPendingBalanceCreditCounter: ConfigureConfidentialTransferAccountInstructionDataArgs['maximumPendingBalanceCreditCounter'];\n proofInstructionOffset: ConfigureConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfigureConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfigureConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfigureConfidentialTransferAccountInstructionDataEncoder().encode(\n args as ConfigureConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[3] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[4];\n };\n data: ConfigureConfidentialTransferAccountInstructionData;\n};\n\nexport function parseConfigureConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfigureConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CREATE_NATIVE_MINT_DISCRIMINATOR = 31;\n\nexport function getCreateNativeMintDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_NATIVE_MINT_DISCRIMINATOR);\n}\n\nexport type CreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNativeMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNativeMint extends string\n ? WritableAccount\n : TAccountNativeMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateNativeMintInstructionData = { discriminator: number };\n\nexport type CreateNativeMintInstructionDataArgs = {};\n\nexport function getCreateNativeMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CREATE_NATIVE_MINT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateNativeMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateNativeMintInstructionDataCodec(): FixedSizeCodec<\n CreateNativeMintInstructionDataArgs,\n CreateNativeMintInstructionData\n> {\n return combineCodec(\n getCreateNativeMintInstructionDataEncoder(),\n getCreateNativeMintInstructionDataDecoder()\n );\n}\n\nexport type CreateNativeMintInput<\n TAccountPayer extends string = string,\n TAccountNativeMint extends string = string,\n TAccountSystemProgram extends string = string,\n> = {\n /** Funding account (must be a system account) */\n payer: TransactionSigner;\n /** The native mint address */\n nativeMint: Address;\n /** System program for mint account funding */\n systemProgram?: Address;\n};\n\nexport function getCreateNativeMintInstruction<\n TAccountPayer extends string,\n TAccountNativeMint extends string,\n TAccountSystemProgram extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CreateNativeMintInput<\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n nativeMint: { value: input.nativeMint ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.nativeMint),\n getAccountMeta(accounts.systemProgram),\n ],\n data: getCreateNativeMintInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >);\n}\n\nexport type ParsedCreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account) */\n payer: TAccountMetas[0];\n /** The native mint address */\n nativeMint: TAccountMetas[1];\n /** System program for mint account funding */\n systemProgram: TAccountMetas[2];\n };\n data: CreateNativeMintInstructionData;\n};\n\nexport function parseCreateNativeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateNativeMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n nativeMint: getNextAccount(),\n systemProgram: getNextAccount(),\n },\n data: getCreateNativeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 10;\n\nexport function getDisableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableConfidentialCreditsInstructionDataArgs,\n DisableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableConfidentialCreditsInstructionDataEncoder(),\n getDisableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getDisableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 1;\n\nexport function getDisableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type DisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type DisableCpiGuardInstructionDataArgs = {};\n\nexport function getDisableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n DisableCpiGuardInstructionDataArgs,\n DisableCpiGuardInstructionData\n> {\n return combineCodec(\n getDisableCpiGuardInstructionDataEncoder(),\n getDisableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type DisableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableCpiGuardInstructionData;\n};\n\nexport function parseDisableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getDisableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getDisableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type DisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type DisableHarvestToMintInstructionDataArgs = {};\n\nexport function getDisableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n DisableHarvestToMintInstructionDataArgs,\n DisableHarvestToMintInstructionData\n> {\n return combineCodec(\n getDisableHarvestToMintInstructionDataEncoder(),\n getDisableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type DisableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: DisableHarvestToMintInstructionData;\n};\n\nexport function parseDisableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getDisableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getDisableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 1;\n\nexport function getDisableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type DisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type DisableMemoTransfersInstructionDataArgs = {};\n\nexport function getDisableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n DisableMemoTransfersInstructionDataArgs,\n DisableMemoTransfersInstructionData\n> {\n return combineCodec(\n getDisableMemoTransfersInstructionDataEncoder(),\n getDisableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type DisableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableMemoTransfersInstructionData;\n};\n\nexport function parseDisableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 12;\n\nexport function getDisableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableNonConfidentialCreditsInstructionDataArgs,\n DisableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableNonConfidentialCreditsInstructionDataEncoder(),\n getDisableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMIT_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 250, 166, 180, 250, 13, 12, 184, 70,\n]);\n\nexport function getEmitTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(EMIT_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type EmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? ReadonlyAccount\n : TAccountMetadata,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmitTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Start of range of data to emit */\n start: Option;\n /** End of range of data to emit */\n end: Option;\n};\n\nexport type EmitTokenMetadataInstructionDataArgs = {\n /** Start of range of data to emit */\n start?: OptionOrNullable;\n /** End of range of data to emit */\n end?: OptionOrNullable;\n};\n\nexport function getEmitTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['start', getOptionEncoder(getU64Encoder())],\n ['end', getOptionEncoder(getU64Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: EMIT_TOKEN_METADATA_DISCRIMINATOR,\n start: value.start ?? none(),\n end: value.end ?? none(),\n })\n );\n}\n\nexport function getEmitTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['start', getOptionDecoder(getU64Decoder())],\n ['end', getOptionDecoder(getU64Decoder())],\n ]);\n}\n\nexport function getEmitTokenMetadataInstructionDataCodec(): Codec<\n EmitTokenMetadataInstructionDataArgs,\n EmitTokenMetadataInstructionData\n> {\n return combineCodec(\n getEmitTokenMetadataInstructionDataEncoder(),\n getEmitTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type EmitTokenMetadataInput = {\n metadata: Address;\n start?: EmitTokenMetadataInstructionDataArgs['start'];\n end?: EmitTokenMetadataInstructionDataArgs['end'];\n};\n\nexport function getEmitTokenMetadataInstruction<\n TAccountMetadata extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmitTokenMetadataInput,\n config?: { programAddress?: TProgramAddress }\n): EmitTokenMetadataInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.metadata)],\n data: getEmitTokenMetadataInstructionDataEncoder().encode(\n args as EmitTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as EmitTokenMetadataInstruction);\n}\n\nexport type ParsedEmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n };\n data: EmitTokenMetadataInstructionData;\n};\n\nexport function parseEmitTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmitTokenMetadataInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount() },\n data: getEmitTokenMetadataInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getEmptyConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 4;\n\nexport function getEmptyConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmptyConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type EmptyConfidentialTransferAccountInstructionDataArgs = {\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getEmptyConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n EmptyConfidentialTransferAccountInstructionDataArgs,\n EmptyConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getEmptyConfidentialTransferAccountInstructionDataEncoder(),\n getEmptyConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type EmptyConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n proofInstructionOffset: EmptyConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getEmptyConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmptyConfidentialTransferAccountInput<\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEmptyConfidentialTransferAccountInstructionDataEncoder().encode(\n args as EmptyConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[1];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[2] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: EmptyConfidentialTransferAccountInstructionData;\n};\n\nexport function parseEmptyConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmptyConfidentialTransferAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getEmptyConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 9;\n\nexport function getEnableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableConfidentialCreditsInstructionDataArgs,\n EnableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableConfidentialCreditsInstructionDataEncoder(),\n getEnableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getEnableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 0;\n\nexport function getEnableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type EnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type EnableCpiGuardInstructionDataArgs = {};\n\nexport function getEnableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n EnableCpiGuardInstructionDataArgs,\n EnableCpiGuardInstructionData\n> {\n return combineCodec(\n getEnableCpiGuardInstructionDataEncoder(),\n getEnableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type EnableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableCpiGuardInstructionData;\n};\n\nexport function parseEnableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getEnableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getEnableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type EnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type EnableHarvestToMintInstructionDataArgs = {};\n\nexport function getEnableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n EnableHarvestToMintInstructionDataArgs,\n EnableHarvestToMintInstructionData\n> {\n return combineCodec(\n getEnableHarvestToMintInstructionDataEncoder(),\n getEnableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type EnableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: EnableHarvestToMintInstructionData;\n};\n\nexport function parseEnableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getEnableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getEnableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 0;\n\nexport function getEnableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type EnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type EnableMemoTransfersInstructionDataArgs = {};\n\nexport function getEnableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n EnableMemoTransfersInstructionDataArgs,\n EnableMemoTransfersInstructionData\n> {\n return combineCodec(\n getEnableMemoTransfersInstructionDataEncoder(),\n getEnableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type EnableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableMemoTransfersInstructionData;\n};\n\nexport function parseEnableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 11;\n\nexport function getEnableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableNonConfidentialCreditsInstructionDataArgs,\n EnableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableNonConfidentialCreditsInstructionDataEncoder(),\n getEnableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR = 26;\n\nexport function getHarvestWithheldTokensToMintDiscriminatorBytes() {\n return getU8Encoder().encode(HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR);\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getHarvestWithheldTokensToMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type HarvestWithheldTokensToMintInstructionDataArgs = {};\n\nexport function getHarvestWithheldTokensToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintInstructionDataArgs,\n HarvestWithheldTokensToMintInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintInstructionDataEncoder(),\n getHarvestWithheldTokensToMintInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintInput<\n TAccountMint extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n sources: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.sources.map((address) => ({\n address,\n role: AccountRole.WRITABLE,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as HarvestWithheldTokensToMintInstruction);\n}\n\nexport type ParsedHarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData =\n { discriminator: number; confidentialTransferFeeDiscriminator: number };\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs =\n {};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs,\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(),\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n sources?: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintForConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.sources ?? []).map(\n (address) => ({ address, role: AccountRole.WRITABLE })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getInitializeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferFeeInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: Option
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferFeeInstructionDataArgs = {\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: OptionOrNullable
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferFeeInstructionDataArgs,\n InitializeConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferFeeInstructionDataEncoder(),\n getInitializeConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferFeeInstructionDataArgs['authority'];\n withdrawWithheldAuthorityElGamalPubkey: InitializeConfidentialTransferFeeInstructionDataArgs['withdrawWithheldAuthorityElGamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferFeeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferFeeInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferFeeInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferFeeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getInitializeConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: Option
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferMintInstructionDataArgs = {\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: OptionOrNullable
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferMintInstructionDataArgs,\n InitializeConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferMintInstructionDataEncoder(),\n getInitializeConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferMintInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferMintInstructionDataArgs['authority'];\n autoApproveNewAccounts: InitializeConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: InitializeConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferMintInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferMintInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferMintInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getInitializeDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 0;\n\nexport function getInitializeDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type InitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type InitializeDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getInitializeDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n InitializeDefaultAccountStateInstructionDataArgs,\n InitializeDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getInitializeDefaultAccountStateInstructionDataEncoder(),\n getInitializeDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type InitializeDefaultAccountStateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n state: InitializeDefaultAccountStateInstructionDataArgs['state'];\n};\n\nexport function getInitializeDefaultAccountStateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeDefaultAccountStateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeDefaultAccountStateInstructionDataEncoder().encode(\n args as InitializeDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as InitializeDefaultAccountStateInstruction);\n}\n\nexport type ParsedInitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeDefaultAccountStateInstructionData;\n};\n\nexport function parseInitializeDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeDefaultAccountStateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getInitializeGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The public key for the account that can update the group member address. */\n authority: Option
;\n /** The account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type InitializeGroupMemberPointerInstructionDataArgs = {\n /** The public key for the account that can update the group member address. */\n authority: OptionOrNullable
;\n /** The account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupMemberPointerInstructionDataArgs,\n InitializeGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupMemberPointerInstructionDataEncoder(),\n getInitializeGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupMemberPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupMemberPointerInstructionDataArgs['authority'];\n memberAddress: InitializeGroupMemberPointerInstructionDataArgs['memberAddress'];\n};\n\nexport function getInitializeGroupMemberPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupMemberPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupMemberPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupMemberPointerInstructionDataEncoder().encode(\n args as InitializeGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupMemberPointerInstruction);\n}\n\nexport type ParsedInitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupMemberPointerInstructionData;\n};\n\nexport function parseInitializeGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupMemberPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getInitializeGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The public key for the account that can update the group address. */\n authority: Option
;\n /** The account address that holds the group. */\n groupAddress: Option
;\n};\n\nexport type InitializeGroupPointerInstructionDataArgs = {\n /** The public key for the account that can update the group address. */\n authority: OptionOrNullable
;\n /** The account address that holds the group. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupPointerInstructionDataArgs,\n InitializeGroupPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupPointerInstructionDataEncoder(),\n getInitializeGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupPointerInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupPointerInstructionDataArgs['authority'];\n groupAddress: InitializeGroupPointerInstructionDataArgs['groupAddress'];\n };\n\nexport function getInitializeGroupPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupPointerInstructionDataEncoder().encode(\n args as InitializeGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupPointerInstruction);\n}\n\nexport type ParsedInitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupPointerInstructionData;\n};\n\nexport function parseInitializeGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getI16Decoder,\n getI16Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getInitializeInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The public key for the account that can update the rate */\n rateAuthority: Option
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport type InitializeInterestBearingMintInstructionDataArgs = {\n /** The public key for the account that can update the rate */\n rateAuthority: OptionOrNullable
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport function getInitializeInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n [\n 'rateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n [\n 'rateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getInitializeInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n InitializeInterestBearingMintInstructionDataArgs,\n InitializeInterestBearingMintInstructionData\n> {\n return combineCodec(\n getInitializeInterestBearingMintInstructionDataEncoder(),\n getInitializeInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeInterestBearingMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n rateAuthority: InitializeInterestBearingMintInstructionDataArgs['rateAuthority'];\n rate: InitializeInterestBearingMintInstructionDataArgs['rate'];\n};\n\nexport function getInitializeInterestBearingMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeInterestBearingMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeInterestBearingMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeInterestBearingMintInstructionDataEncoder().encode(\n args as InitializeInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeInterestBearingMintInstruction);\n}\n\nexport type ParsedInitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeInterestBearingMintInstructionData;\n};\n\nexport function parseInitializeInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeInterestBearingMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getInitializeMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The public key for the account that can update the metadata address. */\n authority: Option
;\n /** The account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type InitializeMetadataPointerInstructionDataArgs = {\n /** The public key for the account that can update the metadata address. */\n authority: OptionOrNullable
;\n /** The account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getInitializeMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeMetadataPointerInstructionDataArgs,\n InitializeMetadataPointerInstructionData\n> {\n return combineCodec(\n getInitializeMetadataPointerInstructionDataEncoder(),\n getInitializeMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeMetadataPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeMetadataPointerInstructionDataArgs['authority'];\n metadataAddress: InitializeMetadataPointerInstructionDataArgs['metadataAddress'];\n};\n\nexport function getInitializeMetadataPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMetadataPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMetadataPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMetadataPointerInstructionDataEncoder().encode(\n args as InitializeMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeMetadataPointerInstruction);\n}\n\nexport type ParsedInitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMetadataPointerInstructionData;\n};\n\nexport function parseInitializeMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMetadataPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR = 25;\n\nexport function getInitializeMintCloseAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type InitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintCloseAuthorityInstructionData = {\n discriminator: number;\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: Option
;\n};\n\nexport type InitializeMintCloseAuthorityInstructionDataArgs = {\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getInitializeMintCloseAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['closeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['closeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataCodec(): Codec<\n InitializeMintCloseAuthorityInstructionDataArgs,\n InitializeMintCloseAuthorityInstructionData\n> {\n return combineCodec(\n getInitializeMintCloseAuthorityInstructionDataEncoder(),\n getInitializeMintCloseAuthorityInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintCloseAuthorityInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n closeAuthority: InitializeMintCloseAuthorityInstructionDataArgs['closeAuthority'];\n};\n\nexport function getInitializeMintCloseAuthorityInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintCloseAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintCloseAuthorityInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMintCloseAuthorityInstructionDataEncoder().encode(\n args as InitializeMintCloseAuthorityInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintCloseAuthorityInstruction);\n}\n\nexport type ParsedInitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMintCloseAuthorityInstructionData;\n};\n\nexport function parseInitializeMintCloseAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintCloseAuthorityInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMintCloseAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR = 32;\n\nexport function getInitializeNonTransferableMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeNonTransferableMintInstructionData = {\n discriminator: number;\n};\n\nexport type InitializeNonTransferableMintInstructionDataArgs = {};\n\nexport function getInitializeNonTransferableMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeNonTransferableMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeNonTransferableMintInstructionDataCodec(): FixedSizeCodec<\n InitializeNonTransferableMintInstructionDataArgs,\n InitializeNonTransferableMintInstructionData\n> {\n return combineCodec(\n getInitializeNonTransferableMintInstructionDataEncoder(),\n getInitializeNonTransferableMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeNonTransferableMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint account to initialize. */\n mint: Address;\n};\n\nexport function getInitializeNonTransferableMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeNonTransferableMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeNonTransferableMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeNonTransferableMintInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeNonTransferableMintInstruction);\n}\n\nexport type ParsedInitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeNonTransferableMintInstructionData;\n};\n\nexport function parseInitializeNonTransferableMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeNonTransferableMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeNonTransferableMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR = 44;\n\nexport function getInitializePausableConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR = 0;\n\nexport function getInitializePausableConfigPausableDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR\n );\n}\n\nexport type InitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePausableConfigInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n /** The authority that can pause and resume the mint. */\n authority: Option
;\n};\n\nexport type InitializePausableConfigInstructionDataArgs = {\n /** The authority that can pause and resume the mint. */\n authority: OptionOrNullable
;\n};\n\nexport function getInitializePausableConfigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR,\n pausableDiscriminator: INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePausableConfigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializePausableConfigInstructionDataCodec(): FixedSizeCodec<\n InitializePausableConfigInstructionDataArgs,\n InitializePausableConfigInstructionData\n> {\n return combineCodec(\n getInitializePausableConfigInstructionDataEncoder(),\n getInitializePausableConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializePausableConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n authority: InitializePausableConfigInstructionDataArgs['authority'];\n};\n\nexport function getInitializePausableConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePausableConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePausableConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePausableConfigInstructionDataEncoder().encode(\n args as InitializePausableConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializePausableConfigInstruction);\n}\n\nexport type ParsedInitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializePausableConfigInstructionData;\n};\n\nexport function parseInitializePausableConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePausableConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePausableConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR = 35;\n\nexport function getInitializePermanentDelegateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR);\n}\n\nexport type InitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePermanentDelegateInstructionData = {\n discriminator: number;\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport type InitializePermanentDelegateInstructionDataArgs = {\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport function getInitializePermanentDelegateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['delegate', getAddressEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePermanentDelegateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['delegate', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializePermanentDelegateInstructionDataCodec(): FixedSizeCodec<\n InitializePermanentDelegateInstructionDataArgs,\n InitializePermanentDelegateInstructionData\n> {\n return combineCodec(\n getInitializePermanentDelegateInstructionDataEncoder(),\n getInitializePermanentDelegateInstructionDataDecoder()\n );\n}\n\nexport type InitializePermanentDelegateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n delegate: InitializePermanentDelegateInstructionDataArgs['delegate'];\n};\n\nexport function getInitializePermanentDelegateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePermanentDelegateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePermanentDelegateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePermanentDelegateInstructionDataEncoder().encode(\n args as InitializePermanentDelegateInstructionDataArgs\n ),\n programAddress,\n } as InitializePermanentDelegateInstruction);\n}\n\nexport type ParsedInitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializePermanentDelegateInstructionData;\n};\n\nexport function parseInitializePermanentDelegateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePermanentDelegateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePermanentDelegateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getF64Decoder,\n getF64Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 43;\n\nexport function getInitializeScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeScaledUiAmountMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeScaledUiAmountMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The authority that can update the multiplier */\n authority: Option
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport type InitializeScaledUiAmountMintInstructionDataArgs = {\n /** The authority that can update the multiplier */\n authority: OptionOrNullable
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport function getInitializeScaledUiAmountMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Decoder()],\n ]);\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataCodec(): FixedSizeCodec<\n InitializeScaledUiAmountMintInstructionDataArgs,\n InitializeScaledUiAmountMintInstructionData\n> {\n return combineCodec(\n getInitializeScaledUiAmountMintInstructionDataEncoder(),\n getInitializeScaledUiAmountMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeScaledUiAmountMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeScaledUiAmountMintInstructionDataArgs['authority'];\n multiplier: InitializeScaledUiAmountMintInstructionDataArgs['multiplier'];\n};\n\nexport function getInitializeScaledUiAmountMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeScaledUiAmountMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeScaledUiAmountMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeScaledUiAmountMintInstructionDataEncoder().encode(\n args as InitializeScaledUiAmountMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeScaledUiAmountMintInstruction);\n}\n\nexport type ParsedInitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeScaledUiAmountMintInstructionData;\n};\n\nexport function parseInitializeScaledUiAmountMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeScaledUiAmountMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeScaledUiAmountMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_DISCRIMINATOR = new Uint8Array([\n 121, 113, 108, 39, 54, 51, 0, 4,\n]);\n\nexport function getInitializeTokenGroupDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Update authority for the group */\n updateAuthority: Option
;\n /** The maximum number of group members */\n maxSize: bigint;\n};\n\nexport type InitializeTokenGroupInstructionDataArgs = {\n /** Update authority for the group */\n updateAuthority: OptionOrNullable
;\n /** The maximum number of group members */\n maxSize: number | bigint;\n};\n\nexport function getInitializeTokenGroupInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTokenGroupInstructionDataCodec(): Codec<\n InitializeTokenGroupInstructionDataArgs,\n InitializeTokenGroupInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupInstructionDataEncoder(),\n getInitializeTokenGroupInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupInput<\n TAccountGroup extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n group: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n updateAuthority: InitializeTokenGroupInstructionDataArgs['updateAuthority'];\n maxSize: InitializeTokenGroupInstructionDataArgs['maxSize'];\n};\n\nexport function getInitializeTokenGroupInstruction<\n TAccountGroup extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupInput<\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenGroupInstructionDataEncoder().encode(\n args as InitializeTokenGroupInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n mint: TAccountMetas[1];\n mintAuthority: TAccountMetas[2];\n };\n data: InitializeTokenGroupInstructionData;\n};\n\nexport function parseInitializeTokenGroupInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n group: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR = new Uint8Array([\n 152, 32, 222, 176, 223, 237, 116, 134,\n]);\n\nexport function getInitializeTokenGroupMemberDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMember extends string | AccountMeta = string,\n TAccountMemberMint extends string | AccountMeta = string,\n TAccountMemberMintAuthority extends string | AccountMeta = string,\n TAccountGroup extends string | AccountMeta = string,\n TAccountGroupUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMember extends string\n ? WritableAccount\n : TAccountMember,\n TAccountMemberMint extends string\n ? ReadonlyAccount\n : TAccountMemberMint,\n TAccountMemberMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMemberMintAuthority,\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountGroupUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupMemberInstructionData = {\n discriminator: ReadonlyUint8Array;\n};\n\nexport type InitializeTokenGroupMemberInstructionDataArgs = {};\n\nexport function getInitializeTokenGroupMemberInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getBytesEncoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataDecoder(): Decoder {\n return getStructDecoder([['discriminator', getBytesDecoder()]]);\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataCodec(): Codec<\n InitializeTokenGroupMemberInstructionDataArgs,\n InitializeTokenGroupMemberInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupMemberInstructionDataEncoder(),\n getInitializeTokenGroupMemberInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupMemberInput<\n TAccountMember extends string = string,\n TAccountMemberMint extends string = string,\n TAccountMemberMintAuthority extends string = string,\n TAccountGroup extends string = string,\n TAccountGroupUpdateAuthority extends string = string,\n> = {\n member: Address;\n memberMint: Address;\n memberMintAuthority: TransactionSigner;\n group: Address;\n groupUpdateAuthority: TransactionSigner;\n};\n\nexport function getInitializeTokenGroupMemberInstruction<\n TAccountMember extends string,\n TAccountMemberMint extends string,\n TAccountMemberMintAuthority extends string,\n TAccountGroup extends string,\n TAccountGroupUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupMemberInput<\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n member: { value: input.member ?? null, isWritable: true },\n memberMint: { value: input.memberMint ?? null, isWritable: false },\n memberMintAuthority: {\n value: input.memberMintAuthority ?? null,\n isWritable: false,\n },\n group: { value: input.group ?? null, isWritable: true },\n groupUpdateAuthority: {\n value: input.groupUpdateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.member),\n getAccountMeta(accounts.memberMint),\n getAccountMeta(accounts.memberMintAuthority),\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.groupUpdateAuthority),\n ],\n data: getInitializeTokenGroupMemberInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n member: TAccountMetas[0];\n memberMint: TAccountMetas[1];\n memberMintAuthority: TAccountMetas[2];\n group: TAccountMetas[3];\n groupUpdateAuthority: TAccountMetas[4];\n };\n data: InitializeTokenGroupMemberInstructionData;\n};\n\nexport function parseInitializeTokenGroupMemberInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupMemberInstruction {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n member: getNextAccount(),\n memberMint: getNextAccount(),\n memberMintAuthority: getNextAccount(),\n group: getNextAccount(),\n groupUpdateAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupMemberInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 210, 225, 30, 162, 88, 184, 77, 141,\n]);\n\nexport function getInitializeTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type InitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlyAccount\n : TAccountUpdateAuthority,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport type InitializeTokenMetadataInstructionDataArgs = {\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport function getInitializeTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_METADATA_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getInitializeTokenMetadataInstructionDataCodec(): Codec<\n InitializeTokenMetadataInstructionDataArgs,\n InitializeTokenMetadataInstructionData\n> {\n return combineCodec(\n getInitializeTokenMetadataInstructionDataEncoder(),\n getInitializeTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenMetadataInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n name: InitializeTokenMetadataInstructionDataArgs['name'];\n symbol: InitializeTokenMetadataInstructionDataArgs['symbol'];\n uri: InitializeTokenMetadataInstructionDataArgs['uri'];\n};\n\nexport function getInitializeTokenMetadataInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenMetadataInput<\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenMetadataInstructionDataEncoder().encode(\n args as InitializeTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n mint: TAccountMetas[2];\n mintAuthority: TAccountMetas[3];\n };\n data: InitializeTokenMetadataInstructionData;\n};\n\nexport function parseInitializeTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenMetadataInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n metadata: getNextAccount(),\n updateAuthority: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenMetadataInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR = 26;\n\nexport function getInitializeTransferFeeConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferFeeConfigTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferFeeConfigInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: Option
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: Option
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type InitializeTransferFeeConfigInstructionDataArgs = {\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: OptionOrNullable
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: OptionOrNullable
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getInitializeTransferFeeConfigInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeConfigAuthority', getOptionEncoder(getAddressEncoder())],\n ['withdrawWithheldAuthority', getOptionEncoder(getAddressEncoder())],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR,\n transferFeeDiscriminator:\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeConfigAuthority', getOptionDecoder(getAddressDecoder())],\n ['withdrawWithheldAuthority', getOptionDecoder(getAddressDecoder())],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataCodec(): Codec<\n InitializeTransferFeeConfigInstructionDataArgs,\n InitializeTransferFeeConfigInstructionData\n> {\n return combineCodec(\n getInitializeTransferFeeConfigInstructionDataEncoder(),\n getInitializeTransferFeeConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferFeeConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n transferFeeConfigAuthority: InitializeTransferFeeConfigInstructionDataArgs['transferFeeConfigAuthority'];\n withdrawWithheldAuthority: InitializeTransferFeeConfigInstructionDataArgs['withdrawWithheldAuthority'];\n transferFeeBasisPoints: InitializeTransferFeeConfigInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: InitializeTransferFeeConfigInstructionDataArgs['maximumFee'];\n};\n\nexport function getInitializeTransferFeeConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferFeeConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferFeeConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferFeeConfigInstructionDataEncoder().encode(\n args as InitializeTransferFeeConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferFeeConfigInstruction);\n}\n\nexport type ParsedInitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferFeeConfigInstructionData;\n};\n\nexport function parseInitializeTransferFeeConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferFeeConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferFeeConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getInitializeTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The public key for the account that can update the program id */\n authority: Option
;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type InitializeTransferHookInstructionDataArgs = {\n /** The public key for the account that can update the program id */\n authority: OptionOrNullable
;\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getInitializeTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeTransferHookInstructionDataCodec(): FixedSizeCodec<\n InitializeTransferHookInstructionDataArgs,\n InitializeTransferHookInstructionData\n> {\n return combineCodec(\n getInitializeTransferHookInstructionDataEncoder(),\n getInitializeTransferHookInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferHookInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeTransferHookInstructionDataArgs['authority'];\n programId: InitializeTransferHookInstructionDataArgs['programId'];\n };\n\nexport function getInitializeTransferHookInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferHookInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferHookInstructionDataEncoder().encode(\n args as InitializeTransferHookInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferHookInstruction);\n}\n\nexport type ParsedInitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferHookInstructionData;\n};\n\nexport function parseInitializeTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferHookInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const PAUSE_DISCRIMINATOR = 44;\n\nexport function getPauseDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_DISCRIMINATOR);\n}\n\nexport const PAUSE_PAUSABLE_DISCRIMINATOR = 1;\n\nexport function getPausePausableDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type PauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type PauseInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type PauseInstructionDataArgs = {};\n\nexport function getPauseInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: PAUSE_DISCRIMINATOR,\n pausableDiscriminator: PAUSE_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getPauseInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getPauseInstructionDataCodec(): FixedSizeCodec<\n PauseInstructionDataArgs,\n PauseInstructionData\n> {\n return combineCodec(\n getPauseInstructionDataEncoder(),\n getPauseInstructionDataDecoder()\n );\n}\n\nexport type PauseInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can pause the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getPauseInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: PauseInput,\n config?: { programAddress?: TProgramAddress }\n): PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getPauseInstructionDataEncoder().encode({}),\n programAddress,\n } as PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedPauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can pause the mint. */\n authority: TAccountMetas[1];\n };\n data: PauseInstructionData;\n};\n\nexport function parsePauseInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedPauseInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getPauseInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getExtensionTypeDecoder,\n getExtensionTypeEncoder,\n type ExtensionType,\n type ExtensionTypeArgs,\n} from '../types';\n\nexport const REALLOCATE_DISCRIMINATOR = 29;\n\nexport function getReallocateDiscriminatorBytes() {\n return getU8Encoder().encode(REALLOCATE_DISCRIMINATOR);\n}\n\nexport type ReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountPayer extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ReallocateInstructionData = {\n discriminator: number;\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport type ReallocateInstructionDataArgs = {\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport function getReallocateInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n [\n 'newExtensionTypes',\n getArrayEncoder(getExtensionTypeEncoder(), { size: 'remainder' }),\n ],\n ]),\n (value) => ({ ...value, discriminator: REALLOCATE_DISCRIMINATOR })\n );\n}\n\nexport function getReallocateInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n [\n 'newExtensionTypes',\n getArrayDecoder(getExtensionTypeDecoder(), { size: 'remainder' }),\n ],\n ]);\n}\n\nexport function getReallocateInstructionDataCodec(): Codec<\n ReallocateInstructionDataArgs,\n ReallocateInstructionData\n> {\n return combineCodec(\n getReallocateInstructionDataEncoder(),\n getReallocateInstructionDataDecoder()\n );\n}\n\nexport type ReallocateInput<\n TAccountToken extends string = string,\n TAccountPayer extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to reallocate. */\n token: Address;\n /** The payer account to fund reallocation. */\n payer: TransactionSigner;\n /** System program for reallocation funding. */\n systemProgram?: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n newExtensionTypes: ReallocateInstructionDataArgs['newExtensionTypes'];\n multiSigners?: Array;\n};\n\nexport function getReallocateInstruction<\n TAccountToken extends string,\n TAccountPayer extends string,\n TAccountSystemProgram extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ReallocateInput<\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n payer: { value: input.payer ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getReallocateInstructionDataEncoder().encode(\n args as ReallocateInstructionDataArgs\n ),\n programAddress,\n } as ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to reallocate. */\n token: TAccountMetas[0];\n /** The payer account to fund reallocation. */\n payer: TAccountMetas[1];\n /** System program for reallocation funding. */\n systemProgram: TAccountMetas[2];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ReallocateInstructionData;\n};\n\nexport function parseReallocateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedReallocateInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n payer: getNextAccount(),\n systemProgram: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getReallocateInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR = new Uint8Array([\n 234, 18, 32, 56, 89, 141, 37, 181,\n]);\n\nexport function getRemoveTokenMetadataKeyDiscriminatorBytes() {\n return getBytesEncoder().encode(REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR);\n}\n\nexport type RemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RemoveTokenMetadataKeyInstructionData = {\n discriminator: ReadonlyUint8Array;\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport type RemoveTokenMetadataKeyInstructionDataArgs = {\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent?: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport function getRemoveTokenMetadataKeyInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['idempotent', getBooleanEncoder()],\n ['key', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR,\n idempotent: value.idempotent ?? false,\n })\n );\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['idempotent', getBooleanDecoder()],\n ['key', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataCodec(): Codec<\n RemoveTokenMetadataKeyInstructionDataArgs,\n RemoveTokenMetadataKeyInstructionData\n> {\n return combineCodec(\n getRemoveTokenMetadataKeyInstructionDataEncoder(),\n getRemoveTokenMetadataKeyInstructionDataDecoder()\n );\n}\n\nexport type RemoveTokenMetadataKeyInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n idempotent?: RemoveTokenMetadataKeyInstructionDataArgs['idempotent'];\n key: RemoveTokenMetadataKeyInstructionDataArgs['key'];\n};\n\nexport function getRemoveTokenMetadataKeyInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RemoveTokenMetadataKeyInput,\n config?: { programAddress?: TProgramAddress }\n): RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getRemoveTokenMetadataKeyInstructionDataEncoder().encode(\n args as RemoveTokenMetadataKeyInstructionDataArgs\n ),\n programAddress,\n } as RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedRemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: RemoveTokenMetadataKeyInstructionData;\n};\n\nexport function parseRemoveTokenMetadataKeyInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRemoveTokenMetadataKeyInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getRemoveTokenMetadataKeyInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const RESUME_DISCRIMINATOR = 44;\n\nexport function getResumeDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_DISCRIMINATOR);\n}\n\nexport const RESUME_PAUSABLE_DISCRIMINATOR = 2;\n\nexport function getResumePausableDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type ResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ResumeInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type ResumeInstructionDataArgs = {};\n\nexport function getResumeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: RESUME_DISCRIMINATOR,\n pausableDiscriminator: RESUME_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getResumeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getResumeInstructionDataCodec(): FixedSizeCodec<\n ResumeInstructionDataArgs,\n ResumeInstructionData\n> {\n return combineCodec(\n getResumeInstructionDataEncoder(),\n getResumeInstructionDataDecoder()\n );\n}\n\nexport type ResumeInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can resume the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getResumeInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ResumeInput,\n config?: { programAddress?: TProgramAddress }\n): ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getResumeInstructionDataEncoder().encode({}),\n programAddress,\n } as ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can resume the mint. */\n authority: TAccountMetas[1];\n };\n data: ResumeInstructionData;\n};\n\nexport function parseResumeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedResumeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getResumeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SET_TRANSFER_FEE_DISCRIMINATOR = 26;\n\nexport function getSetTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport const SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getSetTransferFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport type SetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountTransferFeeConfigAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountTransferFeeConfigAuthority extends string\n ? ReadonlyAccount\n : TAccountTransferFeeConfigAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetTransferFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type SetTransferFeeInstructionDataArgs = {\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getSetTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_TRANSFER_FEE_DISCRIMINATOR,\n transferFeeDiscriminator: SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getSetTransferFeeInstructionDataCodec(): FixedSizeCodec<\n SetTransferFeeInstructionDataArgs,\n SetTransferFeeInstructionData\n> {\n return combineCodec(\n getSetTransferFeeInstructionDataEncoder(),\n getSetTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type SetTransferFeeInput<\n TAccountMint extends string = string,\n TAccountTransferFeeConfigAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority:\n | Address\n | TransactionSigner;\n transferFeeBasisPoints: SetTransferFeeInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: SetTransferFeeInstructionDataArgs['maximumFee'];\n multiSigners?: Array;\n};\n\nexport function getSetTransferFeeInstruction<\n TAccountMint extends string,\n TAccountTransferFeeConfigAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n transferFeeConfigAuthority: {\n value: input.transferFeeConfigAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.transferFeeConfigAuthority),\n ...remainingAccounts,\n ],\n data: getSetTransferFeeInstructionDataEncoder().encode(\n args as SetTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n >);\n}\n\nexport type ParsedSetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority: TAccountMetas[1];\n };\n data: SetTransferFeeInstructionData;\n};\n\nexport function parseSetTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetTransferFeeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n transferFeeConfigAuthority: getNextAccount(),\n },\n data: getSetTransferFeeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR = 26;\n\nexport function getTransferCheckedWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getTransferCheckedWithFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type TransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedWithFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: bigint;\n};\n\nexport type TransferCheckedWithFeeInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: number | bigint;\n};\n\nexport function getTransferCheckedWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['fee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR,\n transferFeeDiscriminator:\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getTransferCheckedWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['fee', getU64Decoder()],\n ]);\n}\n\nexport function getTransferCheckedWithFeeInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedWithFeeInstructionDataArgs,\n TransferCheckedWithFeeInstructionData\n> {\n return combineCodec(\n getTransferCheckedWithFeeInstructionDataEncoder(),\n getTransferCheckedWithFeeInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedWithFeeInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: Address;\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: Address;\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedWithFeeInstructionDataArgs['amount'];\n decimals: TransferCheckedWithFeeInstructionDataArgs['decimals'];\n fee: TransferCheckedWithFeeInstructionDataArgs['fee'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedWithFeeInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedWithFeeInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedWithFeeInstructionDataEncoder().encode(\n args as TransferCheckedWithFeeInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: TAccountMetas[0];\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[1];\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedWithFeeInstructionData;\n};\n\nexport function parseTransferCheckedWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedWithFeeInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getUpdateConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 1;\n\nexport function getUpdateConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type UpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type UpdateConfidentialTransferMintInstructionDataArgs = {\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getUpdateConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n UpdateConfidentialTransferMintInstructionDataArgs,\n UpdateConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getUpdateConfidentialTransferMintInstructionDataEncoder(),\n getUpdateConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateConfidentialTransferMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n autoApproveNewAccounts: UpdateConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: UpdateConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getUpdateConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getUpdateConfidentialTransferMintInstructionDataEncoder().encode(\n args as UpdateConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateConfidentialTransferMintInstructionData;\n};\n\nexport function parseUpdateConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateConfidentialTransferMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getUpdateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 1;\n\nexport function getUpdateDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type UpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFreezeAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFreezeAuthority extends string\n ? ReadonlyAccount\n : TAccountFreezeAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type UpdateDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getUpdateDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n UpdateDefaultAccountStateInstructionDataArgs,\n UpdateDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getUpdateDefaultAccountStateInstructionDataEncoder(),\n getUpdateDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type UpdateDefaultAccountStateInput<\n TAccountMint extends string = string,\n TAccountFreezeAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority:\n | Address\n | TransactionSigner;\n state: UpdateDefaultAccountStateInstructionDataArgs['state'];\n multiSigners?: Array;\n};\n\nexport function getUpdateDefaultAccountStateInstruction<\n TAccountMint extends string,\n TAccountFreezeAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n freezeAuthority: {\n value: input.freezeAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.freezeAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateDefaultAccountStateInstructionDataEncoder().encode(\n args as UpdateDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n >);\n}\n\nexport type ParsedUpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority: TAccountMetas[1];\n };\n data: UpdateDefaultAccountStateInstructionData;\n};\n\nexport function parseUpdateDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateDefaultAccountStateInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), freezeAuthority: getNextAccount() },\n data: getUpdateDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getUpdateGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupMemberPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupMemberPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupMemberPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The new account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type UpdateGroupMemberPointerInstructionDataArgs = {\n /** The new account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupMemberPointerInstructionDataArgs,\n UpdateGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupMemberPointerInstructionDataEncoder(),\n getUpdateGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupMemberPointerInput<\n TAccountMint extends string = string,\n TAccountGroupMemberPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority:\n | Address\n | TransactionSigner;\n memberAddress: UpdateGroupMemberPointerInstructionDataArgs['memberAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupMemberPointerInstruction<\n TAccountMint extends string,\n TAccountGroupMemberPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupMemberPointerInput<\n TAccountMint,\n TAccountGroupMemberPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupMemberPointerAuthority: {\n value: input.groupMemberPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupMemberPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupMemberPointerInstructionDataEncoder().encode(\n args as UpdateGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupMemberPointerInstructionData;\n};\n\nexport function parseUpdateGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupMemberPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupMemberPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getUpdateGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupPointerAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The new account address that holds the group configurations. */\n groupAddress: Option
;\n};\n\nexport type UpdateGroupPointerInstructionDataArgs = {\n /** The new account address that holds the group configurations. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupPointerInstructionDataArgs,\n UpdateGroupPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupPointerInstructionDataEncoder(),\n getUpdateGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupPointerInput<\n TAccountMint extends string = string,\n TAccountGroupPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority:\n | Address\n | TransactionSigner;\n groupAddress: UpdateGroupPointerInstructionDataArgs['groupAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupPointerInstruction<\n TAccountMint extends string,\n TAccountGroupPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupPointerAuthority: {\n value: input.groupPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupPointerInstructionDataEncoder().encode(\n args as UpdateGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupPointerInstructionData;\n};\n\nexport function parseUpdateGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getUpdateMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountMetadataPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountMetadataPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountMetadataPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The new account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type UpdateMetadataPointerInstructionDataArgs = {\n /** The new account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getUpdateMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateMetadataPointerInstructionDataArgs,\n UpdateMetadataPointerInstructionData\n> {\n return combineCodec(\n getUpdateMetadataPointerInstructionDataEncoder(),\n getUpdateMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateMetadataPointerInput<\n TAccountMint extends string = string,\n TAccountMetadataPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority:\n | Address\n | TransactionSigner;\n metadataAddress: UpdateMetadataPointerInstructionDataArgs['metadataAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMetadataPointerInstruction<\n TAccountMint extends string,\n TAccountMetadataPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMetadataPointerInput<\n TAccountMint,\n TAccountMetadataPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n metadataPointerAuthority: {\n value: input.metadataPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.metadataPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateMetadataPointerInstructionDataEncoder().encode(\n args as UpdateMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n >);\n}\n\nexport type ParsedUpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority: TAccountMetas[1];\n };\n data: UpdateMetadataPointerInstructionData;\n};\n\nexport function parseUpdateMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMetadataPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n metadataPointerAuthority: getNextAccount(),\n },\n data: getUpdateMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getF64Decoder,\n getF64Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR = 43;\n\nexport function getUpdateMultiplierScaledUiMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateMultiplierScaledUiMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? WritableAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMultiplierScaledUiMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: bigint;\n};\n\nexport type UpdateMultiplierScaledUiMintInstructionDataArgs = {\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: number | bigint;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n ['multiplier', getF64Encoder()],\n ['effectiveTimestamp', getI64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n ['multiplier', getF64Decoder()],\n ['effectiveTimestamp', getI64Decoder()],\n ]);\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataCodec(): FixedSizeCodec<\n UpdateMultiplierScaledUiMintInstructionDataArgs,\n UpdateMultiplierScaledUiMintInstructionData\n> {\n return combineCodec(\n getUpdateMultiplierScaledUiMintInstructionDataEncoder(),\n getUpdateMultiplierScaledUiMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The multiplier authority. */\n authority: Address | TransactionSigner;\n multiplier: UpdateMultiplierScaledUiMintInstructionDataArgs['multiplier'];\n effectiveTimestamp: UpdateMultiplierScaledUiMintInstructionDataArgs['effectiveTimestamp'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMultiplierScaledUiMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateMultiplierScaledUiMintInstructionDataEncoder().encode(\n args as UpdateMultiplierScaledUiMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The multiplier authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateMultiplierScaledUiMintInstructionData;\n};\n\nexport function parseUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMultiplierScaledUiMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateMultiplierScaledUiMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI16Decoder,\n getI16Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getUpdateRateInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateRateInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRateAuthority extends string\n ? WritableAccount\n : TAccountRateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateRateInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The interest rate to update. */\n rate: number;\n};\n\nexport type UpdateRateInterestBearingMintInstructionDataArgs = {\n /** The interest rate to update. */\n rate: number;\n};\n\nexport function getUpdateRateInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n UpdateRateInterestBearingMintInstructionDataArgs,\n UpdateRateInterestBearingMintInstructionData\n> {\n return combineCodec(\n getUpdateRateInterestBearingMintInstructionDataEncoder(),\n getUpdateRateInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateRateInterestBearingMintInput<\n TAccountMint extends string = string,\n TAccountRateAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint rate authority. */\n rateAuthority:\n | Address\n | TransactionSigner;\n rate: UpdateRateInterestBearingMintInstructionDataArgs['rate'];\n multiSigners?: Array;\n};\n\nexport function getUpdateRateInterestBearingMintInstruction<\n TAccountMint extends string,\n TAccountRateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateRateInterestBearingMintInput<\n TAccountMint,\n TAccountRateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rateAuthority: { value: input.rateAuthority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rateAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateRateInterestBearingMintInstructionDataEncoder().encode(\n args as UpdateRateInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n >);\n}\n\nexport type ParsedUpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint rate authority. */\n rateAuthority: TAccountMetas[1];\n };\n data: UpdateRateInterestBearingMintInstructionData;\n};\n\nexport function parseUpdateRateInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateRateInterestBearingMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rateAuthority: getNextAccount() },\n data: getUpdateRateInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR = new Uint8Array([\n 108, 37, 171, 143, 248, 30, 18, 110,\n]);\n\nexport function getUpdateTokenGroupMaxSizeDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR);\n}\n\nexport type UpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupMaxSizeInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New max size for the group */\n maxSize: bigint;\n};\n\nexport type UpdateTokenGroupMaxSizeInstructionDataArgs = {\n /** New max size for the group */\n maxSize: number | bigint;\n};\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataCodec(): Codec<\n UpdateTokenGroupMaxSizeInstructionDataArgs,\n UpdateTokenGroupMaxSizeInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupMaxSizeInstructionDataEncoder(),\n getUpdateTokenGroupMaxSizeInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupMaxSizeInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n updateAuthority: TransactionSigner;\n maxSize: UpdateTokenGroupMaxSizeInstructionDataArgs['maxSize'];\n};\n\nexport function getUpdateTokenGroupMaxSizeInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupMaxSizeInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupMaxSizeInstructionDataEncoder().encode(\n args as UpdateTokenGroupMaxSizeInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupMaxSizeInstructionData;\n};\n\nexport function parseUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupMaxSizeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupMaxSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR = new Uint8Array(\n [161, 105, 88, 1, 237, 221, 216, 203]\n);\n\nexport function getUpdateTokenGroupUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionDataArgs = {\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenGroupUpdateAuthorityInstructionDataArgs,\n UpdateTokenGroupUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n /** Current update authority */\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenGroupUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenGroupUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n /** Current update authority */\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupUpdateAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getTokenMetadataFieldDecoder,\n getTokenMetadataFieldEncoder,\n type TokenMetadataField,\n type TokenMetadataFieldArgs,\n} from '../types';\n\nexport const UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR = new Uint8Array([\n 221, 233, 49, 45, 181, 202, 220, 200,\n]);\n\nexport function getUpdateTokenMetadataFieldDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR);\n}\n\nexport type UpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataFieldInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Field to update in the metadata. */\n field: TokenMetadataField;\n /** Value to write for the field. */\n value: string;\n};\n\nexport type UpdateTokenMetadataFieldInstructionDataArgs = {\n /** Field to update in the metadata. */\n field: TokenMetadataFieldArgs;\n /** Value to write for the field. */\n value: string;\n};\n\nexport function getUpdateTokenMetadataFieldInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['field', getTokenMetadataFieldEncoder()],\n ['value', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['field', getTokenMetadataFieldDecoder()],\n ['value', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataCodec(): Codec<\n UpdateTokenMetadataFieldInstructionDataArgs,\n UpdateTokenMetadataFieldInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataFieldInstructionDataEncoder(),\n getUpdateTokenMetadataFieldInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataFieldInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n field: UpdateTokenMetadataFieldInstructionDataArgs['field'];\n value: UpdateTokenMetadataFieldInstructionDataArgs['value'];\n};\n\nexport function getUpdateTokenMetadataFieldInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataFieldInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataFieldInstructionDataEncoder().encode(\n args as UpdateTokenMetadataFieldInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataFieldInstructionData;\n};\n\nexport function parseUpdateTokenMetadataFieldInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataFieldInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataFieldInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR =\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]);\n\nexport function getUpdateTokenMetadataUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionDataArgs = {\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenMetadataUpdateAuthorityInstructionDataArgs,\n UpdateTokenMetadataUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenMetadataUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenMetadataUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getUpdateTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 1;\n\nexport function getUpdateTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type UpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type UpdateTransferHookInstructionDataArgs = {\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getUpdateTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTransferHookInstructionDataCodec(): FixedSizeCodec<\n UpdateTransferHookInstructionDataArgs,\n UpdateTransferHookInstructionData\n> {\n return combineCodec(\n getUpdateTransferHookInstructionDataEncoder(),\n getUpdateTransferHookInstructionDataDecoder()\n );\n}\n\nexport type UpdateTransferHookInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The transfer hook authority. */\n authority: Address | TransactionSigner;\n programId: UpdateTransferHookInstructionDataArgs['programId'];\n multiSigners?: Array;\n};\n\nexport function getUpdateTransferHookInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateTransferHookInstructionDataEncoder().encode(\n args as UpdateTransferHookInstructionDataArgs\n ),\n programAddress,\n } as UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The transfer hook authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateTransferHookInstructionData;\n};\n\nexport function parseUpdateTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTransferHookInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR = 38;\n\nexport function getWithdrawExcessLamportsDiscriminatorBytes() {\n return getU8Encoder().encode(WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR);\n}\n\nexport type WithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceAccount extends string | AccountMeta = string,\n TAccountDestinationAccount extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceAccount extends string\n ? WritableAccount\n : TAccountSourceAccount,\n TAccountDestinationAccount extends string\n ? WritableAccount\n : TAccountDestinationAccount,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawExcessLamportsInstructionData = { discriminator: number };\n\nexport type WithdrawExcessLamportsInstructionDataArgs = {};\n\nexport function getWithdrawExcessLamportsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawExcessLamportsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getWithdrawExcessLamportsInstructionDataCodec(): FixedSizeCodec<\n WithdrawExcessLamportsInstructionDataArgs,\n WithdrawExcessLamportsInstructionData\n> {\n return combineCodec(\n getWithdrawExcessLamportsInstructionDataEncoder(),\n getWithdrawExcessLamportsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawExcessLamportsInput<\n TAccountSourceAccount extends string = string,\n TAccountDestinationAccount extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** Account holding excess lamports. */\n sourceAccount: Address;\n /** Destination account for withdrawn lamports. */\n destinationAccount: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawExcessLamportsInstruction<\n TAccountSourceAccount extends string,\n TAccountDestinationAccount extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawExcessLamportsInput<\n TAccountSourceAccount,\n TAccountDestinationAccount,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceAccount: { value: input.sourceAccount ?? null, isWritable: true },\n destinationAccount: {\n value: input.destinationAccount ?? null,\n isWritable: true,\n },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceAccount),\n getAccountMeta(accounts.destinationAccount),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawExcessLamportsInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Account holding excess lamports. */\n sourceAccount: TAccountMetas[0];\n /** Destination account for withdrawn lamports. */\n destinationAccount: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: WithdrawExcessLamportsInstructionData;\n};\n\nexport function parseWithdrawExcessLamportsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawExcessLamportsInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceAccount: getNextAccount(),\n destinationAccount: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawExcessLamportsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromAccountsDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getWithdrawWithheldTokensFromAccountsTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport type WithdrawWithheldTokensFromAccountsInstructionDataArgs = {\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsInstructionDataArgs['numTokenAccounts'];\n multiSigners?: Array;\n sources: Array
;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = [\n ...(args.multiSigners ?? []).map((signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })),\n ...args.sources.map((address) => ({ address, role: AccountRole.WRITABLE })),\n ];\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromAccountsInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['numTokenAccounts'];\n proofInstructionOffset: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type WithdrawWithheldTokensFromMintInstructionDataArgs = {};\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintInstructionDataArgs,\n WithdrawWithheldTokensFromMintInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromMintInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account if proof is read from record */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n proofInstructionOffset: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account if proof is read from record */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","import {\n type GetAccountInfoApi,\n type Rpc,\n Address,\n UnixTimestamp,\n unwrapOption,\n} from '@solana/kit';\nimport { fetchSysvarClock } from '@solana/sysvars';\nimport { fetchMint } from './generated';\n\n// Constants\nconst ONE_IN_BASIS_POINTS = 10000;\nconst SECONDS_PER_YEAR = 60 * 60 * 24 * 365.24;\n\n/**\n * Calculates the exponent for the interest rate formula.\n * @param t1 - The start time in seconds.\n * @param t2 - The end time in seconds.\n * @param r - The interest rate in basis points.\n *\n * @returns The calculated exponent.\n */\nfunction calculateExponentForTimesAndRate(t1: number, t2: number, r: number) {\n const timespan = t2 - t1;\n if (timespan < 0) {\n throw new Error('Invalid timespan: end time before start time');\n }\n\n const numerator = r * timespan;\n const exponent = numerator / (SECONDS_PER_YEAR * ONE_IN_BASIS_POINTS);\n return Math.exp(exponent);\n}\n\n/**\n * Calculates the total scale factor for an interest bearing token by combining two exponential functions:\n * One for the period between initialization and last update using the pre-update average rate,\n * and another for the period between last update and current time using the current rate.\n *\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points before last update\n * @param currentRate Current interest rate in basis points\n *\n * @returns The total scale factor as a product of the two exponential functions\n */\nfunction calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n}: {\n currentTimestamp: number;\n lastUpdateTimestamp: number;\n initializationTimestamp: number;\n preUpdateAverageRate: number;\n currentRate: number;\n}): number {\n // Calculate pre-update exponent\n const preUpdateExp = calculateExponentForTimesAndRate(\n initializationTimestamp,\n lastUpdateTimestamp,\n preUpdateAverageRate\n );\n\n // Calculate post-update exponent\n const postUpdateExp = calculateExponentForTimesAndRate(\n lastUpdateTimestamp,\n currentTimestamp,\n currentRate\n );\n\n return preUpdateExp * postUpdateExp;\n}\n\n/**\n * Calculates the decimal factor for a given number of decimals\n * @param decimals - Number of decimals\n * @returns The decimal factor (e.g., 100 for 2 decimals)\n */\nfunction getDecimalFactor(decimals: number): number {\n return Math.pow(10, decimals);\n}\n\n/**\n * Retrieves the current timestamp from the Solana clock sysvar.\n * @param rpc - The Solana rpc object.\n * @returns A promise that resolves to the current timestamp in seconds.\n * @throws An error if the sysvar clock cannot be fetched or parsed.\n */\nasync function getSysvarClockTimestamp(\n rpc: Rpc\n): Promise {\n const info = await fetchSysvarClock(rpc);\n if (!info) {\n throw new Error('Failed to fetch sysvar clock');\n }\n return info.unixTimestamp;\n}\n\n// ========== INTEREST BEARING MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with interest bearing extension without simulating a transaction\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n * In general to calculate compounding interest over a period of time, the formula is:\n * A = P * e^(r * t) where\n * A = final amount after interest\n * P = principal amount (initial investment)\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n * e = mathematical constant (~2.718)\n *\n * In this case, we are calculating the total scale factor for the interest bearing extension which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 and r2 are the interest rates before and after the last update, and t1 and t2 are the times in years between\n * the initialization timestamp and the last update timestamp, and between the last update timestamp and the current timestamp.\n *\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (1 basis point = 0.01%) before last update\n * @param currentRate Current interest rate in basis points\n *\n * @return Amount scaled by accrued interest as a string with appropriate decimal places\n */\nexport function amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): string {\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Scale the amount by the total interest factor\n const scaledAmount = Number(amount) * totalScale;\n const decimalFactor = getDecimalFactor(decimals);\n\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert an amount with interest back to the original amount without interest\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n *\n * @param uiAmount UI Amount (principal plus continuously compounding interest) to be converted back to original principal\n * @param decimals Number of decimals for the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (hundredths of a percent) before the last update\n * @param currentRate Current interest rate in basis points\n *\n * In general to calculate the principal from the UI amount, the formula is:\n * P = A / (e^(r * t)) where\n * P = principal\n * A = UI amount\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n *\n * In this case, we are calculating the principal by dividing the UI amount by the total scale factor which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 is the pre-update average rate, r2 is the current rate, t1 is the time in years between the initialization timestamp and the last update timestamp,\n * and t2 is the time in years between the last update timestamp and the current timestamp.\n * then to calculate the principal, we divide the UI amount by the total scale factor:\n * P = A / totalScale\n *\n * @return Original amount (principal) without interest\n */\nexport function uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Calculate original principal by dividing the UI amount by the total scale\n const originalPrincipal = uiAmountScaled / totalScale;\n return BigInt(Math.trunc(originalPrincipal));\n}\n\n// ========== SCALED UI AMOUNT MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with scaled UI amount extension\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param multiplier Multiplier to scale the amount\n * @return Scaled UI amount as a string\n */\nexport function amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n multiplier: number\n): string {\n const scaledAmount = Number(amount) * multiplier;\n const decimalFactor = getDecimalFactor(decimals);\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert a UI amount back to the raw amount for a mint with a scaled UI amount extension\n * @param uiAmount UI Amount to be converted back to raw amount\n * @param decimals Number of decimals for the mint\n * @param multiplier Multiplier for the scaled UI amount\n *\n * @return Raw amount\n */\nexport function uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n multiplier: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n const rawAmount = uiAmountScaled / multiplier;\n return BigInt(Math.trunc(rawAmount));\n}\n\n// ========== MAIN ENTRY POINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint without simulating a transaction\n * This implements the same logic as `process_amount_to_ui_amount` in\n * solana-labs/solana-program-library/token/program-2022/src/processor.rs\n * and `process_amount_to_ui_amount` in solana-labs/solana-program-library/token/program/src/processor.rs\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param amount Amount of tokens to be converted to Ui Amount\n *\n * @return Ui Amount generated\n */\nexport async function amountToUiAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n amount: bigint\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const amountNumber = Number(amount);\n const decimalsFactor = getDecimalFactor(accountInfo.data.decimals);\n return (amountNumber / decimalsFactor).toString();\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n\n/**\n * Convert a UI amount back to the raw amount\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param uiAmount UI Amount to be converted back to raw amount\n *\n * @return Raw amount\n */\nexport async function uiAmountToAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n uiAmount: string\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const uiAmountScaled =\n parseFloat(uiAmount) * getDecimalFactor(accountInfo.data.decimals);\n return BigInt(Math.trunc(uiAmountScaled));\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n","import {\n Address,\n Instruction,\n isNone,\n isOption,\n TransactionSigner,\n wrapNullable,\n} from '@solana/kit';\nimport {\n ExtensionArgs,\n getDisableMemoTransfersInstruction,\n getEnableMemoTransfersInstruction,\n getEnableCpiGuardInstruction,\n getDisableCpiGuardInstruction,\n getInitializeConfidentialTransferMintInstruction,\n getInitializeDefaultAccountStateInstruction,\n getInitializeGroupMemberPointerInstruction,\n getInitializeGroupPointerInstruction,\n getInitializeInterestBearingMintInstruction,\n getInitializeMetadataPointerInstruction,\n getInitializeMintCloseAuthorityInstruction,\n getInitializeTokenGroupInstruction,\n getInitializeTokenMetadataInstruction,\n getInitializeTransferFeeConfigInstruction,\n getInitializeNonTransferableMintInstruction,\n getInitializeTransferHookInstruction,\n getInitializePermanentDelegateInstruction,\n getInitializeScaledUiAmountMintInstruction,\n getInitializeConfidentialTransferFeeInstruction,\n getInitializePausableConfigInstruction,\n} from './generated';\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _before_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPreInitializeInstructionsForMintExtensions(\n mint: Address,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'ConfidentialTransferMint':\n return [\n getInitializeConfidentialTransferMintInstruction({\n mint,\n ...extension,\n }),\n ];\n case 'DefaultAccountState':\n return [\n getInitializeDefaultAccountStateInstruction({\n mint,\n state: extension.state,\n }),\n ];\n case 'TransferFeeConfig':\n return [\n getInitializeTransferFeeConfigInstruction({\n mint,\n transferFeeConfigAuthority: extension.transferFeeConfigAuthority,\n withdrawWithheldAuthority: extension.withdrawWithheldAuthority,\n transferFeeBasisPoints:\n extension.newerTransferFee.transferFeeBasisPoints,\n maximumFee: extension.newerTransferFee.maximumFee,\n }),\n ];\n case 'MetadataPointer':\n return [\n getInitializeMetadataPointerInstruction({\n mint,\n authority: extension.authority,\n metadataAddress: extension.metadataAddress,\n }),\n ];\n case 'InterestBearingConfig':\n return [\n getInitializeInterestBearingMintInstruction({\n mint,\n rateAuthority: extension.rateAuthority,\n rate: extension.currentRate,\n }),\n ];\n case 'ScaledUiAmountConfig':\n return [\n getInitializeScaledUiAmountMintInstruction({\n mint,\n authority: extension.authority,\n multiplier: extension.multiplier,\n }),\n ];\n case 'PausableConfig':\n return [\n getInitializePausableConfigInstruction({\n mint,\n authority: extension.authority,\n }),\n ];\n case 'GroupPointer':\n return [\n getInitializeGroupPointerInstruction({\n mint,\n authority: extension.authority,\n groupAddress: extension.groupAddress,\n }),\n ];\n case 'GroupMemberPointer':\n return [\n getInitializeGroupMemberPointerInstruction({\n mint,\n authority: extension.authority,\n memberAddress: extension.memberAddress,\n }),\n ];\n case 'NonTransferable':\n return getInitializeNonTransferableMintInstruction({ mint });\n case 'TransferHook':\n return [\n getInitializeTransferHookInstruction({\n mint,\n authority: extension.authority,\n programId: extension.programId,\n }),\n ];\n case 'PermanentDelegate':\n return getInitializePermanentDelegateInstruction({\n mint,\n delegate: extension.delegate,\n });\n case 'ConfidentialTransferFee':\n return [\n getInitializeConfidentialTransferFeeInstruction({\n mint,\n authority: extension.authority,\n withdrawWithheldAuthorityElGamalPubkey: extension.elgamalPubkey,\n }),\n ];\n case 'MintCloseAuthority':\n return getInitializeMintCloseAuthorityInstruction({\n closeAuthority: extension.closeAuthority,\n mint,\n });\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _after_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPostInitializeInstructionsForMintExtensions(\n mint: Address,\n authority: TransactionSigner,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension): Instruction[] => {\n switch (extension.__kind) {\n case 'TokenMetadata':\n // eslint-disable-next-line no-case-declarations\n const tokenMetadataUpdateAuthority = isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority);\n if (isNone(tokenMetadataUpdateAuthority)) {\n return [];\n }\n return [\n getInitializeTokenMetadataInstruction({\n metadata: mint,\n updateAuthority: tokenMetadataUpdateAuthority.value,\n mint,\n mintAuthority: authority,\n name: extension.name,\n symbol: extension.symbol,\n uri: extension.uri,\n }),\n ];\n case 'TokenGroup':\n return [\n getInitializeTokenGroupInstruction({\n group: mint,\n updateAuthority: isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority),\n mint,\n mintAuthority: authority,\n maxSize: extension.maxSize,\n }),\n ];\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a token address, its owner and a list of token extensions, returns a list\n * of instructions that MUST be run _after_ the `initializeAccount` instruction\n * to properly initialize the given extensions on the token account.\n */\nexport function getPostInitializeInstructionsForTokenExtensions(\n token: Address,\n owner: TransactionSigner | Address,\n extensions: ExtensionArgs[],\n multiSigners?: TransactionSigner[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'MemoTransfer':\n return [\n extension.requireIncomingTransferMemos\n ? getEnableMemoTransfersInstruction({ owner, token, multiSigners })\n : getDisableMemoTransfersInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n case 'CpiGuard':\n return [\n extension.lockCpi\n ? getEnableCpiGuardInstruction({ owner, token, multiSigners })\n : getDisableCpiGuardInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n default:\n return [];\n }\n });\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst TOKEN_BASE_SIZE = 165;\n\nexport function getTokenSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return TOKEN_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n );\n return TOKEN_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n padLeftEncoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst MINT_BASE_SIZE = 82;\n\nexport function getMintSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return MINT_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n );\n return MINT_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","/**\n * Token program addresses for SPL Token and Token-2022\n * These addresses are the same across all Solana networks (mainnet, devnet, testnet)\n */\nexport const TOKEN_PROGRAM_ADDRESS = \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\";\nexport const TOKEN_2022_PROGRAM_ADDRESS = \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\";\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS = \"ComputeBudget111111111111111111111111111111\";\nexport const MEMO_PROGRAM_ADDRESS = \"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\";\n\n/**\n * Phantom/Solflare Lighthouse program address\n * Phantom and Solflare wallets inject Lighthouse instructions for user protection on mainnet transactions.\n * - Phantom adds 1 Lighthouse instruction (4th instruction)\n * - Solflare adds 2 Lighthouse instructions (4th and 5th instructions)\n * We allow these as optional instructions to support these wallets.\n * See: https://github.com/coinbase/x402/issues/828\n */\nexport const LIGHTHOUSE_PROGRAM_ADDRESS = \"L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95\";\n\n/**\n * Default RPC URLs for Solana networks\n */\nexport const DEVNET_RPC_URL = \"https://api.devnet.solana.com\";\nexport const TESTNET_RPC_URL = \"https://api.testnet.solana.com\";\nexport const MAINNET_RPC_URL = \"https://api.mainnet-beta.solana.com\";\nexport const DEVNET_WS_URL = \"wss://api.devnet.solana.com\";\nexport const TESTNET_WS_URL = \"wss://api.testnet.solana.com\";\nexport const MAINNET_WS_URL = \"wss://api.mainnet-beta.solana.com\";\n\n/**\n * USDC token mint addresses (default stablecoin)\n */\nexport const USDC_MAINNET_ADDRESS = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nexport const USDC_DEVNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\";\nexport const USDC_TESTNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\"; // Same as devnet\n\n/**\n * Compute budget configuration\n * All prices are in microlamports (1 lamport = 1,000,000 microlamports)\n */\nexport const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;\nexport const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 5_000_000; // 5 lamports\nexport const DEFAULT_COMPUTE_UNIT_LIMIT = 20_000;\n\n/**\n * How long a transaction is held in the duplicate settlement cache (ms).\n * Covers the Solana blockhash lifetime (~60-90s) with margin.\n */\nexport const SETTLEMENT_TTL_MS = 120_000;\n\n/**\n * Solana address validation regex (base58, 32-44 characters)\n */\nexport const SVM_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * CAIP-2 network identifiers for Solana (V2)\n */\nexport const SOLANA_MAINNET_CAIP2 = \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\";\nexport const SOLANA_DEVNET_CAIP2 = \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\";\nexport const SOLANA_TESTNET_CAIP2 = \"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z\";\n\n/**\n * V1 to V2 network identifier mappings (for backwards compatibility)\n * V1 used simple names like solana, V2 uses CAIP-2\n */\nexport const V1_TO_V2_NETWORK_MAP: Record = {\n solana: SOLANA_MAINNET_CAIP2,\n \"solana-devnet\": SOLANA_DEVNET_CAIP2,\n \"solana-testnet\": SOLANA_TESTNET_CAIP2,\n};\n","import {\n getBase64Encoder,\n getTransactionDecoder,\n getCompiledTransactionMessageDecoder,\n type Transaction,\n createSolanaRpc,\n devnet,\n testnet,\n mainnet,\n type RpcDevnet,\n type SolanaRpcApiDevnet,\n type RpcTestnet,\n type SolanaRpcApiTestnet,\n type RpcMainnet,\n type SolanaRpcApiMainnet,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { TOKEN_2022_PROGRAM_ADDRESS } from \"@solana-program/token-2022\";\nimport type { Network } from \"@x402/core/types\";\nimport {\n SVM_ADDRESS_REGEX,\n DEVNET_RPC_URL,\n TESTNET_RPC_URL,\n MAINNET_RPC_URL,\n USDC_MAINNET_ADDRESS,\n USDC_DEVNET_ADDRESS,\n USDC_TESTNET_ADDRESS,\n SOLANA_MAINNET_CAIP2,\n SOLANA_DEVNET_CAIP2,\n SOLANA_TESTNET_CAIP2,\n V1_TO_V2_NETWORK_MAP,\n} from \"./constants\";\nimport type { ExactSvmPayloadV1 } from \"./types\";\n\n/**\n * Normalize network identifier to CAIP-2 format\n * Handles both V1 names (solana, solana-devnet) and V2 CAIP-2 format\n *\n * @param network - Network identifier (V1 or V2 format)\n * @returns CAIP-2 network identifier\n */\nexport function normalizeNetwork(network: Network): string {\n // If it's already CAIP-2 format (contains \":\"), validate it's supported\n if (network.includes(\":\")) {\n const supported = [SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];\n if (!supported.includes(network)) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return network;\n }\n\n // Otherwise, it's a V1 network name, convert to CAIP-2\n const caip2Network = V1_TO_V2_NETWORK_MAP[network];\n if (!caip2Network) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return caip2Network;\n}\n\n/**\n * Validate Solana address format\n *\n * @param address - Base58 encoded address string\n * @returns true if address is valid, false otherwise\n */\nexport function validateSvmAddress(address: string): boolean {\n return SVM_ADDRESS_REGEX.test(address);\n}\n\n/**\n * Decode a base64 encoded transaction from an SVM payload\n *\n * @param svmPayload - The SVM payload containing a base64 encoded transaction\n * @returns Decoded Transaction object\n */\nexport function decodeTransactionFromPayload(svmPayload: ExactSvmPayloadV1): Transaction {\n try {\n const base64Encoder = getBase64Encoder();\n const transactionBytes = base64Encoder.encode(svmPayload.transaction);\n const transactionDecoder = getTransactionDecoder();\n return transactionDecoder.decode(transactionBytes);\n } catch (error) {\n console.error(\"Error decoding transaction:\", error);\n throw new Error(\"invalid_exact_svm_payload_transaction\");\n }\n}\n\n/**\n * Extract the token sender (owner of the source token account) from a TransferChecked instruction\n *\n * @param transaction - The decoded transaction\n * @returns The token payer address as a base58 string\n */\nexport function getTokenPayerFromTransaction(transaction: Transaction): string {\n const compiled = getCompiledTransactionMessageDecoder().decode(transaction.messageBytes);\n const staticAccounts = compiled.staticAccounts ?? [];\n const instructions = compiled.instructions ?? [];\n\n for (const ix of instructions) {\n const programIndex = ix.programAddressIndex;\n const programAddress = staticAccounts[programIndex].toString();\n\n // Check if this is a token program instruction\n if (\n programAddress === TOKEN_PROGRAM_ADDRESS.toString() ||\n programAddress === TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n const accountIndices: number[] = ix.accountIndices ?? [];\n // TransferChecked account order: [source, mint, destination, owner, ...]\n if (accountIndices.length >= 4) {\n const ownerIndex = accountIndices[3];\n const ownerAddress = staticAccounts[ownerIndex].toString();\n if (ownerAddress) return ownerAddress;\n }\n }\n }\n\n return \"\";\n}\n\n/**\n * Create an RPC client for the specified network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @param customRpcUrl - Optional custom RPC URL\n * @returns RPC client for the specified network\n */\nexport function createRpcClient(\n network: Network,\n customRpcUrl?: string,\n):\n | RpcDevnet\n | RpcTestnet\n | RpcMainnet {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_DEVNET_CAIP2: {\n const url = customRpcUrl || DEVNET_RPC_URL;\n return createSolanaRpc(devnet(url)) as RpcDevnet;\n }\n case SOLANA_TESTNET_CAIP2: {\n const url = customRpcUrl || TESTNET_RPC_URL;\n return createSolanaRpc(testnet(url)) as RpcTestnet;\n }\n case SOLANA_MAINNET_CAIP2: {\n const url = customRpcUrl || MAINNET_RPC_URL;\n return createSolanaRpc(mainnet(url)) as RpcMainnet;\n }\n default:\n throw new Error(`Unsupported network: ${network}`);\n }\n}\n\n/**\n * Get the default USDC mint address for a network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @returns USDC mint address for the network\n */\nexport function getUsdcAddress(network: Network): string {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_MAINNET_CAIP2:\n return USDC_MAINNET_ADDRESS;\n case SOLANA_DEVNET_CAIP2:\n return USDC_DEVNET_ADDRESS;\n case SOLANA_TESTNET_CAIP2:\n return USDC_TESTNET_ADDRESS;\n default:\n throw new Error(`No USDC address configured for network: ${network}`);\n }\n}\n\n/**\n * Convert a decimal amount to token smallest units\n *\n * @param decimalAmount - The decimal amount (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n const amount = parseFloat(decimalAmount);\n if (isNaN(amount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n // Convert to smallest unit (e.g., for USDC with 6 decimals: 0.10 * 10^6 = 100000)\n const [intPart, decPart = \"\"] = String(amount).split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n return tokenAmount;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedRequestHeapFrameInstruction,\n type ParsedRequestUnitsInstruction,\n type ParsedSetComputeUnitLimitInstruction,\n type ParsedSetComputeUnitPriceInstruction,\n type ParsedSetLoadedAccountsDataSizeLimitInstruction,\n} from '../instructions';\n\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS =\n 'ComputeBudget111111111111111111111111111111' as Address<'ComputeBudget111111111111111111111111111111'>;\n\nexport enum ComputeBudgetInstruction {\n RequestUnits,\n RequestHeapFrame,\n SetComputeUnitLimit,\n SetComputeUnitPrice,\n SetLoadedAccountsDataSizeLimit,\n}\n\nexport function identifyComputeBudgetInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ComputeBudgetInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return ComputeBudgetInstruction.RequestUnits;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return ComputeBudgetInstruction.RequestHeapFrame;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitLimit;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitPrice;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n }\n throw new Error(\n 'The provided instruction could not be identified as a computeBudget instruction.'\n );\n}\n\nexport type ParsedComputeBudgetInstruction<\n TProgram extends string = 'ComputeBudget111111111111111111111111111111',\n> =\n | ({\n instructionType: ComputeBudgetInstruction.RequestUnits;\n } & ParsedRequestUnitsInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.RequestHeapFrame;\n } & ParsedRequestHeapFrameInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitLimit;\n } & ParsedSetComputeUnitLimitInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitPrice;\n } & ParsedSetComputeUnitPriceInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n } & ParsedSetLoadedAccountsDataSizeLimitInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_HEAP_FRAME_DISCRIMINATOR = 1;\n\nexport function getRequestHeapFrameDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_HEAP_FRAME_DISCRIMINATOR);\n}\n\nexport type RequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestHeapFrameInstructionData = {\n discriminator: number;\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport type RequestHeapFrameInstructionDataArgs = {\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport function getRequestHeapFrameInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['bytes', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_HEAP_FRAME_DISCRIMINATOR })\n );\n}\n\nexport function getRequestHeapFrameInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['bytes', getU32Decoder()],\n ]);\n}\n\nexport function getRequestHeapFrameInstructionDataCodec(): FixedSizeCodec<\n RequestHeapFrameInstructionDataArgs,\n RequestHeapFrameInstructionData\n> {\n return combineCodec(\n getRequestHeapFrameInstructionDataEncoder(),\n getRequestHeapFrameInstructionDataDecoder()\n );\n}\n\nexport type RequestHeapFrameInput = {\n bytes: RequestHeapFrameInstructionDataArgs['bytes'];\n};\n\nexport function getRequestHeapFrameInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestHeapFrameInput,\n config?: { programAddress?: TProgramAddress }\n): RequestHeapFrameInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestHeapFrameInstructionDataEncoder().encode(\n args as RequestHeapFrameInstructionDataArgs\n ),\n programAddress,\n } as RequestHeapFrameInstruction);\n}\n\nexport type ParsedRequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: RequestHeapFrameInstructionData;\n};\n\nexport function parseRequestHeapFrameInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestHeapFrameInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestHeapFrameInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_UNITS_DISCRIMINATOR = 0;\n\nexport function getRequestUnitsDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_UNITS_DISCRIMINATOR);\n}\n\nexport type RequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestUnitsInstructionData = {\n discriminator: number;\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport type RequestUnitsInstructionDataArgs = {\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport function getRequestUnitsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ['additionalFee', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_UNITS_DISCRIMINATOR })\n );\n}\n\nexport function getRequestUnitsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ['additionalFee', getU32Decoder()],\n ]);\n}\n\nexport function getRequestUnitsInstructionDataCodec(): FixedSizeCodec<\n RequestUnitsInstructionDataArgs,\n RequestUnitsInstructionData\n> {\n return combineCodec(\n getRequestUnitsInstructionDataEncoder(),\n getRequestUnitsInstructionDataDecoder()\n );\n}\n\nexport type RequestUnitsInput = {\n units: RequestUnitsInstructionDataArgs['units'];\n additionalFee: RequestUnitsInstructionDataArgs['additionalFee'];\n};\n\nexport function getRequestUnitsInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestUnitsInput,\n config?: { programAddress?: TProgramAddress }\n): RequestUnitsInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestUnitsInstructionDataEncoder().encode(\n args as RequestUnitsInstructionDataArgs\n ),\n programAddress,\n } as RequestUnitsInstruction);\n}\n\nexport type ParsedRequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = { programAddress: Address; data: RequestUnitsInstructionData };\n\nexport function parseRequestUnitsInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestUnitsInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestUnitsInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR = 2;\n\nexport function getSetComputeUnitLimitDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitLimitInstructionData = {\n discriminator: number;\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport type SetComputeUnitLimitInstructionDataArgs = {\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport function getSetComputeUnitLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitLimitInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitLimitInstructionDataArgs,\n SetComputeUnitLimitInstructionData\n> {\n return combineCodec(\n getSetComputeUnitLimitInstructionDataEncoder(),\n getSetComputeUnitLimitInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitLimitInput = {\n units: SetComputeUnitLimitInstructionDataArgs['units'];\n};\n\nexport function getSetComputeUnitLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitLimitInstructionDataEncoder().encode(\n args as SetComputeUnitLimitInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitLimitInstruction);\n}\n\nexport type ParsedSetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitLimitInstructionData;\n};\n\nexport function parseSetComputeUnitLimitInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR = 3;\n\nexport function getSetComputeUnitPriceDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitPriceInstructionData = {\n discriminator: number;\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: bigint;\n};\n\nexport type SetComputeUnitPriceInstructionDataArgs = {\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: number | bigint;\n};\n\nexport function getSetComputeUnitPriceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['microLamports', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitPriceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['microLamports', getU64Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitPriceInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitPriceInstructionDataArgs,\n SetComputeUnitPriceInstructionData\n> {\n return combineCodec(\n getSetComputeUnitPriceInstructionDataEncoder(),\n getSetComputeUnitPriceInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitPriceInput = {\n microLamports: SetComputeUnitPriceInstructionDataArgs['microLamports'];\n};\n\nexport function getSetComputeUnitPriceInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitPriceInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitPriceInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitPriceInstructionDataEncoder().encode(\n args as SetComputeUnitPriceInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitPriceInstruction);\n}\n\nexport type ParsedSetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitPriceInstructionData;\n};\n\nexport function parseSetComputeUnitPriceInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitPriceInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitPriceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR = 4;\n\nexport function getSetLoadedAccountsDataSizeLimitDiscriminatorBytes() {\n return getU8Encoder().encode(\n SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetLoadedAccountsDataSizeLimitInstructionData = {\n discriminator: number;\n accountDataSizeLimit: number;\n};\n\nexport type SetLoadedAccountsDataSizeLimitInstructionDataArgs = {\n accountDataSizeLimit: number;\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['accountDataSizeLimit', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['accountDataSizeLimit', getU32Decoder()],\n ]);\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataCodec(): FixedSizeCodec<\n SetLoadedAccountsDataSizeLimitInstructionDataArgs,\n SetLoadedAccountsDataSizeLimitInstructionData\n> {\n return combineCodec(\n getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(),\n getSetLoadedAccountsDataSizeLimitInstructionDataDecoder()\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInput = {\n accountDataSizeLimit: SetLoadedAccountsDataSizeLimitInstructionDataArgs['accountDataSizeLimit'];\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetLoadedAccountsDataSizeLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetLoadedAccountsDataSizeLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetLoadedAccountsDataSizeLimitInstructionDataEncoder().encode(\n args as SetLoadedAccountsDataSizeLimitInstructionDataArgs\n ),\n programAddress,\n } as SetLoadedAccountsDataSizeLimitInstruction);\n}\n\nexport type ParsedSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetLoadedAccountsDataSizeLimitInstructionData;\n};\n\nexport function parseSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string,\n>(\n instruction: Instruction & InstructionWithData\n): ParsedSetLoadedAccountsDataSizeLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetLoadedAccountsDataSizeLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * A provisory compute unit limit is used to indicate that the transaction\n * should be estimated for compute units before being sent to the network.\n *\n * Setting it to zero ensures the transaction fails unless it is properly estimated.\n */\nexport const PROVISORY_COMPUTE_UNIT_LIMIT = 0;\n\n/**\n * The maximum compute unit limit that can be set for a transaction.\n */\nexport const MAX_COMPUTE_UNIT_LIMIT = 1_400_000;\n","import {\n BaseTransactionMessage,\n getU32Decoder,\n getU64Decoder,\n Instruction,\n MicroLamports,\n ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n COMPUTE_BUDGET_PROGRAM_ADDRESS,\n ComputeBudgetInstruction,\n identifyComputeBudgetInstruction,\n SetComputeUnitLimitInstruction,\n SetComputeUnitPriceInstruction,\n} from './generated';\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message\n * and its set limit, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndexAndUnits(\n transactionMessage: BaseTransactionMessage\n): { index: number; units: number } | null {\n const index = getSetComputeUnitLimitInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const units = getU32Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n );\n\n return { index, units };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitLimitInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitLimit` instruction.\n */\nexport function isSetComputeUnitLimitInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitLimitInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitLimit\n );\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message\n * and its set micro-lamports, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndexAndMicroLamports(\n transactionMessage: BaseTransactionMessage\n): { index: number; microLamports: MicroLamports } | null {\n const index = getSetComputeUnitPriceInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const microLamports = getU64Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n ) as MicroLamports;\n\n return { index, microLamports };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitPriceInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitPrice` instruction.\n */\nexport function isSetComputeUnitPriceInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitPriceInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitPrice\n );\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n} from '@solana/kit';\nimport { PROVISORY_COMPUTE_UNIT_LIMIT } from './constants';\nimport { getSetComputeUnitLimitInstruction } from './generated';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\n\n/**\n * Appends a `SetComputeUnitLimit` instruction with a provisory\n * compute unit limit to a given transaction message\n * if and only if it does not already have one.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * fillProvisorySetComputeUnitLimitInstruction,\n * // ...\n * );\n * ```\n */\nexport function fillProvisorySetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(transactionMessage: TTransactionMessage) {\n return updateOrAppendSetComputeUnitLimitInstruction(\n (previousUnits) =>\n previousUnits === null ? PROVISORY_COMPUTE_UNIT_LIMIT : previousUnits,\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitLimit` instruction in a transaction message\n * with the given units, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param units - The new compute unit limit, or a function that takes the previous\n * compute unit limit and returns the new limit.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitLimitInstruction(\n * // E.g. Keep the current limit if it is set, otherwise set it to the maximum.\n * (currentUnits) => currentUnits === null ? MAX_COMPUTE_UNIT_LIMIT : currentUnits,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n units: number | ((previousUnits: number | null) => number),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getUnits = (previousUnits: number | null): number =>\n typeof units === 'function' ? units(previousUnits) : units;\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: getUnits(null) }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, units: previousUnits } = instructionDetails;\n const newUnits = getUnits(previousUnits);\n if (newUnits === previousUnits) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitLimitInstruction({ units: newUnits });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport {\n MAX_COMPUTE_UNIT_LIMIT,\n PROVISORY_COMPUTE_UNIT_LIMIT,\n} from './constants';\nimport {\n EstimateComputeUnitLimitFactoryFunction,\n EstimateComputeUnitLimitFactoryFunctionConfig,\n} from './estimateComputeLimitInternal';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\n\ntype EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction = <\n TTransactionMessage extends BaseTransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\n/**\n * Given a transaction message, if it does not have an explicit compute unit limit,\n * estimates the compute unit limit and updates the transaction message with\n * the estimated limit. Otherwise, returns the transaction message unchanged.\n *\n * It requires a function that estimates the compute unit limit.\n *\n * @example\n * ```ts\n * const estimateAndUpdateCUs = estimateAndUpdateProvisoryComputeUnitLimitFactory(\n * estimateComputeUnitLimitFactory({ rpc })\n * );\n *\n * const transactionMessageWithCUs = await estimateAndUpdateCUs(transactionMessage);\n * ```\n *\n * @see {@link estimateAndUpdateProvisoryComputeUnitLimitFactory}\n */\nexport function estimateAndUpdateProvisoryComputeUnitLimitFactory(\n estimateComputeUnitLimit: EstimateComputeUnitLimitFactoryFunction\n): EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction {\n return async function fn(transactionMessage, config) {\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n // If the transaction message already has a compute unit limit instruction\n // which is set to a specific value — i.e. not 0 or the maximum limit —\n // we don't need to estimate the compute unit limit.\n if (\n instructionDetails &&\n instructionDetails.units !== PROVISORY_COMPUTE_UNIT_LIMIT &&\n instructionDetails.units !== MAX_COMPUTE_UNIT_LIMIT\n ) {\n return transactionMessage;\n }\n\n return updateOrAppendSetComputeUnitLimitInstruction(\n await estimateComputeUnitLimit(transactionMessage, config),\n transactionMessage\n );\n };\n}\n","import {\n BaseTransactionMessage,\n Commitment,\n compileTransaction,\n getBase64EncodedWireTransaction,\n isSolanaError,\n isTransactionMessageWithDurableNonceLifetime,\n pipe,\n Rpc,\n SimulateTransactionApi,\n Slot,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaError,\n Transaction,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\nimport { MAX_COMPUTE_UNIT_LIMIT } from './constants';\n\nexport type EstimateComputeUnitLimitFactoryConfig = Readonly<{\n /** An object that supports the {@link SimulateTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}>;\n\nexport type EstimateComputeUnitLimitFactoryFunction = (\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\nexport type EstimateComputeUnitLimitFactoryFunctionConfig = {\n abortSignal?: AbortSignal;\n /**\n * Compute the estimate as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\ntype EstimateComputeUnitLimitConfig =\n EstimateComputeUnitLimitFactoryFunctionConfig &\n Readonly<{\n rpc: Rpc;\n transactionMessage: BaseTransactionMessage &\n TransactionMessageWithFeePayer;\n }>;\n\n/**\n * Simulates a transaction message on the network and returns the number of compute units it\n * consumed during simulation.\n *\n * The estimate this function returns can be used to set a compute unit limit on the transaction.\n * Correctly budgeting a compute unit limit for your transaction message can increase the probability\n * that your transaction will be accepted for processing.\n *\n * If you don't declare a compute unit limit on your transaction, validators will assume an upper\n * limit of 200K compute units (CU) per instruction. Since validators have an incentive to pack as\n * many transactions into each block as possible, they may choose to include transactions that they\n * know will fit into the remaining compute budget for the current block over transactions that\n * might not. For this reason, you should set a compute unit limit on each of your transaction\n * messages, whenever possible.\n *\n * ## Example\n *\n * ```ts\n * import { getSetComputeLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const getComputeUnitEstimateForTransactionMessage =\n * getComputeUnitEstimateForTransactionMessageFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume.\n * const computeUnitsEstimate =\n * await getComputeUnitEstimateForTransactionMessage(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeLimitInstruction({ units: computeUnitsEstimate }),\n * transactionMessage,\n * );\n * ```\n *\n * > [!WARNING]\n * > The compute unit estimate is just that – an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n */\nexport async function estimateComputeUnitLimit({\n transactionMessage,\n ...configs\n}: EstimateComputeUnitLimitConfig): Promise {\n const replaceRecentBlockhash =\n !isTransactionMessageWithDurableNonceLifetime(transactionMessage);\n const transaction = pipe(\n transactionMessage,\n (m) =>\n updateOrAppendSetComputeUnitLimitInstruction(MAX_COMPUTE_UNIT_LIMIT, m),\n compileTransaction\n );\n\n return await simulateTransactionAndGetConsumedUnits({\n transaction,\n replaceRecentBlockhash,\n ...configs,\n });\n}\n\ntype SimulateTransactionAndGetConsumedUnitsConfig = Omit<\n EstimateComputeUnitLimitConfig,\n 'transactionMessage'\n> &\n Readonly<{ replaceRecentBlockhash?: boolean; transaction: Transaction }>;\n\nasync function simulateTransactionAndGetConsumedUnits({\n abortSignal,\n rpc,\n transaction,\n ...simulateConfig\n}: SimulateTransactionAndGetConsumedUnitsConfig): Promise {\n const wireTransactionBytes = getBase64EncodedWireTransaction(transaction);\n\n try {\n const {\n value: { err: transactionError, unitsConsumed },\n } = await rpc\n .simulateTransaction(wireTransactionBytes, {\n ...simulateConfig,\n encoding: 'base64',\n sigVerify: false,\n })\n .send({ abortSignal });\n if (unitsConsumed == null) {\n // This should never be hit, because all RPCs should support `unitsConsumed` by now.\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n );\n }\n // FIXME(https://github.com/anza-xyz/agave/issues/1295): The simulation response returns\n // compute units as a u64, but the `SetComputeLimit` instruction only accepts a u32. Until\n // this changes, downcast it.\n const downcastUnitsConsumed =\n unitsConsumed > 4_294_967_295n ? 4_294_967_295 : Number(unitsConsumed);\n if (transactionError) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n {\n cause: transactionError,\n unitsConsumed: downcastUnitsConsumed,\n }\n );\n }\n return downcastUnitsConsumed;\n } catch (e) {\n if (\n isSolanaError(\n e,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n )\n )\n throw e;\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n { cause: e }\n );\n }\n}\n","import {\n estimateComputeUnitLimit,\n EstimateComputeUnitLimitFactoryConfig,\n EstimateComputeUnitLimitFactoryFunction,\n} from './estimateComputeLimitInternal';\n\n/**\n * Use this utility to estimate the actual compute unit cost of a given transaction message.\n *\n * Correctly budgeting a compute unit limit for your transaction message can increase the\n * probability that your transaction will be accepted for processing. If you don't declare a compute\n * unit limit on your transaction, validators will assume an upper limit of 200K compute units (CU)\n * per instruction.\n *\n * Since validators have an incentive to pack as many transactions into each block as possible, they\n * may choose to include transactions that they know will fit into the remaining compute budget for\n * the current block over transactions that might not. For this reason, you should set a compute\n * unit limit on each of your transaction messages, whenever possible.\n *\n * > [!WARNING]\n * > The compute unit estimate is just that -- an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n *\n * > [!INFO]\n * > In the event that a transaction message does not already have a `SetComputeUnitLimit`\n * > instruction, this function will add one before simulation. This ensures that the compute unit\n * > consumption of the `SetComputeUnitLimit` instruction itself is included in the estimate.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, estimateComputeUnitLimitFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const estimateComputeUnitLimit = estimateComputeUnitLimitFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume. This is done by\n * // simulating the transaction and grabbing the estimated compute units from the result.\n * const estimatedUnits = await estimateComputeUnitLimit(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeUnitLimitInstruction({ units: estimatedUnits }),\n * transactionMessage,\n * );\n * ```\n */\nexport function estimateComputeUnitLimitFactory({\n rpc,\n}: EstimateComputeUnitLimitFactoryConfig): EstimateComputeUnitLimitFactoryFunction {\n return async function estimateComputeUnitLimitFactoryFunction(\n transactionMessage,\n config\n ) {\n return await estimateComputeUnitLimit({\n ...config,\n rpc,\n transactionMessage,\n });\n };\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n MicroLamports,\n} from '@solana/kit';\nimport { getSetComputeUnitPriceInstruction } from './generated';\nimport { getSetComputeUnitPriceInstructionIndexAndMicroLamports } from './internal';\n\n/**\n * Sets the compute unit price of a transaction message in micro-Lamports.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * (m) => setTransactionMessageComputeUnitPrice(10_000, m),\n * // ...\n * );\n * ```\n */\nexport function setTransactionMessageComputeUnitPrice<\n TTransactionMessage extends BaseTransactionMessage,\n>(microLamports: number | bigint, transactionMessage: TTransactionMessage) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({ microLamports }),\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitPrice` instruction in a transaction message\n * with the given micro-Lamports, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param microLamports - The new compute unit price, or a function that\n * takes the previous price and returns the new one.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitPriceInstruction(\n * // E.g. double the current price or set it to 10_000 if it isn't set.\n * (currentPrice) => currentPrice === null ? 10_000 : currentPrice * 2,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitPriceInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n microLamports:\n | MicroLamports\n | ((previousMicroLamports: MicroLamports | null) => MicroLamports),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getMicroLamports = (\n previousMicroLamports: MicroLamports | null\n ): MicroLamports =>\n typeof microLamports === 'function'\n ? microLamports(previousMicroLamports)\n : microLamports;\n const instructionDetails =\n getSetComputeUnitPriceInstructionIndexAndMicroLamports(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({\n microLamports: getMicroLamports(null),\n }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, microLamports: previousMicroLamports } = instructionDetails;\n const newMicroLamports = getMicroLamports(previousMicroLamports);\n if (newMicroLamports === previousMicroLamports) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitPriceInstruction({\n microLamports: newMicroLamports,\n });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../signer\";\nimport type { ExactSvmPayloadV2 } from \"../../types\";\nimport { createRpcClient } from \"../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme.\n */\nexport class ExactSvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClient instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClient instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise> {\n const rpc = createRpcClient(paymentRequirements.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, paymentRequirements.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: paymentRequirements.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: paymentRequirements.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(paymentRequirements.amount),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = paymentRequirements.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV2 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n}\n","/**\n * V1 exports for the SVM mechanism\n */\nexport { ExactSvmSchemeV1 } from \"../exact/v1\";\n\nexport const NETWORKS: string[] = [\"solana\", \"solana-devnet\", \"solana-testnet\"];\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport type { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../../signer\";\nimport type { ExactSvmPayloadV1 } from \"../../../types\";\nimport { createRpcClient } from \"../../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactSvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClientV1 instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClientV1 instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const rpc = createRpcClient(selectedV1.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, selectedV1.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: selectedV1.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: selectedV1.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(selectedV1.maxAmountRequired),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = selectedV1.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV1 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientSvmSigner } from \"../../signer\";\nimport { ExactSvmScheme } from \"./scheme\";\nimport { ExactSvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering SVM schemes to an x402Client\n */\nexport interface SvmClientConfig {\n /**\n * The SVM signer to use for creating payment payloads\n */\n signer: ClientSvmSigner;\n\n /**\n * Optional payment requirements selector function\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional specific networks to register\n */\n networks?: Network[];\n}\n\n/**\n * Registers SVM payment schemes to an existing x402Client instance.\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for SVM client registration\n * @returns The client instance for chaining\n */\nexport function registerExactSvmScheme(client: x402Client, config: SvmClientConfig): x402Client {\n // Register V2 scheme\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach(network => {\n client.register(network, new ExactSvmScheme(config.signer));\n });\n } else {\n client.register(\"solana:*\", new ExactSvmScheme(config.signer));\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactSvmSchemeV1(config.signer));\n });\n\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * Local x402 Proxy Server\n *\n * Sits between OpenClaw's pi-ai (which makes standard OpenAI-format requests)\n * and BlockRun's API (which requires x402 micropayments).\n *\n * Flow:\n * pi-ai → http://localhost:{port}/v1/chat/completions\n * → proxy forwards to https://blockrun.ai/api/v1/chat/completions\n * → gets 402 → @x402/fetch signs payment → retries\n * → streams response back to pi-ai\n *\n * Optimizations (v0.3.0):\n * - SSE heartbeat: for streaming requests, sends headers + heartbeat immediately\n * before the x402 flow, preventing OpenClaw's 10-15s timeout from firing.\n * - Response dedup: hashes request bodies and caches responses for 30s,\n * preventing double-charging when OpenClaw retries after timeout.\n * - Smart routing: when model is \"blockrun/auto\", classify query and pick cheapest model.\n * - Usage logging: log every request as JSON line to ~/.openclaw/blockrun/logs/\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\n\n// Per-request payment tracking via AsyncLocalStorage (safe for concurrent requests).\n// The x402 onAfterPaymentCreation hook writes the actual payment amount into the\n// request-scoped store, and the logging code reads it after payFetch completes.\nconst paymentStore = new AsyncLocalStorage<{ amountUsd: number }>();\nimport { finished } from \"node:stream\";\nimport type { AddressInfo } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdir, writeFile, readFile, stat as fsStat } from \"node:fs/promises\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { createPublicClient, http } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { x402Client } from \"@x402/fetch\";\nimport { createPayFetchWithPreAuth } from \"./payment-preauth.js\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { toClientEvmSigner } from \"@x402/evm\";\nimport {\n route,\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n DEFAULT_ROUTING_CONFIG,\n type RouterOptions,\n type RoutingDecision,\n type RoutingConfig,\n type ModelPricing,\n type Tier,\n} from \"./router/index.js\";\nimport { classifyByRules } from \"./router/rules.js\";\nimport {\n BLOCKRUN_MODELS,\n OPENCLAW_MODELS,\n resolveModelAlias,\n getModelContextWindow,\n isReasoningModel,\n supportsToolCalling,\n supportsVision,\n} from \"./models.js\";\nimport { logUsage, type UsageEntry } from \"./logger.js\";\nimport { getStats, clearStats } from \"./stats.js\";\nimport { RequestDeduplicator } from \"./dedup.js\";\nimport { ResponseCache, type ResponseCacheConfig } from \"./response-cache.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport type { SolanaBalanceMonitor } from \"./solana-balance.js\";\n\n/** Union type for chain-agnostic balance monitoring */\ntype AnyBalanceMonitor = BalanceMonitor | SolanaBalanceMonitor;\nimport { resolvePaymentChain } from \"./auth.js\";\nimport { compressContext, shouldCompress, type NormalizedMessage } from \"./compression/index.js\";\n// Error classes available for programmatic use but not used in proxy\n// (universal free fallback means we don't throw balance errors anymore)\n// import { InsufficientFundsError, EmptyWalletError } from \"./errors.js\";\nimport { USER_AGENT, VERSION } from \"./version.js\";\nimport {\n SessionStore,\n getSessionId,\n deriveSessionId,\n hashRequestContent,\n type SessionConfig,\n} from \"./session.js\";\nimport { checkForUpdates } from \"./updater.js\";\nimport { loadExcludeList } from \"./exclude-models.js\";\nimport { PROXY_PORT } from \"./config.js\";\nimport { SessionJournal } from \"./journal.js\";\n\nconst BLOCKRUN_API = \"https://blockrun.ai/api\";\nconst BLOCKRUN_SOLANA_API = \"https://sol.blockrun.ai/api\";\nconst IMAGE_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"images\");\n// Routing profile models - virtual models that trigger intelligent routing\nconst AUTO_MODEL = \"blockrun/auto\";\n\nconst ROUTING_PROFILES = new Set([\n \"blockrun/eco\",\n \"eco\",\n \"blockrun/auto\",\n \"auto\",\n \"blockrun/premium\",\n \"premium\",\n]);\nconst FREE_MODEL = \"free/gpt-oss-120b\"; // Last-resort single free model fallback\nconst FREE_MODELS = new Set([\n \"free/gpt-oss-120b\",\n \"free/gpt-oss-20b\",\n \"free/nemotron-ultra-253b\",\n \"free/nemotron-3-super-120b\",\n \"free/nemotron-super-49b\",\n \"free/deepseek-v3.2\",\n \"free/mistral-large-3-675b\",\n \"free/qwen3-coder-480b\",\n \"free/devstral-2-123b\",\n \"free/glm-4.7\",\n \"free/llama-4-maverick\",\n]);\n/**\n * Map free/xxx model IDs to nvidia/xxx for upstream BlockRun API.\n * The \"free/\" prefix is a ClawRouter convention for the /model picker;\n * BlockRun server expects \"nvidia/\" prefix.\n */\nfunction toUpstreamModelId(modelId: string): string {\n if (modelId.startsWith(\"free/\")) {\n return \"nvidia/\" + modelId.slice(\"free/\".length);\n }\n return modelId;\n}\nconst MAX_MESSAGES = 200; // BlockRun API limit - truncate older messages if exceeded\nconst CONTEXT_LIMIT_KB = 5120; // Server-side limit: 5MB in KB\nconst HEARTBEAT_INTERVAL_MS = 2_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 180_000; // 3 minutes (allows for on-chain tx + LLM response)\nconst PER_MODEL_TIMEOUT_MS = 60_000; // 60s per individual model attempt (fallback to next on exceed)\nconst MAX_FALLBACK_ATTEMPTS = 5; // Maximum models to try in fallback chain (increased from 3 to ensure cheap models are tried)\nconst HEALTH_CHECK_TIMEOUT_MS = 2_000; // Timeout for checking existing proxy\nconst RATE_LIMIT_COOLDOWN_MS = 60_000; // 60 seconds cooldown for rate-limited models\nconst OVERLOAD_COOLDOWN_MS = 15_000; // 15 seconds cooldown for overloaded providers\nconst PORT_RETRY_ATTEMPTS = 5; // Max attempts to bind port (handles TIME_WAIT)\nconst PORT_RETRY_DELAY_MS = 1_000; // Delay between retry attempts\nconst MODEL_BODY_READ_TIMEOUT_MS = 300_000; // 5 minutes for model responses (reasoning models are slow)\nconst ERROR_BODY_READ_TIMEOUT_MS = 30_000; // 30 seconds for error/partner body reads\n\nasync function readBodyWithTimeout(\n body: ReadableStream | null,\n timeoutMs: number = MODEL_BODY_READ_TIMEOUT_MS,\n): Promise {\n if (!body) return [];\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n\n let timer: ReturnType | undefined;\n try {\n while (true) {\n const result = await Promise.race([\n reader.read(),\n new Promise((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"Body read timeout\")), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (result.done) break;\n chunks.push(result.value);\n }\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n\n return chunks;\n}\n\n/**\n * Transform upstream payment errors into user-friendly messages.\n * Parses the raw x402 error and formats it nicely.\n */\nfunction transformPaymentError(errorBody: string): string {\n try {\n // Try to parse the error JSON\n const parsed = JSON.parse(errorBody) as {\n error?: string;\n details?: string;\n // blockrun-sol (Solana) format uses code+debug instead of details\n code?: string;\n debug?: string;\n payer?: string;\n };\n\n // Check if this is a payment verification error\n if (parsed.error === \"Payment verification failed\" && parsed.details) {\n // Extract the nested JSON from details\n // Format: \"Verification failed: {json}\\n\"\n const match = parsed.details.match(/Verification failed:\\s*(\\{.*\\})/s);\n if (match) {\n const innerJson = JSON.parse(match[1]) as {\n invalidMessage?: string;\n invalidReason?: string;\n payer?: string;\n };\n\n if (innerJson.invalidReason === \"insufficient_funds\" && innerJson.invalidMessage) {\n // Parse \"insufficient balance: 251 < 11463\"\n const balanceMatch = innerJson.invalidMessage.match(\n /insufficient balance:\\s*(\\d+)\\s*<\\s*(\\d+)/i,\n );\n if (balanceMatch) {\n const currentMicros = parseInt(balanceMatch[1], 10);\n const requiredMicros = parseInt(balanceMatch[2], 10);\n const currentUSD = (currentMicros / 1_000_000).toFixed(6);\n const requiredUSD = (requiredMicros / 1_000_000).toFixed(6);\n const wallet = innerJson.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n return JSON.stringify({\n error: {\n message: `Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,\n type: \"insufficient_funds\",\n wallet: wallet,\n current_balance_usd: currentUSD,\n required_usd: requiredUSD,\n help: `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free`,\n },\n });\n }\n }\n\n // Handle invalid_payload errors (signature issues, malformed payment)\n if (innerJson.invalidReason === \"invalid_payload\") {\n return JSON.stringify({\n error: {\n message: \"Payment signature invalid. This may be a temporary issue.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n // Handle transaction simulation failures (Solana on-chain validation)\n if (innerJson.invalidReason === \"transaction_simulation_failed\") {\n console.error(\n `[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage || \"unknown\"}`,\n );\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, check your Solana USDC balance or try: /model free\",\n },\n });\n }\n }\n }\n\n // Handle blockrun-sol (Solana) format: code=PAYMENT_INVALID + debug=invalidReason string\n if (\n parsed.error === \"Payment verification failed\" &&\n parsed.code === \"PAYMENT_INVALID\" &&\n parsed.debug\n ) {\n const debugLower = parsed.debug.toLowerCase();\n const wallet = parsed.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n if (debugLower.includes(\"insufficient\")) {\n return JSON.stringify({\n error: {\n message: \"Insufficient Solana USDC balance.\",\n type: \"insufficient_funds\",\n wallet,\n help: `Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base`,\n },\n });\n }\n\n if (\n debugLower.includes(\"transaction_simulation_failed\") ||\n debugLower.includes(\"simulation\")\n ) {\n console.error(`[ClawRouter] Solana transaction simulation failed: ${parsed.debug}`);\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n\n if (debugLower.includes(\"invalid signature\") || debugLower.includes(\"invalid_signature\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment signature invalid.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n if (debugLower.includes(\"expired\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment expired. Retrying.\",\n type: \"expired\",\n help: \"This is usually temporary.\",\n },\n });\n }\n\n // Unknown Solana verification error — surface the debug reason\n console.error(\n `[ClawRouter] Solana payment verification failed: ${parsed.debug} payer=${wallet}`,\n );\n return JSON.stringify({\n error: {\n message: `Solana payment verification failed: ${parsed.debug}`,\n type: \"payment_invalid\",\n wallet,\n help: \"Try again or switch to Base: /wallet base\",\n },\n });\n }\n\n // Handle settlement failures (gas estimation, on-chain errors)\n if (\n parsed.error === \"Settlement failed\" ||\n parsed.error === \"Payment settlement failed\" ||\n parsed.details?.includes(\"Settlement failed\") ||\n parsed.details?.includes(\"transaction_simulation_failed\")\n ) {\n const details = parsed.details || \"\";\n const gasError = details.includes(\"unable to estimate gas\");\n\n return JSON.stringify({\n error: {\n message: gasError\n ? \"Payment failed: network congestion or gas issue. Try again.\"\n : \"Payment settlement failed. Try again in a moment.\",\n type: \"settlement_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n } catch {\n // If parsing fails, return original\n }\n return errorBody;\n}\n\n/**\n * Semantic error categories from upstream provider responses.\n * Used to distinguish auth failures from rate limits from server errors\n * so each category can be handled independently without cross-contamination.\n */\nexport type ErrorCategory =\n | \"auth_failure\" // 401, 403: Wrong key or forbidden — don't retry with same key\n | \"quota_exceeded\" // 403 with plan/quota body: Plan limit hit\n | \"rate_limited\" // 429: Actual throttling — 60s cooldown\n | \"overloaded\" // 529, 503+overload body: Provider capacity — 15s cooldown\n | \"server_error\" // 5xx general: Transient — fallback immediately\n | \"payment_error\" // 402: x402 payment or funds issue\n | \"config_error\"; // 400, 413: Bad request content — skip this model\n\n/**\n * Classify an upstream error response into a semantic category.\n * Returns null if the status+body is not a provider-side issue worth retrying.\n */\nexport function categorizeError(status: number, body: string): ErrorCategory | null {\n if (status === 401) return \"auth_failure\";\n if (status === 402) return \"payment_error\";\n if (status === 403) {\n if (/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)) return \"quota_exceeded\";\n return \"auth_failure\"; // generic 403 = forbidden = likely auth issue\n }\n if (status === 429) return \"rate_limited\";\n if (status === 529) return \"overloaded\";\n if (status === 503 && /overload|capacity|too.*many.*request/i.test(body)) return \"overloaded\";\n if (status >= 500) return \"server_error\";\n if (status === 400 || status === 413) {\n // Only fallback on content-size or billing patterns; bare 400 = our bug, don't cycle\n if (PROVIDER_ERROR_PATTERNS.some((p) => p.test(body))) return \"config_error\";\n return null;\n }\n return null;\n}\n\n/**\n * Track rate-limited models to avoid hitting them again.\n * Maps model ID to the timestamp when the rate limit was hit.\n */\nconst rateLimitedModels = new Map();\n\n/** Per-model overload tracking (529/503 capacity errors) — shorter cooldown than rate limits. */\nconst overloadedModels = new Map();\n\n/** Per-model error category counts (in-memory, resets on restart). */\ntype ProviderErrorCounts = {\n auth_failure: number;\n quota_exceeded: number;\n rate_limited: number;\n overloaded: number;\n server_error: number;\n payment_error: number;\n config_error: number;\n};\nconst perProviderErrors = new Map();\n\n/** Record an error category hit for a model. */\nfunction recordProviderError(modelId: string, category: ErrorCategory): void {\n if (!perProviderErrors.has(modelId)) {\n perProviderErrors.set(modelId, {\n auth_failure: 0,\n quota_exceeded: 0,\n rate_limited: 0,\n overloaded: 0,\n server_error: 0,\n payment_error: 0,\n config_error: 0,\n });\n }\n perProviderErrors.get(modelId)![category]++;\n}\n\n/**\n * Check if a model is currently rate-limited (in cooldown period).\n */\nfunction isRateLimited(modelId: string): boolean {\n const hitTime = rateLimitedModels.get(modelId);\n if (!hitTime) return false;\n\n const elapsed = Date.now() - hitTime;\n if (elapsed >= RATE_LIMIT_COOLDOWN_MS) {\n rateLimitedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Mark a model as rate-limited.\n */\nfunction markRateLimited(modelId: string): void {\n rateLimitedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`);\n}\n\n/**\n * Mark a model as temporarily overloaded (529/503 capacity).\n * Shorter cooldown than rate limits since capacity restores quickly.\n */\nfunction markOverloaded(modelId: string): void {\n overloadedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`);\n}\n\n/** Check if a model is in its overload cooldown period. */\nfunction isOverloaded(modelId: string): boolean {\n const hitTime = overloadedModels.get(modelId);\n if (!hitTime) return false;\n if (Date.now() - hitTime >= OVERLOAD_COOLDOWN_MS) {\n overloadedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Reorder models to put rate-limited ones at the end.\n */\nfunction prioritizeNonRateLimited(models: string[]): string[] {\n const available: string[] = [];\n const degraded: string[] = [];\n\n for (const model of models) {\n if (isRateLimited(model) || isOverloaded(model)) {\n degraded.push(model);\n } else {\n available.push(model);\n }\n }\n\n return [...available, ...degraded];\n}\n\n/**\n * Check if response socket is writable (prevents write-after-close errors).\n * Returns true only if all conditions are safe for writing.\n */\nfunction canWrite(res: ServerResponse): boolean {\n return (\n !res.writableEnded &&\n !res.destroyed &&\n res.socket !== null &&\n !res.socket.destroyed &&\n res.socket.writable\n );\n}\n\n/**\n * Safe write with backpressure handling.\n * Returns true if write succeeded, false if socket is closed or write failed.\n */\nfunction safeWrite(res: ServerResponse, data: string | Buffer): boolean {\n if (!canWrite(res)) {\n const bytes = typeof data === \"string\" ? Buffer.byteLength(data) : data.length;\n console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`);\n return false;\n }\n return res.write(data);\n}\n\n// Extra buffer for balance check (on top of estimateAmount's 20% buffer)\n// Total effective buffer: 1.2 * 1.5 = 1.8x (80% safety margin)\n// This prevents x402 payment failures after streaming headers are sent,\n// which would trigger OpenClaw's 5-24 hour billing cooldown.\nconst BALANCE_CHECK_BUFFER = 1.5;\n\n/**\n * Get the proxy port from pre-loaded configuration.\n * Port is validated at module load time, this just returns the cached value.\n */\nexport function getProxyPort(): number {\n return PROXY_PORT;\n}\n\n/**\n * Check if a proxy is already running on the given port.\n * Returns the wallet address if running, undefined otherwise.\n */\nasync function checkExistingProxy(\n port: number,\n): Promise<{ wallet: string; paymentChain?: string } | undefined> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);\n\n try {\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const data = (await response.json()) as {\n status?: string;\n wallet?: string;\n paymentChain?: string;\n };\n if (data.status === \"ok\" && data.wallet) {\n return { wallet: data.wallet, paymentChain: data.paymentChain };\n }\n }\n return undefined;\n } catch {\n clearTimeout(timeoutId);\n return undefined;\n }\n}\n\n/**\n * Error patterns that indicate a provider-side issue (not user's fault).\n * These errors should trigger fallback to the next model in the chain.\n */\nconst PROVIDER_ERROR_PATTERNS = [\n /billing/i,\n /insufficient.*balance/i,\n /credits/i,\n /quota.*exceeded/i,\n /rate.*limit/i,\n /model.*unavailable/i,\n /model.*not.*available/i,\n /service.*unavailable/i,\n /capacity/i,\n /overloaded/i,\n /temporarily.*unavailable/i,\n /api.*key.*invalid/i,\n /authentication.*failed/i,\n /request too large/i,\n /request.*size.*exceeds/i,\n /payload too large/i,\n /payment.*verification.*failed/i,\n /model.*not.*allowed/i,\n /unknown.*model/i,\n];\n\n/**\n * \"Successful\" response bodies that are actually provider degradation placeholders.\n * Some upstream providers occasionally return these with HTTP 200.\n */\nconst DEGRADED_RESPONSE_PATTERNS = [\n /the ai service is temporarily overloaded/i,\n /service is temporarily overloaded/i,\n /please try again in a moment/i,\n];\n\n/**\n * Known low-quality loop signatures seen during provider degradation windows.\n */\nconst DEGRADED_LOOP_PATTERNS = [\n /the boxed is the response\\./i,\n /the response is the text\\./i,\n /the final answer is the boxed\\./i,\n];\n\nfunction extractAssistantContent(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") return undefined;\n const record = payload as Record;\n const choices = record.choices;\n if (!Array.isArray(choices) || choices.length === 0) return undefined;\n\n const firstChoice = choices[0];\n if (!firstChoice || typeof firstChoice !== \"object\") return undefined;\n const choice = firstChoice as Record;\n const message = choice.message;\n if (!message || typeof message !== \"object\") return undefined;\n const content = (message as Record).content;\n return typeof content === \"string\" ? content : undefined;\n}\n\nfunction hasKnownLoopSignature(text: string): boolean {\n const matchCount = DEGRADED_LOOP_PATTERNS.reduce(\n (count, pattern) => (pattern.test(text) ? count + 1 : count),\n 0,\n );\n if (matchCount >= 2) return true;\n\n // Generic repetitive loop fallback for short repeated lines.\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n if (lines.length < 8) return false;\n\n const counts = new Map();\n for (const line of lines) {\n counts.set(line, (counts.get(line) ?? 0) + 1);\n }\n\n const maxRepeat = Math.max(...counts.values());\n const uniqueRatio = counts.size / lines.length;\n return maxRepeat >= 3 && uniqueRatio <= 0.45;\n}\n\n/**\n * Detect degraded 200-response payloads that should trigger model fallback.\n * Returns a short reason when fallback should happen, otherwise undefined.\n */\nexport function detectDegradedSuccessResponse(body: string): string | undefined {\n const trimmed = body.trim();\n if (!trimmed) return undefined;\n\n // Plain-text placeholder response.\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(trimmed))) {\n return \"degraded response: overloaded placeholder\";\n }\n\n // Plain-text looping garbage response.\n if (hasKnownLoopSignature(trimmed)) {\n return \"degraded response: repetitive loop output\";\n }\n\n try {\n const parsed = JSON.parse(trimmed) as Record;\n\n // Some providers return JSON error payloads with HTTP 200.\n const errorField = parsed.error;\n let errorText = \"\";\n if (typeof errorField === \"string\") {\n errorText = errorField;\n } else if (errorField && typeof errorField === \"object\") {\n const errObj = errorField as Record;\n errorText = [\n typeof errObj.message === \"string\" ? errObj.message : \"\",\n typeof errObj.type === \"string\" ? errObj.type : \"\",\n typeof errObj.code === \"string\" ? errObj.code : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n }\n if (errorText && PROVIDER_ERROR_PATTERNS.some((pattern) => pattern.test(errorText))) {\n return `degraded response: ${errorText.slice(0, 120)}`;\n }\n\n // Successful wrapper with bad assistant content.\n const assistantContent = extractAssistantContent(parsed);\n if (!assistantContent) return undefined;\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(assistantContent))) {\n return \"degraded response: overloaded assistant content\";\n }\n if (hasKnownLoopSignature(assistantContent)) {\n return \"degraded response: repetitive assistant loop\";\n }\n } catch {\n // Not JSON - handled by plaintext checks above.\n }\n\n return undefined;\n}\n\n/**\n * Valid message roles for OpenAI-compatible APIs.\n * Some clients send non-standard roles (e.g., \"developer\" instead of \"system\").\n */\nconst VALID_ROLES = new Set([\"system\", \"user\", \"assistant\", \"tool\", \"function\"]);\n\n/**\n * Role mappings for non-standard roles.\n * Maps client-specific roles to standard OpenAI roles.\n */\nconst ROLE_MAPPINGS: Record = {\n developer: \"system\", // OpenAI's newer API uses \"developer\" for system messages\n model: \"assistant\", // Some APIs use \"model\" instead of \"assistant\"\n};\n\ntype ChatMessage = { role: string; content: string | unknown };\n\n/**\n * Anthropic tool ID pattern: only alphanumeric, underscore, and hyphen allowed.\n * Error: \"messages.X.content.Y.tool_use.id: String should match pattern '^[a-zA-Z0-9_-]+$'\"\n */\nconst VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\n/**\n * Sanitize a tool ID to match Anthropic's required pattern.\n * Replaces invalid characters with underscores.\n */\nfunction sanitizeToolId(id: string | undefined): string | undefined {\n if (!id || typeof id !== \"string\") return id;\n if (VALID_TOOL_ID_PATTERN.test(id)) return id;\n\n // Replace invalid characters with underscores\n return id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n}\n\n/**\n * Type for messages with tool calls (OpenAI format).\n */\ntype MessageWithTools = ChatMessage & {\n tool_calls?: Array<{ id?: string; type?: string; function?: unknown }>;\n tool_call_id?: string;\n};\n\n/**\n * Type for content blocks that may contain tool IDs (Anthropic format in OpenAI wrapper).\n */\ntype ContentBlock = {\n type?: string;\n id?: string;\n tool_use_id?: string;\n [key: string]: unknown;\n};\n\n/**\n * Sanitize all tool IDs in messages to match Anthropic's pattern.\n * Handles both OpenAI format (tool_calls, tool_call_id) and content block formats.\n */\nfunction sanitizeToolIds(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const sanitized = messages.map((msg) => {\n const typedMsg = msg as MessageWithTools;\n let msgChanged = false;\n let newMsg = { ...msg } as MessageWithTools;\n\n // Sanitize tool_calls[].id in assistant messages\n if (typedMsg.tool_calls && Array.isArray(typedMsg.tool_calls)) {\n const newToolCalls = typedMsg.tool_calls.map((tc) => {\n if (tc.id && typeof tc.id === \"string\") {\n const sanitized = sanitizeToolId(tc.id);\n if (sanitized !== tc.id) {\n msgChanged = true;\n return { ...tc, id: sanitized };\n }\n }\n return tc;\n });\n if (msgChanged) {\n newMsg = { ...newMsg, tool_calls: newToolCalls };\n }\n }\n\n // Sanitize tool_call_id in tool messages\n if (typedMsg.tool_call_id && typeof typedMsg.tool_call_id === \"string\") {\n const sanitized = sanitizeToolId(typedMsg.tool_call_id);\n if (sanitized !== typedMsg.tool_call_id) {\n msgChanged = true;\n newMsg = { ...newMsg, tool_call_id: sanitized };\n }\n }\n\n // Sanitize content blocks if content is an array (Anthropic-style content)\n if (Array.isArray(typedMsg.content)) {\n const newContent = (typedMsg.content as ContentBlock[]).map((block) => {\n if (!block || typeof block !== \"object\") return block;\n\n let blockChanged = false;\n let newBlock = { ...block };\n\n // tool_use blocks have \"id\"\n if (block.type === \"tool_use\" && block.id && typeof block.id === \"string\") {\n const sanitized = sanitizeToolId(block.id);\n if (sanitized !== block.id) {\n blockChanged = true;\n newBlock = { ...newBlock, id: sanitized };\n }\n }\n\n // tool_result blocks have \"tool_use_id\"\n if (\n block.type === \"tool_result\" &&\n block.tool_use_id &&\n typeof block.tool_use_id === \"string\"\n ) {\n const sanitized = sanitizeToolId(block.tool_use_id);\n if (sanitized !== block.tool_use_id) {\n blockChanged = true;\n newBlock = { ...newBlock, tool_use_id: sanitized };\n }\n }\n\n if (blockChanged) {\n msgChanged = true;\n return newBlock;\n }\n return block;\n });\n\n if (msgChanged) {\n newMsg = { ...newMsg, content: newContent };\n }\n }\n\n if (msgChanged) {\n hasChanges = true;\n return newMsg;\n }\n return msg;\n });\n\n return hasChanges ? sanitized : messages;\n}\n\n/**\n * Normalize message roles to standard OpenAI format.\n * Converts non-standard roles (e.g., \"developer\") to valid ones.\n */\nfunction normalizeMessageRoles(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n if (VALID_ROLES.has(msg.role)) return msg;\n\n const mappedRole = ROLE_MAPPINGS[msg.role];\n if (mappedRole) {\n hasChanges = true;\n return { ...msg, role: mappedRole };\n }\n\n // Unknown role - default to \"user\" to avoid API errors\n hasChanges = true;\n return { ...msg, role: \"user\" };\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Normalize messages for Google models.\n * Google's Gemini API requires the first non-system message to be from \"user\".\n * If conversation starts with \"assistant\"/\"model\", prepend a placeholder user message.\n */\n\nfunction normalizeMessagesForGoogle(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n // Find first non-system message\n let firstNonSystemIdx = -1;\n for (let i = 0; i < messages.length; i++) {\n if (messages[i].role !== \"system\") {\n firstNonSystemIdx = i;\n break;\n }\n }\n\n // If no non-system messages, return as-is\n if (firstNonSystemIdx === -1) return messages;\n\n const firstRole = messages[firstNonSystemIdx].role;\n\n // If first non-system message is already \"user\", no change needed\n if (firstRole === \"user\") return messages;\n\n // If first non-system message is \"assistant\" or \"model\", prepend a user message\n if (firstRole === \"assistant\" || firstRole === \"model\") {\n const normalized = [...messages];\n normalized.splice(firstNonSystemIdx, 0, {\n role: \"user\",\n content: \"(continuing conversation)\",\n });\n return normalized;\n }\n\n return messages;\n}\n\n/**\n * Check if a model is a Google model that requires message normalization.\n */\nfunction isGoogleModel(modelId: string): boolean {\n return modelId.startsWith(\"google/\") || modelId.startsWith(\"gemini\");\n}\n\n/**\n * Extended message type for thinking-enabled conversations.\n */\ntype ExtendedChatMessage = ChatMessage & {\n tool_calls?: unknown[];\n reasoning_content?: unknown;\n};\n\n/**\n * Normalize messages for thinking-enabled requests.\n * When thinking/extended_thinking is enabled, assistant messages with tool_calls\n * must have reasoning_content (can be empty string if not present).\n * Error: \"400 thinking is enabled but reasoning_content is missing in assistant tool call message\"\n */\nfunction normalizeMessagesForThinking(messages: ExtendedChatMessage[]): ExtendedChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n // Skip if not assistant or already has reasoning_content\n if (msg.role !== \"assistant\" || msg.reasoning_content !== undefined) {\n return msg;\n }\n\n // Check for OpenAI format: tool_calls array\n const hasOpenAIToolCalls =\n msg.tool_calls && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;\n\n // Check for Anthropic format: content array with tool_use blocks\n const hasAnthropicToolUse =\n Array.isArray(msg.content) &&\n (msg.content as Array<{ type?: string }>).some((block) => block?.type === \"tool_use\");\n\n if (hasOpenAIToolCalls || hasAnthropicToolUse) {\n hasChanges = true;\n return { ...msg, reasoning_content: \"\" };\n }\n return msg;\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Remove \"blockrun\" branding from system messages before sending upstream.\n *\n * OpenClaw embeds `model=blockrun/auto` and `default_model=blockrun/auto` in its\n * system prompt Runtime section. LLMs pick up \"blockrun\" and adopt it as their\n * identity (e.g. \"I'm Blockrun\"), overriding the user's SOUL.md persona.\n *\n * This function replaces `blockrun/` references with the actual resolved\n * model name, and strips any remaining \"blockrun/\" prefix so the upstream LLM\n * never sees \"blockrun\" as an identity to adopt.\n */\nexport function debrandSystemMessages(\n messages: ChatMessage[],\n resolvedModel: string,\n): ChatMessage[] {\n // Routing profile names that get replaced with the actual model\n const PROFILE_NAMES = [\"auto\", \"free\", \"eco\", \"premium\"];\n const profilePattern = new RegExp(`\\\\bblockrun/(${PROFILE_NAMES.join(\"|\")})\\\\b`, \"gi\");\n // Also handle \"blockrun//\" → \"/\"\n const prefixPattern = /\\bblockrun\\/(?=[a-z])/gi;\n\n let hasChanges = false;\n const result = messages.map((msg) => {\n if (msg.role !== \"system\" || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n\n // Replace routing profiles (blockrun/auto etc.) with resolved model\n const afterProfiles = content.replace(profilePattern, resolvedModel);\n\n // Replace remaining blockrun/ prefix (e.g. blockrun/openai/gpt-4o → openai/gpt-4o)\n const afterPrefix = afterProfiles.replace(prefixPattern, \"\");\n\n if (afterPrefix !== content) {\n hasChanges = true;\n content = afterPrefix;\n }\n\n return content !== msg.content ? { ...msg, content } : msg;\n });\n\n return hasChanges ? result : messages;\n}\n\n/**\n * Result of truncating messages.\n */\ntype TruncationResult = {\n messages: T[];\n wasTruncated: boolean;\n originalCount: number;\n truncatedCount: number;\n};\n\n/**\n * Truncate messages to stay under BlockRun's MAX_MESSAGES limit.\n * Keeps all system messages and the most recent conversation history.\n * Returns the messages and whether truncation occurred.\n */\nfunction truncateMessages(messages: T[]): TruncationResult {\n if (!messages || messages.length <= MAX_MESSAGES) {\n return {\n messages,\n wasTruncated: false,\n originalCount: messages?.length ?? 0,\n truncatedCount: messages?.length ?? 0,\n };\n }\n\n // Separate system messages from conversation\n const systemMsgs = messages.filter((m) => m.role === \"system\");\n const conversationMsgs = messages.filter((m) => m.role !== \"system\");\n\n // Keep all system messages + most recent conversation messages\n const maxConversation = MAX_MESSAGES - systemMsgs.length;\n const truncatedConversation = conversationMsgs.slice(-maxConversation);\n\n const result = [...systemMsgs, ...truncatedConversation];\n\n console.log(\n `[ClawRouter] Truncated messages: ${messages.length} → ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`,\n );\n\n return {\n messages: result,\n wasTruncated: true,\n originalCount: messages.length,\n truncatedCount: result.length,\n };\n}\n\n// Kimi/Moonshot models use special Unicode tokens for thinking boundaries.\n// Pattern: <|begin▁of▁thinking|>content<|end▁of▁thinking|>\n// The | is fullwidth vertical bar (U+FF5C), ▁ is lower one-eighth block (U+2581).\n\n// Match full Kimi thinking blocks: <|begin...|>content<|end...|>\nconst KIMI_BLOCK_RE = /<[||][^<>]*begin[^<>]*[||]>[\\s\\S]*?<[||][^<>]*end[^<>]*[||]>/gi;\n\n// Match standalone Kimi tokens like <|end▁of▁thinking|>\nconst KIMI_TOKEN_RE = /<[||][^<>]*[||]>/g;\n\n// Standard thinking tags that may leak through from various models\nconst THINKING_TAG_RE = /<\\s*\\/?\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>/gi;\n\n// Full thinking blocks: content\nconst THINKING_BLOCK_RE =\n /<\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>[\\s\\S]*?<\\s*\\/\\s*(?:think(?:ing)?|thought|antthinking)\\s*>/gi;\n\n/**\n * Strip thinking tokens and blocks from model response content.\n * Handles both Kimi-style Unicode tokens and standard XML-style tags.\n *\n * NOTE: DSML tags (<|DSML|...>) are NOT stripped - those are tool calls\n * that should be handled by the API, not hidden from users.\n */\nfunction stripThinkingTokens(content: string): string {\n if (!content) return content;\n // Strip full Kimi thinking blocks first (begin...end with content)\n let cleaned = content.replace(KIMI_BLOCK_RE, \"\");\n // Strip remaining standalone Kimi tokens\n cleaned = cleaned.replace(KIMI_TOKEN_RE, \"\");\n // Strip full thinking blocks (...)\n cleaned = cleaned.replace(THINKING_BLOCK_RE, \"\");\n // Strip remaining standalone thinking tags\n cleaned = cleaned.replace(THINKING_TAG_RE, \"\");\n return cleaned;\n}\n\n/** Callback info for low balance warning */\nexport type LowBalanceInfo = {\n balanceUSD: string;\n walletAddress: string;\n};\n\n/** Callback info for insufficient funds error */\nexport type InsufficientFundsInfo = {\n balanceUSD: string;\n requiredUSD: string;\n walletAddress: string;\n};\n\n/**\n * Wallet config: either a plain EVM private key string, or the full\n * resolution object from resolveOrGenerateWalletKey() which may include\n * Solana keys. Using the full object prevents callers from accidentally\n * forgetting to forward Solana key bytes.\n */\nexport type WalletConfig = string | { key: string; solanaPrivateKeyBytes?: Uint8Array };\n\nexport type PaymentChain = \"base\" | \"solana\";\n\nexport type ProxyOptions = {\n wallet: WalletConfig;\n apiBase?: string;\n /** Payment chain: \"base\" (default) or \"solana\". Can also be set via CLAWROUTER_PAYMENT_CHAIN env var. */\n paymentChain?: PaymentChain;\n /** Port to listen on (default: 8402) */\n port?: number;\n routingConfig?: Partial;\n /** Request timeout in ms (default: 180000 = 3 minutes). Covers on-chain tx + LLM response. */\n requestTimeoutMs?: number;\n /** Skip balance checks (for testing only). Default: false */\n skipBalanceCheck?: boolean;\n /** Override the balance monitor with a mock (for testing only). */\n _balanceMonitorOverride?: AnyBalanceMonitor;\n /**\n * Session persistence config. When enabled, maintains model selection\n * across requests within a session to prevent mid-task model switching.\n */\n sessionConfig?: Partial;\n /**\n * Auto-compress large requests to reduce network usage.\n * When enabled, requests are automatically compressed using\n * LLM-safe context compression (15-40% reduction).\n * Default: true\n */\n autoCompressRequests?: boolean;\n /**\n * Threshold in KB to trigger auto-compression (default: 180).\n * Requests larger than this are compressed before sending.\n * Set to 0 to compress all requests.\n */\n compressionThresholdKB?: number;\n /**\n * Response caching config. When enabled, identical requests return\n * cached responses instead of making new API calls.\n * Default: enabled with 10 minute TTL, 200 max entries.\n */\n cacheConfig?: ResponseCacheConfig;\n /**\n * Maximum total spend (in USD) per session run.\n * Default: undefined (no limit). Example: 0.5 = $0.50 per session.\n */\n maxCostPerRunUsd?: number;\n /**\n * How to enforce the per-run cost cap.\n * - 'graceful' (default): when budget runs low, downgrade to cheaper models; use free model\n * as last resort. Only hard-stops when no model can serve the request.\n * - 'strict': immediately return 429 once the session spend reaches the cap.\n */\n maxCostPerRunMode?: \"graceful\" | \"strict\";\n /**\n * Set of model IDs to exclude from routing.\n * Excluded models are filtered out of fallback chains.\n * Loaded from ~/.openclaw/blockrun/exclude-models.json\n */\n excludeModels?: Set;\n onReady?: (port: number) => void;\n onError?: (error: Error) => void;\n onPayment?: (info: { model: string; amount: string; network: string }) => void;\n onRouted?: (decision: RoutingDecision) => void;\n /** Called when balance drops below $1.00 (warning, request still proceeds) */\n onLowBalance?: (info: LowBalanceInfo) => void;\n /** Called when balance is insufficient for a request (request fails) */\n onInsufficientFunds?: (info: InsufficientFundsInfo) => void;\n};\n\nexport type ProxyHandle = {\n port: number;\n baseUrl: string;\n walletAddress: string;\n solanaAddress?: string;\n balanceMonitor: AnyBalanceMonitor;\n close: () => Promise;\n};\n\n/**\n * Build model pricing map from BLOCKRUN_MODELS.\n */\nfunction buildModelPricing(): Map {\n const map = new Map();\n for (const m of BLOCKRUN_MODELS) {\n if (m.id === AUTO_MODEL) continue; // skip meta-model\n map.set(m.id, { inputPrice: m.inputPrice, outputPrice: m.outputPrice });\n }\n return map;\n}\n\ntype ModelListEntry = {\n id: string;\n object: \"model\";\n created: number;\n owned_by: string;\n};\n\n/**\n * Build `/v1/models` response entries from the full OpenClaw model registry.\n * This includes alias IDs (e.g., `flash`, `kimi`) so `/model ` works reliably.\n */\nexport function buildProxyModelList(\n createdAt: number = Math.floor(Date.now() / 1000),\n): ModelListEntry[] {\n const seen = new Set();\n return OPENCLAW_MODELS.filter((model) => {\n if (seen.has(model.id)) return false;\n seen.add(model.id);\n return true;\n }).map((model) => ({\n id: model.id,\n object: \"model\",\n created: createdAt,\n owned_by: model.id.includes(\"/\") ? (model.id.split(\"/\")[0] ?? \"blockrun\") : \"blockrun\",\n }));\n}\n\n/**\n * Merge partial routing config overrides with defaults.\n */\nfunction mergeRoutingConfig(overrides?: Partial): RoutingConfig {\n if (!overrides) return DEFAULT_ROUTING_CONFIG;\n return {\n ...DEFAULT_ROUTING_CONFIG,\n ...overrides,\n classifier: { ...DEFAULT_ROUTING_CONFIG.classifier, ...overrides.classifier },\n scoring: { ...DEFAULT_ROUTING_CONFIG.scoring, ...overrides.scoring },\n tiers: { ...DEFAULT_ROUTING_CONFIG.tiers, ...overrides.tiers },\n overrides: { ...DEFAULT_ROUTING_CONFIG.overrides, ...overrides.overrides },\n };\n}\n\n/**\n * Estimate USDC cost for a request based on model pricing.\n * Returns amount string in USDC smallest unit (6 decimals) or undefined if unknown.\n */\nfunction estimateAmount(\n modelId: string,\n bodyLength: number,\n maxTokens: number,\n): string | undefined {\n const model = BLOCKRUN_MODELS.find((m) => m.id === modelId);\n if (!model) return undefined;\n\n // Rough estimate: ~4 chars per token for input\n const estimatedInputTokens = Math.ceil(bodyLength / 4);\n const estimatedOutputTokens = maxTokens || model.maxOutput || 4096;\n\n const costUsd =\n (estimatedInputTokens / 1_000_000) * model.inputPrice +\n (estimatedOutputTokens / 1_000_000) * model.outputPrice;\n\n // Convert to USDC 6-decimal integer, add 20% buffer for estimation error\n // Minimum 1000 ($0.001) to match CDP Facilitator's enforced minimum payment\n const amountMicros = Math.max(1000, Math.ceil(costUsd * 1.2 * 1_000_000));\n return amountMicros.toString();\n}\n\n// Image pricing table (must match server's IMAGE_MODELS in blockrun/src/lib/models.ts)\n// Server applies 5% margin on top of these prices.\nconst IMAGE_PRICING: Record }> = {\n \"openai/dall-e-3\": {\n default: 0.04,\n sizes: { \"1024x1024\": 0.04, \"1792x1024\": 0.08, \"1024x1792\": 0.08 },\n },\n \"openai/gpt-image-1\": {\n default: 0.02,\n sizes: { \"1024x1024\": 0.02, \"1536x1024\": 0.04, \"1024x1536\": 0.04 },\n },\n \"black-forest/flux-1.1-pro\": { default: 0.04 },\n \"google/nano-banana\": { default: 0.05 },\n \"google/nano-banana-pro\": {\n default: 0.1,\n sizes: { \"1024x1024\": 0.1, \"2048x2048\": 0.1, \"4096x4096\": 0.15 },\n },\n};\n\n/**\n * Estimate the cost of an image generation/editing request.\n * Matches server-side calculateImagePrice() including 5% margin.\n */\nfunction estimateImageCost(model: string, size?: string, n: number = 1): number {\n const pricing = IMAGE_PRICING[model];\n if (!pricing) return 0.04 * n * 1.05; // fallback: assume $0.04/image + margin\n const sizePrice = size && pricing.sizes ? pricing.sizes[size] : undefined;\n const pricePerImage = sizePrice ?? pricing.default;\n return pricePerImage * n * 1.05; // 5% server margin\n}\n\n/**\n * Proxy a partner API request through x402 payment flow.\n *\n * Simplified proxy for partner endpoints (/v1/x/*, /v1/partner/*).\n * No smart routing, SSE, compression, or sessions — just collect body,\n * forward via payFetch (which handles 402 automatically), and stream back.\n */\nasync function proxyPartnerRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n getActualPaymentUsd: () => number,\n): Promise {\n const startTime = Date.now();\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const body = Buffer.concat(bodyChunks);\n\n // Forward headers (strip hop-by-hop)\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") headers[key] = value;\n }\n if (!headers[\"content-type\"]) headers[\"content-type\"] = \"application/json\";\n headers[\"user-agent\"] = USER_AGENT;\n\n console.log(`[ClawRouter] Partner request: ${req.method} ${req.url}`);\n\n const upstream = await payFetch(upstreamUrl, {\n method: req.method ?? \"POST\",\n headers,\n body: body.length > 0 ? new Uint8Array(body) : undefined,\n });\n\n // Forward response headers\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\") return;\n responseHeaders[key] = value;\n });\n\n res.writeHead(upstream.status, responseHeaders);\n\n // Stream response body\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body, ERROR_BODY_READ_TIMEOUT_MS);\n for (const chunk of chunks) {\n safeWrite(res, Buffer.from(chunk));\n }\n }\n\n res.end();\n\n const latencyMs = Date.now() - startTime;\n console.log(`[ClawRouter] Partner response: ${upstream.status} (${latencyMs}ms)`);\n\n // Log partner usage with actual x402 payment amount (previously logged cost: 0)\n const partnerCost = getActualPaymentUsd();\n logUsage({\n timestamp: new Date().toISOString(),\n model: \"partner\",\n tier: \"PARTNER\",\n cost: partnerCost,\n baselineCost: partnerCost,\n savings: 0,\n latencyMs,\n partnerId:\n (req.url?.split(\"?\")[0] ?? \"\").replace(/^\\/v1\\//, \"\").replace(/\\//g, \"_\") || \"unknown\",\n service: \"partner\",\n }).catch(() => {});\n}\n\n/**\n * Read a local image file and return it as a base64 data URI.\n * Supports ~/ home directory expansion.\n */\nfunction readImageFileAsDataUri(filePath: string): string {\n const resolved = filePath.startsWith(\"~/\") ? join(homedir(), filePath.slice(2)) : filePath;\n\n if (!existsSync(resolved)) {\n throw new Error(`Image file not found: ${resolved}`);\n }\n\n const ext = resolved.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mimeMap: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n };\n const mime = mimeMap[ext] ?? \"image/png\";\n const data = readFileSync(resolved);\n return `data:${mime};base64,${data.toString(\"base64\")}`;\n}\n\n/**\n * Upload a base64 data URI to catbox.moe and return a public URL.\n * Google image models (nano-banana) return data URIs instead of hosted URLs,\n * which breaks Telegram and other clients that can't render raw base64.\n */\nasync function uploadDataUriToHost(dataUri: string): Promise {\n const match = dataUri.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (!match) throw new Error(\"Invalid data URI format\");\n const [, mimeType, b64Data] = match;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType.split(\"/\")[1] ?? \"png\");\n\n const buffer = Buffer.from(b64Data, \"base64\");\n const blob = new Blob([buffer], { type: mimeType });\n\n const form = new FormData();\n form.append(\"reqtype\", \"fileupload\");\n form.append(\"fileToUpload\", blob, `image.${ext}`);\n\n const uploadController = new AbortController();\n const uploadTimeout = setTimeout(() => uploadController.abort(), 30_000);\n try {\n const resp = await fetch(\"https://catbox.moe/user/api.php\", {\n method: \"POST\",\n body: form,\n signal: uploadController.signal,\n });\n\n if (!resp.ok) throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);\n const result = await resp.text();\n if (result.startsWith(\"https://\")) {\n return result.trim();\n }\n throw new Error(`catbox.moe upload failed: ${result}`);\n } finally {\n clearTimeout(uploadTimeout);\n }\n}\n\n/**\n * Start the local x402 proxy server.\n *\n * If a proxy is already running on the target port, reuses it instead of failing.\n * Port can be configured via BLOCKRUN_PROXY_PORT environment variable.\n *\n * Returns a handle with the assigned port, base URL, and a close function.\n */\nexport async function startProxy(options: ProxyOptions): Promise {\n // Normalize wallet config: string = EVM-only, object = full resolution\n const walletKey = typeof options.wallet === \"string\" ? options.wallet : options.wallet.key;\n const solanaPrivateKeyBytes =\n typeof options.wallet === \"string\" ? undefined : options.wallet.solanaPrivateKeyBytes;\n\n // Payment chain: options > env var > persisted file > default \"base\".\n // No dynamic switching — user selects chain via /wallet solana or /wallet base.\n const paymentChain = options.paymentChain ?? (await resolvePaymentChain());\n const apiBase =\n options.apiBase ??\n (paymentChain === \"solana\" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API);\n if (paymentChain === \"solana\" && !solanaPrivateKeyBytes) {\n console.warn(\n `[ClawRouter] ⚠ Payment chain is Solana but no mnemonic found — falling back to Base (EVM).`,\n );\n console.warn(\n `[ClawRouter] To fix: run \"npx @blockrun/clawrouter wallet recover\" if your mnemonic exists,`,\n );\n console.warn(`[ClawRouter] or run \"npx @blockrun/clawrouter chain base\" to switch to EVM.`);\n } else if (paymentChain === \"solana\") {\n console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`);\n }\n\n // Determine port: options.port > env var > default\n const listenPort = options.port ?? getProxyPort();\n\n // Check if a proxy is already running on this port\n const existingProxy = await checkExistingProxy(listenPort);\n if (existingProxy) {\n // Proxy already running — reuse it instead of failing with EADDRINUSE\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const baseUrl = `http://127.0.0.1:${listenPort}`;\n\n // Verify the existing proxy is using the same wallet (or warn if different)\n if (existingProxy.wallet !== account.address) {\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account.address}. Reusing existing proxy.`,\n );\n }\n\n // Verify the existing proxy is using the same payment chain\n if (existingProxy.paymentChain) {\n if (existingProxy.paymentChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${existingProxy.paymentChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n } else if (paymentChain !== \"base\") {\n // Old proxy doesn't report chain — assume Base. Reject if Solana was requested.\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`,\n );\n throw new Error(\n `Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n\n // Derive Solana address if keys are available (for wallet status display)\n let reuseSolanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n reuseSolanaAddress = solanaSigner.address;\n }\n\n // Use chain-appropriate balance monitor (lazy import to avoid loading @solana/kit on Base chain)\n let balanceMonitor: AnyBalanceMonitor;\n if (paymentChain === \"solana\" && reuseSolanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n balanceMonitor = new SolanaBalanceMonitor(reuseSolanaAddress);\n } else {\n balanceMonitor = new BalanceMonitor(account.address);\n }\n\n options.onReady?.(listenPort);\n\n return {\n port: listenPort,\n baseUrl,\n walletAddress: existingProxy.wallet,\n solanaAddress: reuseSolanaAddress,\n balanceMonitor,\n close: async () => {\n // No-op: we didn't start this proxy, so we shouldn't close it\n },\n };\n }\n\n // Create x402 payment client with EVM scheme (always available)\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const evmPublicClient = createPublicClient({ chain: base, transport: http() });\n const evmSigner = toClientEvmSigner(account, evmPublicClient);\n const x402 = new x402Client();\n registerExactEvmScheme(x402, { signer: evmSigner });\n\n // Register Solana scheme if key is available\n // Uses registerExactSvmScheme helper which registers:\n // - solana:* wildcard (catches any CAIP-2 Solana network)\n // - V1 compat names: \"solana\", \"solana-devnet\", \"solana-testnet\"\n let solanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { registerExactSvmScheme } = await import(\"@x402/svm/exact/client\");\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n solanaAddress = solanaSigner.address;\n registerExactSvmScheme(x402, { signer: solanaSigner });\n console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`);\n }\n\n // Log which chain is used for each payment and capture actual payment amount\n x402.onAfterPaymentCreation(async (context) => {\n const network = context.selectedRequirements.network;\n const chain = network.startsWith(\"eip155\")\n ? \"Base (EVM)\"\n : network.startsWith(\"solana\")\n ? \"Solana\"\n : network;\n // Capture actual payment amount in USD (amount is in USDC micro units, 6 decimals)\n const amountMicros = parseInt(context.selectedRequirements.amount || \"0\", 10);\n const amountUsd = amountMicros / 1_000_000;\n // Write to request-scoped store (if available)\n const store = paymentStore.getStore();\n if (store) store.amountUsd = amountUsd;\n console.log(`[ClawRouter] Payment signed on ${chain} (${network}) — $${amountUsd.toFixed(6)}`);\n });\n\n const payFetch = createPayFetchWithPreAuth(fetch, x402, undefined, {\n skipPreAuth: paymentChain === \"solana\",\n });\n\n // Create balance monitor for pre-request checks (lazy import to avoid loading @solana/kit on Base chain)\n let balanceMonitor: AnyBalanceMonitor;\n if (options._balanceMonitorOverride) {\n balanceMonitor = options._balanceMonitorOverride;\n } else if (paymentChain === \"solana\" && solanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n balanceMonitor = new SolanaBalanceMonitor(solanaAddress);\n } else {\n balanceMonitor = new BalanceMonitor(account.address);\n }\n\n // Build router options (100% local — no external API calls for routing)\n const routingConfig = mergeRoutingConfig(options.routingConfig);\n const modelPricing = buildModelPricing();\n const routerOpts: RouterOptions = {\n config: routingConfig,\n modelPricing,\n };\n\n // Request deduplicator (shared across all requests)\n const deduplicator = new RequestDeduplicator();\n\n // Response cache for identical requests (longer TTL than dedup)\n const responseCache = new ResponseCache(options.cacheConfig);\n\n // Session store for model persistence (prevents mid-task model switching)\n const sessionStore = new SessionStore(options.sessionConfig);\n\n // Session journal for memory (enables agents to recall earlier work)\n const sessionJournal = new SessionJournal();\n\n // Track active connections for graceful cleanup\n const connections = new Set();\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n // Wrap in paymentStore.run() so x402 hook can write actual payment amount per-request\n paymentStore.run({ amountUsd: 0 }, async () => {\n // Add stream error handlers to prevent server crashes\n req.on(\"error\", (err) => {\n console.error(`[ClawRouter] Request stream error: ${err.message}`);\n // Don't throw - just log and let request handler deal with it\n });\n\n res.on(\"error\", (err) => {\n console.error(`[ClawRouter] Response stream error: ${err.message}`);\n // Don't try to write to failed socket - just log\n });\n\n // Finished wrapper for guaranteed cleanup on response completion/error\n finished(res, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Response finished with error: ${err.message}`);\n }\n // Note: heartbeatInterval cleanup happens in res.on(\"close\") handler\n // Note: completed and dedup cleanup happens in the res.on(\"close\") handler below\n });\n\n // Request finished wrapper for complete stream lifecycle tracking\n finished(req, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Request finished with error: ${err.message}`);\n }\n });\n\n // Health check with optional balance info\n if (req.url === \"/health\" || req.url?.startsWith(\"/health?\")) {\n const url = new URL(req.url, \"http://localhost\");\n const full = url.searchParams.get(\"full\") === \"true\";\n\n const response: Record = {\n status: \"ok\",\n wallet: account.address,\n paymentChain,\n };\n if (solanaAddress) {\n response.solana = solanaAddress;\n }\n\n if (full) {\n try {\n const balanceInfo = await balanceMonitor.checkBalance();\n response.balance = balanceInfo.balanceUSD;\n response.isLow = balanceInfo.isLow;\n response.isEmpty = balanceInfo.isEmpty;\n } catch {\n response.balanceError = \"Could not fetch balance\";\n }\n }\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(response));\n return;\n }\n\n // Cache stats endpoint\n if (req.url === \"/cache\" || req.url?.startsWith(\"/cache?\")) {\n const stats = responseCache.getStats();\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(JSON.stringify(stats, null, 2));\n return;\n }\n\n // Stats clear endpoint - delete all log files\n if (req.url === \"/stats\" && req.method === \"DELETE\") {\n try {\n const result = await clearStats();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ cleared: true, deletedFiles: result.deletedFiles }));\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // Stats API endpoint - returns JSON for programmatic access\n if (req.url === \"/stats\" || req.url?.startsWith(\"/stats?\")) {\n try {\n const url = new URL(req.url, \"http://localhost\");\n const days = parseInt(url.searchParams.get(\"days\") || \"7\", 10);\n const stats = await getStats(Math.min(days, 30));\n\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(\n JSON.stringify(\n {\n ...stats,\n providerErrors: Object.fromEntries(perProviderErrors),\n },\n null,\n 2,\n ),\n );\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to get stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // --- Handle /v1/models locally (no upstream call needed) ---\n if (req.url === \"/v1/models\" && req.method === \"GET\") {\n const models = buildProxyModelList();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ object: \"list\", data: models }));\n return;\n }\n\n // --- Serve locally cached images (~/.openclaw/blockrun/images/) ---\n if (req.url?.startsWith(\"/images/\") && req.method === \"GET\") {\n const filename = req.url\n .slice(\"/images/\".length)\n .split(\"?\")[0]!\n .replace(/[^a-zA-Z0-9._-]/g, \"\");\n if (!filename) {\n res.writeHead(400);\n res.end(\"Bad request\");\n return;\n }\n const filePath = join(IMAGE_DIR, filename);\n try {\n const s = await fsStat(filePath);\n if (!s.isFile()) throw new Error(\"not a file\");\n const ext = filename.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mime: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n };\n const data = await readFile(filePath);\n res.writeHead(200, {\n \"Content-Type\": mime[ext] ?? \"application/octet-stream\",\n \"Content-Length\": data.length,\n });\n res.end(data);\n } catch {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image not found\" }));\n }\n return;\n }\n\n // --- Handle /v1/images/generations: proxy with x402 payment + save data URIs locally ---\n // NOTE: image generation endpoints bypass maxCostPerRun budget tracking entirely.\n // Cost is charged via x402 micropayment directly — no session accumulation or cap enforcement.\n if (req.url === \"/v1/images/generations\" && req.method === \"POST\") {\n const imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const reqBody = Buffer.concat(chunks);\n // Parse request for usage logging\n let imgModel = \"unknown\";\n let imgCost = 0;\n try {\n const parsed = JSON.parse(reqBody.toString());\n imgModel = parsed.model || \"openai/dall-e-3\";\n const n = parsed.n || 1;\n imgCost = estimateImageCost(imgModel, parsed.size, n);\n } catch {\n /* use defaults */\n }\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/generations`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image generation usage with actual x402 payment (previously missing entirely)\n const imgActualCost = paymentStore.getStore()?.amountUsd ?? imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: imgModel,\n tier: \"IMAGE\",\n cost: imgActualCost,\n baselineCost: imgActualCost,\n savings: 0,\n latencyMs: Date.now() - imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image generation error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image generation failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle /v1/images/image2image: proxy with x402 payment + save images locally ---\n // Accepts image as: data URI, local file path, ~/path, or HTTP(S) URL\n if (req.url === \"/v1/images/image2image\" && req.method === \"POST\") {\n const img2imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const rawBody = Buffer.concat(chunks);\n\n // Resolve image/mask fields: file paths and URLs → data URIs\n let reqBody: string;\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgModel = \"openai/gpt-image-1\";\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgCost = 0;\n try {\n const parsed = JSON.parse(rawBody.toString());\n for (const field of [\"image\", \"mask\"] as const) {\n const val = parsed[field];\n if (typeof val !== \"string\" || !val) continue;\n if (val.startsWith(\"data:\")) {\n // Already a data URI — pass through\n } else if (val.startsWith(\"https://\") || val.startsWith(\"http://\")) {\n // Download URL → data URI\n const imgResp = await fetch(val);\n if (!imgResp.ok)\n throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const buf = Buffer.from(await imgResp.arrayBuffer());\n parsed[field] = `data:${contentType};base64,${buf.toString(\"base64\")}`;\n console.log(\n `[ClawRouter] img2img: downloaded ${field} URL → data URI (${buf.length} bytes)`,\n );\n } else {\n // Local file path → data URI\n parsed[field] = readImageFileAsDataUri(val);\n console.log(`[ClawRouter] img2img: read ${field} file → data URI`);\n }\n }\n // Default model if not specified\n if (!parsed.model) parsed.model = \"openai/gpt-image-1\";\n img2imgModel = parsed.model;\n img2imgCost = estimateImageCost(img2imgModel, parsed.size, parsed.n || 1);\n reqBody = JSON.stringify(parsed);\n } catch (parseErr) {\n const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\", details: msg }));\n return;\n }\n\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image editing usage with actual x402 payment (previously missing entirely)\n const img2imgActualCost = paymentStore.getStore()?.amountUsd ?? img2imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost,\n baselineCost: img2imgActualCost,\n savings: 0,\n latencyMs: Date.now() - img2imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image editing error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image editing failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle partner API paths (/v1/x/*, /v1/partner/*) ---\n if (req.url?.match(/^\\/v1\\/(?:x|partner)\\//)) {\n try {\n await proxyPartnerRequest(\n req,\n res,\n apiBase,\n payFetch,\n () => paymentStore.getStore()?.amountUsd ?? 0,\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Partner proxy error: ${error.message}`, type: \"partner_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Only proxy paths starting with /v1\n if (!req.url?.startsWith(\"/v1\")) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not found\" }));\n return;\n }\n\n try {\n await proxyRequest(\n req,\n res,\n apiBase,\n payFetch,\n options,\n routerOpts,\n deduplicator,\n balanceMonitor,\n sessionStore,\n responseCache,\n sessionJournal,\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Proxy error: ${error.message}`, type: \"proxy_error\" },\n }),\n );\n } else if (!res.writableEnded) {\n // Headers already sent (streaming) — send error as SSE event\n res.write(\n `data: ${JSON.stringify({ error: { message: error.message, type: \"proxy_error\" } })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n }\n }\n }); // end paymentStore.run()\n });\n\n // Listen on configured port with retry logic for TIME_WAIT handling\n // When gateway restarts quickly, the port may still be in TIME_WAIT state.\n // We retry with delay instead of incorrectly assuming a proxy is running.\n const tryListen = (attempt: number): Promise => {\n return new Promise((resolveAttempt, rejectAttempt) => {\n const onError = async (err: NodeJS.ErrnoException) => {\n server.removeListener(\"error\", onError);\n\n if (err.code === \"EADDRINUSE\") {\n // Port is in use - check if a proxy is actually running\n const existingProxy2 = await checkExistingProxy(listenPort);\n if (existingProxy2) {\n // Proxy is actually running - this is fine, reuse it\n console.log(`[ClawRouter] Existing proxy detected on port ${listenPort}, reusing`);\n rejectAttempt({\n code: \"REUSE_EXISTING\",\n wallet: existingProxy2.wallet,\n existingChain: existingProxy2.paymentChain,\n });\n return;\n }\n\n // Port is in TIME_WAIT (no proxy responding) - retry after delay\n if (attempt < PORT_RETRY_ATTEMPTS) {\n console.log(\n `[ClawRouter] Port ${listenPort} in TIME_WAIT, retrying in ${PORT_RETRY_DELAY_MS}ms (attempt ${attempt}/${PORT_RETRY_ATTEMPTS})`,\n );\n rejectAttempt({ code: \"RETRY\", attempt });\n return;\n }\n\n // Max retries exceeded\n console.error(\n `[ClawRouter] Port ${listenPort} still in use after ${PORT_RETRY_ATTEMPTS} attempts`,\n );\n rejectAttempt(err);\n return;\n }\n\n rejectAttempt(err);\n };\n\n server.once(\"error\", onError);\n server.listen(listenPort, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onError);\n resolveAttempt();\n });\n });\n };\n\n // Retry loop for port binding\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= PORT_RETRY_ATTEMPTS; attempt++) {\n try {\n await tryListen(attempt);\n break; // Success\n } catch (err: unknown) {\n const error = err as {\n code?: string;\n wallet?: string;\n existingChain?: string;\n attempt?: number;\n };\n\n if (error.code === \"REUSE_EXISTING\" && error.wallet) {\n // Validate payment chain matches (same check as pre-listen reuse path)\n if (error.existingChain && error.existingChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${error.existingChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n { cause: err },\n );\n }\n\n // Proxy is running, reuse it\n const baseUrl = `http://127.0.0.1:${listenPort}`;\n options.onReady?.(listenPort);\n return {\n port: listenPort,\n baseUrl,\n walletAddress: error.wallet,\n balanceMonitor,\n close: async () => {\n // No-op: we didn't start this proxy, so we shouldn't close it\n },\n };\n }\n\n if (error.code === \"RETRY\") {\n // Wait before retry\n await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS));\n continue;\n }\n\n // Other error - throw\n lastError = err as Error;\n break;\n }\n }\n\n if (lastError) {\n throw lastError;\n }\n\n // Server is now listening - set up remaining handlers\n const addr = server.address() as AddressInfo;\n const port = addr.port;\n const baseUrl = `http://127.0.0.1:${port}`;\n\n options.onReady?.(port);\n\n // Check for updates (non-blocking)\n checkForUpdates();\n\n // Add runtime error handler AFTER successful listen\n // This handles errors that occur during server operation (not just startup)\n server.on(\"error\", (err) => {\n console.error(`[ClawRouter] Server runtime error: ${err.message}`);\n options.onError?.(err);\n // Don't crash - log and continue\n });\n\n // Handle client connection errors (bad requests, socket errors)\n server.on(\"clientError\", (err, socket) => {\n console.error(`[ClawRouter] Client error: ${err.message}`);\n // Send 400 Bad Request if socket is still writable\n if (socket.writable && !socket.destroyed) {\n socket.end(\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\");\n }\n });\n\n // Track connections for graceful cleanup\n server.on(\"connection\", (socket) => {\n connections.add(socket);\n\n // Set 5-minute timeout for streaming requests\n socket.setTimeout(300_000);\n\n socket.on(\"timeout\", () => {\n console.error(`[ClawRouter] Socket timeout, destroying connection`);\n socket.destroy();\n });\n\n socket.on(\"end\", () => {\n // Half-closed by client (FIN received)\n });\n\n socket.on(\"error\", (err) => {\n console.error(`[ClawRouter] Socket error: ${err.message}`);\n });\n\n socket.on(\"close\", () => {\n connections.delete(socket);\n });\n });\n\n return {\n port,\n baseUrl,\n walletAddress: account.address,\n solanaAddress,\n balanceMonitor,\n close: () =>\n new Promise((res, rej) => {\n const timeout = setTimeout(() => {\n rej(new Error(\"[ClawRouter] Close timeout after 4s\"));\n }, 4000);\n\n sessionStore.close();\n // Destroy all active connections before closing server\n for (const socket of connections) {\n socket.destroy();\n }\n connections.clear();\n server.close((err) => {\n clearTimeout(timeout);\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n }),\n };\n}\n\n/** Result of attempting a model request */\ntype ModelRequestResult = {\n success: boolean;\n response?: Response;\n errorBody?: string;\n errorStatus?: number;\n isProviderError?: boolean;\n errorCategory?: ErrorCategory; // Semantic error classification\n};\n\n/**\n * Attempt a request with a specific model.\n * Returns the response or error details for fallback decision.\n */\nasync function tryModelRequest(\n upstreamUrl: string,\n method: string,\n headers: Record,\n body: Buffer,\n modelId: string,\n maxTokens: number,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n balanceMonitor: AnyBalanceMonitor,\n signal: AbortSignal,\n): Promise {\n // Update model in body and normalize messages\n let requestBody = body;\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(modelId);\n\n // Normalize message roles (e.g., \"developer\" -> \"system\")\n if (Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessageRoles(parsed.messages as ChatMessage[]);\n }\n\n // Remove \"blockrun\" branding from system messages so upstream LLMs don't\n // adopt \"Blockrun\" as their identity (overriding user's SOUL.md persona).\n if (Array.isArray(parsed.messages)) {\n parsed.messages = debrandSystemMessages(parsed.messages as ChatMessage[], modelId);\n }\n\n // Truncate messages to stay under BlockRun's limit (200 messages)\n if (Array.isArray(parsed.messages)) {\n const truncationResult = truncateMessages(parsed.messages as ChatMessage[]);\n parsed.messages = truncationResult.messages;\n }\n\n // Sanitize tool IDs to match Anthropic's pattern (alphanumeric, underscore, hyphen only)\n if (Array.isArray(parsed.messages)) {\n parsed.messages = sanitizeToolIds(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for Google models (first non-system message must be \"user\")\n if (isGoogleModel(modelId) && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForGoogle(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for thinking-enabled requests (add reasoning_content to tool calls)\n // Check request flags AND target model - reasoning models have thinking enabled server-side\n const hasThinkingEnabled = !!(\n parsed.thinking ||\n parsed.extended_thinking ||\n isReasoningModel(modelId)\n );\n if (hasThinkingEnabled && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForThinking(parsed.messages as ExtendedChatMessage[]);\n }\n\n requestBody = Buffer.from(JSON.stringify(parsed));\n } catch {\n // If body isn't valid JSON, use as-is\n }\n\n try {\n const response = await payFetch(upstreamUrl, {\n method,\n headers,\n body: requestBody.length > 0 ? new Uint8Array(requestBody) : undefined,\n signal,\n });\n\n // Check for provider errors\n if (response.status !== 200) {\n // Clone response to read body without consuming it\n const errorBodyChunks = await readBodyWithTimeout(response.body, ERROR_BODY_READ_TIMEOUT_MS);\n const errorBody = Buffer.concat(errorBodyChunks).toString();\n const category = categorizeError(response.status, errorBody);\n\n return {\n success: false,\n errorBody,\n errorStatus: response.status,\n isProviderError: category !== null,\n errorCategory: category ?? undefined,\n };\n }\n\n // Detect provider degradation hidden inside HTTP 200 responses.\n const contentType = response.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"json\") || contentType.includes(\"text\")) {\n try {\n const clonedChunks = await readBodyWithTimeout(\n response.clone().body,\n ERROR_BODY_READ_TIMEOUT_MS,\n );\n const responseBody = Buffer.concat(clonedChunks).toString();\n const degradedReason = detectDegradedSuccessResponse(responseBody);\n if (degradedReason) {\n return {\n success: false,\n errorBody: degradedReason,\n errorStatus: 503,\n isProviderError: true,\n };\n }\n } catch {\n // Ignore body inspection failures and pass through response.\n }\n }\n\n return { success: true, response };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return {\n success: false,\n errorBody: errorMsg,\n errorStatus: 500,\n isProviderError: true, // Network errors are retryable\n };\n }\n}\n\n/**\n * Proxy a single request through x402 payment flow to BlockRun API.\n *\n * Optimizations applied in order:\n * 1. Dedup check — if same request body seen within 30s, replay cached response\n * 2. Streaming heartbeat — for stream:true, send 200 + heartbeats immediately\n * 3. Smart routing — when model is \"blockrun/auto\", pick cheapest capable model\n * 4. Fallback chain — on provider errors, try next model in tier's fallback list\n */\nasync function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n options: ProxyOptions,\n routerOpts: RouterOptions,\n deduplicator: RequestDeduplicator,\n balanceMonitor: AnyBalanceMonitor,\n sessionStore: SessionStore,\n responseCache: ResponseCache,\n sessionJournal: SessionJournal,\n): Promise {\n const startTime = Date.now();\n\n // Build upstream URL: /v1/chat/completions → https://blockrun.ai/api/v1/chat/completions\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n let body = Buffer.concat(bodyChunks);\n\n // Track original context size for response headers\n const originalContextSizeKB = Math.ceil(body.length / 1024);\n\n // Routing debug info is on by default; disable with x-clawrouter-debug: false\n const debugMode = req.headers[\"x-clawrouter-debug\"] !== \"false\";\n\n // --- Smart routing ---\n let routingDecision: RoutingDecision | undefined;\n let hasTools = false; // true when request includes a tools schema\n let hasVision = false; // true when request includes image_url content parts\n let isStreaming = false;\n let modelId = \"\";\n let maxTokens = 4096;\n let routingProfile: \"eco\" | \"auto\" | \"premium\" | null = null;\n let balanceFallbackNotice: string | undefined;\n let budgetDowngradeNotice: string | undefined;\n let budgetDowngradeHeaderMode: \"downgraded\" | undefined;\n let accumulatedContent = \"\"; // For session journal event extraction\n let responseInputTokens: number | undefined;\n let responseOutputTokens: number | undefined;\n const isChatCompletion = req.url?.includes(\"/chat/completions\");\n\n // Extract session ID early for journal operations (header-only at this point)\n const sessionId = getSessionId(req.headers as Record);\n // Full session ID (header + content-derived) — populated once messages are parsed\n let effectiveSessionId: string | undefined = sessionId;\n\n if (isChatCompletion && body.length > 0) {\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n isStreaming = parsed.stream === true;\n modelId = (parsed.model as string) || \"\";\n maxTokens = (parsed.max_tokens as number) || 4096;\n let bodyModified = false;\n\n // Extract last user message content (used by session journal + /debug command)\n const parsedMessages = Array.isArray(parsed.messages)\n ? (parsed.messages as Array<{ role: string; content: unknown }>)\n : [];\n const lastUserMsg = [...parsedMessages].reverse().find((m) => m.role === \"user\");\n\n // Early tool detection for ALL request types (explicit model + routing profile).\n // The routing-profile branch may re-assign below (no-op since same value).\n hasTools = Array.isArray(parsed.tools) && (parsed.tools as unknown[]).length > 0;\n const rawLastContent = lastUserMsg?.content;\n const lastContent =\n typeof rawLastContent === \"string\"\n ? rawLastContent\n : Array.isArray(rawLastContent)\n ? (rawLastContent as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n\n // --- Session Journal: Inject context if needed ---\n // Check if the last user message asks about past work\n if (sessionId && parsedMessages.length > 0) {\n const messages = parsedMessages;\n\n if (sessionJournal.needsContext(lastContent)) {\n const journalText = sessionJournal.format(sessionId);\n if (journalText) {\n // Find system message and prepend journal, or add a new system message\n const sysIdx = messages.findIndex((m) => m.role === \"system\");\n if (sysIdx >= 0 && typeof messages[sysIdx].content === \"string\") {\n messages[sysIdx] = {\n ...messages[sysIdx],\n content: journalText + \"\\n\\n\" + messages[sysIdx].content,\n };\n } else {\n messages.unshift({ role: \"system\", content: journalText });\n }\n parsed.messages = messages;\n bodyModified = true;\n console.log(\n `[ClawRouter] Injected session journal (${journalText.length} chars) for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n }\n\n // --- /debug command: return routing diagnostics without calling upstream ---\n if (lastContent.startsWith(\"/debug\")) {\n const debugPrompt = lastContent.slice(\"/debug\".length).trim() || \"hello\";\n const messages = parsed.messages as Array<{ role: string; content: unknown }>;\n const systemMsg = messages?.find((m) => m.role === \"system\");\n const systemPrompt = typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n const fullText = `${systemPrompt ?? \"\"} ${debugPrompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // Determine routing profile\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n const profileName = normalizedModel.replace(\"blockrun/\", \"\");\n const debugProfile = (\n [\"eco\", \"auto\", \"premium\"].includes(profileName) ? profileName : \"auto\"\n ) as \"eco\" | \"auto\" | \"premium\";\n\n // Run scoring\n const scoring = classifyByRules(\n debugPrompt,\n systemPrompt,\n estimatedTokens,\n DEFAULT_ROUTING_CONFIG.scoring,\n );\n\n // Run full routing decision\n const debugRouting = route(debugPrompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: debugProfile,\n });\n\n // Format dimension scores\n const dimLines = (scoring.dimensions ?? [])\n .map((d) => {\n const nameStr = (d.name + \":\").padEnd(24);\n const scoreStr = d.score.toFixed(2).padStart(6);\n const sigStr = d.signal ? ` [${d.signal}]` : \"\";\n return ` ${nameStr}${scoreStr}${sigStr}`;\n })\n .join(\"\\n\");\n\n // Session info\n const sess = sessionId ? sessionStore.getSession(sessionId) : undefined;\n const sessLine = sess\n ? `Session: ${sessionId!.slice(0, 8)}... → pinned: ${sess.model} (${sess.requestCount} requests)`\n : sessionId\n ? `Session: ${sessionId.slice(0, 8)}... → no pinned model`\n : \"Session: none\";\n\n const { simpleMedium, mediumComplex, complexReasoning } =\n DEFAULT_ROUTING_CONFIG.scoring.tierBoundaries;\n\n const debugText = [\n \"ClawRouter Debug\",\n \"\",\n `Profile: ${debugProfile} | Tier: ${debugRouting.tier} | Model: ${debugRouting.model}`,\n `Confidence: ${debugRouting.confidence.toFixed(2)} | Cost: $${debugRouting.costEstimate.toFixed(4)} | Savings: ${(debugRouting.savings * 100).toFixed(0)}%`,\n `Reasoning: ${debugRouting.reasoning}`,\n \"\",\n `Scoring (weighted: ${scoring.score.toFixed(3)})`,\n dimLines,\n \"\",\n `Tier Boundaries: SIMPLE <${simpleMedium.toFixed(2)} | MEDIUM <${mediumComplex.toFixed(2)} | COMPLEX <${complexReasoning.toFixed(2)} | REASONING >=${complexReasoning.toFixed(2)}`,\n \"\",\n sessLine,\n ].join(\"\\n\");\n\n // Build synthetic OpenAI chat completion response\n const completionId = `chatcmpl-debug-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n const syntheticResponse = {\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: debugText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n\n if (isStreaming) {\n // SSE streaming response\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n const sseChunk = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n delta: { role: \"assistant\", content: debugText },\n finish_reason: null,\n },\n ],\n };\n const sseDone = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }],\n };\n res.write(`data: ${JSON.stringify(sseChunk)}\\n\\n`);\n res.write(`data: ${JSON.stringify(sseDone)}\\n\\n`);\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(syntheticResponse));\n }\n console.log(`[ClawRouter] /debug command → ${debugRouting.tier} | ${debugRouting.model}`);\n return;\n }\n\n // --- /imagegen command: generate an image via BlockRun image API ---\n if (lastContent.startsWith(\"/imagegen\")) {\n const imageArgs = lastContent.slice(\"/imagegen\".length).trim();\n\n // Parse optional flags: /imagegen --model dall-e-3 --size 1792x1024 a cute cat\n let imageModel = \"google/nano-banana\";\n let imageSize = \"1024x1024\";\n let imagePrompt = imageArgs;\n\n // Extract --model flag\n const modelMatch = imageArgs.match(/--model\\s+(\\S+)/);\n if (modelMatch) {\n const raw = modelMatch[1];\n // Resolve shorthand aliases\n const IMAGE_MODEL_ALIASES: Record = {\n \"dall-e-3\": \"openai/dall-e-3\",\n dalle3: \"openai/dall-e-3\",\n dalle: \"openai/dall-e-3\",\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n flux: \"black-forest/flux-1.1-pro\",\n \"flux-pro\": \"black-forest/flux-1.1-pro\",\n banana: \"google/nano-banana\",\n \"nano-banana\": \"google/nano-banana\",\n \"banana-pro\": \"google/nano-banana-pro\",\n \"nano-banana-pro\": \"google/nano-banana-pro\",\n };\n imageModel = IMAGE_MODEL_ALIASES[raw] ?? raw;\n imagePrompt = imagePrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n // Extract --size flag\n const sizeMatch = imageArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (sizeMatch) {\n imageSize = sizeMatch[1];\n imagePrompt = imagePrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n if (!imagePrompt) {\n const errorText = [\n \"Usage: /imagegen \",\n \"\",\n \"Options:\",\n \" --model Model to use (default: nano-banana)\",\n \" --size Image size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" nano-banana Google Gemini Flash — $0.05/image\",\n \" banana-pro Google Gemini Pro — $0.10/image (up to 4K)\",\n \" dall-e-3 OpenAI DALL-E 3 — $0.04/image\",\n \" gpt-image OpenAI GPT Image 1 — $0.02/image\",\n \" flux Black Forest Flux 1.1 Pro — $0.04/image\",\n \"\",\n \"Examples:\",\n \" /imagegen a cat wearing sunglasses\",\n \" /imagegen --model dall-e-3 a futuristic city at sunset\",\n \" /imagegen --model banana-pro --size 2048x2048 mountain landscape\",\n ].join(\"\\n\");\n\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: errorText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: errorText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n console.log(`[ClawRouter] /imagegen command → showing usage help`);\n return;\n }\n\n // Call upstream image generation API\n console.log(\n `[ClawRouter] /imagegen command → ${imageModel} (${imageSize}): ${imagePrompt.slice(0, 80)}...`,\n );\n try {\n const imageUpstreamUrl = `${apiBase}/v1/images/generations`;\n const imageBody = JSON.stringify({\n model: imageModel,\n prompt: imagePrompt,\n size: imageSize,\n n: 1,\n });\n const imageResponse = await payFetch(imageUpstreamUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: imageBody,\n });\n\n const imageResult = (await imageResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!imageResponse.ok || imageResult.error) {\n const errMsg =\n typeof imageResult.error === \"string\"\n ? imageResult.error\n : ((imageResult.error as { message?: string })?.message ??\n `HTTP ${imageResponse.status}`);\n responseText = `Image generation failed: ${errMsg}`;\n console.log(`[ClawRouter] /imagegen error: ${errMsg}`);\n } else {\n const images = imageResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image generation returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /imagegen: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\n \"Image generated but upload failed. Try again or use --model dall-e-3.\",\n );\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${imageModel} | Size: ${imageSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /imagegen success: ${images.length} image(s) generated`);\n // Log /imagegen usage with actual x402 payment\n const imagegenActualCost =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(imageModel, imageSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: imageModel,\n tier: \"IMAGE\",\n cost: imagegenActualCost,\n baselineCost: imagegenActualCost,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n // Return as synthetic chat completion\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: responseText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: responseText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /imagegen error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image generation failed: ${errMsg}`, type: \"image_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // --- /img2img command: edit an image via BlockRun image2image API ---\n if (lastContent.startsWith(\"/img2img\")) {\n const imgArgs = lastContent.slice(\"/img2img\".length).trim();\n\n let img2imgModel = \"openai/gpt-image-1\";\n let img2imgSize = \"1024x1024\";\n let imagePath: string | null = null;\n let maskPath: string | null = null;\n let img2imgPrompt = imgArgs;\n\n const imageMatch = imgArgs.match(/--image\\s+(\\S+)/);\n if (imageMatch) {\n imagePath = imageMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--image\\s+\\S+/, \"\").trim();\n }\n\n const maskMatch = imgArgs.match(/--mask\\s+(\\S+)/);\n if (maskMatch) {\n maskPath = maskMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--mask\\s+\\S+/, \"\").trim();\n }\n\n const img2imgSizeMatch = imgArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (img2imgSizeMatch) {\n img2imgSize = img2imgSizeMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n const img2imgModelMatch = imgArgs.match(/--model\\s+(\\S+)/);\n if (img2imgModelMatch) {\n const raw = img2imgModelMatch[1];\n const IMG2IMG_ALIASES: Record = {\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n };\n img2imgModel = IMG2IMG_ALIASES[raw] ?? raw;\n img2imgPrompt = img2imgPrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n const usageText = [\n \"Usage: /img2img --image \",\n \"\",\n \"Options:\",\n \" --image Source image path (required)\",\n \" --mask Mask image path (optional, white = area to edit)\",\n \" --model Model (default: gpt-image-1)\",\n \" --size Output size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" gpt-image-1 OpenAI GPT Image 1 — $0.02/image\",\n \"\",\n \"Examples:\",\n \" /img2img --image ~/photo.png change background to starry sky\",\n \" /img2img --image ./cat.jpg --mask ./mask.png remove the background\",\n \" /img2img --image /tmp/portrait.png --size 1536x1024 add a hat\",\n ].join(\"\\n\");\n\n const sendImg2ImgText = (text: string) => {\n const completionId = `chatcmpl-img2img-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: { role: \"assistant\", content: text }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/img2img\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n };\n\n if (!imagePath || !img2imgPrompt) {\n sendImg2ImgText(usageText);\n return;\n }\n\n let imageDataUri: string;\n let maskDataUri: string | undefined;\n try {\n imageDataUri = readImageFileAsDataUri(imagePath);\n if (maskPath) maskDataUri = readImageFileAsDataUri(maskPath);\n } catch (fileErr) {\n const fileErrMsg = fileErr instanceof Error ? fileErr.message : String(fileErr);\n sendImg2ImgText(`Failed to read image file: ${fileErrMsg}`);\n return;\n }\n\n console.log(\n `[ClawRouter] /img2img → ${img2imgModel} (${img2imgSize}): ${img2imgPrompt.slice(0, 80)}`,\n );\n\n try {\n const img2imgBody = JSON.stringify({\n model: img2imgModel,\n prompt: img2imgPrompt,\n image: imageDataUri,\n ...(maskDataUri ? { mask: maskDataUri } : {}),\n size: img2imgSize,\n n: 1,\n });\n\n const img2imgResponse = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: img2imgBody,\n });\n\n const img2imgResult = (await img2imgResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!img2imgResponse.ok || img2imgResult.error) {\n const errMsg =\n typeof img2imgResult.error === \"string\"\n ? img2imgResult.error\n : ((img2imgResult.error as { message?: string })?.message ??\n `HTTP ${img2imgResponse.status}`);\n responseText = `Image editing failed: ${errMsg}`;\n console.log(`[ClawRouter] /img2img error: ${errMsg}`);\n } else {\n const images = img2imgResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image editing returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /img2img: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\"Image edited but upload failed. Try again.\");\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${img2imgModel} | Size: ${img2imgSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /img2img success: ${images.length} image(s)`);\n // Log /img2img usage with actual x402 payment\n const img2imgActualCost2 =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(img2imgModel, img2imgSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost2,\n baselineCost: img2imgActualCost2,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n sendImg2ImgText(responseText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /img2img error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image editing failed: ${errMsg}`, type: \"img2img_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Force stream: false — BlockRun API doesn't support streaming yet\n // ClawRouter handles SSE heartbeat simulation for upstream compatibility\n if (parsed.stream === true) {\n parsed.stream = false;\n bodyModified = true;\n }\n\n // Normalize model name for comparison (trim whitespace, lowercase)\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n\n // Resolve model aliases (e.g., \"claude\" -> \"anthropic/claude-sonnet-4-6\")\n const resolvedModel = resolveModelAlias(normalizedModel);\n const wasAlias = resolvedModel !== normalizedModel;\n\n // Check both normalizedModel and resolvedModel — OpenClaw may send \"openai/eco\"\n // which resolveModelAlias strips to \"eco\" (a valid routing profile)\n const isRoutingProfile =\n ROUTING_PROFILES.has(normalizedModel) || ROUTING_PROFILES.has(resolvedModel);\n\n // Extract routing profile type (free/eco/auto/premium)\n if (isRoutingProfile) {\n const profileName = resolvedModel.replace(\"blockrun/\", \"\");\n routingProfile = profileName as \"eco\" | \"auto\" | \"premium\";\n }\n\n // Debug: log received model name\n console.log(\n `[ClawRouter] Received model: \"${parsed.model}\" -> normalized: \"${normalizedModel}\"${wasAlias ? ` -> alias: \"${resolvedModel}\"` : \"\"}${routingProfile ? `, profile: ${routingProfile}` : \"\"}`,\n );\n\n // For explicit model requests, always canonicalize the model ID before upstream calls.\n // This ensures case/whitespace variants (e.g. \"DEEPSEEK/...\" or \" model \") route correctly.\n if (!isRoutingProfile) {\n if (parsed.model !== resolvedModel) {\n parsed.model = resolvedModel;\n bodyModified = true;\n }\n modelId = resolvedModel;\n }\n\n // Handle routing profiles (free/eco/auto/premium)\n if (isRoutingProfile) {\n {\n // eco/auto/premium - use tier routing\n // Check for session persistence - use pinned model if available\n // Fall back to deriving a session ID from message content when OpenClaw\n // doesn't send an explicit x-session-id header (the default behaviour).\n effectiveSessionId =\n getSessionId(req.headers as Record) ??\n deriveSessionId(parsedMessages);\n const existingSession = effectiveSessionId\n ? sessionStore.getSession(effectiveSessionId)\n : undefined;\n\n // Extract prompt from last user message (handles both string and Anthropic array content)\n const rawPrompt = lastUserMsg?.content;\n const prompt =\n typeof rawPrompt === \"string\"\n ? rawPrompt\n : Array.isArray(rawPrompt)\n ? (rawPrompt as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n const systemMsg = parsedMessages.find((m) => m.role === \"system\");\n const systemPrompt =\n typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n\n // Tool detection — when tools are present, force agentic tiers for reliable tool use\n const tools = parsed.tools as unknown[] | undefined;\n hasTools = Array.isArray(tools) && tools.length > 0;\n\n if (hasTools && tools) {\n console.log(`[ClawRouter] Tools detected (${tools.length}), forcing agentic tiers`);\n }\n\n // Vision detection: scan messages for image_url content parts\n hasVision = parsedMessages.some((m) => {\n if (Array.isArray(m.content)) {\n return (m.content as Array<{ type: string }>).some((p) => p.type === \"image_url\");\n }\n return false;\n });\n if (hasVision) {\n console.log(`[ClawRouter] Vision content detected, filtering to vision-capable models`);\n }\n\n // Always route based on current request content\n routingDecision = route(prompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: routingProfile ?? undefined,\n hasTools,\n });\n\n // Keep agentic routing when tools are present, even for SIMPLE queries.\n // Tool-using requests need models with reliable function-call support;\n // demoting to non-agentic tiers causes fallback to models that refuse\n // tool schemas (gemini-flash-lite, deepseek) or lack tool support entirely.\n if (hasTools && routingDecision.tier === \"SIMPLE\") {\n console.log(\n `[ClawRouter] SIMPLE+tools: keeping agentic model ${routingDecision.model} (tools need reliable function-call support)`,\n );\n }\n\n if (existingSession) {\n // Never downgrade: only upgrade the session when the current request needs a higher\n // tier. This fixes the OpenClaw startup-message bias (the startup message always\n // scores low-complexity, which previously pinned all subsequent real queries to a\n // cheap model) while still preventing mid-task model switching on simple follow-ups.\n const tierRank: Record = {\n SIMPLE: 0,\n MEDIUM: 1,\n COMPLEX: 2,\n REASONING: 3,\n };\n const existingRank = tierRank[existingSession.tier] ?? 0;\n const newRank = tierRank[routingDecision.tier] ?? 0;\n\n if (newRank > existingRank) {\n // Current request needs higher capability — upgrade the session\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... upgrading: ${existingSession.tier} → ${routingDecision.tier} (${routingDecision.model})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n }\n } else if (routingDecision.tier === \"SIMPLE\") {\n // SIMPLE follow-up in an active session: let it use cheap routing.\n // e.g. \"你好\" or \"thanks\" after a complex task should not inherit the\n // expensive session model or recount all context tokens on a paid model.\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... SIMPLE follow-up, using cheap model: ${routingDecision.model} (bypassing pinned ${existingSession.tier})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // routingDecision already reflects cheap model — no override needed\n } else {\n // Keep existing higher-tier model (prevent downgrade mid-task)\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... keeping pinned model: ${existingSession.model} (${existingSession.tier} >= ${routingDecision.tier})`,\n );\n parsed.model = existingSession.model;\n modelId = existingSession.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // Reflect the actual model used in the routing decision for logging/fallback\n routingDecision = {\n ...routingDecision,\n model: existingSession.model,\n tier: existingSession.tier as Tier,\n };\n }\n\n // --- Three-strike escalation: detect repetitive request patterns ---\n const lastAssistantMsg = [...parsedMessages]\n .reverse()\n .find((m) => m.role === \"assistant\");\n const assistantToolCalls = (\n lastAssistantMsg as { tool_calls?: Array<{ function?: { name?: string } }> }\n )?.tool_calls;\n const toolCallNames = Array.isArray(assistantToolCalls)\n ? assistantToolCalls\n .map((tc) => tc.function?.name)\n .filter((n): n is string => Boolean(n))\n : undefined;\n const contentHash = hashRequestContent(prompt, toolCallNames);\n const shouldEscalate = sessionStore.recordRequestHash(effectiveSessionId!, contentHash);\n\n if (shouldEscalate) {\n const activeTierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n const escalation = sessionStore.escalateSession(\n effectiveSessionId!,\n activeTierConfigs,\n );\n if (escalation) {\n console.log(\n `[ClawRouter] ⚡ 3-strike escalation: ${existingSession.model} → ${escalation.model} (${existingSession.tier} → ${escalation.tier})`,\n );\n parsed.model = escalation.model;\n modelId = escalation.model;\n routingDecision = {\n ...routingDecision,\n model: escalation.model,\n tier: escalation.tier as Tier,\n };\n }\n }\n } else {\n // No session — pin this routing decision for future requests\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... pinned to model: ${routingDecision.model}`,\n );\n }\n }\n\n options.onRouted?.(routingDecision);\n }\n }\n\n // Ensure effectiveSessionId is set for explicit model requests via content hash fallback.\n // Routing profile requests already derive session ID from message content (see line above).\n // Explicit model requests (openai/gpt-4o, anthropic/claude-*, etc.) without an\n // x-session-id header would otherwise have no session ID → maxCostPerRun not tracked.\n if (!effectiveSessionId && parsedMessages.length > 0) {\n effectiveSessionId = deriveSessionId(parsedMessages);\n }\n\n // Rebuild body if modified — map free/xxx → nvidia/xxx for upstream\n if (bodyModified) {\n if (parsed.model && typeof parsed.model === \"string\") {\n parsed.model = toUpstreamModelId(parsed.model);\n }\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Log routing errors so they're not silently swallowed\n const errorMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Routing error: ${errorMsg}`);\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n options.onError?.(new Error(`Routing failed: ${errorMsg}`));\n }\n }\n\n // --- Auto-compression ---\n // Compress large requests to reduce network usage and improve performance\n const autoCompress = options.autoCompressRequests ?? true;\n const compressionThreshold = options.compressionThresholdKB ?? 180;\n const requestSizeKB = Math.ceil(body.length / 1024);\n\n if (autoCompress && requestSizeKB > compressionThreshold) {\n try {\n console.log(\n `[ClawRouter] Request size ${requestSizeKB}KB exceeds threshold ${compressionThreshold}KB, applying compression...`,\n );\n\n // Parse messages for compression\n const parsed = JSON.parse(body.toString()) as {\n messages?: NormalizedMessage[];\n [key: string]: unknown;\n };\n\n if (parsed.messages && parsed.messages.length > 0 && shouldCompress(parsed.messages)) {\n // Apply compression with conservative settings\n const compressionResult = await compressContext(parsed.messages, {\n enabled: true,\n preserveRaw: false, // Don't need originals in proxy\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // Disabled: requires model to understand codebook\n paths: false, // Disabled: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // Disabled: may lose important context\n dynamicCodebook: false, // Disabled: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false,\n },\n });\n\n const compressedSizeKB = Math.ceil(compressionResult.compressedChars / 1024);\n const savings = (((requestSizeKB - compressedSizeKB) / requestSizeKB) * 100).toFixed(1);\n\n console.log(\n `[ClawRouter] Compressed ${requestSizeKB}KB → ${compressedSizeKB}KB (${savings}% reduction)`,\n );\n\n // Update request body with compressed messages\n parsed.messages = compressionResult.messages;\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Compression failed - continue with original request\n console.warn(\n `[ClawRouter] Compression failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // --- Response cache check (long-term, 10min TTL) ---\n const cacheKey = ResponseCache.generateKey(body);\n const reqHeaders: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (typeof value === \"string\") reqHeaders[key] = value;\n }\n if (responseCache.shouldCache(body, reqHeaders)) {\n const cachedResponse = responseCache.get(cacheKey);\n if (cachedResponse) {\n console.log(`[ClawRouter] Cache HIT for ${cachedResponse.model} (saved API call)`);\n res.writeHead(cachedResponse.status, cachedResponse.headers);\n res.end(cachedResponse.body);\n return;\n }\n }\n\n // --- Dedup check (short-term, 30s TTL for retries) ---\n const dedupKey = RequestDeduplicator.hash(body);\n\n // Check dedup cache (catches retries within 30s)\n const cached = deduplicator.getCached(dedupKey);\n if (cached) {\n res.writeHead(cached.status, cached.headers);\n res.end(cached.body);\n return;\n }\n\n // Check in-flight — wait for the original request to complete\n const inflight = deduplicator.getInflight(dedupKey);\n if (inflight) {\n const result = await inflight;\n res.writeHead(result.status, result.headers);\n res.end(result.body);\n return;\n }\n\n // Register this request as in-flight\n deduplicator.markInflight(dedupKey);\n\n // --- Pre-request balance check ---\n // Estimate cost and check if wallet has sufficient balance\n // Skip if skipBalanceCheck is set (for testing) or if using free model\n let estimatedCostMicros: bigint | undefined;\n // Use `let` so the balance-fallback path can update this when modelId is switched to a free model.\n let isFreeModel = FREE_MODELS.has(modelId ?? \"\");\n\n if (modelId && !options.skipBalanceCheck && !isFreeModel) {\n const estimated = estimateAmount(modelId, body.length, maxTokens);\n if (estimated) {\n estimatedCostMicros = BigInt(estimated);\n\n // Apply extra buffer for balance check to prevent x402 failures after streaming starts.\n // This is aggressive to avoid triggering OpenClaw's 5-24 hour billing cooldown.\n const bufferedCostMicros =\n (estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100))) / 100n;\n\n // Check balance before proceeding (using buffered amount)\n const sufficiency = await balanceMonitor.checkSufficient(bufferedCostMicros);\n\n if (sufficiency.info.isEmpty || !sufficiency.sufficient) {\n // Wallet is empty or insufficient — fallback to free model\n const originalModel = modelId;\n console.log(\n `[ClawRouter] Wallet ${sufficiency.info.isEmpty ? \"empty\" : \"insufficient\"} (${sufficiency.info.balanceUSD}), falling back to free model: ${FREE_MODEL} (requested: ${originalModel})`,\n );\n modelId = FREE_MODEL;\n isFreeModel = true; // keep in sync — budget logic gates on !isFreeModel\n // Update the body with new model (map free/ → nvidia/ for upstream)\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(FREE_MODEL);\n body = Buffer.from(JSON.stringify(parsed));\n\n // Set notice to prepend to response so user knows about the fallback\n balanceFallbackNotice = sufficiency.info.isEmpty\n ? `> **⚠️ Wallet empty** — using free model. Fund your wallet to use ${originalModel}.\\n\\n`\n : `> **⚠️ Insufficient balance** (${sufficiency.info.balanceUSD}) — using free model instead of ${originalModel}.\\n\\n`;\n\n // Notify about the fallback\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n });\n } else if (sufficiency.info.isLow) {\n // Balance is low but sufficient — warn and proceed\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n });\n }\n }\n }\n\n // --- Cost cap check: strict mode hard-stop ---\n // In 'strict' mode, reject if the projected session spend (accumulated + this request's\n // estimate) would exceed the cap. Checking projected cost (not just historical) prevents\n // a single large request from overshooting the cap before it's recorded.\n // In 'graceful' mode (default), the cap is enforced via model downgrade below.\n // Must happen before streaming headers are sent.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"strict\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n // Include this request's estimated cost so even the first request is blocked\n // if it would push the session over the cap.\n const thisReqEstStr =\n estimatedCostMicros !== undefined\n ? estimatedCostMicros.toString()\n : modelId\n ? estimateAmount(modelId, body.length, maxTokens)\n : undefined;\n const thisReqEstUsd = thisReqEstStr ? Number(thisReqEstStr) / 1_000_000 : 0;\n const projectedCostUsd = runCostUsd + thisReqEstUsd;\n if (projectedCostUsd > options.maxCostPerRunUsd) {\n console.log(\n `[ClawRouter] Cost cap exceeded for session ${effectiveSessionId.slice(0, 8)}...: projected $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) > $${options.maxCostPerRunUsd} limit`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter cost cap exceeded: projected spend $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) would exceed limit $${options.maxCostPerRunUsd}`,\n type: \"cost_cap_exceeded\",\n code: \"cost_cap_exceeded\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n\n // --- Budget pre-check: block when remaining budget can't cover the request ---\n // Must happen BEFORE streaming headers (429 can't be sent after SSE headers are flushed).\n // Three cases that require a hard block rather than graceful downgrade:\n // (A) tool/COMPLEX/REASONING routing profile — free model can't substitute\n // (B) explicit model request (no routing profile) — user chose a specific model,\n // silently substituting with free model would be deceptive regardless of task type\n // Simple routing profile requests are handled later via graceful downgrade.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const isComplexOrAgentic =\n hasTools || routingDecision?.tier === \"COMPLEX\" || routingDecision?.tier === \"REASONING\";\n\n if (isComplexOrAgentic) {\n // Case A: tool/complex/agentic routing profile — check global model table\n // Intentionally exclude free models: they cannot handle complex/agentic tasks.\n const canAffordAnyNonFreeModel = BLOCKRUN_MODELS.some((m) => {\n if (FREE_MODELS.has(m.id)) return false;\n const est = estimateAmount(m.id, body.length, maxTokens);\n return est !== undefined && Number(est) / 1_000_000 <= remainingUsd;\n });\n if (!canAffordAnyNonFreeModel) {\n console.log(\n `[ClawRouter] Budget insufficient for agentic/complex session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (silent downgrade would corrupt tool/complex responses)`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n } else if (!routingDecision && modelId && !FREE_MODELS.has(modelId)) {\n // Case B: explicit model request (user chose a specific model, not a routing profile).\n // Silently substituting their choice with free model is deceptive — block instead.\n const est = estimateAmount(modelId, body.length, maxTokens);\n const canAfford = !est || Number(est) / 1_000_000 <= remainingUsd;\n if (!canAfford) {\n console.log(\n `[ClawRouter] Budget insufficient for explicit model ${modelId} in session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (user explicitly chose ${modelId})`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue using ${modelId}.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n }\n\n // --- Streaming: early header flush + heartbeat ---\n let heartbeatInterval: ReturnType | undefined;\n let headersSentEarly = false;\n\n if (isStreaming) {\n // Send 200 + SSE headers immediately, before x402 flow\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n headersSentEarly = true;\n\n // First heartbeat immediately\n safeWrite(res, \": heartbeat\\n\\n\");\n\n // Continue heartbeats every 2s while waiting for upstream\n heartbeatInterval = setInterval(() => {\n if (canWrite(res)) {\n safeWrite(res, \": heartbeat\\n\\n\");\n } else {\n // Socket closed, stop heartbeat\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n }, HEARTBEAT_INTERVAL_MS);\n }\n\n // Forward headers, stripping host, connection, and content-length\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") {\n headers[key] = value;\n }\n }\n if (!headers[\"content-type\"]) {\n headers[\"content-type\"] = \"application/json\";\n }\n headers[\"user-agent\"] = USER_AGENT;\n\n // --- Client disconnect cleanup ---\n let completed = false;\n res.on(\"close\", () => {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n // Remove from in-flight if client disconnected before completion\n if (!completed) {\n deduplicator.removeInflight(dedupKey);\n }\n });\n\n // --- Request timeout ---\n // Global controller: hard deadline for the entire request (all model attempts combined).\n // Each model attempt gets its own per-model controller (PER_MODEL_TIMEOUT_MS).\n // If a model times out individually, we fall back to the next model instead of failing.\n // Only the global timeout causes an immediate error.\n const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const globalController = new AbortController();\n const timeoutId = setTimeout(() => globalController.abort(), timeoutMs);\n\n try {\n // --- Build fallback chain ---\n // If we have a routing decision, get the full fallback chain for the tier\n // Otherwise, just use the current model (no fallback for explicit model requests)\n let modelsToTry: string[];\n const excludeList = options.excludeModels ?? loadExcludeList();\n if (routingDecision) {\n // Estimate total context: input tokens (~4 chars per token) + max output tokens\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const estimatedTotalTokens = estimatedInputTokens + maxTokens;\n\n // Use tier configs from the routing decision (set by RouterStrategy)\n const tierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n // Get full chain first, then filter by context\n const fullChain = getFallbackChain(routingDecision.tier, tierConfigs);\n const contextFiltered = getFallbackChainFiltered(\n routingDecision.tier,\n tierConfigs,\n estimatedTotalTokens,\n getModelContextWindow,\n );\n\n // Log if models were filtered out due to context limits\n const contextExcluded = fullChain.filter((m) => !contextFiltered.includes(m));\n if (contextExcluded.length > 0) {\n console.log(\n `[ClawRouter] Context filter (~${estimatedTotalTokens} tokens): excluded ${contextExcluded.join(\", \")}`,\n );\n }\n\n // Filter out user-excluded models\n const excludeFiltered = filterByExcludeList(contextFiltered, excludeList);\n const excludeExcluded = contextFiltered.filter((m) => !excludeFiltered.includes(m));\n if (excludeExcluded.length > 0) {\n console.log(\n `[ClawRouter] Exclude filter: excluded ${excludeExcluded.join(\", \")} (user preference)`,\n );\n }\n\n // Filter to models that support tool calling when request has tools.\n // Prevents models like grok-code-fast-1 from outputting tool invocations\n // as plain text JSON (the \"talking to itself\" bug).\n let toolFiltered = filterByToolCalling(excludeFiltered, hasTools, supportsToolCalling);\n const toolExcluded = excludeFiltered.filter((m) => !toolFiltered.includes(m));\n if (toolExcluded.length > 0) {\n console.log(\n `[ClawRouter] Tool-calling filter: excluded ${toolExcluded.join(\", \")} (no structured function call support)`,\n );\n }\n\n // Filter out models that declare toolCalling but fail tool compliance in practice.\n // gemini-2.5-flash-lite refuses certain tool schemas (e.g. brave search) while\n // cheaper models like nvidia/gpt-oss-120b handle them fine.\n const TOOL_NONCOMPLIANT_MODELS = [\n \"google/gemini-2.5-flash-lite\",\n \"google/gemini-3-pro-preview\",\n \"google/gemini-3.1-pro\",\n ];\n if (hasTools && toolFiltered.length > 1) {\n const compliant = toolFiltered.filter((m) => !TOOL_NONCOMPLIANT_MODELS.includes(m));\n if (compliant.length > 0 && compliant.length < toolFiltered.length) {\n const dropped = toolFiltered.filter((m) => TOOL_NONCOMPLIANT_MODELS.includes(m));\n console.log(\n `[ClawRouter] Tool-compliance filter: excluded ${dropped.join(\", \")} (unreliable tool schema handling)`,\n );\n toolFiltered = compliant;\n }\n }\n\n // Filter to models that support vision when request has image_url content\n const visionFiltered = filterByVision(toolFiltered, hasVision, supportsVision);\n const visionExcluded = toolFiltered.filter((m) => !visionFiltered.includes(m));\n if (visionExcluded.length > 0) {\n console.log(\n `[ClawRouter] Vision filter: excluded ${visionExcluded.join(\", \")} (no vision support)`,\n );\n }\n\n // Limit to MAX_FALLBACK_ATTEMPTS to prevent infinite loops\n modelsToTry = visionFiltered.slice(0, MAX_FALLBACK_ATTEMPTS);\n\n // Deprioritize rate-limited models (put them at the end)\n modelsToTry = prioritizeNonRateLimited(modelsToTry);\n } else {\n // For explicit model requests, use the requested model\n modelsToTry = modelId ? [modelId] : [];\n }\n\n // Ensure free model is the last-resort fallback for non-tool requests.\n // Skip free fallback when tools are present — nvidia/gpt-oss-120b lacks\n // tool calling support and would produce broken responses for agentic tasks.\n if (!hasTools && !modelsToTry.includes(FREE_MODEL) && !excludeList.has(FREE_MODEL)) {\n modelsToTry.push(FREE_MODEL); // last-resort free fallback\n }\n\n // --- Budget-aware routing (graceful mode) ---\n // Filter modelsToTry to only models that fit within the remaining session budget.\n // Simple tasks (no tools, non-complex tier): downgrade with visible warning.\n // Complex/agentic tasks with no affordable model: already blocked above (before streaming headers).\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const beforeFilter = [...modelsToTry];\n modelsToTry = modelsToTry.filter((m) => {\n if (FREE_MODELS.has(m)) return true; // free models always fit (no cost)\n const est = estimateAmount(m, body.length, maxTokens);\n if (!est) return true; // no pricing data → keep (permissive)\n return Number(est) / 1_000_000 <= remainingUsd;\n });\n\n const excluded = beforeFilter.filter((m) => !modelsToTry.includes(m));\n\n // Second-pass block: the pre-check caught obvious cases early (before streaming headers).\n // Here we recheck against the actual filtered modelsToTry chain. If the ONLY remaining\n // models are free, we must block rather than silently degrade for:\n // (A) complex/agentic routing profile tasks (tools / COMPLEX / REASONING tier)\n // (B) explicit model requests (user chose a specific model; free substitution is deceptive)\n // The pre-check already handles case (B) for non-streaming; this is a safety net for\n // streaming requests where SSE headers may have already been sent.\n const isComplexOrAgenticFilter =\n hasTools ||\n routingDecision?.tier === \"COMPLEX\" ||\n routingDecision?.tier === \"REASONING\" ||\n routingDecision === undefined; // explicit model: no routing profile → user chose the model\n const filteredToFreeOnly =\n modelsToTry.length > 0 && modelsToTry.every((m) => FREE_MODELS.has(m));\n\n if (isComplexOrAgenticFilter && filteredToFreeOnly) {\n const budgetSummary = `$${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget filter left only free model for complex/agentic session — blocking (${budgetSummary})`,\n );\n const errPayload = JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: remaining budget (${budgetSummary}) cannot support a complex/tool request. Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n });\n if (heartbeatInterval) clearInterval(heartbeatInterval);\n if (headersSentEarly) {\n // Streaming: inject error SSE event + [DONE] and close\n safeWrite(res, `data: ${errPayload}\\n\\ndata: [DONE]\\n\\n`);\n res.end();\n } else {\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(errPayload);\n }\n deduplicator.removeInflight(dedupKey);\n return;\n }\n\n if (excluded.length > 0) {\n const budgetSummary =\n remainingUsd > 0\n ? `$${remainingUsd.toFixed(4)} remaining`\n : `budget exhausted ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget downgrade (${budgetSummary}): excluded ${excluded.join(\", \")}`,\n );\n\n // A: Set visible warning notice — prepended to response so user sees the downgrade\n const fromModel = excluded[0];\n const usingFree = modelsToTry.length === 1 && FREE_MODELS.has(modelsToTry[0]);\n if (usingFree) {\n budgetDowngradeNotice = `> **⚠️ Budget cap reached** ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd}) — downgraded to free model. Quality may be reduced. Increase \\`maxCostPerRun\\` to continue with ${fromModel}.\\n\\n`;\n } else {\n const toModel = modelsToTry[0] ?? FREE_MODEL; // last resort\n budgetDowngradeNotice = `> **⚠️ Budget low** ($${remainingUsd > 0 ? remainingUsd.toFixed(4) : \"0.0000\"} remaining) — using ${toModel} instead of ${fromModel}.\\n\\n`;\n }\n // B: Header flag for orchestration layers (e.g. OpenClaw can pause/warn the user)\n budgetDowngradeHeaderMode = \"downgraded\";\n }\n }\n\n // --- Fallback loop: try each model until success ---\n let upstream: Response | undefined;\n let lastError: { body: string; status: number } | undefined;\n let actualModelUsed = modelId;\n const failedAttempts: Array<{ model: string; reason: string; status: number }> = [];\n\n for (let i = 0; i < modelsToTry.length; i++) {\n const tryModel = modelsToTry[i];\n const isLastAttempt = i === modelsToTry.length - 1;\n\n // Abort immediately if global deadline has already fired\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n console.log(`[ClawRouter] Trying model ${i + 1}/${modelsToTry.length}: ${tryModel}`);\n\n // Per-model abort controller — each model attempt gets its own 60s window.\n // When it fires, the fallback loop moves to the next model rather than failing.\n const modelController = new AbortController();\n const modelTimeoutId = setTimeout(() => modelController.abort(), PER_MODEL_TIMEOUT_MS);\n const combinedSignal = AbortSignal.any([globalController.signal, modelController.signal]);\n\n const result = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n combinedSignal,\n );\n clearTimeout(modelTimeoutId);\n\n // If the global deadline fired during this attempt, bail out entirely\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n // If the per-model timeout fired (but not global), treat as fallback-worthy error\n if (!result.success && modelController.signal.aborted && !isLastAttempt) {\n console.log(\n `[ClawRouter] Model ${tryModel} timed out after ${PER_MODEL_TIMEOUT_MS}ms, trying fallback`,\n );\n recordProviderError(tryModel, \"server_error\");\n continue;\n }\n\n if (result.success && result.response) {\n upstream = result.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Success with model: ${tryModel}`);\n // Accumulate estimated cost to session for maxCostPerRun tracking\n if (options.maxCostPerRunUsd && effectiveSessionId && !FREE_MODELS.has(tryModel)) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n\n // Request failed\n lastError = {\n body: result.errorBody || \"Unknown error\",\n status: result.errorStatus || 500,\n };\n failedAttempts.push({\n model: tryModel,\n reason: result.errorCategory || `HTTP ${result.errorStatus || 500}`,\n status: result.errorStatus || 500,\n });\n\n // Payment error (insufficient funds, simulation failure) — skip remaining\n // paid models, jump straight to free model. No point trying other paid\n // models with the same wallet state.\n // Must be checked BEFORE isProviderError gate: payment settlement failures\n // may return non-standard HTTP codes that categorizeError doesn't recognize,\n // causing isProviderError=false and breaking out of the fallback loop.\n const isPaymentErr =\n /payment.*verification.*failed|payment.*settlement.*failed|insufficient.*funds|transaction_simulation_failed/i.test(\n result.errorBody || \"\",\n );\n if (isPaymentErr && !FREE_MODELS.has(tryModel) && !isLastAttempt) {\n failedAttempts.push({\n ...failedAttempts[failedAttempts.length - 1],\n reason: \"payment_error\",\n });\n const freeIdx = modelsToTry.indexOf(FREE_MODEL);\n if (freeIdx > i + 1) {\n console.log(`[ClawRouter] Payment error — skipping to free model: ${FREE_MODEL}`);\n i = freeIdx - 1; // loop will increment to freeIdx\n continue;\n }\n // Free model not in chain — add it and try\n if (freeIdx === -1) {\n modelsToTry.push(FREE_MODEL);\n console.log(`[ClawRouter] Payment error — appending free model: ${FREE_MODEL}`);\n continue;\n }\n }\n\n // If it's a provider error and not the last attempt, try next model\n if (result.isProviderError && !isLastAttempt) {\n const isExplicitModelError = !routingDecision;\n const isUnknownExplicitModel =\n isExplicitModelError && /unknown.*model|invalid.*model/i.test(result.errorBody || \"\");\n if (isUnknownExplicitModel) {\n console.log(\n `[ClawRouter] Explicit model error from ${tryModel}, not falling back: ${result.errorBody?.slice(0, 100)}`,\n );\n break;\n }\n\n // Record error and apply category-specific handling\n const errorCat = result.errorCategory;\n if (errorCat) {\n recordProviderError(tryModel, errorCat);\n }\n\n if (errorCat === \"rate_limited\") {\n // --- Stepped backoff retry (429) ---\n // Token-bucket rate limits often recover within milliseconds.\n // Retry once after 200ms before treating this as a model-level failure.\n if (!isLastAttempt && !globalController.signal.aborted) {\n console.log(\n `[ClawRouter] Rate-limited on ${tryModel}, retrying in 200ms before failover`,\n );\n await new Promise((resolve) => setTimeout(resolve, 200));\n if (!globalController.signal.aborted) {\n const retryController = new AbortController();\n const retryTimeoutId = setTimeout(\n () => retryController.abort(),\n PER_MODEL_TIMEOUT_MS,\n );\n const retrySignal = AbortSignal.any([\n globalController.signal,\n retryController.signal,\n ]);\n const retryResult = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n retrySignal,\n );\n clearTimeout(retryTimeoutId);\n if (retryResult.success && retryResult.response) {\n upstream = retryResult.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Rate-limit retry succeeded for: ${tryModel}`);\n if (options.maxCostPerRunUsd && effectiveSessionId && tryModel !== FREE_MODEL) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n // Retry also failed — fall through to markRateLimited\n }\n }\n markRateLimited(tryModel);\n // Check for server-side update hint in 429 response\n try {\n const parsed = JSON.parse(result.errorBody || \"{}\");\n if (parsed.update_available) {\n console.log(\"\");\n console.log(\n `\\x1b[33m⬆️ ClawRouter ${parsed.update_available} available (you have ${VERSION})\\x1b[0m`,\n );\n console.log(\n ` Run: \\x1b[36mcurl -fsSL ${parsed.update_url || \"https://blockrun.ai/ClawRouter-update\"} | bash\\x1b[0m`,\n );\n console.log(\"\");\n }\n } catch {\n /* ignore parse errors */\n }\n } else if (errorCat === \"overloaded\") {\n markOverloaded(tryModel);\n } else if (errorCat === \"auth_failure\" || errorCat === \"quota_exceeded\") {\n console.log(\n `[ClawRouter] 🔑 ${errorCat === \"auth_failure\" ? \"Auth failure\" : \"Quota exceeded\"} for ${tryModel} — check provider config`,\n );\n }\n\n console.log(\n `[ClawRouter] Provider error from ${tryModel}, trying fallback: ${result.errorBody?.slice(0, 100)}`,\n );\n continue;\n }\n\n // Not a provider error or last attempt — stop trying\n if (!result.isProviderError) {\n console.log(\n `[ClawRouter] Non-provider error from ${tryModel}, not retrying: ${result.errorBody?.slice(0, 100)}`,\n );\n }\n break;\n }\n\n // Clear timeout — request attempts completed\n clearTimeout(timeoutId);\n\n // Clear heartbeat — real data is about to flow\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // --- Emit routing debug info (opt-in via x-clawrouter-debug: true header) ---\n // For streaming: SSE comment (invisible to most clients, visible in raw stream)\n // For non-streaming: response headers added later\n if (debugMode && headersSentEarly && routingDecision) {\n const debugComment = `: x-clawrouter-debug profile=${routingProfile ?? \"auto\"} tier=${routingDecision.tier} model=${actualModelUsed} agentic=${routingDecision.agenticScore?.toFixed(2) ?? \"n/a\"} confidence=${routingDecision.confidence.toFixed(2)} reasoning=${routingDecision.reasoning}\\n\\n`;\n safeWrite(res, debugComment);\n }\n\n // Update routing decision with actual model used (for logging)\n // IMPORTANT: Recalculate cost for the actual model, not the original primary\n if (routingDecision && actualModelUsed !== routingDecision.model) {\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const newCosts = calculateModelCost(\n actualModelUsed,\n routerOpts.modelPricing,\n estimatedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n routingDecision = {\n ...routingDecision,\n model: actualModelUsed,\n reasoning: `${routingDecision.reasoning} | fallback to ${actualModelUsed}`,\n costEstimate: newCosts.costEstimate,\n baselineCost: newCosts.baselineCost,\n savings: newCosts.savings,\n };\n options.onRouted?.(routingDecision);\n\n // Update session pin to the actual model used — ensures the next request in\n // this conversation starts from the fallback model rather than retrying the\n // primary and falling back again (prevents the \"model keeps jumping\" issue).\n if (effectiveSessionId) {\n sessionStore.setSession(effectiveSessionId, actualModelUsed, routingDecision.tier);\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... updated pin to fallback: ${actualModelUsed}`,\n );\n }\n }\n\n // --- Handle case where all models failed ---\n if (!upstream) {\n // Build structured error summary listing all attempted models\n const attemptSummary =\n failedAttempts.length > 0\n ? failedAttempts.map((a) => `${a.model} (${a.reason})`).join(\", \")\n : \"unknown\";\n const structuredMessage =\n failedAttempts.length > 0\n ? `All ${failedAttempts.length} models failed. Tried: ${attemptSummary}`\n : \"All models in fallback chain failed\";\n console.log(`[ClawRouter] ${structuredMessage}`);\n const rawErrBody = lastError?.body || structuredMessage;\n const errStatus = lastError?.status || 502;\n\n // Transform payment errors into user-friendly messages\n const transformedErr = transformPaymentError(rawErrBody);\n\n if (headersSentEarly) {\n // Streaming: send error as SSE event\n // If transformed error is already JSON, parse and use it; otherwise wrap in standard format\n let errPayload: string;\n try {\n const parsed = JSON.parse(transformedErr);\n errPayload = JSON.stringify(parsed);\n } catch {\n errPayload = JSON.stringify({\n error: { message: rawErrBody, type: \"provider_error\", status: errStatus },\n });\n }\n const errEvent = `data: ${errPayload}\\n\\n`;\n safeWrite(res, errEvent);\n safeWrite(res, \"data: [DONE]\\n\\n\");\n res.end();\n\n const errBuf = Buffer.from(errEvent + \"data: [DONE]\\n\\n\");\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: errBuf,\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: send transformed error response with context headers\n res.writeHead(errStatus, {\n \"Content-Type\": \"application/json\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n res.end(transformedErr);\n\n deduplicator.complete(dedupKey, {\n status: errStatus,\n headers: { \"content-type\": \"application/json\" },\n body: Buffer.from(transformedErr),\n completedAt: Date.now(),\n });\n }\n return;\n }\n\n // --- Stream response and collect for dedup cache ---\n const responseChunks: Buffer[] = [];\n\n if (headersSentEarly) {\n // Streaming: headers already sent. Response should be 200 at this point\n // (non-200 responses are handled in the fallback loop above)\n\n // Convert non-streaming JSON response to SSE streaming format for client\n // (BlockRun API returns JSON since we forced stream:false)\n // OpenClaw expects: object=\"chat.completion.chunk\" with choices[].delta (not message)\n // We emit proper incremental deltas to match OpenAI's streaming format exactly\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n\n // Combine chunks and transform to streaming format\n const jsonBody = Buffer.concat(chunks);\n const jsonStr = jsonBody.toString();\n try {\n const rsp = JSON.parse(jsonStr) as {\n id?: string;\n object?: string;\n created?: number;\n model?: string;\n choices?: Array<{\n index?: number;\n message?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n delta?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: unknown;\n };\n\n // Extract input token count from upstream response\n if (rsp.usage && typeof rsp.usage === \"object\") {\n const u = rsp.usage as Record;\n if (typeof u.prompt_tokens === \"number\") responseInputTokens = u.prompt_tokens;\n if (typeof u.completion_tokens === \"number\") responseOutputTokens = u.completion_tokens;\n }\n\n // Build base chunk structure (reused for all chunks)\n // Match OpenAI's exact format including system_fingerprint\n const baseChunk = {\n id: rsp.id ?? `chatcmpl-${Date.now()}`,\n object: \"chat.completion.chunk\",\n created: rsp.created ?? Math.floor(Date.now() / 1000),\n model: actualModelUsed || rsp.model || \"unknown\",\n system_fingerprint: null,\n };\n\n // Process each choice (usually just one)\n if (rsp.choices && Array.isArray(rsp.choices)) {\n for (const choice of rsp.choices) {\n // Strip thinking tokens (Kimi <|...|> and standard tags)\n const rawContent = choice.message?.content ?? choice.delta?.content ?? \"\";\n const content = stripThinkingTokens(rawContent);\n const role = choice.message?.role ?? choice.delta?.role ?? \"assistant\";\n const index = choice.index ?? 0;\n\n // Accumulate content for session journal\n if (content) {\n accumulatedContent += content;\n }\n\n // Chunk 1: role only (mimics OpenAI's first chunk)\n const roleChunk = {\n ...baseChunk,\n choices: [{ index, delta: { role }, logprobs: null, finish_reason: null }],\n };\n const roleData = `data: ${JSON.stringify(roleChunk)}\\n\\n`;\n safeWrite(res, roleData);\n responseChunks.push(Buffer.from(roleData));\n\n // Chunk 1.5: balance fallback notice (tells user they got free model)\n if (balanceFallbackNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: balanceFallbackNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n balanceFallbackNotice = undefined; // Only inject once\n }\n\n // Chunk 1.6: budget downgrade notice (A: visible warning when model downgraded)\n if (budgetDowngradeNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: budgetDowngradeNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n budgetDowngradeNotice = undefined; // Only inject once\n }\n\n // Chunk 2: content (single chunk with full content)\n if (content) {\n const contentChunk = {\n ...baseChunk,\n choices: [{ index, delta: { content }, logprobs: null, finish_reason: null }],\n };\n const contentData = `data: ${JSON.stringify(contentChunk)}\\n\\n`;\n safeWrite(res, contentData);\n responseChunks.push(Buffer.from(contentData));\n }\n\n // Chunk 2b: tool_calls (forward tool calls from upstream)\n const toolCalls = choice.message?.tool_calls ?? choice.delta?.tool_calls;\n if (toolCalls && toolCalls.length > 0) {\n const toolCallChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { tool_calls: toolCalls },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const toolCallData = `data: ${JSON.stringify(toolCallChunk)}\\n\\n`;\n safeWrite(res, toolCallData);\n responseChunks.push(Buffer.from(toolCallData));\n }\n\n // Chunk 3: finish_reason (signals completion)\n const finishChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: {},\n logprobs: null,\n finish_reason:\n toolCalls && toolCalls.length > 0\n ? \"tool_calls\"\n : (choice.finish_reason ?? \"stop\"),\n },\n ],\n };\n const finishData = `data: ${JSON.stringify(finishChunk)}\\n\\n`;\n safeWrite(res, finishData);\n responseChunks.push(Buffer.from(finishData));\n }\n }\n } catch {\n // If parsing fails, send raw response as single chunk\n const sseData = `data: ${jsonStr}\\n\\n`;\n safeWrite(res, sseData);\n responseChunks.push(Buffer.from(sseData));\n }\n }\n\n // Send cost summary as SSE comment before terminator\n if (routingDecision) {\n const costComment = `: cost=$${routingDecision.costEstimate.toFixed(4)} savings=${(routingDecision.savings * 100).toFixed(0)}% model=${actualModelUsed} tier=${routingDecision.tier}\\n\\n`;\n safeWrite(res, costComment);\n responseChunks.push(Buffer.from(costComment));\n }\n\n // Send SSE terminator\n safeWrite(res, \"data: [DONE]\\n\\n\");\n responseChunks.push(Buffer.from(\"data: [DONE]\\n\\n\"));\n res.end();\n\n // Cache for dedup\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: Buffer.concat(responseChunks),\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: forward status and headers from upstream\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n // Skip hop-by-hop headers and content-encoding (fetch already decompresses)\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\")\n return;\n responseHeaders[key] = value;\n });\n\n // Add context usage headers\n responseHeaders[\"x-context-used-kb\"] = String(originalContextSizeKB);\n responseHeaders[\"x-context-limit-kb\"] = String(CONTEXT_LIMIT_KB);\n\n // Add routing debug headers (opt-in via x-clawrouter-debug: true header)\n if (debugMode && routingDecision) {\n responseHeaders[\"x-clawrouter-profile\"] = routingProfile ?? \"auto\";\n responseHeaders[\"x-clawrouter-tier\"] = routingDecision.tier;\n responseHeaders[\"x-clawrouter-model\"] = actualModelUsed;\n responseHeaders[\"x-clawrouter-confidence\"] = routingDecision.confidence.toFixed(2);\n responseHeaders[\"x-clawrouter-reasoning\"] = routingDecision.reasoning;\n if (routingDecision.agenticScore !== undefined) {\n responseHeaders[\"x-clawrouter-agentic-score\"] = routingDecision.agenticScore.toFixed(2);\n }\n }\n\n // Always include cost visibility headers when routing is active\n if (routingDecision) {\n responseHeaders[\"x-clawrouter-cost\"] = routingDecision.costEstimate.toFixed(6);\n responseHeaders[\"x-clawrouter-savings\"] = `${(routingDecision.savings * 100).toFixed(0)}%`;\n }\n\n // Collect full body for possible notice injection\n const bodyParts: Buffer[] = [];\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n for (const chunk of chunks) {\n bodyParts.push(Buffer.from(chunk));\n }\n }\n\n let responseBody = Buffer.concat(bodyParts);\n\n // Prepend balance fallback notice to response content\n if (balanceFallbackNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n balanceFallbackNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n balanceFallbackNotice = undefined;\n }\n\n // A: Prepend budget downgrade notice to response content\n if (budgetDowngradeNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n budgetDowngradeNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n budgetDowngradeNotice = undefined;\n }\n\n // Inject actualModelUsed into non-streaming response model field\n if (actualModelUsed && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as { model?: string };\n if (parsed.model !== undefined) {\n parsed.model = actualModelUsed;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip model injection */\n }\n }\n\n // B: Add budget downgrade headers for orchestration layers\n if (budgetDowngradeHeaderMode) {\n responseHeaders[\"x-clawrouter-budget-downgrade\"] = \"1\";\n responseHeaders[\"x-clawrouter-budget-mode\"] = budgetDowngradeHeaderMode;\n budgetDowngradeHeaderMode = undefined;\n }\n\n // Update content-length header since body may have changed\n responseHeaders[\"content-length\"] = String(responseBody.length);\n res.writeHead(upstream.status, responseHeaders);\n safeWrite(res, responseBody);\n responseChunks.push(responseBody);\n res.end();\n\n // Cache for dedup (short-term, 30s)\n deduplicator.complete(dedupKey, {\n status: upstream.status,\n headers: responseHeaders,\n body: responseBody,\n completedAt: Date.now(),\n });\n\n // Cache for response cache (long-term, 10min) - only successful non-streaming\n if (upstream.status === 200 && responseCache.shouldCache(body)) {\n responseCache.set(cacheKey, {\n body: responseBody,\n status: upstream.status,\n headers: responseHeaders,\n model: actualModelUsed,\n });\n console.log(\n `[ClawRouter] Cached response for ${actualModelUsed} (${responseBody.length} bytes)`,\n );\n }\n\n // Extract content and token usage from non-streaming response\n try {\n const rspJson = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n usage?: Record;\n };\n if (rspJson.choices?.[0]?.message?.content) {\n accumulatedContent = rspJson.choices[0].message.content;\n }\n if (rspJson.usage && typeof rspJson.usage === \"object\") {\n if (typeof rspJson.usage.prompt_tokens === \"number\")\n responseInputTokens = rspJson.usage.prompt_tokens;\n if (typeof rspJson.usage.completion_tokens === \"number\")\n responseOutputTokens = rspJson.usage.completion_tokens;\n }\n } catch {\n // Ignore parse errors - journal just won't have content for this response\n }\n }\n\n // --- Session Journal: Extract and record events from response ---\n if (sessionId && accumulatedContent) {\n const events = sessionJournal.extractEvents(accumulatedContent);\n if (events.length > 0) {\n sessionJournal.record(sessionId, events, actualModelUsed);\n console.log(\n `[ClawRouter] Recorded ${events.length} events to session journal for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n\n // --- Optimistic balance deduction after successful response ---\n if (estimatedCostMicros !== undefined) {\n balanceMonitor.deductEstimated(estimatedCostMicros);\n }\n\n // Mark request as completed (for client disconnect cleanup)\n completed = true;\n } catch (err) {\n // Clear timeout on error\n clearTimeout(timeoutId);\n\n // Clear heartbeat on error\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // Remove in-flight entry so retries aren't blocked\n deduplicator.removeInflight(dedupKey);\n\n // Invalidate balance cache on payment failure (might be out of date)\n balanceMonitor.invalidate();\n\n // Convert abort error to more descriptive timeout error\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err });\n }\n\n throw err;\n }\n\n // --- Usage logging (fire-and-forget) ---\n // Use actual x402 payment amount from the per-request AsyncLocalStorage store.\n // This is the real amount the user paid — no estimation needed.\n // Falls back to local estimate only for free models (no x402 payment).\n const logModel = routingDecision?.model ?? modelId;\n if (logModel) {\n const actualPayment = paymentStore.getStore()?.amountUsd ?? 0;\n\n // For free models (no x402 payment), use local cost calculation as fallback\n let logCost: number;\n let logBaseline: number;\n let logSavings: number;\n if (actualPayment > 0) {\n logCost = actualPayment;\n // Calculate baseline for savings comparison\n const chargedInputTokens = Math.ceil(body.length / 4);\n const modelDef = BLOCKRUN_MODELS.find((m) => m.id === logModel);\n const chargedOutputTokens = modelDef ? Math.min(maxTokens, modelDef.maxOutput) : maxTokens;\n const baseline = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n chargedOutputTokens,\n routingProfile ?? undefined,\n );\n logBaseline = baseline.baselineCost;\n logSavings = logBaseline > 0 ? Math.max(0, (logBaseline - logCost) / logBaseline) : 0;\n } else {\n // Free model — no payment, calculate locally\n const chargedInputTokens = Math.ceil(body.length / 4);\n const costs = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n logCost = costs.costEstimate;\n logBaseline = costs.baselineCost;\n logSavings = costs.savings;\n }\n\n const entry: UsageEntry = {\n timestamp: new Date().toISOString(),\n model: logModel,\n tier: routingDecision?.tier ?? \"DIRECT\",\n cost: logCost,\n baselineCost: logBaseline,\n savings: logSavings,\n latencyMs: Date.now() - startTime,\n ...(responseInputTokens !== undefined && { inputTokens: responseInputTokens }),\n ...(responseOutputTokens !== undefined && { outputTokens: responseOutputTokens }),\n };\n logUsage(entry).catch(() => {});\n }\n}\n","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\n}\n","import type {\n Abi,\n AbiParameter,\n AbiParameterToPrimitiveType,\n ExtractAbiEvents,\n} from 'abitype'\n\nimport {\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeEventTopics'\n\nexport type EncodeEventTopicsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n ///\n hasEvents = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiEvents] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >,\n allErrorNames = ContractEventName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { eventName?: eventName | allErrorNames | undefined }\n : { eventName: eventName | allErrorNames }\n : { eventName?: eventName | allErrorNames | undefined }\n> &\n (hasEvents extends true ? unknown : never)\n\nexport type EncodeEventTopicsReturnType = [Hex, ...(Hex | Hex[] | null)[]]\n\nexport type EncodeEventTopicsErrorType =\n | AbiEventNotFoundErrorType\n | EncodeArgErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nexport function encodeEventTopics<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n>(\n parameters: EncodeEventTopicsParameters,\n): EncodeEventTopicsReturnType {\n const { abi, eventName, args } = parameters as EncodeEventTopicsParameters\n\n let abiItem = abi[0]\n if (eventName) {\n const item = getAbiItem({ abi, name: eventName })\n if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'event')\n throw new AbiEventNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toEventSelector(definition as EventDefinition)\n\n let topics: (Hex | Hex[] | null)[] = []\n if (args && 'inputs' in abiItem) {\n const indexedInputs = abiItem.inputs?.filter(\n (param) => 'indexed' in param && param.indexed,\n )\n const args_ = Array.isArray(args)\n ? args\n : Object.values(args).length > 0\n ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])\n : []\n\n if (args_.length > 0) {\n topics =\n indexedInputs?.map((param, i) => {\n if (Array.isArray(args_[i]))\n return args_[i].map((_: any, j: number) =>\n encodeArg({ param, value: args_[i][j] }),\n )\n return typeof args_[i] !== 'undefined' && args_[i] !== null\n ? encodeArg({ param, value: args_[i] })\n : null\n }) ?? []\n }\n }\n return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | EncodeAbiParametersErrorType\n | FilterTypeNotSupportedErrorType\n | ErrorType\n\nfunction encodeArg({\n param,\n value,\n}: {\n param: AbiParameter\n value: AbiParameterToPrimitiveType\n}) {\n if (param.type === 'string' || param.type === 'bytes')\n return keccak256(toBytes(value as string))\n if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n throw new FilterTypeNotSupportedError(param.type)\n return encodeAbiParameters([param], [value])\n}\n","import { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n constructor(type: string) {\n super(`Filter type \"${type}\" is not supported.`, {\n name: 'FilterTypeNotSupportedError',\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n abi: abi\n eventName?: eventName | ContractEventName | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n * @default false\n */\n strict?: strict | boolean | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (undefined extends eventName\n ? {\n args?: undefined\n }\n : MaybeExtractEventArgsFromAbi extends infer eventFilterArgs\n ? {\n args?:\n | eventFilterArgs\n | (args extends eventFilterArgs ? args : never)\n | undefined\n }\n : {\n args?: undefined\n })\n\nexport type CreateContractEventFilterReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', abi, eventName, args, strict, fromBlock, toBlock>\n\nexport type CreateContractEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const { address, abi, args, eventName, fromBlock, strict, toBlock } =\n parameters as CreateContractEventFilterParameters\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n const topics = eventName\n ? encodeEventTopics({\n abi,\n args,\n eventName,\n } as unknown as EncodeEventTopicsParameters)\n : undefined\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n topics,\n },\n ],\n })\n\n return {\n abi,\n args,\n eventName,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n type: 'event',\n } as unknown as CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn, PublicRpcSchema } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n method:\n | 'eth_newFilter'\n | 'eth_newPendingTransactionFilter'\n | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n PublicRpcSchema,\n { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n id: Hex,\n) => EIP1193RequestFn\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope(\n client: Client,\n { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n const requestMap: Record = {}\n\n if (client.transport.type === 'fallback')\n client.transport.onResponse?.(\n ({\n method: method_,\n response: id,\n status,\n transport,\n }: Parameters[0]) => {\n if (status === 'success' && method === method_)\n requestMap[id as Hex] = transport.request\n },\n )\n\n return ((id) =>\n requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi } 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 type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n GetValue,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from './estimateGas.js'\n\nexport type EstimateContractGasParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n> = ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit, 'data' | 'to' | 'value'> &\n GetValue<\n abi,\n functionName,\n EstimateGasParameters extends EstimateGasParameters\n ? EstimateGasParameters['value']\n : EstimateGasParameters['value']\n > & {\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n }\n\nexport type EstimateContractGasReturnType = bigint\n\nexport type EstimateContractGasErrorType = GetContractErrorReturnType<\n EncodeFunctionDataErrorType | EstimateGasErrorType | ParseAccountErrorType\n>\n\n/**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateContractGas } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await estimateContractGas(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\nexport async function estimateContractGas<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs,\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n parameters: EstimateContractGasParameters,\n): Promise {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...request\n } = parameters as EstimateContractGasParameters\n const data = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n\n try {\n const gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n data: `${data}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...request,\n } as unknown as EstimateGasParameters)\n return gas\n } catch (error) {\n const account = request.account ? parseAccount(request.account) : undefined\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/estimateContractGas',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport { InternalRpcError, InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType = Omit<\n ContractFunctionExecutionErrorType,\n 'cause'\n> & {\n cause:\n | cause\n | ContractFunctionZeroDataErrorType\n | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError>(\n err: err,\n {\n abi,\n address,\n args,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args: any\n address?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const error = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as BaseError\n const { code, data, details, message, shortMessage } =\n error as RawContractError\n\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName })\n if (\n ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || details || message || shortMessage)) ||\n (code === InvalidInputRpcError.code &&\n details === 'execution reverted' &&\n data)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message:\n error instanceof RpcRequestError\n ? details\n : (shortMessage ?? message),\n })\n }\n return err\n })()\n\n return new ContractFunctionExecutionError(cause as BaseError, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n }) as GetContractErrorReturnType\n}\n","import type { Address } from 'abitype'\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 { BaseError } from '../../errors/base.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestParameterType,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n account?: Account | Address | undefined\n prepare?:\n | boolean\n | readonly PrepareTransactionRequestParameterType[]\n | undefined\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 FormattedEstimateGas =\n FormattedTransactionRequest\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\n | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in gas units). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n args: EstimateGasParameters,\n): Promise {\n const { account: account_ = client.account, prepare = true } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n const parameters = (() => {\n if (Array.isArray(prepare)) return prepare\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n if (account?.type !== 'local') return ['blobVersionedHashes']\n return undefined\n })()\n\n try {\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (args.to) return args.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (args.authorizationList && args.authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: args.authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = prepare\n ? ((await prepareTransactionRequest(client, {\n ...args,\n parameters,\n to,\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters)\n : args\n\n // If we get `gas` back from the prepared transaction request, which is\n // different from the `gas` we provided, it was likely filled by other means\n // during request preparation (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n // (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n if (gas && args.gas !== gas) return gas\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\n\n assertRequest(args as AssertRequestParameters)\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest,\n 'estimateGas',\n )\n\n return BigInt(\n await client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [\n request,\n block ?? client.experimental_blockTag ?? 'latest',\n rpcStateOverride,\n ]\n : block\n ? [request, block]\n : [request],\n }),\n )\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\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 type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { size } from '../data/size.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n if (size(signatureHex) !== 65) throw new Error('invalid signature length')\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise {\n return publicKeyToAddress(await recoverPublicKey({ hash, signature }))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { AuthorizationRequest } from '../../types/authorization.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type NumberToHexErrorType, numberToHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters =\n AuthorizationRequest & {\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, nonce, to } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n address,\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 { 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 { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../signature/recoverAddress.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n > = OneOf,\n //\n _signature = Hex | ByteArray | OneOf,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization:\n | authorization\n | OneOf\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n >,\n>(\n parameters: RecoverAuthorizationAddressParameters,\n): Promise {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as AuthorizationRequest),\n signature: (signature ?? authorization) as Signature,\n })\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError 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, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Estimate Gas Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'EstimateGasExecutionError',\n })\n this.cause = cause\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.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 GetEstimateGasErrorReturnType = Omit<\n EstimateGasExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError>(\n err: err,\n {\n docsPath,\n ...args\n }: Omit & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n): GetEstimateGasErrorReturnType {\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 EstimateGasExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetEstimateGasErrorReturnType\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n type EstimateFeesPerGasErrorType,\n internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type GetBlockErrorType,\n getBlock as getBlock_,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetTransactionCountErrorType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { LruMap } from '../../utils/lru.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport {\n type FillTransactionErrorType,\n type FillTransactionParameters,\n fillTransaction,\n} from '../public/fillTransaction.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\n/** @internal */\nexport const eip1559NetworkCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport const supportsFillTransaction = /*#__PURE__*/ new LruMap(128)\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType extends 'legacy'\n ? unknown\n : GetTransactionType,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick)\n>\n\nexport type PrepareTransactionRequestErrorType =\n | AccountNotFoundErrorType\n | AssertRequestErrorType\n | ParseAccountErrorType\n | GetBlockErrorType\n | GetTransactionCountErrorType\n | EstimateGasErrorType\n | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n let request = args as PrepareTransactionRequestParameters\n\n request.account ??= client.account\n request.parameters ??= defaultParameters\n\n const {\n account: account_,\n chain = client.chain,\n nonceManager,\n parameters,\n } = request\n\n const prepareTransactionRequest = (() => {\n if (typeof chain?.prepareTransactionRequest === 'function')\n return {\n fn: chain.prepareTransactionRequest,\n runAt: ['beforeFillTransaction'],\n }\n if (Array.isArray(chain?.prepareTransactionRequest))\n return {\n fn: chain.prepareTransactionRequest[0],\n runAt: chain.prepareTransactionRequest[1].runAt,\n }\n return undefined\n })()\n\n let chainId: number | undefined\n async function getChainId(): Promise {\n if (chainId) return chainId\n if (typeof request.chainId !== 'undefined') return request.chainId\n if (chain) return chain.id\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n const account = account_ ? parseAccount(account_) : account_\n\n let nonce = request.nonce\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n nonceManager\n ) {\n const chainId = await getChainId()\n nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n }\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillTransaction')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillTransaction',\n },\n )\n nonce ??= request.nonce\n }\n\n const attemptFill = (() => {\n // Do not attempt if blobs are provided.\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n request.kzg &&\n request.blobs\n )\n return false\n\n // Do not attempt if `eth_fillTransaction` is not supported.\n if (supportsFillTransaction.get(client.uid) === false) return false\n\n // Should attempt `eth_fillTransaction` if \"fees\" or \"gas\" are required to be populated,\n // otherwise, can just use the other individual calls.\n const shouldAttempt = ['fees', 'gas'].some((parameter) =>\n parameters.includes(parameter as PrepareTransactionRequestParameterType),\n )\n if (!shouldAttempt) return false\n\n // Check if `eth_fillTransaction` needs to be called.\n if (parameters.includes('chainId') && typeof request.chainId !== 'number')\n return true\n if (parameters.includes('nonce') && typeof nonce !== 'number') return true\n if (\n parameters.includes('fees') &&\n typeof request.gasPrice !== 'bigint' &&\n (typeof request.maxFeePerGas !== 'bigint' ||\n typeof (request as any).maxPriorityFeePerGas !== 'bigint')\n )\n return true\n if (parameters.includes('gas') && typeof request.gas !== 'bigint')\n return true\n return false\n })()\n\n const fillResult = attemptFill\n ? await getAction(\n client,\n fillTransaction,\n 'fillTransaction',\n )({ ...request, nonce } as FillTransactionParameters)\n .then((result) => {\n const {\n chainId,\n from,\n gas,\n gasPrice,\n nonce,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n type,\n ...rest\n } = result.transaction\n supportsFillTransaction.set(client.uid, true)\n return {\n ...request,\n ...(from ? { from } : {}),\n ...(type ? { type } : {}),\n ...(typeof chainId !== 'undefined' ? { chainId } : {}),\n ...(typeof gas !== 'undefined' ? { gas } : {}),\n ...(typeof gasPrice !== 'undefined' ? { gasPrice } : {}),\n ...(typeof nonce !== 'undefined' ? { nonce } : {}),\n ...(typeof maxFeePerBlobGas !== 'undefined'\n ? { maxFeePerBlobGas }\n : {}),\n ...(typeof maxFeePerGas !== 'undefined' ? { maxFeePerGas } : {}),\n ...(typeof maxPriorityFeePerGas !== 'undefined'\n ? { maxPriorityFeePerGas }\n : {}),\n ...('nonceKey' in rest && typeof rest.nonceKey !== 'undefined'\n ? { nonceKey: rest.nonceKey }\n : {}),\n }\n })\n .catch((e) => {\n const error = e as FillTransactionErrorType\n\n if (error.name !== 'TransactionExecutionError') return request\n\n const unsupported = error.walk?.((e) => {\n const error = e as BaseError\n return (\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n )\n })\n if (unsupported) supportsFillTransaction.set(client.uid, false)\n\n return request\n })\n : request\n\n nonce ??= fillResult.nonce\n\n request = {\n ...(fillResult as any),\n ...(account ? { from: account?.address } : {}),\n ...(nonce ? { nonce } : {}),\n }\n const { blobs, gas, kzg, type } = request\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillParameters')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillParameters',\n },\n )\n }\n\n let block: Block | undefined\n async function getBlock(): Promise {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n !nonceManager\n )\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n let isEip1559Network = eip1559NetworkCache.get(client.uid)\n if (typeof isEip1559Network === 'undefined') {\n const block = await getBlock()\n isEip1559Network = typeof block?.baseFeePerGas === 'bigint'\n eip1559NetworkCache.set(client.uid, isEip1559Network)\n }\n request.type = isEip1559Network ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof request.maxPriorityFeePerGas === 'undefined' &&\n request.maxFeePerGas &&\n request.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof request.maxFeePerGas !== 'undefined' ||\n typeof request.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n if (typeof request.gasPrice === 'undefined') {\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account,\n prepare: account?.type === 'local' ? [] : ['blobVersionedHashes'],\n } as EstimateGasParameters)\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('afterFillParameters')\n )\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'afterFillParameters',\n },\n )\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\n )\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToBigIntErrorType,\n hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChainParameter\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n | GetBlockErrorType\n | HexToBigIntErrorType\n | RequestErrorType\n | GetBlockErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n): Promise {\n return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args: EstimateMaxPriorityFeePerGasParameters & {\n block?: Block | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\n const maxPriorityFeePerGasHex = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n })\n return hexToBigInt(maxPriorityFeePerGasHex)\n } catch {\n // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n const [block, gasPrice] = await Promise.all([\n block_\n ? Promise.resolve(block_)\n : getAction(client, getBlock, 'getBlock')({}),\n getAction(client, getGasPrice, 'getGasPrice')({}),\n ])\n\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n if (maxPriorityFeePerGas < 0n) return 0n\n return maxPriorityFeePerGas\n }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n }) {\n let identifier = 'Block'\n if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n super(`${identifier} could not be found.`, { name: 'BlockNotFoundError' })\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetBlockErrorType =\n | BlockNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n includeTransactions: includeTransactions_,\n }: GetBlockParameters = {},\n): Promise> {\n const includeTransactions = includeTransactions_ ?? false\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let block: RpcBlock | null = null\n if (blockHash) {\n block = await client.request(\n {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n const format = client.chain?.formatters?.block?.format || formatBlock\n return format(block, 'getBlock')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(\n block: ExactPartial,\n _?: string | undefined,\n) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string') return transaction\n return formatTransaction(transaction)\n })\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { SignedAuthorizationList } from '../../types/authorization.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcAuthorizationList, RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n | 'blockHash'\n | 'blockNumber'\n | 'transactionIndex'\n\nexport type FormattedTransaction<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(\n transaction: ExactPartial,\n _?: string | undefined,\n) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? (transactionType as any)[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n } as Transaction\n\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\n\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity) return Number(transaction.yParity)\n\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n) return 0\n if (transaction_.v === 1n || transaction_.v === 28n) return 1\n if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n }\n\n return undefined\n })()\n\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') delete transaction_.maxFeePerBlobGas\n\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map((authorization) => ({\n address: (authorization as any).address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n })) as SignedAuthorizationList\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const gasPrice = await client.request({\n method: 'eth_gasPrice',\n })\n return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesLegacy,\n FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n type EstimateMaxPriorityFeePerGasErrorType,\n internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n type extends FeeValuesType = FeeValuesType,\n> = {\n /**\n * The type of fee values to return.\n *\n * - `legacy`: Returns the legacy gas price.\n * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n *\n * @default 'eip1559'\n */\n type?: type | FeeValuesType | undefined\n} & GetChainParameter\n\nexport type EstimateFeesPerGasReturnType<\n type extends FeeValuesType = FeeValuesType,\n> =\n | (type extends 'legacy' ? FeeValuesLegacy : never)\n | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n | BaseFeeScalarErrorType\n | EstimateMaxPriorityFeePerGasErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args?: EstimateFeesPerGasParameters | undefined,\n): Promise> {\n return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args: EstimateFeesPerGasParameters & {\n block?: Block | undefined\n request?: PrepareTransactionRequestParameters | undefined\n },\n): Promise> {\n const {\n block: block_,\n chain = client.chain,\n request,\n type = 'eip1559',\n } = args || {}\n\n const baseFeeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n return chain.fees.baseFeeMultiplier({\n block: block_ as Block,\n client,\n request,\n } as ChainFeesFnParameters)\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiply = (base: bigint) =>\n (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n BigInt(denominator)\n\n const block = block_\n ? block_\n : await getAction(client, getBlock, 'getBlock')({})\n\n if (typeof chain?.fees?.estimateFeesPerGas === 'function') {\n const fees = (await chain.fees.estimateFeesPerGas({\n block: block_ as Block,\n client,\n multiply,\n request,\n type,\n } as ChainEstimateFeesPerGasFnParameters)) as unknown as EstimateFeesPerGasReturnType\n\n if (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client,\n {\n block: block as Block,\n chain,\n request,\n },\n )\n\n const baseFeePerGas = multiply(block.baseFeePerGas)\n const maxFeePerGas =\n request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as EstimateFeesPerGasReturnType\n }\n\n const gasPrice =\n request?.gasPrice ??\n multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n return {\n gasPrice,\n } as EstimateFeesPerGasReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n /** The account address. */\n address: Address\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [\n address,\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : blockTag,\n ],\n },\n {\n dedupe: Boolean(blockNumber),\n },\n )\n return hexToNumber(count)\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 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","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\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 {\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 {\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 type { Address } from 'abitype'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { BaseFeeScalarError } from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport { getBlock } from './getBlock.js'\nimport { getChainId as getChainId_ } from './getChainId.js'\n\nexport type FillTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetAccountParameter &\n GetChainParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n }\n\nexport type FillTransactionReturnType<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = {\n raw: Hex\n transaction: FormattedTransaction<_derivedChain>\n}\n\nexport type FillTransactionErrorType =\n | GetTransactionErrorReturnType\n | ErrorType\n\n/**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { fillTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await fillTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function fillTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n): Promise> {\n const {\n account = client.account,\n accessList,\n authorizationList,\n chain = client.chain,\n blobVersionedHashes,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce: nonce_,\n nonceManager,\n to,\n type,\n value,\n ...rest\n } = parameters\n\n const nonce = await (async () => {\n if (!account) return nonce_\n if (!nonceManager) return nonce_\n if (typeof nonce_ !== 'undefined') return nonce_\n const account_ = parseAccount(account)\n const chainId = chain\n ? chain.id\n : await getAction(client, getChainId_, 'getChainId')({})\n return await nonceManager.consume({\n address: account_.address,\n chainId,\n client,\n })\n })()\n\n assertRequest(parameters)\n\n const chainFormat = chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account: account ? parseAccount(account) : undefined,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'fillTransaction',\n )\n\n try {\n const response = await client.request({\n method: 'eth_fillTransaction',\n params: [request],\n })\n const format = chain?.formatters?.transaction?.format || formatTransaction\n\n const transaction = format(response.tx)\n\n // Remove unnecessary fields.\n delete transaction.blockHash\n delete transaction.blockNumber\n delete transaction.r\n delete transaction.s\n delete transaction.transactionIndex\n delete transaction.v\n delete transaction.yParity\n\n // Rewrite fields.\n transaction.data = transaction.input\n\n // Preference supplied fees (some nodes do not take these preferences).\n if (transaction.gas) transaction.gas = parameters.gas ?? transaction.gas\n if (transaction.gasPrice)\n transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice\n if (transaction.maxFeePerBlobGas)\n transaction.maxFeePerBlobGas =\n parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas\n if (transaction.maxFeePerGas)\n transaction.maxFeePerGas =\n parameters.maxFeePerGas ?? transaction.maxFeePerGas\n if (transaction.maxPriorityFeePerGas)\n transaction.maxPriorityFeePerGas =\n parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas\n if (transaction.nonce)\n transaction.nonce = parameters.nonce ?? transaction.nonce\n\n // Build fee multiplier function.\n const feeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function') {\n const block = await getAction(client, getBlock, 'getBlock')({})\n return chain.fees.baseFeeMultiplier({\n block,\n client,\n request: parameters,\n } as ChainFeesFnParameters)\n }\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (feeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = feeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiplyFee = (base: bigint) =>\n (base * BigInt(Math.ceil(feeMultiplier * denominator))) /\n BigInt(denominator)\n\n // Apply fee multiplier.\n if (transaction.maxFeePerGas && !parameters.maxFeePerGas)\n transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas)\n if (transaction.gasPrice && !parameters.gasPrice)\n transaction.gasPrice = multiplyFee(transaction.gasPrice)\n\n return {\n raw: response.raw,\n transaction: {\n from: request.from,\n ...transaction,\n },\n }\n } catch (err) {\n throw getTransactionError(\n err as BaseError,\n {\n ...parameters,\n chain: client.chain,\n } as never,\n )\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport {\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n} from '../../errors/transaction.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 GetTransactionErrorParameters = Omit<\n SendTransactionParameters,\n 'account' | 'chain'\n> & {\n account: Account | null\n chain?: Chain | undefined\n docsPath?: string | undefined\n}\n\nexport type GetTransactionErrorReturnType = Omit<\n TransactionExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getTransactionError>(\n err: err,\n { docsPath, ...args }: GetTransactionErrorParameters,\n): GetTransactionErrorReturnType {\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 TransactionExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetTransactionErrorReturnType\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type GetLogsErrorType,\n type GetLogsParameters,\n getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n)\n\nexport type GetContractEventsReturnType<\n abi extends Abi | readonly unknown[] = readonly unknown[],\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n ///\n isPending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetContractEventsErrorType =\n | GetAbiItemErrorType\n | GetLogsErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/contract/getContractEvents#getcontractevents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetContractEventsReturnType\n> {\n const {\n abi,\n address,\n args,\n blockHash,\n eventName,\n fromBlock,\n toBlock,\n strict,\n } = parameters\n const event = eventName\n ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n : undefined\n const events = !event\n ? (abi as Abi).filter((x) => x.type === 'event')\n : undefined\n return getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n blockHash,\n event,\n events,\n fromBlock,\n toBlock,\n strict,\n } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","// TODO(v3): checksum address.\n\nimport type { Abi, AbiEvent, AbiEventParameter, Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractEventName, GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport { toBytes } from '../encoding/toBytes.js'\nimport { formatLog } from '../formatters/log.js'\nimport { keccak256 } from '../hash/keccak256.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type DecodeEventLogErrorType,\n decodeEventLog,\n} from './decodeEventLog.js'\n\nexport type ParseEventLogsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n allArgs = GetEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n {\n EnableUnion: true\n IndexedOnly: false\n Required: false\n }\n >,\n> = {\n /** Contract ABI. */\n abi: abi\n /** Arguments for the event. */\n args?: allArgs | undefined\n /** Contract event. */\n eventName?:\n | eventName\n | ContractEventName\n | ContractEventName[]\n | undefined\n /** List of logs. */\n logs: (Log | RpcLog)[]\n strict?: strict | boolean | undefined\n}\n\nexport type ParseEventLogsReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n derivedEventName extends\n | ContractEventName\n | undefined = eventName extends ContractEventName[]\n ? eventName[number]\n : eventName,\n> = Log[]\n\nexport type ParseEventLogsErrorType = DecodeEventLogErrorType | ErrorType\n\n/**\n * Extracts & decodes logs matching the provided signature(s) (`abi` + optional `eventName`)\n * from a set of opaque logs.\n *\n * @param parameters - {@link ParseEventLogsParameters}\n * @returns The logs. {@link ParseEventLogsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { parseEventLogs } from 'viem/op-stack'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const receipt = await getTransactionReceipt(client, {\n * hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea',\n * })\n *\n * const logs = parseEventLogs({ logs: receipt.logs })\n * // [{ args: { ... }, eventName: 'TransactionDeposited', ... }, ...]\n */\nexport function parseEventLogs<\n abi extends Abi | readonly unknown[],\n strict extends boolean | undefined = true,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = undefined,\n>(\n parameters: ParseEventLogsParameters,\n): ParseEventLogsReturnType {\n const { abi, args, logs, strict = true } = parameters\n\n const eventName = (() => {\n if (!parameters.eventName) return undefined\n if (Array.isArray(parameters.eventName)) return parameters.eventName\n return [parameters.eventName as string]\n })()\n\n const abiTopics = (abi as Abi)\n .filter((abiItem) => abiItem.type === 'event')\n .map((abiItem) => ({\n abi: abiItem,\n selector: toEventSelector(abiItem),\n }))\n\n return logs\n .map((log) => {\n // Normalize RpcLog (hex-encoded quantities) to Log (bigint/number).\n // When logs come directly from an RPC response (e.g. eth_getLogs),\n // fields like blockNumber are hex strings instead of bigints.\n const formattedLog =\n typeof log.blockNumber === 'string' ? formatLog(log as RpcLog) : log\n\n // Find all matching ABI items with the same selector.\n // Multiple events can share the same selector but differ in indexed parameters\n // (e.g., ERC20 vs ERC721 Transfer events).\n const abiItems = abiTopics.filter(\n (abiTopic) => formattedLog.topics[0] === abiTopic.selector,\n )\n if (abiItems.length === 0) return null\n\n // Try each matching ABI item until one successfully decodes.\n let event: { eventName: string; args: unknown } | undefined\n let abiItem: { abi: AbiEvent; selector: Address } | undefined\n\n for (const item of abiItems) {\n try {\n event = decodeEventLog({\n ...formattedLog,\n abi: [item.abi],\n strict: true,\n })\n abiItem = item\n break\n } catch {\n // Try next ABI item\n }\n }\n\n // If strict decoding failed for all, and we're in non-strict mode,\n // fall back to the first matching ABI item.\n if (!event && !strict) {\n abiItem = abiItems[0]\n try {\n event = decodeEventLog({\n data: formattedLog.data,\n topics: formattedLog.topics,\n abi: [abiItem.abi],\n strict: false,\n })\n } catch {\n // If decoding still fails, return partial log in non-strict mode.\n const isUnnamed = abiItem.abi.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n return {\n ...formattedLog,\n args: isUnnamed ? [] : {},\n eventName: abiItem.abi.name,\n }\n }\n }\n\n // If no event was found, return null.\n if (!event || !abiItem) return null\n\n // Check that the decoded event name matches the provided event name.\n if (eventName && !eventName.includes(event.eventName)) return null\n\n // Check that the decoded event args match the provided args.\n if (\n !includesArgs({\n args: event.args,\n inputs: abiItem.abi.inputs,\n matchArgs: args,\n })\n )\n return null\n\n return { ...event, ...formattedLog }\n })\n .filter(Boolean) as unknown as ParseEventLogsReturnType<\n abi,\n eventName,\n strict\n >\n}\n\nfunction includesArgs(parameters: {\n args: unknown\n inputs: AbiEvent['inputs']\n matchArgs: unknown\n}) {\n const { args, inputs, matchArgs } = parameters\n\n if (!matchArgs) return true\n if (!args) return false\n\n function isEqual(input: AbiEventParameter, value: unknown, arg: unknown) {\n try {\n if (input.type === 'address')\n return isAddressEqual(value as Address, arg as Address)\n if (input.type === 'string' || input.type === 'bytes')\n return keccak256(toBytes(value as string)) === arg\n return value === arg\n } catch {\n return false\n }\n }\n\n if (Array.isArray(args) && Array.isArray(matchArgs)) {\n return matchArgs.every((value, index) => {\n if (value === null || value === undefined) return true\n const input = inputs[index]\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) => isEqual(input, value, args[index]))\n })\n }\n\n if (\n typeof args === 'object' &&\n !Array.isArray(args) &&\n typeof matchArgs === 'object' &&\n !Array.isArray(matchArgs)\n )\n return Object.entries(matchArgs).every(([key, value]) => {\n if (value === null || value === undefined) return true\n const input = inputs.find((input) => input.name === key)\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) =>\n isEqual(input, value, (args as Record)[key]),\n )\n })\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n blockTimestamp: log.blockTimestamp\n ? BigInt(log.blockTimestamp)\n : log.blockTimestamp === null\n ? null\n : undefined,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n } as Log\n}\n","import type { Abi, AbiParameter } from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgsFromTopics,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n Prettify,\n UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n> = {\n abi: abi\n data?: data | undefined\n eventName?: eventName | ContractEventName | undefined\n strict?: strict | boolean | undefined\n topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n ///\n allEventNames extends\n ContractEventName = eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n> = IsNarrowable extends true\n ? {\n [name in allEventNames]: Prettify<\n {\n eventName: name\n } & UnionEvaluate<\n ContractEventArgsFromTopics extends infer allArgs\n ? topics extends readonly []\n ? data extends undefined\n ? { args?: undefined }\n : { args?: allArgs | undefined }\n : { args: allArgs }\n : never\n >\n >\n }[allEventNames]\n : {\n eventName: eventName\n args: readonly unknown[] | undefined\n }\n\nexport type DecodeEventLogErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiEventSignatureEmptyTopicsErrorType\n | AbiEventSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | DecodeLogTopicsMismatchErrorType\n | DecodeLogDataMismatchErrorType\n | FormatAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n>(\n parameters: DecodeEventLogParameters,\n): DecodeEventLogReturnType {\n const {\n abi,\n data,\n strict: strict_,\n topics,\n } = parameters as DecodeEventLogParameters\n\n const strict = strict_ ?? true\n const [signature, ...argTopics] = topics\n if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n const abiItem = abi.find(\n (x) =>\n x.type === 'event' &&\n signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n )\n\n if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n const { name, inputs } = abiItem\n const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n const args: any = isUnnamed ? [] : {}\n\n // Decode topics (indexed args).\n const indexedInputs = inputs\n .map((x, i) => [x, i] as const)\n .filter(([x]) => 'indexed' in x && x.indexed)\n\n const missingIndexedInputs: [AbiParameter, number][] = []\n\n for (let i = 0; i < indexedInputs.length; i++) {\n const [param, argIndex] = indexedInputs[i]\n const topic = argTopics[i]\n if (!topic) {\n if (strict)\n throw new DecodeLogTopicsMismatch({\n abiItem,\n param: param as AbiParameter & { indexed: boolean },\n })\n // Track missing indexed inputs to decode from data when strict is false\n missingIndexedInputs.push([param, argIndex])\n continue\n }\n args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({\n param,\n value: topic,\n })\n }\n\n // Decode data (non-indexed args + missing indexed args when strict is false).\n const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n\n // When strict is false, missing indexed inputs should be decoded from data\n const inputsToDecode = strict\n ? nonIndexedInputs\n : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]\n\n if (inputsToDecode.length > 0) {\n if (data && data !== '0x') {\n try {\n const decodedData = decodeAbiParameters(\n inputsToDecode,\n data,\n ) as unknown[]\n if (decodedData) {\n let dataIndex = 0\n // First, assign missing indexed parameters (when strict is false)\n if (!strict) {\n for (const [param, argIndex] of missingIndexedInputs) {\n args[isUnnamed ? argIndex : param.name || argIndex] =\n decodedData[dataIndex++]\n }\n }\n // Then, assign non-indexed parameters\n if (isUnnamed) {\n for (let i = 0; i < inputs.length; i++)\n if (args[i] === undefined && dataIndex < decodedData.length)\n args[i] = decodedData[dataIndex++]\n } else\n for (let i = 0; i < nonIndexedInputs.length; i++)\n args[nonIndexedInputs[i].name!] = decodedData[dataIndex++]\n }\n } catch (err) {\n if (strict) {\n if (\n err instanceof AbiDecodingDataSizeTooSmallError ||\n err instanceof PositionOutOfBoundsError\n )\n throw new DecodeLogDataMismatch({\n abiItem,\n data: data,\n params: inputsToDecode,\n size: size(data),\n })\n throw err\n }\n }\n } else if (strict) {\n throw new DecodeLogDataMismatch({\n abiItem,\n data: '0x',\n params: inputsToDecode,\n size: 0,\n })\n }\n }\n\n return {\n eventName: name,\n args: Object.values(args).length > 0 ? args : undefined,\n } as unknown as DecodeEventLogReturnType\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n if (\n param.type === 'string' ||\n param.type === 'bytes' ||\n param.type === 'tuple' ||\n param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n )\n return value\n const decodedArg = decodeAbiParameters([param], value) || []\n return decodedArg[0]\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** Address or list of addresses from which logs originated */\n address?: Address | Address[] | undefined\n} & (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events: abiEvents\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n) &\n (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n )\n\nexport type GetLogsReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetLogsErrorType =\n | DecodeEventLogErrorType\n | EncodeEventTopicsErrorType\n | FormatLogErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n {\n address,\n blockHash,\n fromBlock,\n toBlock,\n event,\n events: events_,\n args,\n strict: strict_,\n }: GetLogsParameters = {},\n): Promise> {\n const strict = strict_ ?? false\n const events = events_ ?? (event ? [event] : undefined)\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args: events_ ? undefined : args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n let logs: RpcLog[]\n if (blockHash) {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [{ address, topics, blockHash }],\n })\n } else {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [\n {\n address,\n topics,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n },\n ],\n })\n }\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!events)\n return formattedLogs as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: events,\n args: args as any,\n logs: formattedLogs,\n strict,\n }) as unknown as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = ContractFunctionReturnType\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n>(\n client: Client,\n parameters: ReadContractParameters,\n): Promise> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { Abi, AbiFunction, AbiStateMutability, Address } from 'abitype'\n\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 type { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, ParseAccount } from '../../types/account.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n ExtractAbiFunctionForArgs,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type {\n IsNarrowable,\n NoInfer,\n Prettify,\n UnionEvaluate,\n UnionOmit,\n} from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { WriteContractParameters } from '../wallet/writeContract.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type GetMutabilityAwareValue<\n abi extends Abi | readonly unknown[],\n mutability extends AbiStateMutability = AbiStateMutability,\n functionName extends ContractFunctionName<\n abi,\n mutability\n > = ContractFunctionName,\n valueType = TransactionRequest['value'],\n args extends ContractFunctionArgs<\n abi,\n mutability,\n functionName\n > = ContractFunctionArgs,\n abiFunction extends AbiFunction = abi extends Abi\n ? ExtractAbiFunctionForArgs\n : AbiFunction,\n _Narrowable extends boolean = IsNarrowable,\n> = _Narrowable extends true\n ? abiFunction['stateMutability'] extends 'payable'\n ? { value?: NoInfer | undefined }\n : abiFunction['payable'] extends true\n ? { value?: NoInfer | undefined }\n : { value?: undefined }\n : { value?: NoInfer | undefined }\n\nexport type SimulateContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n ///\n derivedChain extends Chain | undefined = DeriveChain,\n callParameters extends\n CallParameters = CallParameters,\n> = {\n account?: accountOverride | null | undefined\n chain?: chainOverride | undefined\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n} & ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit<\n callParameters,\n | 'account'\n | 'batch'\n | 'code'\n | 'to'\n | 'data'\n | 'factory'\n | 'factoryData'\n | 'value'\n > &\n GetMutabilityAwareValue<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n callParameters['value'],\n args\n >\n\nexport type SimulateContractReturnType<\n out abi extends Abi | readonly unknown[] = Abi,\n in out functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n in out args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n /** @ts-expect-error cast variance */\n out chain extends Chain | undefined = Chain | undefined,\n out account extends Account | undefined = Account | undefined,\n out chainOverride extends Chain | undefined = Chain | undefined,\n out accountOverride extends Account | Address | null | undefined =\n | Account\n | Address\n | null\n | undefined,\n ///\n in out minimizedAbi extends Abi = readonly [\n ExtractAbiFunctionForArgs<\n abi extends Abi ? abi : Abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >,\n ],\n out resolvedAccount extends\n | Account\n | null\n | undefined = accountOverride extends Account | Address | null\n ? ParseAccount\n : account,\n> = {\n result: ContractFunctionReturnType<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >\n request: Prettify<\n UnionEvaluate<\n UnionOmit<\n WriteContractParameters<\n minimizedAbi,\n functionName,\n args,\n chain,\n undefined,\n chainOverride\n >,\n 'account' | 'abi' | 'args' | 'chain' | 'functionName'\n >\n > &\n ContractFunctionParameters<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n > & {\n chain: DeriveChain\n } & (resolvedAccount extends Account | null\n ? { account: resolvedAccount }\n : { account?: undefined })\n >\n}\n\nexport type SimulateContractErrorType =\n | ParseAccountErrorType\n | EncodeFunctionDataErrorType\n | GetContractErrorReturnType\n | ErrorType\n\n/**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await simulateContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function simulateContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n): Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n> {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...callRequest\n } = parameters as SimulateContractParameters\n\n const account = callRequest.account\n ? parseAccount(callRequest.account)\n : client.account\n const calldata = encodeFunctionData({ abi, args, functionName })\n\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n batch: false,\n data: `${calldata}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...callRequest,\n account,\n })\n const result = decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n })\n const minimizedAbi = abi.filter(\n (abiItem) =>\n 'name' in abiItem && abiItem.name === parameters.functionName,\n )\n return {\n result,\n request: {\n abi: minimizedAbi,\n address,\n args,\n dataSuffix,\n functionName,\n ...callRequest,\n account,\n },\n } as unknown as SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/simulateContract',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport { createContractEventFilter } from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n type GetContractEventsParameters,\n getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchContractEventOnLogsParameter<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = abi extends Abi\n ? Abi extends abi\n ? Log[]\n : Log, strict>[]\n : Log[]\n\nexport type WatchContractEventOnLogsFn<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter) => void\n\nexport type WatchContractEventParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchContractEventOnLogsFn<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n strict\n >\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & GetPollOptions\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n>(\n client: Client,\n parameters: WatchContractEventParameters,\n): WatchContractEventReturnType {\n const {\n abi,\n address,\n args,\n batch = true,\n eventName,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n } = parameters\n\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n const pollContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abi, eventName> | undefined\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createContractEventFilter,\n 'createContractEventFilter',\n )({\n abi,\n address,\n args: args as any,\n eventName: eventName as any,\n strict: strict as any,\n fromBlock,\n })) as Filter<'event', abi, eventName>\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber < blockNumber) {\n logs = await getAction(\n client,\n getContractEvents,\n 'getContractEvents',\n )({\n abi,\n address,\n args,\n eventName,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n strict,\n } as {} as GetContractEventsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n ])\n\n let active = true\n let unsubscribe = () => (active = false)\n return observe(observerId, { onLogs, onError }, (emit) => {\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const topics: LogTopic[] = eventName\n ? encodeEventTopics({\n abi: abi,\n eventName: eventName,\n args,\n } as EncodeEventTopicsParameters)\n : []\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: abi,\n data: log.data,\n topics: log.topics as any,\n strict: strict_,\n })\n const formatted = formatLog(log, {\n args,\n eventName: eventName as string,\n })\n emit.onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n emit.onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollContractEvent() : subscribeContractEvent()\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record\n\nexport type ObserveErrorType = ErrorType\n\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map<\n string,\n () => void | Promise\n>()\n\ntype EmitFunction = (\n emit: callbacks,\n) => MaybePromise void) | (() => Promise)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction,\n) {\n const callbackId = ++callbackCount\n\n const getListeners = () => listenersCache.get(observerId) || []\n\n const unsubscribe = () => {\n const listeners = getListeners()\n listenersCache.set(\n observerId,\n listeners.filter((cb: any) => cb.id !== callbackId),\n )\n }\n\n const unwatch = () => {\n const listeners = getListeners()\n if (!listeners.some((cb: any) => cb.id === callbackId)) return\n const cleanup = cleanupCache.get(observerId)\n if (listeners.length === 1 && cleanup) {\n const p = cleanup()\n if (p instanceof Promise) p.catch(() => {})\n }\n unsubscribe()\n }\n\n const listeners = getListeners()\n listenersCache.set(observerId, [\n ...listeners,\n { id: callbackId, fns: callbacks },\n ])\n\n if (listeners && listeners.length > 0) return unwatch\n\n const emit: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract]\n }\n\n const cleanup = fn(emit)\n if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n return unwatch\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise) | undefined\n // The interval (in ms).\n interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise,\n { emitOnBegin, initialWaitTime, interval }: PollOptions,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | undefined | void\n if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n const initialWait = (await initialWaitTime?.(data)) ?? interval\n await wait(initialWait)\n\n const poll = async () => {\n if (!active) return\n await fn({ unpoll: unwatch })\n await wait(interval)\n poll()\n }\n\n poll()\n }\n watch()\n\n return unwatch\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache(cacheKey: string) {\n const buildCache = (cacheKey: string, cache: Map) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype WithCacheParameters = {\n /** The key to cache the data against. */\n cacheKey: string\n /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n cacheTime?: number | undefined\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache(\n fn: () => Promise,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache(cacheKey)\n\n // If a response exists in the cache, and it's not expired, return it\n // and do not invoke the promise.\n // If the max age is 0, the cache is disabled.\n const response = cache.response.get()\n if (response && cacheTime > 0) {\n const age = Date.now() - response.created.getTime()\n if (age < cacheTime) return response.data\n }\n\n let promise = cache.promise.get()\n if (!promise) {\n promise = fn()\n\n // Store the promise in the cache so that subsequent invocations\n // will wait for the same promise to resolve (deduping).\n cache.promise.set(promise)\n }\n\n try {\n const data = await promise\n\n // Store the response in the cache so that subsequent invocations\n // will return the same response.\n cache.response.set({ created: new Date(), data })\n\n return data\n } finally {\n // Clear the promise cache so that subsequent invocations will\n // invoke the promise again.\n cache.promise.clear()\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\nexport function getBlockNumberCache(id: string) {\n return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber(\n client: Client,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcLog } from '../../index.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter\n}\n\nexport type GetFilterChangesReturnType<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = filterType extends 'event'\n ? Log[]\n : Hash[]\n\nexport type GetFilterChangesErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n transport extends Transport,\n chain extends Chain | undefined,\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const strict = 'strict' in filter && filter.strict\n\n const logs = await filter.request({\n method: 'eth_getFilterChanges',\n params: [filter.id],\n })\n\n if (typeof logs[0] === 'string')\n return logs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n\n const formattedLogs = logs.map((log) => formatLog(log as RpcLog))\n if (!('abi' in filter) || !filter.abi)\n return formattedLogs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n filter: Filter\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n _client: Client,\n { filter }: UninstallFilterParameters,\n): Promise {\n return filter.request({\n method: 'eth_uninstallFilter',\n params: [filter.id],\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction(\n client: Client,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry(\n fn: () => Promise,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial,\n _?: string | undefined,\n) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[\n transactionReceipt.type as keyof typeof transactionType\n ] || transactionReceipt.type\n : null,\n } as TransactionReceipt\n\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { DataSuffix } from '../types/dataSuffix.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify | undefined\n }\n | undefined\n /**\n * Default block tag to use for RPC requests.\n *\n * If the chain supports a pre-confirmation mechanism\n * (set via `chain.experimental_preconfirmationTime`), defaults to `'pending'`.\n *\n * @default 'latest'\n */\n experimental_blockTag?: BlockTag | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default chain.blockTime / 3\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default chain.blockTime / 3\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial>,\n >(\n fn: (\n client: Client,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** Default block tag to use for RPC requests. */\n experimental_blockTag?: BlockTag | undefined\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType['config'] & ReturnType['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n chain,\n ccipRead,\n dataSuffix,\n key = 'base',\n name = 'Base Client',\n type = 'base',\n } = parameters\n\n const experimental_blockTag =\n parameters.experimental_blockTag ??\n (typeof chain?.experimental_preconfirmationTime === 'number'\n ? 'pending'\n : undefined)\n const blockTime = chain?.blockTime ?? 12_000\n\n const defaultPollingInterval = Math.min(\n Math.max(Math.floor(blockTime / 2), 500),\n 4_000,\n )\n const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval\n const cacheTime = parameters.cacheTime ?? pollingInterval\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n account,\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n dataSuffix,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n ...(experimental_blockTag ? { experimental_blockTag } : {}),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema(): rpcSchema {\n return null as any\n}\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n addressResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n Pick & {\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS address for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Name to get the address for.\n */\n name: string\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n | GetChainContractAddressErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | DecodeFunctionResultErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress(\n client: Client,\n parameters: GetEnsAddressParameters,\n): Promise {\n const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } =\n parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n const args = (() => {\n if (coinType != null) return [namehash(name), BigInt(coinType)] as const\n return [namehash(name)] as const\n })()\n\n try {\n const functionData = encodeFunctionData({\n abi: addressResolverAbi,\n functionName: 'addr',\n args,\n })\n\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolveWithGateways',\n args: [\n toHex(packetToBytes(name)),\n functionData,\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const address = decodeFunctionResult({\n abi: addressResolverAbi,\n args,\n functionName: 'addr',\n data: res[0],\n })\n\n if (address === '0x') return null\n if (trim(address) === '0x00') return null\n return address\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(err: unknown): boolean {\n if (!(err instanceof BaseError)) return false\n const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (!(cause instanceof ContractFunctionRevertedError)) return false\n\n if (cause.data?.errorName === 'HttpError') return true\n if (cause.data?.errorName === 'ResolverError') return true\n if (cause.data?.errorName === 'ResolverNotContract') return true\n if (cause.data?.errorName === 'ResolverNotFound') return true\n if (cause.data?.errorName === 'ReverseAddressMismatch') return true\n if (cause.data?.errorName === 'UnsupportedResolverProfile') return true\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n type ToBytesErrorType,\n toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | ToBytesErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ConcatErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0x08c85f2f4059e930c45a6aeff9dcd3bd95dc3c5c1cddef6a0626b31152248560'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n let result = new Uint8Array(32).fill(0) as ByteArray\n if (!name) return bytesToHex(result)\n\n const labels = name.split('.')\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n const hashed = hashFromEncodedLabel\n ? toBytes(hashFromEncodedLabel)\n : keccak256(stringToBytes(labels[i]), 'bytes')\n result = keccak256(concat([result, hashed]), 'bytes')\n }\n\n return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n if (label.length !== 66) return null\n if (label.indexOf('[') !== 0) return null\n if (label.indexOf(']') !== 65) return null\n const hash = `0x${label.slice(1, 65)}`\n if (!isHex(hash)) return null\n return hash\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n type EncodeLabelhashErrorType,\n encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n | EncodeLabelhashErrorType\n | LabelhashErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n *\n * @example\n * packetToBytes('awkweb.eth')\n * '0x0661776b7765620365746800'\n *\n * @see https://docs.ens.domains/resolution/names#dns\n *\n */\nexport function packetToBytes(packet: string): ByteArray {\n // strip leading and trailing `.`\n const value = packet.replace(/^\\.|\\.$/gm, '')\n if (value.length === 0) return new Uint8Array(1)\n\n const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n let offset = 0\n const list = value.split('.')\n for (let i = 0; i < list.length; i++) {\n let encoded = stringToBytes(list[i])\n // if the length is > 255, make the encoded label value a labelhash\n // this is compatible with the universal resolver\n if (encoded.byteLength > 255)\n encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n bytes[offset] = encoded.length\n bytes.set(encoded, offset + 1)\n offset += encoded.length + 1\n }\n\n if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n return bytes\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n const result = new Uint8Array(32).fill(0)\n if (!label) return bytesToHex(result)\n return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","import { BaseError } from './base.js'\n\nexport type EnsAvatarInvalidMetadataErrorType =\n EnsAvatarInvalidMetadataError & {\n name: 'EnsAvatarInvalidMetadataError'\n }\nexport class EnsAvatarInvalidMetadataError extends BaseError {\n constructor({ data }: { data: any }) {\n super(\n 'Unable to extract image from metadata. The metadata may be malformed or invalid.',\n {\n metaMessages: [\n '- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.',\n '',\n `Provided data: ${JSON.stringify(data)}`,\n ],\n name: 'EnsAvatarInvalidMetadataError',\n },\n )\n }\n}\n\nexport type EnsAvatarInvalidNftUriErrorType = EnsAvatarInvalidNftUriError & {\n name: 'EnsAvatarInvalidNftUriError'\n}\nexport class EnsAvatarInvalidNftUriError extends BaseError {\n constructor({ reason }: { reason: string }) {\n super(`ENS NFT avatar URI is invalid. ${reason}`, {\n name: 'EnsAvatarInvalidNftUriError',\n })\n }\n}\n\nexport type EnsAvatarUriResolutionErrorType = EnsAvatarUriResolutionError & {\n name: 'EnsAvatarUriResolutionError'\n}\nexport class EnsAvatarUriResolutionError extends BaseError {\n constructor({ uri }: { uri: string }) {\n super(\n `Unable to resolve ENS avatar URI \"${uri}\". The URI may be malformed, invalid, or does not respond with a valid image.`,\n { name: 'EnsAvatarUriResolutionError' },\n )\n }\n}\n\nexport type EnsAvatarUnsupportedNamespaceErrorType =\n EnsAvatarUnsupportedNamespaceError & {\n name: 'EnsAvatarUnsupportedNamespaceError'\n }\nexport class EnsAvatarUnsupportedNamespaceError extends BaseError {\n constructor({ namespace }: { namespace: string }) {\n super(\n `ENS NFT avatar namespace \"${namespace}\" is not supported. Must be \"erc721\" or \"erc1155\".`,\n { name: 'EnsAvatarUnsupportedNamespaceError' },\n )\n }\n}\n\nexport type EnsInvalidChainIdErrorType = EnsInvalidChainIdError & {\n name: 'EnsInvalidChainIdError'\n}\nexport class EnsInvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId: number }) {\n super(\n `Invalid ENSIP-11 chainId: ${chainId}. Must be between 0 and 0x7fffffff, or 1.`,\n {\n name: 'EnsInvalidChainIdError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n type ReadContractErrorType,\n readContract,\n} from '../../../actions/public/readContract.js'\nimport type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport {\n EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n} from '../../../errors/ens.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\ntype UriItem = {\n uri: string\n isOnChain: boolean\n isEncoded: boolean\n}\n\nconst networkRegex =\n /(?https?:\\/\\/[^/]*|ipfs:\\/|ipns:\\/|ar:\\/)?(?\\/)?(?ipfs\\/|ipns\\/)?(?[\\w\\-.]+)(?\\/.*)?/\nconst ipfsHashRegex =\n /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\\/(?[\\w\\-.]+))?(?\\/.*)?$/\nconst base64Regex = /^data:([a-zA-Z\\-/+]*);base64,([^\"].*)/\nconst dataURIRegex = /^data:([a-zA-Z\\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/\n\ntype IsImageUriErrorType = ErrorType\n\n/** @internal */\nexport async function isImageUri(uri: string) {\n try {\n const res = await fetch(uri, { method: 'HEAD' })\n // retrieve content type header to check if content is image\n if (res.status === 200) {\n const contentType = res.headers.get('content-type')\n return contentType?.startsWith('image/')\n }\n return false\n } catch (error: any) {\n // if error is not cors related then fail\n if (typeof error === 'object' && typeof error.response !== 'undefined') {\n return false\n }\n // fail in NodeJS, since the error is not cors but any other network issue\n if (!Object.hasOwn(globalThis, 'Image')) return false\n // in case of cors, use image api to validate if given url is an actual image\n return new Promise((resolve) => {\n const img = new Image()\n img.onload = () => {\n resolve(true)\n }\n img.onerror = () => {\n resolve(false)\n }\n img.src = uri\n })\n }\n}\n\ntype GetGatewayErrorType = ErrorType\n\n/** @internal */\nexport function getGateway(custom: string | undefined, defaultGateway: string) {\n if (!custom) return defaultGateway\n if (custom.endsWith('/')) return custom.slice(0, -1)\n return custom\n}\n\nexport type ResolveAvatarUriErrorType =\n | GetGatewayErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport function resolveAvatarUri({\n uri,\n gatewayUrls,\n}: {\n uri: string\n gatewayUrls?: AssetGatewayUrls | undefined\n}): UriItem {\n const isEncoded = base64Regex.test(uri)\n if (isEncoded) return { uri, isOnChain: true, isEncoded }\n\n const ipfsGateway = getGateway(gatewayUrls?.ipfs, 'https://ipfs.io')\n const arweaveGateway = getGateway(gatewayUrls?.arweave, 'https://arweave.net')\n\n const networkRegexMatch = uri.match(networkRegex)\n const {\n protocol,\n subpath,\n target,\n subtarget = '',\n } = networkRegexMatch?.groups || {}\n\n const isIPNS = protocol === 'ipns:/' || subpath === 'ipns/'\n const isIPFS =\n protocol === 'ipfs:/' || subpath === 'ipfs/' || ipfsHashRegex.test(uri)\n\n if (uri.startsWith('http') && !isIPNS && !isIPFS) {\n let replacedUri = uri\n if (gatewayUrls?.arweave)\n replacedUri = uri.replace(/https:\\/\\/arweave.net/g, gatewayUrls?.arweave)\n return { uri: replacedUri, isOnChain: false, isEncoded: false }\n }\n\n if ((isIPNS || isIPFS) && target) {\n return {\n uri: `${ipfsGateway}/${isIPNS ? 'ipns' : 'ipfs'}/${target}${subtarget}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n if (protocol === 'ar:/' && target) {\n return {\n uri: `${arweaveGateway}/${target}${subtarget || ''}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n let parsedUri = uri.replace(dataURIRegex, '')\n if (parsedUri.startsWith(' {\n try {\n const res = await fetch(uri).then((res) => res.json())\n const image = await parseAvatarUri({\n gatewayUrls,\n uri: getJsonImage(res),\n })\n return image\n } catch {\n throw new EnsAvatarUriResolutionError({ uri })\n }\n}\n\nexport type ParseAvatarUriErrorType =\n | ResolveAvatarUriErrorType\n | IsImageUriErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport async function parseAvatarUri({\n gatewayUrls,\n uri,\n}: {\n gatewayUrls?: AssetGatewayUrls | undefined\n uri: string\n}): Promise {\n const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls })\n if (isOnChain) return resolvedURI\n\n // check if resolvedURI is an image, if it is return the url\n const isImage = await isImageUri(resolvedURI)\n if (isImage) return resolvedURI\n\n throw new EnsAvatarUriResolutionError({ uri })\n}\n\ntype ParsedNft = {\n chainID: number\n namespace: string\n contractAddress: Address\n tokenID: string\n}\n\nexport type ParseNftUriErrorType = EnsAvatarInvalidNftUriErrorType | ErrorType\n\nexport function parseNftUri(uri_: string): ParsedNft {\n let uri = uri_\n // parse valid nft spec (CAIP-22/CAIP-29)\n // @see: https://github.com/ChainAgnostic/CAIPs/tree/master/CAIPs\n if (uri.startsWith('did:nft:')) {\n // convert DID to CAIP\n uri = uri.replace('did:nft:', '').replace(/_/g, '/')\n }\n\n const [reference, asset_namespace, tokenID] = uri.split('/')\n const [eip_namespace, chainID] = reference.split(':')\n const [erc_namespace, contractAddress] = asset_namespace.split(':')\n\n if (!eip_namespace || eip_namespace.toLowerCase() !== 'eip155')\n throw new EnsAvatarInvalidNftUriError({ reason: 'Only EIP-155 supported' })\n if (!chainID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Chain ID not found' })\n if (!contractAddress)\n throw new EnsAvatarInvalidNftUriError({\n reason: 'Contract address not found',\n })\n if (!tokenID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Token ID not found' })\n if (!erc_namespace)\n throw new EnsAvatarInvalidNftUriError({ reason: 'ERC namespace not found' })\n\n return {\n chainID: Number.parseInt(chainID, 10),\n namespace: erc_namespace.toLowerCase(),\n contractAddress: contractAddress as Address,\n tokenID,\n }\n}\n\nexport type GetNftTokenUriErrorType =\n | ReadContractErrorType\n | EnsAvatarUnsupportedNamespaceErrorType\n | ErrorType\n\nexport async function getNftTokenUri(\n client: Client,\n { nft }: { nft: ParsedNft },\n) {\n if (nft.namespace === 'erc721') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'tokenURI',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'tokenURI',\n args: [BigInt(nft.tokenID)],\n })\n }\n if (nft.namespace === 'erc1155') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'uri',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: '_id', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'uri',\n args: [BigInt(nft.tokenID)],\n })\n }\n throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace })\n}\n","import type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\nimport {\n type GetJsonImageErrorType,\n type GetMetadataAvatarUriErrorType,\n type GetNftTokenUriErrorType,\n getJsonImage,\n getMetadataAvatarUri,\n getNftTokenUri,\n type ParseAvatarUriErrorType,\n type ParseNftUriErrorType,\n parseAvatarUri,\n parseNftUri,\n type ResolveAvatarUriErrorType,\n resolveAvatarUri,\n} from './utils.js'\n\nexport type ParseAvatarRecordErrorType =\n | ParseNftAvatarUriErrorType\n | ParseAvatarUriErrorType\n | ErrorType\n\n/*\n * @description Parses an ENS avatar record.\n *\n * @example\n * parseAvatarRecord('eip155:1/erc1155:0xb32979486938aa9694bfc898f35dbed459f44424/10063')\n * 'https://ipfs.io/ipfs/QmSP4nq9fnN9dAiCj42ug9Wa79rqmQerZXZch82VqpiH7U/image.gif'\n *\n * @see https://docs.ens.domains/web/avatars\n *\n */\nexport async function parseAvatarRecord(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n if (/eip155:/i.test(record))\n return parseNftAvatarUri(client, { gatewayUrls, record })\n return parseAvatarUri({ uri: record, gatewayUrls })\n}\n\ntype ParseNftAvatarUriErrorType =\n | ParseNftUriErrorType\n | GetNftTokenUriErrorType\n | ResolveAvatarUriErrorType\n | ParseAvatarUriErrorType\n | GetJsonImageErrorType\n | GetMetadataAvatarUriErrorType\n | ErrorType\n\nasync function parseNftAvatarUri(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n // parse NFT URI into properties\n const nft = parseNftUri(record)\n // fetch tokenURI from the NFT contract\n const nftUri = await getNftTokenUri(client, { nft })\n // resolve the URI from the fetched tokenURI\n const {\n uri: resolvedNftUri,\n isOnChain,\n isEncoded,\n } = resolveAvatarUri({ uri: nftUri, gatewayUrls })\n\n // if the resolved URI is on chain, return the data\n if (\n isOnChain &&\n (resolvedNftUri.includes('data:application/json;base64,') ||\n resolvedNftUri.startsWith('{'))\n ) {\n const encodedJson = isEncoded\n ? // if it is encoded, decode it\n atob(resolvedNftUri.replace('data:application/json;base64,', ''))\n : // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)\n resolvedNftUri\n\n const decoded = JSON.parse(encodedJson)\n return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls })\n }\n\n let uriTokenId = nft.tokenID\n if (nft.namespace === 'erc1155')\n uriTokenId = uriTokenId.replace('0x', '').padStart(64, '0')\n\n return getMetadataAvatarUri({\n gatewayUrls,\n uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId),\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n textResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsTextParameters = Prettify<\n Pick & {\n /** ENS name to get Text for. */\n name: string\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Text record to retrieve. */\n key: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsTextReturnType = string | null\n\nexport type GetEnsTextErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | DecodeFunctionResultErrorType\n\n/**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsText, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await getEnsText(client, {\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\nexport async function getEnsText(\n client: Client,\n parameters: GetEnsTextParameters,\n): Promise {\n const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n args: [\n toHex(packetToBytes(name)),\n encodeFunctionData({\n abi: textResolverAbi,\n functionName: 'text',\n args: [namehash(name), key],\n }),\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n functionName: 'resolveWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const record = decodeFunctionResult({\n abi: textResolverAbi,\n functionName: 'text',\n data: res[0],\n })\n\n return record === '' ? null : record\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../types/ens.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type ParseAvatarRecordErrorType,\n parseAvatarRecord,\n} from '../../utils/ens/avatar/parseAvatarRecord.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetEnsTextErrorType,\n type GetEnsTextParameters,\n getEnsText,\n} from './getEnsText.js'\n\nexport type GetEnsAvatarParameters = Prettify<\n Omit & {\n /** Gateway urls to resolve IPFS and/or Arweave assets. */\n assetGatewayUrls?: AssetGatewayUrls | undefined\n }\n>\n\nexport type GetEnsAvatarReturnType = string | null\n\nexport type GetEnsAvatarErrorType =\n | GetEnsTextErrorType\n | ParseAvatarRecordErrorType\n | ErrorType\n\n/**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAvatar, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await getEnsAvatar(client, {\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\nexport async function getEnsAvatar(\n client: Client,\n {\n blockNumber,\n blockTag,\n assetGatewayUrls,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress,\n }: GetEnsAvatarParameters,\n): Promise {\n const record = await getAction(\n client,\n getEnsText,\n 'getEnsText',\n )({\n blockNumber,\n blockTag,\n key: 'avatar',\n name,\n universalResolverAddress,\n gatewayUrls,\n strict,\n })\n if (!record) return null\n try {\n return await parseAvatarRecord(client, {\n record,\n gatewayUrls: assetGatewayUrls,\n })\n } catch {\n return null\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalResolverReverseAbi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport type { PacketToBytesErrorType } from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsNameParameters = Prettify<\n Pick & {\n /**\n * Address to get ENS name for.\n */\n address: Address\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS name for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsNameReturnType = string | null\n\nexport type GetEnsNameErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName(\n client: Client,\n parameters: GetEnsNameParameters,\n): Promise {\n const {\n address,\n blockNumber,\n blockTag,\n coinType = 60n,\n gatewayUrls,\n strict,\n } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverReverseAbi,\n args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]],\n functionName: 'reverseWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const [name] = await readContractAction(readContractParameters)\n\n return name || null\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsResolverParameters = Prettify<\n Pick & {\n /** Name to get the address for. */\n name: string\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsResolverReturnType = Address\n\nexport type GetEnsResolverErrorType =\n | GetChainContractAddressErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsResolver, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await getEnsResolver(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\nexport async function getEnsResolver(\n client: Client,\n parameters: GetEnsResolverParameters,\n): Promise {\n const { blockNumber, blockTag, name } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld)))\n throw new Error(\n `${name} is not a valid ENS TLD (${tlds?.join(', ')}) for chain \"${chain.name}\" (id: ${chain.id}).`,\n )\n\n const [resolverAddress] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address: universalResolverAddress,\n abi: [\n {\n inputs: [{ type: 'bytes' }],\n name: 'findResolver',\n outputs: [\n { type: 'address' },\n { type: 'bytes32' },\n { type: 'uint256' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ],\n functionName: 'findResolver',\n args: [toHex(packetToBytes(name))],\n blockNumber,\n blockTag,\n })\n return resolverAddress\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport {\n type GetEnsAddressParameters,\n type GetEnsAddressReturnType,\n getEnsAddress,\n} from '../../actions/ens/getEnsAddress.js'\nimport {\n type GetEnsAvatarParameters,\n type GetEnsAvatarReturnType,\n getEnsAvatar,\n} from '../../actions/ens/getEnsAvatar.js'\nimport {\n type GetEnsNameParameters,\n type GetEnsNameReturnType,\n getEnsName,\n} from '../../actions/ens/getEnsName.js'\nimport {\n type GetEnsResolverParameters,\n type GetEnsResolverReturnType,\n getEnsResolver,\n} from '../../actions/ens/getEnsResolver.js'\nimport {\n type GetEnsTextParameters,\n type GetEnsTextReturnType,\n getEnsText,\n} from '../../actions/ens/getEnsText.js'\nimport {\n type CallParameters,\n type CallReturnType,\n call,\n} from '../../actions/public/call.js'\nimport {\n type CreateAccessListParameters,\n type CreateAccessListReturnType,\n createAccessList,\n} from '../../actions/public/createAccessList.js'\nimport {\n type CreateBlockFilterReturnType,\n createBlockFilter,\n} from '../../actions/public/createBlockFilter.js'\nimport {\n type CreateContractEventFilterParameters,\n type CreateContractEventFilterReturnType,\n createContractEventFilter,\n} from '../../actions/public/createContractEventFilter.js'\nimport {\n type CreateEventFilterParameters,\n type CreateEventFilterReturnType,\n createEventFilter,\n} from '../../actions/public/createEventFilter.js'\nimport {\n type CreatePendingTransactionFilterReturnType,\n createPendingTransactionFilter,\n} from '../../actions/public/createPendingTransactionFilter.js'\nimport {\n type EstimateContractGasParameters,\n type EstimateContractGasReturnType,\n estimateContractGas,\n} from '../../actions/public/estimateContractGas.js'\nimport {\n type EstimateFeesPerGasParameters,\n type EstimateFeesPerGasReturnType,\n estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasParameters,\n type EstimateGasReturnType,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type EstimateMaxPriorityFeePerGasParameters,\n type EstimateMaxPriorityFeePerGasReturnType,\n estimateMaxPriorityFeePerGas,\n} from '../../actions/public/estimateMaxPriorityFeePerGas.js'\nimport {\n type FillTransactionParameters,\n type FillTransactionReturnType,\n fillTransaction,\n} from '../../actions/public/fillTransaction.js'\nimport {\n type GetBalanceParameters,\n type GetBalanceReturnType,\n getBalance,\n} from '../../actions/public/getBalance.js'\nimport {\n type GetBlobBaseFeeReturnType,\n getBlobBaseFee,\n} from '../../actions/public/getBlobBaseFee.js'\nimport {\n type GetBlockParameters,\n type GetBlockReturnType,\n getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetBlockNumberParameters,\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from '../../actions/public/getBlockNumber.js'\nimport {\n type GetBlockTransactionCountParameters,\n type GetBlockTransactionCountReturnType,\n getBlockTransactionCount,\n} from '../../actions/public/getBlockTransactionCount.js'\nimport {\n type GetChainIdReturnType,\n getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n type GetCodeParameters,\n type GetCodeReturnType,\n getCode,\n} from '../../actions/public/getCode.js'\nimport {\n type GetContractEventsParameters,\n type GetContractEventsReturnType,\n getContractEvents,\n} from '../../actions/public/getContractEvents.js'\nimport {\n type GetDelegationParameters,\n type GetDelegationReturnType,\n getDelegation,\n} from '../../actions/public/getDelegation.js'\nimport {\n type GetEip712DomainParameters,\n type GetEip712DomainReturnType,\n getEip712Domain,\n} from '../../actions/public/getEip712Domain.js'\nimport {\n type GetFeeHistoryParameters,\n type GetFeeHistoryReturnType,\n getFeeHistory,\n} from '../../actions/public/getFeeHistory.js'\nimport {\n type GetFilterChangesParameters,\n type GetFilterChangesReturnType,\n getFilterChanges,\n} from '../../actions/public/getFilterChanges.js'\nimport {\n type GetFilterLogsParameters,\n type GetFilterLogsReturnType,\n getFilterLogs,\n} from '../../actions/public/getFilterLogs.js'\nimport {\n type GetGasPriceReturnType,\n getGasPrice,\n} from '../../actions/public/getGasPrice.js'\nimport {\n type GetLogsParameters,\n type GetLogsReturnType,\n getLogs,\n} from '../../actions/public/getLogs.js'\nimport {\n type GetProofParameters,\n type GetProofReturnType,\n getProof,\n} from '../../actions/public/getProof.js'\nimport {\n type GetStorageAtParameters,\n type GetStorageAtReturnType,\n getStorageAt,\n} from '../../actions/public/getStorageAt.js'\nimport {\n type GetTransactionParameters,\n type GetTransactionReturnType,\n getTransaction,\n} from '../../actions/public/getTransaction.js'\nimport {\n type GetTransactionConfirmationsParameters,\n type GetTransactionConfirmationsReturnType,\n getTransactionConfirmations,\n} from '../../actions/public/getTransactionConfirmations.js'\nimport {\n type GetTransactionCountParameters,\n type GetTransactionCountReturnType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport {\n type GetTransactionReceiptParameters,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from '../../actions/public/getTransactionReceipt.js'\nimport {\n type MulticallParameters,\n type MulticallReturnType,\n multicall,\n} from '../../actions/public/multicall.js'\nimport {\n type ReadContractParameters,\n type ReadContractReturnType,\n readContract,\n} from '../../actions/public/readContract.js'\nimport {\n type SimulateBlocksParameters,\n type SimulateBlocksReturnType,\n simulateBlocks,\n} from '../../actions/public/simulateBlocks.js'\nimport {\n type SimulateCallsParameters,\n type SimulateCallsReturnType,\n simulateCalls,\n} from '../../actions/public/simulateCalls.js'\nimport {\n type SimulateContractParameters,\n type SimulateContractReturnType,\n simulateContract,\n} from '../../actions/public/simulateContract.js'\nimport {\n type UninstallFilterParameters,\n type UninstallFilterReturnType,\n uninstallFilter,\n} from '../../actions/public/uninstallFilter.js'\nimport {\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from '../../actions/public/verifyHash.js'\nimport {\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from '../../actions/public/verifyMessage.js'\nimport {\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from '../../actions/public/verifyTypedData.js'\nimport {\n type WaitForTransactionReceiptParameters,\n type WaitForTransactionReceiptReturnType,\n waitForTransactionReceipt,\n} from '../../actions/public/waitForTransactionReceipt.js'\nimport {\n type WatchBlockNumberParameters,\n type WatchBlockNumberReturnType,\n watchBlockNumber,\n} from '../../actions/public/watchBlockNumber.js'\nimport {\n type WatchBlocksParameters,\n type WatchBlocksReturnType,\n watchBlocks,\n} from '../../actions/public/watchBlocks.js'\nimport {\n type WatchContractEventParameters,\n type WatchContractEventReturnType,\n watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n type WatchEventParameters,\n type WatchEventReturnType,\n watchEvent,\n} from '../../actions/public/watchEvent.js'\nimport {\n type WatchPendingTransactionsParameters,\n type WatchPendingTransactionsReturnType,\n watchPendingTransactions,\n} from '../../actions/public/watchPendingTransactions.js'\nimport {\n type VerifySiweMessageParameters,\n type VerifySiweMessageReturnType,\n verifySiweMessage,\n} from '../../actions/siwe/verifySiweMessage.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\n type PrepareTransactionRequestReturnType,\n prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n type SendRawTransactionSyncParameters,\n type SendRawTransactionSyncReturnType,\n sendRawTransactionSync,\n} from '../../actions/wallet/sendRawTransactionSync.js'\nimport type { Account } from '../../types/account.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { FeeValuesType } from '../../types/fee.js'\nimport type { FilterType } from '../../types/filter.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type PublicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\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 args - {@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 *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await client.call({\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n call: (parameters: CallParameters) => Promise\n /**\n * Creates an EIP-2930 access list that you can include in a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param args - {@link CreateAccessListParameters}\n * @returns The call data. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const data = await client.createAccessList({\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n createAccessList: (\n parameters: CreateAccessListParameters,\n ) => Promise\n /**\n * Creates a Filter to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @returns Filter. {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, createBlockFilter, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\n createBlockFilter: () => Promise\n /**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param args - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\n createContractEventFilter: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param args - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\n createEventFilter: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _EventName extends string | undefined = MaybeAbiEventName,\n _Args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n >(\n args?:\n | CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n | undefined,\n ) => Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n >\n /**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\n createPendingTransactionFilter: () => Promise\n /**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * @remarks\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await client.estimateContractGas({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\n estimateContractGas: <\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n >(\n args: EstimateContractGasParameters,\n ) => Promise\n /**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param args - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await client.estimateGas({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n estimateGas: (\n args: EstimateGasParameters,\n ) => Promise\n /**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.fillTransaction({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n fillTransaction: <\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n ) => Promise>\n /**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * @remarks\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param args - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await client.getBalance({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\n getBalance: (args: GetBalanceParameters) => Promise\n /**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await client.getBlobBaseFee()\n */\n getBlobBaseFee: () => Promise\n /**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getBlock()\n */\n getBlock: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args?: GetBlockParameters | undefined,\n ) => Promise>\n /**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param args - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await client.getBlockNumber()\n * // 69420n\n */\n getBlockNumber: (\n args?: GetBlockNumberParameters | undefined,\n ) => Promise\n /**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await client.getBlockTransactionCount()\n */\n getBlockTransactionCount: (\n args?: GetBlockTransactionCountParameters | undefined,\n ) => Promise\n /** @deprecated Use `getCode` instead. */\n getBytecode: (args: GetCodeParameters) => Promise\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await client.getChainId()\n * // 1\n */\n getChainId: () => Promise\n /**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param args - {@link GetBytecodeParameters}\n * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getCode({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\n getCode: (args: GetCodeParameters) => Promise\n /**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/actions/public/getContractEvents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { wagmiAbi } from './abi'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\n getContractEvents: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetContractEventsReturnType\n >\n /**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param args - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await client.getDelegation({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getDelegation: (\n args: GetDelegationParameters,\n ) => Promise\n /**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await client.getEip712Domain({\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\n getEip712Domain: (\n args: GetEip712DomainParameters,\n ) => Promise\n /**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await client.getEnsAddress({\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\n getEnsAddress: (\n args: GetEnsAddressParameters,\n ) => Promise\n /**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await client.getEnsAvatar({\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\n getEnsAvatar: (\n args: GetEnsAvatarParameters,\n ) => Promise\n /**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param args - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await client.getEnsName({\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\n getEnsName: (args: GetEnsNameParameters) => Promise\n /**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await client.getEnsResolver({\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\n getEnsResolver: (\n args: GetEnsResolverParameters,\n ) => Promise\n /**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await client.getEnsText({\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\n getEnsText: (args: GetEnsTextParameters) => Promise\n /**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param args - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await client.getFeeHistory({\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\n getFeeHistory: (\n args: GetFeeHistoryParameters,\n ) => Promise\n /**\n * Returns an estimate for the fees per gas for a transaction to be included\n * in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateFeesPerGas()\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\n estimateFeesPerGas: <\n chainOverride extends Chain | undefined = undefined,\n type extends FeeValuesType = 'eip1559',\n >(\n args?: EstimateFeesPerGasParameters | undefined,\n ) => Promise>\n /**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * @remarks\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param args - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createBlockFilter()\n * const hashes = await client.getFilterChanges({ filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * const hashes = await client.getFilterChanges({ filter })\n */\n getFilterChanges: <\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * @remarks\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param args - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterLogs({ filter })\n */\n getFilterLogs: <\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterLogsParameters,\n ) => Promise<\n GetFilterLogsReturnType\n >\n /**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await client.getGasPrice()\n */\n getGasPrice: () => Promise\n /**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param args - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getLogs()\n */\n getLogs: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args?:\n | GetLogsParameters\n | undefined,\n ) => Promise<\n GetLogsReturnType\n >\n /**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getProof({\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\n getProof: (args: GetProofParameters) => Promise\n /**\n * Returns an estimate for the max priority fee per gas (in wei) for a transaction\n * to be included in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()\n * // 10000000n\n */\n estimateMaxPriorityFeePerGas: <\n chainOverride extends Chain | undefined = undefined,\n >(\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n ) => Promise\n /**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param args - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getStorageAt({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\n getStorageAt: (\n args: GetStorageAtParameters,\n ) => Promise\n /**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param args - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await client.getTransaction({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransaction: (\n args: GetTransactionParameters,\n ) => Promise>\n /**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param args - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await client.getTransactionConfirmations({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionConfirmations: (\n args: GetTransactionConfirmationsParameters,\n ) => Promise\n /**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has broadcast / sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param args - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await client.getTransactionCount({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getTransactionCount: (\n args: GetTransactionCountParameters,\n ) => Promise\n /**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt)\n *\n * @param args - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.getTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionReceipt: (\n args: GetTransactionReceiptParameters,\n ) => Promise>\n /**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param args - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const result = await client.multicall({\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\n multicall: <\n const contracts extends readonly unknown[],\n allowFailure extends boolean = true,\n >(\n args: MulticallParameters,\n ) => Promise>\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\n prepareTransactionRequest: <\n const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * @remarks\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.readContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\n readContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n >(\n args: ReadContractParameters,\n ) => Promise>\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await client.sendRawTransaction({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransaction: (\n args: SendRawTransactionParameters,\n ) => Promise\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionSyncParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await client.sendRawTransactionSync({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransactionSync: (\n args: SendRawTransactionSyncParameters,\n ) => Promise>\n /**\n * @deprecated Use `simulateBlocks` instead.\n */\n simulate: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateBlocks({\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateParameters}\n * @returns Simulated blocks. {@link SimulateReturnType}\n */\n simulateBlocks: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateCalls({\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n */\n simulateCalls: (\n args: SimulateCallsParameters,\n ) => Promise>\n /**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * @remarks\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.simulateContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n simulateContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n ) => Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n >\n /**\n * Verify that a hash was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyHash}\n *\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\n verifyHash: (args: VerifyHashParameters) => Promise\n /**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\n verifyMessage: (\n args: VerifyMessageParameters,\n ) => Promise\n /**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\n verifySiweMessage: (\n args: VerifySiweMessageParameters,\n ) => Promise\n /**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\n verifyTypedData: (\n args: VerifyTypedDataParameters,\n ) => Promise\n /**\n * Destroys a Filter that was created from one of the following Actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * @param args - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await client.createPendingTransactionFilter()\n * const uninstalled = await client.uninstallFilter({ filter })\n * // true\n */\n uninstallFilter: (\n args: UninstallFilterParameters,\n ) => Promise\n /**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * @remarks\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param args - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.waitForTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n waitForTransactionReceipt: (\n args: WaitForTransactionReceiptParameters,\n ) => Promise>\n /**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlockNumber({\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\n watchBlockNumber: (\n args: WatchBlockNumberParameters,\n ) => WatchBlockNumberReturnType\n /**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlocks({\n * onBlock: (block) => console.log(block),\n * })\n */\n watchBlocks: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args: WatchBlocksParameters<\n transport,\n chain,\n includeTransactions,\n blockTag\n >,\n ) => WatchBlocksReturnType\n /**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * @remarks\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchContractEvent({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchContractEvent: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchContractEventParameters,\n ) => WatchContractEventReturnType\n /**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * @remarks\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchEvent({\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchEvent: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchEventParameters,\n ) => WatchEventReturnType\n /**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * @remarks\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param args - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchPendingTransactions({\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\n watchPendingTransactions: (\n args: WatchPendingTransactionsParameters,\n ) => WatchPendingTransactionsReturnType\n}\n\nexport function publicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(\n client: Client,\n): PublicActions {\n return {\n call: (args) => call(client, args),\n createAccessList: (args) => createAccessList(client, args),\n createBlockFilter: () => createBlockFilter(client),\n createContractEventFilter: (args) =>\n createContractEventFilter(client, args),\n createEventFilter: (args) => createEventFilter(client, args),\n createPendingTransactionFilter: () =>\n createPendingTransactionFilter(client),\n estimateContractGas: (args) => estimateContractGas(client, args as any),\n estimateGas: (args) => estimateGas(client, args),\n getBalance: (args) => getBalance(client, args),\n getBlobBaseFee: () => getBlobBaseFee(client),\n getBlock: (args) => getBlock(client, args),\n getBlockNumber: (args) => getBlockNumber(client, args),\n getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),\n getBytecode: (args) => getCode(client, args),\n getChainId: () => getChainId(client),\n getCode: (args) => getCode(client, args),\n getContractEvents: (args) => getContractEvents(client, args),\n getDelegation: (args) => getDelegation(client, args),\n getEip712Domain: (args) => getEip712Domain(client, args),\n getEnsAddress: (args) => getEnsAddress(client, args),\n getEnsAvatar: (args) => getEnsAvatar(client, args),\n getEnsName: (args) => getEnsName(client, args),\n getEnsResolver: (args) => getEnsResolver(client, args),\n getEnsText: (args) => getEnsText(client, args),\n getFeeHistory: (args) => getFeeHistory(client, args),\n estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),\n getFilterChanges: (args) => getFilterChanges(client, args),\n getFilterLogs: (args) => getFilterLogs(client, args),\n getGasPrice: () => getGasPrice(client),\n getLogs: (args) => getLogs(client, args as any),\n getProof: (args) => getProof(client, args),\n estimateMaxPriorityFeePerGas: (args) =>\n estimateMaxPriorityFeePerGas(client, args),\n fillTransaction: (args) => fillTransaction(client, args),\n getStorageAt: (args) => getStorageAt(client, args),\n getTransaction: (args) => getTransaction(client, args),\n getTransactionConfirmations: (args) =>\n getTransactionConfirmations(client, args),\n getTransactionCount: (args) => getTransactionCount(client, args),\n getTransactionReceipt: (args) => getTransactionReceipt(client, args),\n multicall: (args) => multicall(client, args),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n readContract: (args) => readContract(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n sendRawTransactionSync: (args) => sendRawTransactionSync(client, args),\n simulate: (args) => simulateBlocks(client, args),\n simulateBlocks: (args) => simulateBlocks(client, args),\n simulateCalls: (args) => simulateCalls(client, args),\n simulateContract: (args) => simulateContract(client, args),\n verifyHash: (args) => verifyHash(client, args),\n verifyMessage: (args) => verifyMessage(client, args),\n verifySiweMessage: (args) => verifySiweMessage(client, args),\n verifyTypedData: (args) => verifyTypedData(client, args),\n uninstallFilter: (args) => uninstallFilter(client, args),\n waitForTransactionReceipt: (args) =>\n waitForTransactionReceipt(client, args),\n watchBlocks: (args) => watchBlocks(client, args),\n watchBlockNumber: (args) => watchBlockNumber(client, args),\n watchContractEvent: (args) => watchContractEvent(client, args),\n watchEvent: (args) => watchEvent(client, args),\n watchPendingTransactions: (args) => watchPendingTransactions(client, args),\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { AccessList, TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, Prettify, UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\n\nexport type CreateAccessListParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n FormattedTransactionRequest,\n 'from' | 'nonce' | 'accessList'\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | 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 )\n\nexport type CreateAccessListReturnType = Prettify<{\n accessList: AccessList\n gasUsed: bigint\n}>\n\nexport type CreateAccessListErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | RequestErrorType\n>\n\n/**\n * Creates an EIP-2930 access list.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param client - Client to use\n * @param parameters - {@link CreateAccessListParameters}\n * @returns The access list. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createAccessList } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await createAccessList(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function createAccessList(\n client: Client,\n args: CreateAccessListParameters,\n): Promise {\n const {\n account: account_ = client.account,\n blockNumber,\n blockTag = 'latest',\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n } as TransactionRequest,\n 'createAccessList',\n ) as TransactionRequest\n\n const response = await client.request({\n method: 'eth_createAccessList',\n params: [request as ExactPartial, block],\n })\n return {\n accessList: response.accessList,\n gasUsed: BigInt(response.gasUsed),\n }\n } catch (err) {\n throw getCallError(err as ErrorType, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateBlockFilterReturnType = Filter<'block'>\n\nexport type CreateBlockFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\nexport async function createBlockFilter(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newBlockFilter',\n })\n const id = await client.request({\n method: 'eth_newBlockFilter',\n })\n return { id, request: getRequest(id), type: 'block' }\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex, LogTopic } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateEventFilterParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (MaybeExtractEventArgsFromAbi<\n abiEvents,\n _eventName\n> extends infer eventFilterArgs\n ?\n | {\n args:\n | eventFilterArgs\n | (_args extends eventFilterArgs ? _args : never)\n event: abiEvent\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: abiEvent | undefined\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events: abiEvents | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n }\n : {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n })\n\nexport type CreateEventFilterReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = Prettify<\n Filter<'event', abiEvents, _eventName, _args, strict, fromBlock, toBlock>\n>\n\nexport type CreateEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param client - Client to use\n * @param parameters - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\nexport async function createEventFilter<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n event,\n events: events_,\n fromBlock,\n strict,\n toBlock,\n }: CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n > = {} as any,\n): Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n> {\n const events = events_ ?? (event ? [event] : undefined)\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n ...(topics.length ? { topics } : {}),\n },\n ],\n })\n\n return {\n abi: events,\n args,\n eventName: event ? (event as AbiEvent).name : undefined,\n fromBlock,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n toBlock,\n type: 'event',\n } as unknown as CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreatePendingTransactionFilterReturnType = Filter<'transaction'>\n\nexport type CreatePendingTransactionFilterErrorType =\n | RequestErrorType\n | ErrorType\n\n/**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\nexport async function createPendingTransactionFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newPendingTransactionFilter',\n })\n const id = await client.request({\n method: 'eth_newPendingTransactionFilter',\n })\n return { id, request: getRequest(id), type: 'transaction' }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport { decodeFunctionResult } from '../../utils/abi/decodeFunctionResult.js'\nimport { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type CallParameters, call } from './call.js'\n\nexport type GetBalanceParameters = {\n /** The address of the account. */\n address: Address\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 /** The balance of the account at a block tag. */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance(\n client: Client,\n {\n address,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n }: GetBalanceParameters,\n): Promise {\n if (client.batch?.multicall && client.chain?.contracts?.multicall3) {\n const multicall3Address = client.chain.contracts.multicall3.address\n\n const calldata = encodeFunctionData({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n })\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n to: multicall3Address,\n data: calldata,\n blockNumber,\n blockTag,\n } as unknown as CallParameters)\n\n return decodeFunctionResult({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n data: data || '0x',\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n\n const balance = await client.request({\n method: 'eth_getBalance',\n params: [address, blockNumberHex || blockTag],\n })\n return BigInt(balance)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetBlobBaseFeeReturnType = bigint\n\nexport type GetBlobBaseFeeErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await getBlobBaseFee(client)\n */\nexport async function getBlobBaseFee<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n): Promise {\n const baseFee = await client.request({\n method: 'eth_blobBaseFee',\n })\n return BigInt(baseFee)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Quantity } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBlockTransactionCountParameters =\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n\nexport type GetBlockTransactionCountReturnType = number\n\nexport type GetBlockTransactionCountErrorType =\n | NumberToHexErrorType\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await getBlockTransactionCount(client)\n */\nexport async function getBlockTransactionCount(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = 'latest',\n }: GetBlockTransactionCountParameters = {},\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let count: Quantity\n if (blockHash) {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByHash',\n params: [blockHash],\n },\n { dedupe: true },\n )\n } else {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByNumber',\n params: [blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n return hexToNumber(count)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetCodeParameters = {\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetCodeReturnType = Hex | undefined\n\nexport type GetCodeErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetCodeParameters}\n * @returns The contract's bytecode. {@link GetCodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCode } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getCode(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getCode(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetCodeParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const hex = await client.request(\n {\n method: 'eth_getCode',\n params: [address, blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n if (hex === '0x') return undefined\n return hex\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport { type SizeErrorType, size } from '../../utils/data/size.js'\nimport { type SliceErrorType, slice } from '../../utils/data/slice.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\n\nexport type GetDelegationParameters = {\n /** The address to check for delegation. */\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetDelegationReturnType = Address | undefined\n\nexport type GetDelegationErrorType =\n | GetAddressErrorType\n | GetCodeErrorType\n | SliceErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param client - Client to use\n * @param parameters - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getDelegation } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await getDelegation(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getDelegation(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetDelegationParameters,\n): Promise {\n const code = await getCode(client, {\n address,\n ...(blockNumber !== undefined ? { blockNumber } : { blockTag }),\n } as GetDelegationParameters)\n\n if (!code) return undefined\n\n // EIP-7702 delegation designator: 0xef0100 prefix (3 bytes) + address (20 bytes) = 23 bytes\n if (size(code) !== 23) return undefined\n\n // Check for EIP-7702 delegation designator prefix\n if (!code.startsWith('0xef0100')) return undefined\n\n // Extract the delegated address (bytes 3-23) and checksum it\n return getAddress(slice(code, 3, 23))\n}\n","import type { Address } from 'abitype'\nimport { BaseError } from './base.js'\n\nexport type Eip712DomainNotFoundErrorType = Eip712DomainNotFoundError & {\n name: 'Eip712DomainNotFoundError'\n}\nexport class Eip712DomainNotFoundError extends BaseError {\n constructor({ address }: { address: Address }) {\n super(`No EIP-712 domain found on contract \"${address}\".`, {\n metaMessages: [\n 'Ensure that:',\n `- The contract is deployed at the address \"${address}\".`,\n '- `eip712Domain()` function exists on the contract.',\n '- `eip712Domain()` function matches signature to ERC-5267 specification.',\n ],\n name: 'Eip712DomainNotFoundError',\n })\n }\n}\n","import type { Address, TypedDataDomain } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip712DomainNotFoundError,\n type Eip712DomainNotFoundErrorType,\n} from '../../errors/eip712.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequiredBy } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from './readContract.js'\n\nexport type GetEip712DomainParameters = {\n address: Address\n} & Pick\n\nexport type GetEip712DomainReturnType = {\n domain: RequiredBy<\n TypedDataDomain,\n 'chainId' | 'name' | 'verifyingContract' | 'salt' | 'version'\n >\n fields: Hex\n extensions: readonly bigint[]\n}\n\nexport type GetEip712DomainErrorType =\n | Eip712DomainNotFoundErrorType\n | ReadContractErrorType\n | ErrorType\n\n/**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, getEip712Domain } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await getEip712Domain(client, {\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\nexport async function getEip712Domain(\n client: Client,\n parameters: GetEip712DomainParameters,\n): Promise {\n const { address, factory, factoryData } = parameters\n\n try {\n const [\n fields,\n name,\n version,\n chainId,\n verifyingContract,\n salt,\n extensions,\n ] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi,\n address,\n functionName: 'eip712Domain',\n factory,\n factoryData,\n })\n\n return {\n domain: {\n name,\n version,\n chainId: Number(chainId),\n verifyingContract,\n salt,\n },\n extensions,\n fields,\n }\n } catch (e) {\n const error = e as ReadContractErrorType\n if (\n error.name === 'ContractFunctionExecutionError' &&\n error.cause.name === 'ContractFunctionZeroDataError'\n ) {\n throw new Eip712DomainNotFoundError({ address })\n }\n throw error\n }\n}\n\nconst abi = [\n {\n inputs: [],\n name: 'eip712Domain',\n outputs: [\n { name: 'fields', type: 'bytes1' },\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n { name: 'extensions', type: 'uint256[]' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatFeeHistoryErrorType,\n formatFeeHistory,\n} from '../../utils/formatters/feeHistory.js'\n\nexport type GetFeeHistoryParameters = {\n /**\n * Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.\n */\n blockCount: number\n /**\n * A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used.\n */\n rewardPercentiles: number[]\n} & (\n | {\n blockNumber?: undefined\n /**\n * Highest number block of the requested range.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n | {\n /** Highest number block of the requested range. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\nexport type GetFeeHistoryReturnType = FeeHistory\n\nexport type GetFeeHistoryErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | FormatFeeHistoryErrorType\n\n/**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param client - Client to use\n * @param parameters - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getFeeHistory } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await getFeeHistory(client, {\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\nexport async function getFeeHistory(\n client: Client,\n {\n blockCount,\n blockNumber,\n blockTag = 'latest',\n rewardPercentiles,\n }: GetFeeHistoryParameters,\n): Promise {\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const feeHistory = await client.request(\n {\n method: 'eth_feeHistory',\n params: [\n numberToHex(blockCount),\n blockNumberHex || blockTag,\n rewardPercentiles,\n ],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n return formatFeeHistory(feeHistory)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RpcFeeHistory } from '../../types/rpc.js'\n\nexport type FormatFeeHistoryErrorType = ErrorType\n\nexport function formatFeeHistory(feeHistory: RpcFeeHistory): FeeHistory {\n return {\n baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),\n gasUsedRatio: feeHistory.gasUsedRatio,\n oldestBlock: BigInt(feeHistory.oldestBlock),\n reward: feeHistory.reward?.map((reward) =>\n reward.map((value) => BigInt(value)),\n ),\n }\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterLogsParameters<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<'event', abi, eventName, any, strict, fromBlock, toBlock>\n}\nexport type GetFilterLogsReturnType<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetFilterLogsErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterLogs(client, { filter })\n */\nexport async function getFilterLogs<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterLogsParameters,\n): Promise<\n GetFilterLogsReturnType\n> {\n const strict = filter.strict ?? false\n\n const logs = await filter.request({\n method: 'eth_getFilterLogs',\n params: [filter.id],\n })\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!filter.abi)\n return formattedLogs as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Address } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatProofErrorType,\n formatProof,\n} from '../../utils/formatters/proof.js'\n\nexport type GetProofParameters = {\n /** Account address. */\n address: Address\n /** Array of storage-keys that should be proofed and included. */\n storageKeys: Hash[]\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetProofReturnType = Proof\n\nexport type GetProofErrorType =\n | NumberToHexErrorType\n | FormatProofErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getProof } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getProof(client, {\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\nexport async function getProof(\n client: Client,\n {\n address,\n blockNumber,\n blockTag: blockTag_,\n storageKeys,\n }: GetProofParameters,\n): Promise {\n const blockTag = blockTag_ ?? 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n const proof = await client.request({\n method: 'eth_getProof',\n params: [address, storageKeys, blockNumberHex || blockTag],\n })\n\n return formatProof(proof)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../../types/authorization.js'\nimport { toHex } from '../encoding/toHex.js'\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.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 { chainId, nonce, ...signature } = authorization\n const contractAddress = authorization.address\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 {\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 { MaybePromise, OneOf } from '../../types/utils.js'\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../authorization/serializeAuthorizationList.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 {\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\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> = (\n transaction: OneOf,\n signature?: Signature | undefined,\n) => MaybePromise<\n SerializedTransactionReturnType<\n OneOf,\n _transactionType\n >\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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(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 ? numberToHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return numberToHex(1)\n\n return v === 27n ? '0x' : numberToHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\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 { chainId } = authorization\n const address = authorization.address\n if (!isAddress(address)) throw new InvalidAddressError({ address })\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 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 type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type GetAddressErrorType, getAddress } from '../address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../address/isAddressEqual.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n recoverAuthorizationAddress,\n} from './recoverAuthorizationAddress.js'\n\nexport type VerifyAuthorizationParameters =\n RecoverAuthorizationAddressParameters & {\n /** The address that signed the Authorization object. */\n address: Address\n }\n\nexport type VerifyAuthorizationReturnType = boolean\n\nexport type VerifyAuthorizationErrorType =\n | IsAddressEqualErrorType\n | GetAddressErrorType\n | RecoverAuthorizationAddressErrorType\n | ErrorType\n\n/**\n * Verify that an Authorization object was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/utilities/verifyAuthorization}\n *\n * @param parameters - {@link VerifyAuthorizationParameters}\n * @returns Whether or not the signature is valid. {@link VerifyAuthorizationReturnType}\n */\nexport async function verifyAuthorization({\n address,\n authorization,\n signature,\n}: VerifyAuthorizationParameters): Promise {\n return isAddressEqual(\n getAddress(address),\n await recoverAuthorizationAddress({\n authorization,\n signature,\n }),\n )\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n WalletConnectSessionSettlementError,\n type WalletConnectSessionSettlementErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | AtomicityNotSupportedErrorType\n | AtomicReadyWalletRejectedUpgradeErrorType\n | BundleTooLargeErrorType\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | DuplicateIdErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownBundleIdErrorType\n | UnknownRpcErrorType\n | UnsupportedChainIdErrorType\n | UnsupportedNonOptionalCapabilityErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WalletConnectSessionSettlementErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest Promise>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n methods,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n\n const { method } = args\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n\n const requestId = dedupe\n ? stringToHex(`${uid}.${stringify(args)}`)\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n\n // 5700\n case UnsupportedNonOptionalCapabilityError.code:\n throw new UnsupportedNonOptionalCapabilityError(err)\n // 5710\n case UnsupportedChainIdError.code:\n throw new UnsupportedChainIdError(err)\n // 5720\n case DuplicateIdError.code:\n throw new DuplicateIdError(err)\n // 5730\n case UnknownBundleIdError.code:\n throw new UnknownBundleIdError(err)\n // 5740\n case BundleTooLargeError.code:\n throw new BundleTooLargeError(err)\n // 5750\n case AtomicReadyWalletRejectedUpgradeError.code:\n throw new AtomicReadyWalletRejectedUpgradeError(err)\n // 5760\n case AtomicityNotSupportedError.code:\n throw new AtomicityNotSupportedError(err)\n\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n\n // WalletConnect: Session Settlement Failed\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n case WalletConnectSessionSettlementError.code:\n throw new WalletConnectSessionSettlementError(err)\n\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter, 10) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe(\n fn: () => Promise,\n { enabled = true, id }: WithDedupeOptions,\n): Promise {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport type DefineChainReturnType = Prettify<\n chain &\n (chain['extendSchema'] extends Record\n ? {\n extend: (\n extended: extended,\n ) => Assign\n }\n : {})\n>\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain,\n>(chain: chain): DefineChainReturnType, chain>> {\n const chainInstance = {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign, chain>\n\n function extend(base: typeof chainInstance) {\n type ExtendFn = (base: typeof chainInstance) => unknown\n return (fnOrExtended: ExtendFn | Record) => {\n const properties = (\n typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended\n ) as (typeof chainInstance)['extendSchema']\n const combined = { ...base, ...properties }\n return Object.assign(combined, { extend: extend(combined) })\n }\n }\n\n return Object.assign(chainInstance, {\n extend: extend(chainInstance),\n }) as never\n}\n\nexport function extendSchema>(): schema {\n return {} as schema\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n} from 'abitype'\nexport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nexport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from '../accounts/utils/publicKeyToAddress.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './abi/decodeAbiParameters.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n encodeDeployData,\n} from './abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n encodeErrorResult,\n} from './abi/encodeErrorResult.js'\nexport {\n type EncodeArgErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from './abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n encodeFunctionResult,\n} from './abi/encodeFunctionResult.js'\nexport { type EncodePackedErrorType, encodePacked } from './abi/encodePacked.js'\nexport {\n type FormatAbiItemErrorType,\n type FormatAbiParamErrorType,\n type FormatAbiParamsErrorType,\n formatAbiItem,\n formatAbiParams,\n} from './abi/formatAbiItem.js'\nexport {\n type FormatAbiItemWithArgsErrorType,\n formatAbiItemWithArgs,\n} from './abi/formatAbiItemWithArgs.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './abi/parseEventLogs.js'\nexport {\n type ChecksumAddressErrorType,\n getAddress,\n} from './address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './address/getContractAddress.js'\nexport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from './address/isAddressEqual.js'\nexport {\n type HashAuthorizationErrorType,\n type HashAuthorizationParameters,\n type HashAuthorizationReturnType,\n hashAuthorization,\n} from './authorization/hashAuthorization.js'\nexport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n type RecoverAuthorizationAddressReturnType,\n recoverAuthorizationAddress,\n} from './authorization/recoverAuthorizationAddress.js'\nexport {\n type SerializeAuthorizationListErrorType,\n type SerializeAuthorizationListReturnType,\n serializeAuthorizationList,\n} from './authorization/serializeAuthorizationList.js'\nexport {\n type VerifyAuthorizationErrorType,\n type VerifyAuthorizationParameters,\n type VerifyAuthorizationReturnType,\n verifyAuthorization,\n} from './authorization/verifyAuthorization.js'\nexport {\n buildRequest,\n type RequestErrorType,\n} from './buildRequest.js'\nexport {\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './chain/assertCurrentChain.js'\nexport { defineChain } from './chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n concat,\n concatBytes,\n concatHex,\n} from './data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n pad,\n padBytes,\n padHex,\n} from './data/pad.js'\nexport { type SizeErrorType, size } from './data/size.js'\nexport {\n type AssertEndOffsetErrorType,\n type AssertStartOffsetErrorType,\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n type SliceReturnType,\n slice,\n sliceBytes,\n sliceHex,\n} from './data/slice.js'\nexport { type TrimErrorType, type TrimReturnType, trim } from './data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBigInt as bytesToBigint,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n type FromBytesReturnType,\n fromBytes,\n} from './encoding/fromBytes.js'\nexport {\n type AssertSizeErrorType,\n type FromHexErrorType,\n type FromHexParameters,\n type FromHexReturnType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBigIntOpts,\n type HexToBoolErrorType,\n type HexToBoolOpts,\n type HexToNumberErrorType,\n type HexToNumberOpts,\n type HexToStringErrorType,\n type HexToStringOpts,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n fromRlp,\n} from './encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n type HexToRlpErrorType,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './encoding/toRlp.js'\nexport {\n type GetCallErrorReturnType,\n getCallError,\n} from './errors/getCallError.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './errors/getContractError.js'\nexport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from './errors/getEstimateGasError.js'\nexport {\n containsNodeError,\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './errors/getNodeError.js'\nexport {\n type GetTransactionErrorParameters,\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from './errors/getTransactionError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './formatters/block.js'\nexport { type ExtractErrorType, extract } from './formatters/extract.js'\nexport {\n type DefineFormatterErrorType,\n defineFormatter,\n} from './formatters/formatter.js'\nexport { type FormatLogErrorType, formatLog } from './formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n} from './formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from './formatters/transactionRequest.js'\nexport { getAction } from './getAction.js'\nexport { type IsHashErrorType, isHash } from './hash/isHash.js'\nexport { type Keccak256ErrorType, keccak256 } from './hash/keccak256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './hash/ripemd160.js'\nexport { type Sha256ErrorType, sha256 } from './hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './hash/toFunctionSignature.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './nonceManager.js'\nexport { arrayRegex, bytesRegex, integerRegex } from './regex.js'\nexport {\n getSocket,\n rpc,\n type WebSocketAsyncErrorType,\n type WebSocketAsyncOptions,\n type WebSocketAsyncReturnType,\n type WebSocketErrorType,\n type WebSocketOptions,\n type WebSocketReturnType,\n} from './rpc/compat.js'\nexport {\n getHttpRpcClient,\n type HttpRequestErrorType,\n type HttpRequestParameters,\n type HttpRequestReturnType,\n type HttpRpcClient,\n type HttpRpcClientOptions,\n} from './rpc/http.js'\nexport {\n type GetSocketParameters,\n type GetSocketRpcClientErrorType,\n type GetSocketRpcClientParameters,\n getSocketRpcClient,\n type Socket,\n type SocketRpcClient,\n socketClientCache,\n} from './rpc/socket.js'\nexport { getWebSocketRpcClient } from './rpc/webSocket.js'\nexport {\n type HashMessageErrorType,\n type HashMessageReturnType,\n hashMessage,\n} from './signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashStruct,\n hashTypedData,\n} from './signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './signature/isErc8010Signature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './signature/parseErc8010Signature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './signature/recoverPublicKey.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './signature/recoverTypedDataAddress.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './signature/serializeErc8010Signature.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n parseTransaction,\n} from './transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './transaction/serializeAccessList.js'\nexport {\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './typedData.js'\nexport { type FormatEtherErrorType, formatEther } from './unit/formatEther.js'\nexport { type FormatGweiErrorType, formatGwei } from './unit/formatGwei.js'\nexport { type FormatUnitsErrorType, formatUnits } from './unit/formatUnits.js'\nexport { type ParseEtherErrorType, parseEther } from './unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './unit/parseGwei.js'\nexport { type ParseUnitsErrorType, parseUnits } from './unit/parseUnits.js'\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport type { MaybePromise } from '../../types/utils.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Override for the fetch function used to make requests. */\n fetchFn?:\n | ((input: string | URL | Request, init?: RequestInit) => Promise)\n | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit | undefined\n /** A callback to handle the request. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Override for the fetch function used to make requests. */\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request(\n params: HttpRequestParameters,\n ): Promise>\n}\n\nexport function getHttpRpcClient(\n url_: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n const { url, headers: headers_url } = parseUrl(url_)\n\n return {\n async request(params) {\n const {\n body,\n fetchFn = options.fetchFn ?? fetch,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n ...headers_url,\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n const args = (await onRequest?.(request, init)) ?? { ...init, url }\n const response = await fetchFn(args.url ?? url, args)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n\n/** @internal */\nexport function parseUrl(url_: string) {\n try {\n const url = new URL(url_)\n\n const result = (() => {\n // Handle Basic authentication credentials\n if (url.username) {\n const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`\n url.username = ''\n url.password = ''\n\n return {\n url: url.toString(),\n headers: { Authorization: `Basic ${btoa(credentials)}` },\n }\n }\n\n return\n })()\n\n return { url: url.toString(), ...result }\n } catch {\n return { url: url_ }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout(\n fn: ({\n signal,\n }: {\n signal: AbortController['signal'] | null\n }) => Promise,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\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","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 bytesToHex,\n type StringToHexErrorType,\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","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from '../../types/typedData.js'\nimport type { UnionOmit } from '../../types/utils.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 getTypesForEIP712Domain,\n type ValidateTypedDataErrorType,\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 const typedData extends TypedData | Record = TypedData,\n>({\n domain,\n types,\n}: UnionOmit, 'primaryType'>) {\n return hashStruct({\n data: domain as Record,\n primaryType: 'EIP712Domain',\n types: types as Record,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>({\n data,\n primaryType,\n types,\n}: MessageDefinition) {\n const encoded = encodeData({\n data: data as Record,\n primaryType,\n types: types as Record,\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') return [{ type: 'bytes32' }, keccak256(value)]\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, 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_, 10) / 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_, 10))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_, 10),\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}: {\n domain?: TypedDataDomain | undefined\n}): 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 typeof domain?.chainId === 'bigint') && {\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: domain as never,\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","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 * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Authorization from '../core/Authorization.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport * as Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-8010 signature. */\nexport type Unwrapped = {\n /** Authorization signed by the delegatee. */\n authorization: Authorization.Authorization\n /** Data to initialize the delegation. */\n data?: Hex.Hex | undefined\n /** The original signature. */\n signature: Hex.Hex\n /** Address of the initializer. */\n to?: Address.Address | undefined\n}\n\n/** Wrapped ERC-8010 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-8010 wrapped signatures.\n */\nexport const magicBytes =\n '0x8010801080108010801080108010801080108010801080108010801080108010' as const\n\n/** Suffix ABI parameters for the ERC-8010 wrapped signature. */\nexport const suffixParameters = AbiParameters.from(\n '(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data',\n)\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * SignatureErc8010.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-8010 wrapped signature.\n * ```\n *\n * @param value - The value to assert.\n */\nexport function assert(value: Unwrapped | Wrapped) {\n if (typeof value === 'string') {\n if (Hex.slice(value, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(value)\n } else Signature.assert(value.authorization)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc8010.from('0x...') // [!code focus]\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc8010.from({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * })\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } }\n * ```\n *\n * @param value - Value to parse.\n * @returns Parsed value.\n */\nexport function from(value: Unwrapped | Wrapped): Unwrapped {\n if (typeof value === 'string') return unwrap(value)\n return value\n}\n\nexport declare namespace from {\n type ErrorType = unwrap.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Unwraps an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const { authorization, data, signature } = SignatureErc8010.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to unwrap.\n * @returns Unwrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const suffixLength = Hex.toNumber(Hex.slice(wrapped, -64, -32))\n const suffix = Hex.slice(wrapped, -suffixLength - 64, -64)\n const signature = Hex.slice(wrapped, 0, -suffixLength - 64)\n\n const [auth, to, data] = AbiParameters.decode(suffixParameters, suffix)\n\n const authorization = Authorization.from({\n address: auth.delegation,\n chainId: Number(auth.chainId),\n nonce: auth.nonce,\n yParity: auth.yParity,\n r: auth.r,\n s: auth.s,\n })\n\n return {\n authorization,\n signature,\n ...(data && data !== '0x' ? { data, to } : {}),\n }\n}\n\nexport declare namespace unwrap {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Wraps a signature into [ERC-8010 format](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md).\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc8010.wrap({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Values to wrap.\n * @returns Wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature } = value\n\n assert(value)\n\n const self = Secp256k1.recoverAddress({\n payload: Authorization.getSignPayload(value.authorization),\n signature: Signature.from(value.authorization),\n })\n\n const suffix = AbiParameters.encode(suffixParameters, [\n {\n ...value.authorization,\n delegation: value.authorization.address,\n chainId: BigInt(value.authorization.chainId),\n },\n value.to ?? self,\n data ?? '0x',\n ])\n const suffixLength = Hex.fromNumber(Hex.size(suffix), { size: 32 })\n return Hex.concat(signature, suffix, suffixLength, magicBytes)\n}\n\nexport declare namespace wrap {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const valid = SignatureErc8010.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param value - The value to validate.\n * @returns `true` if the value is valid, `false` otherwise.\n */\nexport function validate(value: Unwrapped | Wrapped): boolean {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-8010 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc8010.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-8010 wrapped signature.`)\n }\n}\n","import * as abitype from 'abitype'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiParameters.js'\nimport * as Cursor from './internal/cursor.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for ABI parameters. */\nexport type AbiParameters = readonly abitype.AbiParameter[]\n\n/** A parameter on an {@link ox#AbiParameters.AbiParameters}. */\nexport type Parameter = abitype.AbiParameter\n\n/** A packed ABI type. */\nexport type PackedAbiType =\n | abitype.SolidityAddress\n | abitype.SolidityBool\n | abitype.SolidityBytes\n | abitype.SolidityInt\n | abitype.SolidityString\n | abitype.SolidityArrayWithoutTuple\n\n/**\n * Decodes ABI-encoded data into its respective primitive values based on ABI Parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * You can pass **JSON ABI** Parameters:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' },\n * ],\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @param parameters - The set of ABI parameters to decode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param data - ABI encoded data.\n * @param options - Decoding options.\n * @returns Array of decoded values.\n */\nexport function decode<\n const parameters extends AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n>(\n parameters: parameters,\n data: Bytes.Bytes | Hex.Hex,\n options?: decode.Options,\n): decode.ReturnType\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n parameters: AbiParameters,\n data: Bytes.Bytes | Hex.Hex,\n options: {\n as?: 'Array' | 'Object' | undefined\n checksumAddress?: boolean | undefined\n } = {},\n): readonly unknown[] | Record {\n const { as = 'Array', checksumAddress = false } = options\n\n const bytes = typeof data === 'string' ? Bytes.fromHex(data) : data\n const cursor = Cursor.create(bytes)\n\n if (Bytes.size(bytes) === 0 && parameters.length > 0)\n throw new ZeroDataError()\n if (Bytes.size(bytes) && Bytes.size(bytes) < 32)\n throw new DataSizeTooSmallError({\n data: typeof data === 'string' ? data : Hex.fromBytes(data),\n parameters: parameters as readonly Parameter[],\n size: Bytes.size(bytes),\n })\n\n let consumed = 0\n const values: any = as === 'Array' ? [] : {}\n for (let i = 0; i < parameters.length; ++i) {\n const param = parameters[i] as Parameter\n cursor.setPosition(consumed)\n const [data, consumed_] = internal.decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: 0,\n })\n consumed += consumed_\n if (as === 'Array') values.push(data)\n else values[param.name ?? i] = data\n }\n return values\n}\n\nexport declare namespace decode {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Object' | 'Array' | undefined\n /**\n * Whether decoded addresses should be checksummed.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n\n type ReturnType<\n parameters extends AbiParameters = AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n > = parameters extends readonly []\n ? as extends 'Object'\n ? {}\n : []\n : as extends 'Object'\n ? internal.ToObject\n : internal.ToPrimitiveTypes\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | internal.decodeParameter.ErrorType\n | ZeroDataError\n | DataSizeTooSmallError\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes primitive values into ABI encoded data as per the [Application Binary Interface (ABI) Specification](https://docs.soliditylang.org/en/latest/abi-spec).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * Specify **JSON ABI** Parameters as schema:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * [\n * { type: 'string', name: 'name' },\n * { type: 'uint', name: 'age' },\n * { type: 'bool', name: 'isOwner' },\n * ],\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @param parameters - The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param values - The set of primitive values that correspond to the ABI types defined in `parameters`.\n * @returns ABI encoded data.\n */\nexport function encode<\n const parameters extends AbiParameters | readonly unknown[],\n>(\n parameters: parameters,\n values: parameters extends AbiParameters\n ? internal.ToPrimitiveTypes\n : never,\n options?: encode.Options,\n): Hex.Hex {\n const { checksumAddress = false } = options ?? {}\n\n if (parameters.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: parameters.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParameters = internal.prepareParameters({\n checksumAddress,\n parameters: parameters as readonly Parameter[],\n values: values as any,\n })\n const data = internal.encode(preparedParameters)\n if (data.length === 0) return '0x'\n return data\n}\n\nexport declare namespace encode {\n type ErrorType =\n | LengthMismatchError\n | internal.encode.ErrorType\n | internal.prepareParameters.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /**\n * Whether addresses should be checked against their checksum.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n}\n\n/**\n * Encodes an array of primitive values to a [packed ABI encoding](https://docs.soliditylang.org/en/latest/abi-spec.html#non-standard-packed-mode).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const encoded = AbiParameters.encodePacked(\n * ['address', 'string'],\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 'hello world'],\n * )\n * // @log: '0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64'\n * ```\n *\n * @param types - Set of ABI types to pack encode.\n * @param values - The set of primitive values that correspond to the ABI types defined in `types`.\n * @returns The encoded packed data.\n */\nexport function encodePacked<\n const packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: packedAbiTypes, values: encodePacked.Values): Hex.Hex {\n if (types.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: types.length as number,\n givenLength: values.length as number,\n })\n\n const data: Hex.Hex[] = []\n for (let i = 0; i < (types as unknown[]).length; i++) {\n const type = types[i]\n const value = values[i]\n data.push(encodePacked.encode(type, value))\n }\n return Hex.concat(...data)\n}\n\nexport namespace encodePacked {\n export type ErrorType =\n | Hex.concat.ErrorType\n | LengthMismatchError\n | Errors.GlobalErrorType\n\n export type Values<\n packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n > = {\n [key in keyof packedAbiTypes]: packedAbiTypes[key] extends abitype.AbiType\n ? abitype.AbiParameterToPrimitiveType<{ type: packedAbiTypes[key] }>\n : unknown\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc\n export function encode(\n type: packedAbiType,\n value: Values<[packedAbiType]>[0],\n isArray = false,\n ): Hex.Hex {\n if (type === 'address') {\n const address = value as Address.Address\n Address.assert(address)\n return Hex.padLeft(\n address.toLowerCase() as Hex.Hex,\n isArray ? 32 : 0,\n ) as Address.Address\n }\n if (type === 'string') return Hex.fromString(value as string)\n if (type === 'bytes') return value as Hex.Hex\n if (type === 'bool')\n return Hex.padLeft(Hex.fromBoolean(value as boolean), isArray ? 32 : 1)\n\n const intMatch = (type as string).match(Solidity.integerRegex)\n if (intMatch) {\n const [_type, baseType, bits = '256'] = intMatch\n const size = Number.parseInt(bits, 10) / 8\n return Hex.fromNumber(value as number, {\n size: isArray ? 32 : size,\n signed: baseType === 'int',\n })\n }\n\n const bytesMatch = (type as string).match(Solidity.bytesRegex)\n if (bytesMatch) {\n const [_type, size] = bytesMatch\n if (Number.parseInt(size!, 10) !== ((value as Hex.Hex).length - 2) / 2)\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size!, 10),\n value: value as Hex.Hex,\n })\n return Hex.padRight(value as Hex.Hex, isArray ? 32 : 0) as Hex.Hex\n }\n\n const arrayMatch = (type as string).match(Solidity.arrayRegex)\n if (arrayMatch && Array.isArray(value)) {\n const [_type, childType] = arrayMatch\n const data: Hex.Hex[] = []\n for (let i = 0; i < value.length; i++) {\n data.push(encode(childType, value[i], true))\n }\n if (data.length === 0) return '0x'\n return Hex.concat(...data)\n }\n\n throw new InvalidTypeError(type as string)\n }\n}\n\n/**\n * Formats {@link ox#AbiParameters.AbiParameters} into **Human Readable ABI Parameters**.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const formatted = AbiParameters.format([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param parameters - The ABI Parameters to format.\n * @returns The formatted ABI Parameters .\n */\nexport function format<\n const parameters extends readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n>(\n parameters:\n | parameters\n | readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n): abitype.FormatAbiParameters {\n return abitype.formatAbiParameters(parameters)\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses arbitrary **JSON ABI Parameters** or **Human Readable ABI Parameters** into typed {@link ox#AbiParameters.AbiParameters}.\n *\n * @example\n * ### JSON Parameters\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable Parameters\n *\n * Human Readable ABI Parameters can be parsed into a typed {@link ox#AbiParameters.AbiParameters}:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from('address spender, uint256 amount')\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'Foo foo, address bar',\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param parameters - The ABI Parameters to parse.\n * @returns The typed ABI Parameters.\n */\nexport function from<\n const parameters extends AbiParameters | string | readonly string[],\n>(\n parameters: parameters | AbiParameters | string | readonly string[],\n): from.ReturnType {\n if (Array.isArray(parameters) && typeof parameters[0] === 'string')\n return abitype.parseAbiParameters(parameters) as never\n if (typeof parameters === 'string')\n return abitype.parseAbiParameters(parameters) as never\n return parameters as never\n}\n\nexport declare namespace from {\n type ReturnType<\n parameters extends AbiParameters | string | readonly string[],\n > = parameters extends string\n ? abitype.ParseAbiParameters\n : parameters extends readonly string[]\n ? abitype.ParseAbiParameters\n : parameters\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Throws when the data size is too small for the given parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x010f')\n * // ↑ ❌ 2 bytes\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass a valid data size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class DataSizeTooSmallError extends Errors.BaseError {\n override readonly name = 'AbiParameters.DataSizeTooSmallError'\n constructor({\n data,\n parameters,\n size,\n }: { data: Hex.Hex; parameters: readonly Parameter[]; size: number }) {\n super(`Data size of ${size} bytes is too small for given parameters.`, {\n metaMessages: [\n `Params: (${abitype.formatAbiParameters(parameters as readonly [Parameter])})`,\n `Data: ${data} (${size} bytes)`,\n ],\n })\n }\n}\n\n/**\n * Throws when zero data is provided, but data is expected.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x')\n * // ↑ ❌ zero data\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass valid data.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class ZeroDataError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\n/**\n * The length of the array value does not match the length specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('uint256[3]'), [[69n, 420n]])\n * // ↑ expected: 3 ↑ ❌ length: 2\n * // @error: AbiParameters.ArrayLengthMismatchError: ABI encoding array length mismatch\n * // @error: for type `uint256[3]`. Expected: `3`. Given: `2`.\n * ```\n *\n * ### Solution\n *\n * Pass an array of the correct length.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [[69n, 420n, 69n]])\n * // ↑ ✅ length: 3\n * ```\n */\nexport class ArrayLengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n `Array length mismatch for type \\`${type}\\`. Expected: \\`${expectedLength}\\`. Given: \\`${givenLength}\\`.`,\n )\n }\n}\n\n/**\n * The size of the bytes value does not match the size specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('bytes8'), [['0xdeadbeefdeadbeefdeadbeef']])\n * // ↑ expected: 8 bytes ↑ ❌ size: 12 bytes\n * // @error: BytesSizeMismatchError: Size of bytes \"0xdeadbeefdeadbeefdeadbeef\"\n * // @error: (bytes12) does not match expected size (bytes8).\n * ```\n *\n * ### Solution\n *\n * Pass a bytes value of the correct size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['bytes8']), ['0xdeadbeefdeadbeef'])\n * // ↑ ✅ size: 8 bytes\n * ```\n */\nexport class BytesSizeMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.BytesSizeMismatchError'\n constructor({\n expectedSize,\n value,\n }: { expectedSize: number; value: Hex.Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${Hex.size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\n/**\n * The length of the values to encode does not match the length of the ABI parameters.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['string', 'uint256']), ['hello'])\n * // @error: LengthMismatchError: ABI encoding params/values length mismatch.\n * // @error: Expected length (params): 2\n * // @error: Given length (values): 1\n * ```\n *\n * ### Solution\n *\n * Pass the correct number of values to encode.\n *\n * ### Solution\n *\n * Pass a [valid ABI type](https://docs.soliditylang.org/en/develop/abi-spec.html#types).\n */\nexport class LengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.LengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding parameters/values length mismatch.',\n `Expected length (parameters): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * The value provided is not a valid array as specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [69])\n * ```\n *\n * ### Solution\n *\n * Pass an array value.\n */\nexport class InvalidArrayError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidArrayError'\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is not a valid array.`)\n }\n}\n\n/**\n * Throws when the ABI parameter type is invalid.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'lol' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ❌ invalid type\n * // @error: AbiParameters.InvalidTypeError: Type `lol` is not a valid ABI Type.\n * ```\n */\nexport class InvalidTypeError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidTypeError'\n constructor(type: string) {\n super(`Type \\`${type}\\` is not a valid ABI Type.`)\n }\n}\n","import type { Address as abitype_Address } from 'abitype'\nimport * as Bytes from './Bytes.js'\nimport * as Caches from './Caches.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as PublicKey from './PublicKey.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** Root type for Address. */\nexport type Address = abitype_Address\n\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(\n value: string,\n options: assert.Options = {},\n): asserts value is Address {\n const { strict = true } = options\n\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n })\n\n if (strict) {\n if (value.toLowerCase() === value) return\n if (checksum(value as Address) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n })\n }\n}\n\nexport declare namespace assert {\n type Options = {\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\n type ErrorType = InvalidAddressError | Errors.GlobalErrorType\n}\n\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address: string): Address {\n if (Caches.checksum.has(address)) return Caches.checksum.get(address)!\n\n assert(address, { strict: false })\n\n const hexAddress = address.substring(2).toLowerCase()\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' })\n\n const characters = hexAddress.split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1]! >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i]!.toUpperCase()\n }\n if ((hash[i >> 1]! & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1]!.toUpperCase()\n }\n }\n\n const result = `0x${characters.join('')}` as const\n Caches.checksum.set(address, result)\n return result\n}\n\nexport declare namespace checksum {\n type ErrorType =\n | assert.ErrorType\n | Hash.keccak256.ErrorType\n | Bytes.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a stringified address to a typed (optionally checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: true\n * })\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address: string, options: from.Options = {}): Address {\n const { checksum: checksumVal = false } = options\n assert(address)\n if (checksumVal) return checksum(address)\n return address as Address\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | assert.ErrorType\n | checksum.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(\n publicKey: PublicKey.PublicKey,\n options: fromPublicKey.Options = {},\n): Address {\n const address = Hash.keccak256(\n `0x${PublicKey.toHex(publicKey).slice(4)}`,\n ).substring(26)\n return from(`0x${address}`, options)\n}\n\nexport declare namespace fromPublicKey {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA: Address, addressB: Address): boolean {\n assert(addressA, { strict: false })\n assert(addressB, { strict: false })\n return addressA.toLowerCase() === addressB.toLowerCase()\n}\n\nexport declare namespace isEqual {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(\n address: string,\n options: validate.Options = {},\n): address is Address {\n const { strict = true } = options ?? {}\n try {\n assert(address, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\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}\n\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError<\n cause extends InvalidInputError | InvalidChecksumError =\n | InvalidInputError\n | InvalidChecksumError,\n> extends Errors.BaseError {\n override readonly name = 'Address.InvalidAddressError'\n\n constructor({ address, cause }: { address: string; cause: cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n override readonly name = 'Address.InvalidInputError'\n\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.')\n }\n}\n\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n override readonly name = 'Address.InvalidChecksumError'\n\n constructor() {\n super('Address does not match its checksum counterpart.')\n }\n}\n","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see 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 * as Address from './Address.js'\nimport { LruMap } from './internal/lru.js'\n\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap(8192),\n}\n\nexport const checksum = caches.checksum\n\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches)) cache.clear()\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3'\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: keccak256.Options = {},\n): keccak256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_keccak256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace keccak256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [HMAC-SHA256](https://en.wikipedia.org/wiki/HMAC) of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `hmac` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef')\n * // @log: '0x...'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param key - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} key.\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns HMAC-SHA256 hash.\n */\nexport function hmac256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n key: Hex.Hex | Bytes.Bytes,\n value: value | Hex.Hex | Bytes.Bytes,\n options: hmac256.Options = {},\n): hmac256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = hmac(noble_sha256, Bytes.from(key), Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace hmac256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: ripemd160.Options = {},\n): ripemd160.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_ripemd160(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace ripemd160 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: sha256.Options = {},\n): sha256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_sha256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace sha256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value: string): value is Hex.Hex {\n return Hex.validate(value) && Hex.size(value) === 32\n}\n\nexport declare namespace validate {\n type ErrorType =\n | Hex.validate.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial } from './internal/types.js'\nimport * as Json from './Json.js'\n\n/** Root type for an ECDSA Public Key. */\nexport type PublicKey<\n compressed extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n compressed extends true\n ? {\n prefix: numberType\n x: bigintType\n y?: undefined\n }\n : {\n prefix: numberType\n x: bigintType\n y: bigintType\n }\n>\n\n/**\n * Asserts that a {@link ox#PublicKey.PublicKey} is valid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @error: PublicKey.InvalidError: Value \\`{\"y\":\"1\"}\\` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function assert(\n publicKey: ExactPartial,\n options: assert.Options = {},\n): asserts publicKey is PublicKey {\n const { compressed } = options\n const { prefix, x, y } = publicKey\n\n // Uncompressed\n if (\n compressed === false ||\n (typeof x === 'bigint' && typeof y === 'bigint')\n ) {\n if (prefix !== 4)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidUncompressedPrefixError(),\n })\n return\n }\n\n // Compressed\n if (\n compressed === true ||\n (typeof x === 'bigint' && typeof y === 'undefined')\n ) {\n if (prefix !== 3 && prefix !== 2)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidCompressedPrefixError(),\n })\n return\n }\n\n // Unknown/invalid\n throw new InvalidError({ publicKey })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = InvalidError | InvalidPrefixError | Errors.GlobalErrorType\n}\n\n/**\n * Compresses a {@link ox#PublicKey.PublicKey}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const compressed = PublicKey.compress(publicKey) // [!code focus]\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The public key to compress.\n * @returns The compressed public key.\n */\nexport function compress(publicKey: PublicKey): PublicKey {\n const { x, y } = publicKey\n return {\n prefix: y % 2n === 0n ? 2 : 3,\n x,\n }\n}\n\nexport declare namespace compress {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#PublicKey.PublicKey} object from a {@link ox#PublicKey.PublicKey}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from('0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param value - The public key value to instantiate.\n * @returns The instantiated {@link ox#PublicKey.PublicKey}.\n */\nexport function from<\n const publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes,\n>(value: from.Value): from.ReturnType {\n const publicKey = (() => {\n if (Hex.validate(value)) return fromHex(value)\n if (Bytes.validate(value)) return fromBytes(value)\n\n const { prefix, x, y } = value\n if (typeof x === 'bigint' && typeof y === 'bigint')\n return { prefix: prefix ?? 0x04, x, y }\n return { prefix, x }\n })()\n\n assert(publicKey)\n\n return publicKey as never\n}\n\n/** @internal */\ntype CompressedPublicKey = PublicKey\n\n/** @internal */\ntype UncompressedPublicKey = Omit, 'prefix'> & {\n prefix?: PublicKey['prefix'] | undefined\n}\n\nexport declare namespace from {\n type Value<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey | CompressedPublicKey | UncompressedPublicKey\n\n type ReturnType<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey extends CompressedPublicKey | UncompressedPublicKey\n ? publicKey extends UncompressedPublicKey\n ? Compute\n : publicKey\n : PublicKey\n\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromBytes(publicKey: Bytes.Bytes): PublicKey {\n return fromHex(Hex.fromBytes(publicKey))\n}\n\nexport declare namespace fromBytes {\n type ErrorType =\n | fromHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### Deserializing a Compressed Public Key\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75')\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromHex(publicKey: Hex.Hex): PublicKey {\n if (\n publicKey.length !== 132 &&\n publicKey.length !== 130 &&\n publicKey.length !== 68\n )\n throw new InvalidSerializedSizeError({ publicKey })\n\n if (publicKey.length === 130) {\n const x = BigInt(Hex.slice(publicKey, 0, 32))\n const y = BigInt(Hex.slice(publicKey, 32, 64))\n return {\n prefix: 4,\n x,\n y,\n } as never\n }\n\n if (publicKey.length === 132) {\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n const y = BigInt(Hex.slice(publicKey, 33, 65))\n return {\n prefix,\n x,\n y,\n } as never\n }\n\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n return {\n prefix,\n x,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType = Hex.slice.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const bytes = PublicKey.toBytes(publicKey) // [!code focus]\n * // @log: Uint8Array [128, 3, 131, ...]\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toBytes(\n publicKey: PublicKey,\n options: toBytes.Options = {},\n): Bytes.Bytes {\n return Bytes.fromHex(toHex(publicKey, options))\n}\n\nexport declare namespace toBytes {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const hex = PublicKey.toHex(publicKey) // [!code focus]\n * // @log: '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toHex(\n publicKey: PublicKey,\n options: toHex.Options = {},\n): Hex.Hex {\n assert(publicKey)\n\n const { prefix, x, y } = publicKey\n const { includePrefix = true } = options\n\n const publicKey_ = Hex.concat(\n includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x',\n Hex.fromNumber(x, { size: 32 }),\n // If the public key is not compressed, add the y coordinate.\n typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x',\n )\n\n return publicKey_\n}\n\nexport declare namespace toHex {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Validates a {@link ox#PublicKey.PublicKey}. Returns `true` if valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const valid = PublicKey.validate({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @log: false\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function validate(\n publicKey: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(publicKey, options)\n return true\n } catch (_error) {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a public key is invalid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({ y: 1n })\n * // @error: PublicKey.InvalidError: Value `{\"y\":1n}` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n */\nexport class InvalidError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidError'\n\n constructor({ publicKey }: { publicKey: unknown }) {\n super(`Value \\`${Json.stringify(publicKey)}\\` is not a valid public key.`, {\n metaMessages: [\n 'Public key must contain:',\n '- an `x` and `prefix` value (compressed)',\n '- an `x`, `y`, and `prefix` value (uncompressed)',\n ],\n })\n }\n}\n\n/** Thrown when a public key has an invalid prefix. */\nexport class InvalidPrefixError<\n cause extends InvalidCompressedPrefixError | InvalidUncompressedPrefixError =\n | InvalidCompressedPrefixError\n | InvalidUncompressedPrefixError,\n> extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidPrefixError'\n\n constructor({ prefix, cause }: { prefix: number | undefined; cause: cause }) {\n super(`Prefix \"${prefix}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when the public key has an invalid prefix for a compressed public key. */\nexport class InvalidCompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidCompressedPrefixError'\n\n constructor() {\n super('Prefix must be 2 or 3 for compressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid prefix for an uncompressed public key. */\nexport class InvalidUncompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidUncompressedPrefixError'\n\n constructor() {\n super('Prefix must be 4 for uncompressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid serialized size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidSerializedSizeError'\n\n constructor({ publicKey }: { publicKey: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${publicKey}\\` is an invalid public key size.`, {\n metaMessages: [\n 'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',\n `Received ${Hex.size(Hex.from(publicKey))} bytes.`,\n ],\n })\n }\n}\n","import type {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\n} from 'abitype'\nimport * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Bytes from '../Bytes.js'\nimport * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\nimport { integerRegex } from '../Solidity.js'\nimport type * as Cursor from './cursor.js'\nimport type { Compute, IsNarrowable, UnionToIntersection } from './types.js'\n\n/** @internal */\nexport type ParameterToPrimitiveType<\n abiParameter extends AbiParameter | { name: string; type: unknown },\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParameterToPrimitiveType\n\n/** @internal */\nexport type PreparedParameter = { dynamic: boolean; encoded: Hex.Hex }\n\n/** @internal */\nexport type ToObject<\n parameters extends readonly AbiParameter[],\n kind extends AbiParameterKind = AbiParameterKind,\n> = IsNarrowable extends true\n ? Compute<\n UnionToIntersection<\n {\n [index in keyof parameters]: parameters[index] extends {\n name: infer name extends string\n }\n ? {\n [key in name]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n : {\n [key in index]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n }[number]\n >\n >\n : unknown\n\n/** @internal */\nexport type ToPrimitiveTypes<\n abiParameters extends readonly AbiParameter[],\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParametersToPrimitiveTypes\n\n/** @internal */\nexport type Tuple = ParameterToPrimitiveType\n\n/** @internal */\nexport function decodeParameter(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(\n cursor,\n { ...param, type },\n { checksumAddress, length, staticPosition },\n )\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, {\n checksumAddress,\n staticPosition,\n })\n if (param.type === 'address')\n return decodeAddress(cursor, { checksum: checksumAddress })\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 AbiParameters.InvalidTypeError(param.type)\n}\n\nexport declare namespace decodeParameter {\n type ErrorType =\n | decodeArray.ErrorType\n | decodeTuple.ErrorType\n | decodeAddress.ErrorType\n | decodeBool.ErrorType\n | decodeBytes.ErrorType\n | decodeNumber.ErrorType\n | decodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\n/** @internal */\nexport function decodeAddress(\n cursor: Cursor.Cursor,\n options: { checksum?: boolean | undefined } = {},\n) {\n const { checksum = false } = options\n const value = cursor.readBytes(32)\n const wrap = (address: Hex.Hex) =>\n checksum ? Address.checksum(address) : address\n return [wrap(Hex.fromBytes(Bytes.slice(value, -20))), 32]\n}\n\nexport declare namespace decodeAddress {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeArray(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n staticPosition: number\n },\n) {\n const { checksumAddress, length, staticPosition } = options\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 = Bytes.toNumber(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 = Bytes.toNumber(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 checksumAddress,\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeArray {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBool(cursor: Cursor.Cursor) {\n return [Bytes.toBoolean(cursor.readBytes(32), { size: 32 }), 32]\n}\n\nexport declare namespace decodeBool {\n type ErrorType = Bytes.toBoolean.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBytes(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\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 = Bytes.toNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = Bytes.toNumber(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 [Hex.fromBytes(data), 32]\n }\n\n const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))\n return [value, 32]\n}\n\nexport declare namespace decodeBytes {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeNumber(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10)\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? Bytes.toBigInt(value, { signed })\n : Bytes.toNumber(value, { signed }),\n 32,\n ]\n}\n\nexport declare namespace decodeNumber {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport type TupleAbiParameter = AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n}\n\n/** @internal */\nexport function decodeTuple(\n cursor: Cursor.Cursor,\n param: TupleAbiParameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeTuple {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeString(\n cursor: Cursor.Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = Bytes.toNumber(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 = Bytes.toNumber(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 = Bytes.toString(Bytes.trimLeft(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\nexport declare namespace decodeString {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toString.ErrorType\n | Bytes.trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameters<\n const parameters extends AbiParameters.AbiParameters,\n>({\n checksumAddress,\n parameters,\n values,\n}: {\n checksumAddress?: boolean | undefined\n parameters: parameters\n values: parameters extends AbiParameters.AbiParameters\n ? ToPrimitiveTypes\n : never\n}) {\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameters.length; i++) {\n preparedParameters.push(\n prepareParameter({\n checksumAddress,\n parameter: parameters[i]!,\n value: values[i],\n }),\n )\n }\n return preparedParameters\n}\n\n/** @internal */\nexport declare namespace prepareParameters {\n type ErrorType = prepareParameter.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameter<\n const parameter extends AbiParameters.Parameter,\n>({\n checksumAddress = false,\n parameter: parameter_,\n value,\n}: {\n parameter: parameter\n value: parameter extends AbiParameters.Parameter\n ? ParameterToPrimitiveType\n : never\n checksumAddress?: boolean | undefined\n}): PreparedParameter {\n const parameter = parameter_ as AbiParameters.Parameter\n\n const arrayComponents = getArrayComponents(parameter.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, {\n checksumAddress,\n length,\n parameter: {\n ...parameter,\n type,\n },\n })\n }\n if (parameter.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n checksumAddress,\n parameter: parameter as TupleAbiParameter,\n })\n }\n if (parameter.type === 'address') {\n return encodeAddress(value as unknown as Hex.Hex, {\n checksum: checksumAddress,\n })\n }\n if (parameter.type === 'bool') {\n return encodeBoolean(value as unknown as boolean)\n }\n if (parameter.type.startsWith('uint') || parameter.type.startsWith('int')) {\n const signed = parameter.type.startsWith('int')\n const [, , size = '256'] = integerRegex.exec(parameter.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\n }\n if (parameter.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex.Hex, { type: parameter.type })\n }\n if (parameter.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new AbiParameters.InvalidTypeError(parameter.type)\n}\n\n/** @internal */\nexport declare namespace prepareParameter {\n type ErrorType =\n | encodeArray.ErrorType\n | encodeTuple.ErrorType\n | encodeAddress.ErrorType\n | encodeBoolean.ErrorType\n | encodeBytes.ErrorType\n | encodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encode(preparedParameters: PreparedParameter[]): Hex.Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) staticSize += 32\n else staticSize += Hex.size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParameters: Hex.Hex[] = []\n const dynamicParameters: Hex.Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) {\n staticParameters.push(\n Hex.fromNumber(staticSize + dynamicSize, { size: 32 }),\n )\n dynamicParameters.push(encoded)\n dynamicSize += Hex.size(encoded)\n } else {\n staticParameters.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return Hex.concat(...staticParameters, ...dynamicParameters)\n}\n\n/** @internal */\nexport declare namespace encode {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeAddress(\n value: Hex.Hex,\n options: { checksum: boolean },\n): PreparedParameter {\n const { checksum = false } = options\n Address.assert(value, { strict: checksum })\n return {\n dynamic: false,\n encoded: Hex.padLeft(value.toLowerCase() as Hex.Hex),\n }\n}\n\n/** @internal */\nexport declare namespace encodeAddress {\n type ErrorType =\n | Address.assert.ErrorType\n | Hex.padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeArray(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, length, parameter } = options\n\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new AbiParameters.InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiParameters.ArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${parameter.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter,\n value: value[i],\n })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParameters.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encode(preparedParameters)\n if (dynamic) {\n const length = Hex.fromNumber(preparedParameters.length, { size: 32 })\n return {\n dynamic: true,\n encoded:\n preparedParameters.length > 0 ? Hex.concat(length, data) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeArray {\n type ErrorType =\n | AbiParameters.InvalidArrayError\n | AbiParameters.ArrayLengthMismatchError\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBytes(\n value: Hex.Hex,\n { type }: { type: string },\n): PreparedParameter {\n const [, parametersize] = type.split('bytes')\n const bytesSize = Hex.size(value)\n if (!parametersize) {\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_ = Hex.padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32)\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padLeft(Hex.fromNumber(bytesSize, { size: 32 })),\n value_,\n ),\n }\n }\n if (bytesSize !== Number.parseInt(parametersize, 10))\n throw new AbiParameters.BytesSizeMismatchError({\n expectedSize: Number.parseInt(parametersize, 10),\n value,\n })\n return { dynamic: false, encoded: Hex.padRight(value) }\n}\n\n/** @internal */\nexport declare namespace encodeBytes {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.padRight.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBoolean(value: boolean): PreparedParameter {\n if (typeof value !== 'boolean')\n throw new Errors.BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: Hex.padLeft(Hex.fromBoolean(value)) }\n}\n\n/** @internal */\nexport declare namespace encodeBoolean {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.fromBoolean.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeNumber(\n value: number,\n { signed, size }: { signed: boolean; size: number },\n): PreparedParameter {\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 Hex.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: Hex.fromNumber(value, {\n size: 32,\n signed,\n }),\n }\n}\n\n/** @internal */\nexport declare namespace encodeNumber {\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeString(value: string): PreparedParameter {\n const hexValue = Hex.fromString(value)\n const partsLength = Math.ceil(Hex.size(hexValue) / 32)\n const parts: Hex.Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(Hex.padRight(Hex.slice(hexValue, i * 32, (i + 1) * 32)))\n }\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padRight(Hex.fromNumber(Hex.size(hexValue), { size: 32 })),\n ...parts,\n ),\n }\n}\n\n/** @internal */\nexport declare namespace encodeString {\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Hex.padRight.ErrorType\n | Hex.slice.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeTuple<\n const parameter extends AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n },\n>(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, parameter } = options\n\n let dynamic = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameter.components.length; i++) {\n const param_ = parameter.components[i]!\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParameters.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encode(preparedParameters)\n : Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeTuple {\n type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\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\n/** @internal */\nexport function hasDynamicChild(param: AbiParameters.Parameter) {\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({\n ...param,\n type: arrayComponents[1],\n } as AbiParameters.Parameter)\n )\n return true\n\n return false\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\nexport 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 type { Bytes } from '../Bytes.js'\nimport * as Errors from '../Errors.js'\n\n/** @internal */\nexport type Cursor = {\n bytes: Bytes\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): Bytes[number]\n inspectBytes(length: number, position?: number): Bytes\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: Bytes[number]): void\n pushBytes(bytes: Bytes): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): Bytes[number]\n readBytes(length: number, size?: number): Bytes\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\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: Bytes[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: Bytes) {\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\n/** @internal */\nexport function create(\n bytes: Bytes,\n { recursiveReadLimit = 8_192 }: create.Config = {},\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\n/** @internal */\nexport declare namespace create {\n type Config = { recursiveReadLimit?: number | undefined }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport class NegativeOffsetError extends Errors.BaseError {\n override readonly name = 'Cursor.NegativeOffsetError'\n\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`)\n }\n}\n\n/** @internal */\nexport class PositionOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Cursor.PositionOutOfBoundsError'\n\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n )\n }\n}\n\n/** @internal */\nexport class RecursiveReadLimitExceededError extends Errors.BaseError {\n override readonly name = 'Cursor.RecursiveReadLimitExceededError'\n\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n )\n }\n}\n","import type * as Address from './Address.js'\nimport type * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, Mutable, Undefined } from './internal/types.js'\nimport * as Rlp from './Rlp.js'\nimport * as Signature from './Signature.js'\n\n/** Root type for an EIP-7702 Authorization. */\nexport type Authorization<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** Address of the contract to set as code for the Authority. */\n address: Address.Address\n /** Chain ID to authorize. */\n chainId: numberType\n /** Nonce of the Authority to authorize. */\n nonce: bigintType\n } & (signed extends true\n ? Signature.Signature\n : Undefined)\n>\n\n/** RPC representation of an {@link ox#Authorization.Authorization}. */\nexport type Rpc = Authorization\n\n/** List of {@link ox#Authorization.Authorization}. */\nexport type List<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute[]>\n\n/** RPC representation of an {@link ox#Authorization.List}. */\nexport type ListRpc = List\n\n/** Signed representation of a list of {@link ox#Authorization.Authorization}. */\nexport type ListSigned = List<\n true,\n bigintType,\n numberType\n>\n\n/** Signed representation of an {@link ox#Authorization.Authorization}. */\nexport type Signed = Authorization<\n true,\n bigintType,\n numberType\n>\n\n/** Tuple representation of an {@link ox#Authorization.Authorization}. */\nexport type Tuple = signed extends true\n ? readonly [\n chainId: Hex.Hex,\n address: Hex.Hex,\n nonce: Hex.Hex,\n yParity: Hex.Hex,\n r: Hex.Hex,\n s: Hex.Hex,\n ]\n : readonly [chainId: Hex.Hex, address: Hex.Hex, nonce: Hex.Hex]\n\n/** Tuple representation of a signed {@link ox#Authorization.Authorization}. */\nexport type TupleSigned = Tuple\n\n/** Tuple representation of a list of {@link ox#Authorization.Authorization}. */\nexport type TupleList =\n readonly Tuple[]\n\n/** Tuple representation of a list of signed {@link ox#Authorization.Authorization}. */\nexport type TupleListSigned = TupleList\n\n/**\n * Converts an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization object into a typed {@link ox#Authorization.Authorization}.\n *\n * @example\n * An Authorization can be instantiated from an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * A {@link ox#Signature.Signature} can be attached with the `signature` option. The example below demonstrates signing\n * an Authorization with {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: Authorization.getSignPayload(authorization),\n * privateKey: '0x...',\n * })\n *\n * const authorization_signed = Authorization.from(authorization, { signature }) // [!code focus]\n * ```\n *\n * @param authorization - An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n * @param options - Authorization options.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function from<\n const authorization extends Authorization | Rpc,\n const signature extends Signature.Signature | undefined = undefined,\n>(\n authorization: authorization | Authorization,\n options: from.Options = {},\n): from.ReturnType {\n if (typeof authorization.chainId === 'string')\n return fromRpc(authorization) as never\n return { ...authorization, ...options.signature } as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = {\n /** The {@link ox#Signature.Signature} to attach to the Authorization. */\n signature?: signature | Signature.Signature | undefined\n }\n\n type ReturnType<\n authorization extends Authorization | Rpc = Authorization,\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends Signature.Signature ? Readonly : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Rpc} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param authorization - The RPC-formatted Authorization.\n * @returns A signed {@link ox#Authorization.Authorization}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)!\n\n return {\n address,\n chainId: Number(chainId),\n nonce: BigInt(nonce),\n ...signature,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.ListRpc} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * }])\n * ```\n *\n * @param authorizationList - The RPC-formatted Authorization list.\n * @returns A signed {@link ox#Authorization.List}.\n */\nexport function fromRpcList(authorizationList: ListRpc): ListSigned {\n return authorizationList.map(fromRpc)\n}\n\nexport declare namespace fromRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Tuple} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3'\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: }\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3',\n * '0x1',\n * '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90',\n * '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: }\n * ```\n *\n * @param tuple - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function fromTuple(\n tuple: tuple,\n): fromTuple.ReturnType {\n const [chainId, address, nonce, yParity, r, s] = tuple\n let args = {\n address,\n chainId: chainId === '0x' ? 0 : Number(chainId),\n nonce: nonce === '0x' ? 0n : BigInt(nonce),\n }\n if (yParity && r && s)\n args = { ...args, ...Signature.fromTuple([yParity, r, s]) }\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType = Compute<\n Authorization ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.TupleList} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param tupleList - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n * @returns An {@link ox#Authorization.List}.\n */\nexport function fromTupleList(\n tupleList: tupleList,\n): fromTupleList.ReturnType {\n const list: Mutable = []\n for (const tuple of tupleList) list.push(fromTuple(tuple))\n return list as never\n}\n\nexport declare namespace fromTupleList {\n type ReturnType = Compute<\n TupleList ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * The example below demonstrates computing the sign payload for an {@link ox#Authorization.Authorization}. This payload\n * can then be passed to signing functions like {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = Authorization.getSignPayload(authorization) // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload,\n * privateKey: '0x...',\n * })\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: Authorization): Hex.Hex {\n return hash(authorization, { presign: true })\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const hash = Authorization.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The hash.\n */\nexport function hash(\n authorization: Authorization,\n options: hash.Options = {},\n): Hex.Hex {\n const { presign } = options\n return Hash.keccak256(\n Hex.concat(\n '0x05',\n Rlp.fromHex(\n toTuple(\n presign\n ? {\n address: authorization.address,\n chainId: authorization.chainId,\n nonce: authorization.nonce,\n }\n : authorization,\n ),\n ),\n ),\n )\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /** Whether to hash this authorization for signing. @default false */\n presign?: boolean | undefined\n }\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * })\n * ```\n *\n * @param authorization - An Authorization.\n * @returns An RPC-formatted Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, nonce, ...signature } = authorization\n\n return {\n address,\n chainId: Hex.fromNumber(chainId),\n nonce: Hex.fromNumber(nonce),\n ...Signature.toRpc(signature),\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.ListRpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * }])\n * ```\n *\n * @param authorizationList - An Authorization List.\n * @returns An RPC-formatted Authorization List.\n */\nexport function toRpcList(authorizationList: ListSigned): ListRpc {\n return authorizationList.map(toRpc)\n}\n\nexport declare namespace toRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const tuple = Authorization.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n */\nexport function toTuple(\n authorization: authorization,\n): toTuple.ReturnType {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)\n return [\n chainId ? Hex.fromNumber(chainId) : '0x',\n address,\n nonce ? Hex.fromNumber(nonce) : '0x',\n ...(signature ? Signature.toTuple(signature) : []),\n ] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType =\n Compute>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.TupleList}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization_1 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * const authorization_2 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 3,\n * nonce: 20n,\n * })\n *\n * const tuple = Authorization.toTupleList([authorization_1, authorization_2]) // [!code focus]\n * // @log: [\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ],\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param list - An {@link ox#Authorization.List}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n */\nexport function toTupleList<\n const list extends\n | readonly Authorization[]\n | readonly Authorization[],\n>(list?: list | undefined): toTupleList.ReturnType {\n if (!list || list.length === 0) return []\n\n const tupleList: Mutable = []\n for (const authorization of list) tupleList.push(toTuple(authorization))\n\n return tupleList as never\n}\n\nexport declare namespace toTupleList {\n type ReturnType<\n list extends\n | readonly Authorization[]\n | readonly Authorization[],\n > = Compute<\n TupleList[] ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Cursor from './internal/cursor.js'\nimport type { ExactPartial, RecursiveArray } from './internal/types.js'\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toBytes('0x8b68656c6c6f20776f726c64')\n * // Uint8Array([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Bytes.Bytes} value.\n */\nexport function toBytes(\n value: Bytes.Bytes | Hex.Hex,\n): RecursiveArray {\n return to(value, 'Bytes')\n}\n\nexport declare namespace toBytes {\n type ErrorType = to.ErrorType\n}\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toHex('0x8b68656c6c6f20776f726c64')\n * // 0x68656c6c6f20776f726c64\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes.Bytes | Hex.Hex): RecursiveArray {\n return to(value, 'Hex')\n}\n\nexport declare namespace toHex {\n type ErrorType = to.ErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\n/////////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport function to<\n value extends Bytes.Bytes | Hex.Hex,\n to extends 'Hex' | 'Bytes',\n>(value: value, to: to | 'Hex' | 'Bytes'): to.ReturnType {\n const to_ = to ?? (typeof value === 'string' ? 'Hex' : 'Bytes')\n\n const bytes = (() => {\n if (typeof value === 'string') {\n if (value.length > 3 && value.length % 2 !== 0)\n throw new Hex.InvalidLengthError(value)\n return Bytes.fromHex(value)\n }\n return value as Bytes.Bytes\n })()\n\n const cursor = Cursor.create(bytes, {\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n })\n const result = decodeRlpCursor(cursor, to_)\n\n return result as to.ReturnType\n}\n\n/** @internal */\nexport declare namespace to {\n type ReturnType =\n | (to extends 'Bytes' ? RecursiveArray : never)\n | (to extends 'Hex' ? RecursiveArray : never)\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | decodeRlpCursor.ErrorType\n | Cursor.create.ErrorType\n | Hex.InvalidLengthError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\n\n/** @internal */\nexport function decodeRlpCursor(\n cursor: Cursor.Cursor,\n to: to | 'Hex' | 'Bytes' | undefined = 'Hex',\n): decodeRlpCursor.ReturnType {\n if (cursor.bytes.length === 0)\n return (\n to === 'Hex' ? Hex.fromBytes(cursor.bytes) : cursor.bytes\n ) as decodeRlpCursor.ReturnType\n\n const prefix = cursor.readByte()\n if (prefix < 0x80) cursor.decrementPosition(1)\n\n // bytes\n if (prefix < 0xc0) {\n const length = readLength(cursor, prefix, 0x80)\n const bytes = cursor.readBytes(length)\n return (\n to === 'Hex' ? Hex.fromBytes(bytes) : bytes\n ) as decodeRlpCursor.ReturnType\n }\n\n // list\n const length = readLength(cursor, prefix, 0xc0)\n return readList(cursor, length, to) as {} as decodeRlpCursor.ReturnType\n}\n\n/** @internal */\nexport declare namespace decodeRlpCursor {\n type ReturnType = to.ReturnType\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | readLength.ErrorType\n | readList.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readLength(\n cursor: Cursor.Cursor,\n prefix: number,\n offset: number,\n) {\n if (offset === 0x80 && prefix < 0x80) return 1\n if (prefix <= offset + 55) return prefix - offset\n if (prefix === offset + 55 + 1) return cursor.readUint8()\n if (prefix === offset + 55 + 2) return cursor.readUint16()\n if (prefix === offset + 55 + 3) return cursor.readUint24()\n if (prefix === offset + 55 + 4) return cursor.readUint32()\n throw new Errors.BaseError('Invalid RLP prefix')\n}\n\n/** @internal */\nexport declare namespace readLength {\n type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readList(\n cursor: Cursor.Cursor,\n length: number,\n to: to | 'Hex' | 'Bytes',\n) {\n const position = cursor.position\n const value: decodeRlpCursor.ReturnType[] = []\n while (cursor.position - position < length)\n value.push(decodeRlpCursor(cursor, to))\n return value\n}\n\n/** @internal */\nexport declare namespace readList {\n type ErrorType = Errors.GlobalErrorType\n}\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor.Cursor): void\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.from('0x68656c6c6f20776f726c64', { as: 'Hex' })\n * // @log: 0x8b68656c6c6f20776f726c64\n *\n * Rlp.from(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), { as: 'Bytes' })\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function from(\n value: RecursiveArray | RecursiveArray,\n options: from.Options,\n): from.ReturnType {\n const { as } = options\n\n const encodable = getEncodable(value)\n const cursor = Cursor.create(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (as === 'Hex') return Hex.fromBytes(cursor.bytes) as from.ReturnType\n return cursor.bytes as from.ReturnType\n}\n\nexport declare namespace from {\n type Options = {\n /** The type to convert the RLP value to. */\n as: as | 'Hex' | 'Bytes'\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Cursor.create.ErrorType\n | Hex.fromBytes.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.fromBytes(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]))\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromBytes(\n bytes: RecursiveArray,\n options: fromBytes.Options = {},\n): fromBytes.ReturnType {\n const { as = 'Bytes' } = options\n return from(bytes, { as }) as never\n}\n\nexport declare namespace fromBytes {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n *\n * Rlp.fromHex('0x68656c6c6f20776f726c64')\n * // @log: 0x8b68656c6c6f20776f726c64\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromHex(\n hex: RecursiveArray,\n options: fromHex.Options = {},\n): fromHex.ReturnType {\n const { as = 'Hex' } = options\n return from(hex, { as }) as never\n}\n\nexport declare namespace fromHex {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\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.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: Bytes.Bytes | Hex.Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? Bytes.fromHex(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.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 <= 0xff) return 1\n if (length <= 0xff_ff) return 2\n if (length <= 0xff_ff_ff) return 3\n if (length <= 0xff_ff_ff_ff) return 4\n throw new Errors.BaseError('Length is too large.')\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial, OneOf } from './internal/types.js'\nimport * as Json from './Json.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for an ECDSA signature. */\nexport type Signature<\n recovered extends boolean = true,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n recovered extends true\n ? {\n r: bigintType\n s: bigintType\n yParity: numberType\n }\n : {\n r: bigintType\n s: bigintType\n yParity?: numberType | undefined\n }\n>\n\n/** RPC-formatted ECDSA signature. */\nexport type Rpc = Signature<\n recovered,\n Hex.Hex,\n Hex.Hex\n>\n\n/** (Legacy) ECDSA signature. */\nexport type Legacy = {\n r: bigintType\n s: bigintType\n v: numberType\n}\n\n/** RPC-formatted (Legacy) ECDSA signature. */\nexport type LegacyRpc = Legacy\n\nexport type Tuple = readonly [yParity: Hex.Hex, r: Hex.Hex, s: Hex.Hex]\n\n/**\n * Asserts that a Signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.assert({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @error: InvalidSignatureRError:\n * // @error: Value `-549...n` is an invalid r value.\n * // @error: r must be a positive integer less than 2^256.\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function assert(\n signature: ExactPartial,\n options: assert.Options = {},\n): asserts signature is Signature {\n const { recovered } = options\n if (typeof signature.r === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (typeof signature.s === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (recovered && typeof signature.yParity === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (signature.r < 0n || signature.r > Solidity.maxUint256)\n throw new InvalidRError({ value: signature.r })\n if (signature.s < 0n || signature.s > Solidity.maxUint256)\n throw new InvalidSError({ value: signature.s })\n if (\n typeof signature.yParity === 'number' &&\n signature.yParity !== 0 &&\n signature.yParity !== 1\n )\n throw new InvalidYParityError({ value: signature.yParity })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType =\n | MissingPropertiesError\n | InvalidRError\n | InvalidSError\n | InvalidYParityError\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Bytes.Bytes} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param signature - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromBytes(signature: Bytes.Bytes): Signature {\n return fromHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Hex.Hex} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.fromHex('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c')\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param serialized - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromHex(signature: Hex.Hex): Signature {\n if (signature.length !== 130 && signature.length !== 132)\n throw new InvalidSerializedSizeError({ signature })\n\n const r = BigInt(Hex.slice(signature, 0, 32))\n const s = BigInt(Hex.slice(signature, 32, 64))\n\n const yParity = (() => {\n const yParity = Number(`0x${signature.slice(130)}`)\n if (Number.isNaN(yParity)) return undefined\n try {\n return vToYParity(yParity)\n } catch {\n throw new InvalidYParityError({ value: yParity })\n }\n })()\n\n if (typeof yParity === 'undefined')\n return {\n r,\n s,\n } as never\n return {\n r,\n s,\n yParity,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType =\n | Hex.from.ErrorType\n | InvalidSerializedSizeError\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts a {@link ox#Signature.Signature} from an arbitrary object that may include signature properties.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.extract({\n * baz: 'barry',\n * foo: 'bar',\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * zebra: 'stripes',\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @param value - The arbitrary object to extract the signature from.\n * @returns The extracted {@link ox#Signature.Signature}.\n */\nexport function extract(value: extract.Value): Signature | undefined {\n if (typeof value.r === 'undefined') return undefined\n if (typeof value.s === 'undefined') return undefined\n return from(value as any)\n}\n\nexport declare namespace extract {\n type Value = {\n r?: bigint | Hex.Hex | undefined\n s?: bigint | Hex.Hex | undefined\n yParity?: number | Hex.Hex | undefined\n v?: number | Hex.Hex | undefined\n }\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#Signature.Signature} object from a {@link ox#Signature.Signature}, {@link ox#Signature.Legacy}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db801')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @example\n * ### From Legacy\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * v: 27,\n * })\n * // @log: {\n * // @log: r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * // @log: s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * // @log: yParity: 0\n * // @log: }\n * ```\n *\n * @param signature - The signature value to instantiate.\n * @returns The instantiated {@link ox#Signature.Signature}.\n */\nexport function from<\n const signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n>(\n signature:\n | signature\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n): from.ReturnType {\n const signature_ = (() => {\n if (typeof signature === 'string') return fromHex(signature)\n if (signature instanceof Uint8Array) return fromBytes(signature)\n if (typeof signature.r === 'string') return fromRpc(signature)\n if (signature.v) return fromLegacy(signature)\n return {\n r: signature.r,\n s: signature.s,\n ...(typeof signature.yParity !== 'undefined'\n ? { yParity: signature.yParity }\n : {}),\n }\n })()\n assert(signature_)\n return signature_ as never\n}\n\nexport declare namespace from {\n type ReturnType<\n signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n > = signature extends Signature & { v?: undefined }\n ? signature\n : Signature\n\n type ErrorType =\n | assert.ErrorType\n | fromBytes.ErrorType\n | fromHex.ErrorType\n | vToYParity.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerBytes(new Uint8Array([132, 51, 23, ...]))\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerBytes(signature: Bytes.Bytes): Signature {\n return fromDerHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerHex('0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerHex(signature: Hex.Hex): Signature {\n const { r, s } = secp256k1.Signature.fromDER(Hex.from(signature).slice(2))\n return { r, s }\n}\n\nexport declare namespace fromDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Legacy} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.fromLegacy({ r: 1n, s: 2n, v: 28 })\n * // @log: { r: 1n, s: 2n, yParity: 1 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Legacy} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromLegacy(signature: Legacy): Signature {\n return {\n r: signature.r,\n s: signature.s,\n yParity: vToYParity(signature.v),\n }\n}\n\nexport declare namespace fromLegacy {\n type ErrorType = vToYParity.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Rpc} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromRpc({\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Rpc} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromRpc(signature: {\n r: Hex.Hex\n s: Hex.Hex\n yParity?: Hex.Hex | undefined\n v?: Hex.Hex | undefined\n}): Signature {\n const yParity = (() => {\n const v = signature.v ? Number(signature.v) : undefined\n let yParity = signature.yParity ? Number(signature.yParity) : undefined\n if (typeof v === 'number' && typeof yParity !== 'number')\n yParity = vToYParity(v)\n if (typeof yParity !== 'number')\n throw new InvalidYParityError({ value: signature.yParity })\n return yParity\n })()\n\n return {\n r: BigInt(signature.r),\n s: BigInt(signature.s),\n yParity,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Tuple} to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromTuple(['0x01', '0x7b', '0x1c8'])\n * // @log: {\n * // @log: r: 123n,\n * // @log: s: 456n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @param tuple - The {@link ox#Signature.Tuple} to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromTuple(tuple: Tuple): Signature {\n const [yParity, r, s] = tuple\n return from({\n r: r === '0x' ? 0n : BigInt(r),\n s: s === '0x' ? 0n : BigInt(s),\n yParity: yParity === '0x' ? 0 : Number(yParity),\n })\n}\n\nexport declare namespace fromTuple {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toBytes({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: Uint8Array [102, 16, 10, ...]\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toBytes(signature: Signature): Bytes.Bytes {\n return Bytes.fromHex(toHex(signature))\n}\n\nexport declare namespace toBytes {\n type ErrorType =\n | toHex.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toHex({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c'\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toHex(signature: Signature): Hex.Hex {\n assert(signature)\n\n const r = signature.r\n const s = signature.s\n\n const signature_ = Hex.concat(\n Hex.fromNumber(r, { size: 32 }),\n Hex.fromNumber(s, { size: 32 }),\n // If the signature is recovered, add the recovery byte to the signature.\n typeof signature.yParity === 'number'\n ? Hex.fromNumber(yParityToV(signature.yParity), { size: 1 })\n : '0x',\n )\n\n return signature_\n}\n\nexport declare namespace toHex {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerBytes(signature)\n * // @log: Uint8Array [132, 51, 23, ...]\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerBytes(signature: Signature): Bytes.Bytes {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return sig.toDERRawBytes()\n}\n\nexport declare namespace toDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerHex(signature)\n * // @log: '0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8'\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerHex(signature: Signature): Hex.Hex {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return `0x${sig.toDERHex()}`\n}\n\nexport declare namespace toDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Legacy}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.toLegacy({ r: 1n, s: 2n, yParity: 1 })\n * // @log: { r: 1n, s: 2n, v: 28 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Legacy}.\n */\nexport function toLegacy(signature: Signature): Legacy {\n return {\n r: signature.r,\n s: signature.s,\n v: yParityToV(signature.yParity),\n }\n}\n\nexport declare namespace toLegacy {\n type ErrorType = yParityToV.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toRpc({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Rpc}.\n */\nexport function toRpc(signature: Signature): Rpc {\n const { r, s, yParity } = signature\n return {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity: yParity === 0 ? '0x0' : '0x1',\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to a serialized {@link ox#Signature.Tuple} to be used for signatures in Transaction Envelopes, EIP-7702 Authorization Lists, etc.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signatureTuple = Signature.toTuple({\n * r: 123n,\n * s: 456n,\n * yParity: 1,\n * })\n * // @log: [yParity: '0x01', r: '0x7b', s: '0x1c8']\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The {@link ox#Signature.Tuple}.\n */\nexport function toTuple(signature: Signature): Tuple {\n const { r, s, yParity } = signature\n\n return [\n yParity ? '0x01' : '0x',\n r === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(r!)),\n s === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(s!)),\n ] as const\n}\n\nexport declare namespace toTuple {\n type ErrorType =\n | Hex.trimLeft.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a Signature. Returns `true` if the signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const valid = Signature.validate({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: false\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function validate(\n signature: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(signature, options)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const yParity = Signature.vToYParity(28)\n * // @log: 1\n * ```\n *\n * @param v - The ECDSA `v` value to convert.\n * @returns The `yParity` value.\n */\nexport function vToYParity(v: number): Signature['yParity'] {\n if (v === 0 || v === 27) return 0\n if (v === 1 || v === 28) return 1\n if (v >= 35) return v % 2 === 0 ? 1 : 0\n throw new InvalidVError({ value: v })\n}\n\nexport declare namespace vToYParity {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const v = Signature.yParityToV(1)\n * // @log: 28\n * ```\n *\n * @param yParity - The ECDSA `yParity` value to convert.\n * @returns The `v` value.\n */\nexport function yParityToV(yParity: number): number {\n if (yParity === 0) return 27\n if (yParity === 1) return 28\n throw new InvalidYParityError({ value: yParity })\n}\n\nexport declare namespace yParityToV {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/** Thrown when the serialized signature is of an invalid size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSerializedSizeError'\n\n constructor({ signature }: { signature: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${signature}\\` is an invalid signature size.`, {\n metaMessages: [\n 'Expected: 64 bytes or 65 bytes.',\n `Received ${Hex.size(Hex.from(signature))} bytes.`,\n ],\n })\n }\n}\n\n/** Thrown when the signature is missing either an `r`, `s`, or `yParity` property. */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'Signature.MissingPropertiesError'\n\n constructor({ signature }: { signature: unknown }) {\n super(\n `Signature \\`${Json.stringify(signature)}\\` is missing either an \\`r\\`, \\`s\\`, or \\`yParity\\` property.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `r` value. */\nexport class InvalidRError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidRError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid r value. r must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `s` value. */\nexport class InvalidSError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid s value. s must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `yParity` value. */\nexport class InvalidYParityError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidYParityError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid y-parity value. Y-parity must be 0 or 1.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `v` value. */\nexport class InvalidVError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidVError'\n\n constructor({ value }: { value: number }) {\n super(`Value \\`${value}\\` is an invalid v value. v must be 27, 28 or >=35.`)\n }\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Entropy from './internal/entropy.js'\nimport type { OneOf } from './internal/types.js'\nimport * as PublicKey from './PublicKey.js'\nimport type * as Signature from './Signature.js'\n\n/** Re-export of noble/curves secp256k1 utilities. */\nexport const noble = secp256k1\n\n/**\n * Creates a new secp256k1 ECDSA key pair consisting of a private key and its corresponding public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey, publicKey } = Secp256k1.createKeyPair()\n * ```\n *\n * @param options - The options to generate the key pair.\n * @returns The generated key pair containing both private and public keys.\n */\nexport function createKeyPair(\n options: createKeyPair.Options = {},\n): createKeyPair.ReturnType {\n const { as = 'Hex' } = options\n const privateKey = randomPrivateKey({ as })\n const publicKey = getPublicKey({ privateKey })\n\n return {\n privateKey: privateKey as never,\n publicKey,\n }\n}\n\nexport declare namespace createKeyPair {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType = {\n privateKey:\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n publicKey: PublicKey.PublicKey\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the secp256k1 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const publicKey = Secp256k1.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(\n options: getPublicKey.Options,\n): PublicKey.PublicKey {\n const { privateKey } = options\n const point = secp256k1.ProjectivePoint.fromPrivateKey(\n Hex.from(privateKey).slice(2),\n )\n return PublicKey.from(point)\n}\n\nexport declare namespace getPublicKey {\n type Options = {\n /**\n * Private key to compute the public key from.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes a shared secret using ECDH (Elliptic Curve Diffie-Hellman) between a private key and a public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey: privateKeyA } = Secp256k1.createKeyPair()\n * const { publicKey: publicKeyB } = Secp256k1.createKeyPair()\n *\n * const sharedSecret = Secp256k1.getSharedSecret({\n * privateKey: privateKeyA,\n * publicKey: publicKeyB\n * })\n * ```\n *\n * @param options - The options to compute the shared secret.\n * @returns The computed shared secret.\n */\nexport function getSharedSecret(\n options: getSharedSecret.Options,\n): getSharedSecret.ReturnType {\n const { as = 'Hex', privateKey, publicKey } = options\n const point = secp256k1.ProjectivePoint.fromHex(\n PublicKey.toHex(publicKey).slice(2),\n )\n const sharedPoint = point.multiply(\n secp256k1.utils.normPrivateKeyToScalar(Hex.from(privateKey).slice(2)),\n )\n const sharedSecret = sharedPoint.toRawBytes(true) // compressed format\n if (as === 'Hex') return Hex.fromBytes(sharedSecret) as never\n return sharedSecret as never\n}\n\nexport declare namespace getSharedSecret {\n type Options = {\n /**\n * Format of the returned shared secret.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n /**\n * Private key to use for the shared secret computation.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n /**\n * Public key to use for the shared secret computation.\n */\n publicKey: PublicKey.PublicKey\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.toHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random ECDSA private key on the secp256k1 curve.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey(\n options: randomPrivateKey.Options = {},\n): randomPrivateKey.ReturnType {\n const { as = 'Hex' } = options\n const bytes = secp256k1.utils.randomPrivateKey()\n if (as === 'Hex') return Hex.fromBytes(bytes) as never\n return bytes as never\n}\n\nexport declare namespace randomPrivateKey {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing address from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const address = Secp256k1.recoverAddress({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered address.\n */\nexport function recoverAddress(\n options: recoverAddress.Options,\n): recoverAddress.ReturnType {\n return Address.fromPublicKey(recoverPublicKey(options))\n}\n\nexport declare namespace recoverAddress {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = Secp256k1.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(\n options: recoverPublicKey.Options,\n): PublicKey.PublicKey {\n const { payload, signature } = options\n const { r, s, yParity } = signature\n const signature_ = new secp256k1.Signature(\n BigInt(r),\n BigInt(s),\n ).addRecoveryBit(yParity)\n const point = signature_.recoverPublicKey(Hex.from(payload).substring(2))\n return PublicKey.from(point)\n}\n\nexport declare namespace recoverPublicKey {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ErrorType =\n | PublicKey.from.ErrorType\n | Hex.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs the payload with the provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options: sign.Options): Signature.Signature {\n const {\n extraEntropy = Entropy.extraEntropy,\n hash,\n payload,\n privateKey,\n } = options\n const { r, s, recovery } = secp256k1.sign(\n Bytes.from(payload),\n Bytes.from(privateKey),\n {\n extraEntropy:\n typeof extraEntropy === 'boolean'\n ? extraEntropy\n : Hex.from(extraEntropy).slice(2),\n lowS: true,\n ...(hash ? { prehash: true } : {}),\n },\n )\n return {\n r,\n s,\n yParity: recovery,\n }\n}\n\nexport declare namespace sign {\n type Options = {\n /**\n * Extra entropy to add to the signing process. Setting to `false` will disable it.\n * @default true\n */\n extraEntropy?: boolean | Hex.Hex | Bytes.Bytes | undefined\n /**\n * If set to `true`, the payload will be hashed (sha256) before being signed.\n */\n hash?: boolean | undefined\n /**\n * Payload to sign.\n */\n payload: Hex.Hex | Bytes.Bytes\n /**\n * ECDSA private key.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Bytes.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Verifies a payload was signed by the provided address.\n *\n * @example\n * ### Verify with Ethereum Address\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Verify with Public Key\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = '0x...'\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided address.\n */\nexport function verify(options: verify.Options): boolean {\n const { address, hash, payload, publicKey, signature } = options\n if (address)\n return Address.isEqual(address, recoverAddress({ payload, signature }))\n return secp256k1.verify(\n signature,\n Bytes.from(payload),\n PublicKey.toBytes(publicKey),\n ...(hash ? [{ prehash: true, lowS: true }] : []),\n )\n}\n\nexport declare namespace verify {\n type Options = {\n /** If set to `true`, the payload will be hashed (sha256) before being verified. */\n hash?: boolean | undefined\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Address that signed the payload. */\n address: Address.Address\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RpcProof } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../index.js'\n\nexport type FormatProofErrorType = ErrorType\n\nfunction formatStorageProof(storageProof: RpcProof['storageProof']) {\n return storageProof.map((proof) => ({\n ...proof,\n value: BigInt(proof.value),\n }))\n}\n\nexport function formatProof(proof: ExactPartial) {\n return {\n ...proof,\n balance: proof.balance ? BigInt(proof.balance) : undefined,\n nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined,\n storageProof: proof.storageProof\n ? formatStorageProof(proof.storageProof)\n : undefined,\n } as Proof\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetStorageAtParameters = {\n address: Address\n slot: Hex\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetStorageAtReturnType = Hex | undefined\n\nexport type GetStorageAtErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param client - Client to use\n * @param parameters - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getStorageAt(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\nexport async function getStorageAt(\n client: Client,\n { address, blockNumber, blockTag = 'latest', slot }: GetStorageAtParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const data = await client.request({\n method: 'eth_getStorageAt',\n params: [address, slot, blockNumberHex || blockTag],\n })\n return data\n}\n","import type { Address } from '../../accounts/index.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { OneOf, Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters =\n OneOf<\n // eth_getTransactionByBlockHashAndIndex\n | {\n /** The block hash */\n blockHash: Hash\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block number */\n blockNumber: bigint\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block tag. */\n blockTag: blockTag | BlockTag\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByHash\n | {\n /** The hash of the transaction. */\n hash: Hash\n }\n // eth_getTransactionBySenderAndNonce\n | {\n /** The sender of the transaction. */\n sender: Address\n /** The nonce of the transaction on the sender. */\n nonce: number\n }\n >\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetTransactionErrorType =\n | TransactionNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n sender,\n nonce,\n }: GetTransactionParameters,\n): Promise> {\n const blockTag = blockTag_ || 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let transaction: RpcTransaction | null = null\n if (hash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if ((blockNumberHex || blockTag) && typeof index === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n } else if (sender && typeof nonce === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionBySenderAndNonce',\n params: [sender, numberToHex(nonce)],\n },\n { dedupe: true },\n )\n }\n\n if (!transaction)\n throw new TransactionNotFoundError({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n })\n\n const format =\n client.chain?.formatters?.transaction?.format || formatTransaction\n return format(transaction, 'getTransaction')\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { FormattedTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetBlockNumberErrorType,\n getBlockNumber,\n} from './getBlockNumber.js'\nimport {\n type GetTransactionErrorType,\n getTransaction,\n} from './getTransaction.js'\n\nexport type GetTransactionConfirmationsParameters<\n chain extends Chain | undefined = Chain,\n> =\n | {\n /** The transaction hash. */\n hash: Hash\n transactionReceipt?: undefined\n }\n | {\n hash?: undefined\n /** The transaction receipt. */\n transactionReceipt: FormattedTransactionReceipt\n }\n\nexport type GetTransactionConfirmationsReturnType = bigint\n\nexport type GetTransactionConfirmationsErrorType =\n | GetBlockNumberErrorType\n | GetTransactionErrorType\n | ErrorType\n\n/**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionConfirmations } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await getTransactionConfirmations(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionConfirmations<\n chain extends Chain | undefined,\n>(\n client: Client,\n { hash, transactionReceipt }: GetTransactionConfirmationsParameters,\n): Promise {\n const [blockNumber, transaction] = await Promise.all([\n getAction(client, getBlockNumber, 'getBlockNumber')({}),\n hash\n ? getAction(client, getTransaction, 'getTransaction')({ hash })\n : undefined,\n ])\n const transactionBlockNumber =\n transactionReceipt?.blockNumber || transaction?.blockNumber\n if (!transactionBlockNumber) return 0n\n return blockNumber - transactionBlockNumber! + 1n\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n /** The hash of the transaction. */\n hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt(\n client: Client,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(\n receipt,\n 'getTransactionReceipt',\n ) as GetTransactionReceiptReturnType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { multicall3Bytecode } from '../../constants/contracts.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record\n } = {},\n> = Pick<\n CallParameters,\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'stateOverride'\n> & {\n /** The account to use for the multicall. */\n account?: Address | undefined\n /** Whether to allow failures. */\n allowFailure?: allowFailure | boolean | undefined\n /** The size of each batch of calls. */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The contracts to call. */\n contracts: MulticallContracts<\n Narrow,\n { mutability: AbiStateMutability } & options\n >\n /** The address of the multicall3 contract to use. */\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client,\n parameters: MulticallParameters,\n): Promise> {\n const {\n account,\n authorizationList,\n allowFailure = true,\n blockNumber,\n blockOverrides,\n blockTag,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const {\n batchSize = parameters.batchSize ?? 1024,\n deployless = parameters.deployless ?? false,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n\n const multicallAddress = (() => {\n if (parameters.multicallAddress) return parameters.multicallAddress\n if (deployless) return null\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n })()\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n sender: account,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress === null\n ? { code: multicall3Bytecode }\n : { address: multicallAddress }),\n abi: multicall3Abi,\n account,\n args: [calls],\n authorizationList,\n blockNumber,\n blockOverrides,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType\n}\n","import type { Abi, AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\n\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 { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.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 EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { concat } from '../../utils/data/concat.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getContractError } from '../../utils/errors/getContractError.js'\nimport {\n type GetNodeErrorReturnType,\n getNodeError,\n} from '../../utils/errors/getNodeError.js'\nimport {\n type FormatBlockErrorType,\n formatBlock,\n} from '../../utils/formatters/block.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport {\n type FormatTransactionRequestErrorType,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\n\ntype CallExtraProperties = ExactPartial<\n UnionOmit<\n TransactionRequest,\n 'blobs' | 'data' | 'kzg' | 'to' | 'sidecars' | 'value'\n >\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Recipient. `null` if contract deployment. */\n to?: Address | null | undefined\n}\n\nexport type SimulateBlocksParameters<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Blocks to simulate. */\n blocks: readonly {\n /** Block overrides. */\n blockOverrides?: BlockOverrides.BlockOverrides | undefined\n /** Calls to execute. */\n calls: Calls, CallExtraProperties>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n }[]\n /** Whether to return the full transactions. */\n returnFullTransactions?: boolean | undefined\n /** Whether to trace transfers. */\n traceTransfers?: boolean | undefined\n /** Whether to enable validation mode. */\n validation?: boolean | 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)\n\nexport type SimulateBlocksReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = readonly (Block & {\n calls: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n})[]\n\nexport type SimulateBlocksErrorType =\n | AssertRequestErrorType\n | DecodeFunctionResultErrorType\n | EncodeFunctionDataErrorType\n | FormatBlockErrorType\n | FormatTransactionRequestErrorType\n | GetNodeErrorReturnType\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createClient, http, parseEther } from 'viem'\n * import { simulate } from 'viem/actions'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulate(client, {\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateBlocksParameters}\n * @returns Simulated blocks. {@link SimulateBlocksReturnType}\n */\nexport async function simulateBlocks<\n chain extends Chain | undefined,\n const calls extends readonly unknown[],\n>(\n client: Client,\n parameters: SimulateBlocksParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n blocks,\n returnFullTransactions,\n traceTransfers,\n validation,\n } = parameters\n\n try {\n const blockStateCalls = []\n for (const block of blocks) {\n const blockOverrides = block.blockOverrides\n ? BlockOverrides.toRpc(block.blockOverrides)\n : undefined\n const calls = block.calls.map((call_) => {\n const call = call_ as Call\n const account = call.account ? parseAccount(call.account) : undefined\n const data = call.abi ? encodeFunctionData(call) : call.data\n const request = {\n ...call,\n account,\n data: call.dataSuffix\n ? concat([data || '0x', call.dataSuffix])\n : data,\n from: call.from ?? account?.address,\n } as const\n assertRequest(request)\n return formatTransactionRequest(request)\n })\n const stateOverrides = block.stateOverrides\n ? serializeStateOverride(block.stateOverrides)\n : undefined\n\n blockStateCalls.push({\n blockOverrides,\n calls,\n stateOverrides,\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const result = await client.request({\n method: 'eth_simulateV1',\n params: [\n { blockStateCalls, returnFullTransactions, traceTransfers, validation },\n block,\n ],\n })\n\n return result.map((block, i) => ({\n ...formatBlock(block),\n calls: block.calls.map((call, j) => {\n const { abi, args, functionName, to } = blocks[i].calls[j] as Call<\n unknown,\n CallExtraProperties\n >\n\n const data = call.error?.data ?? call.returnData\n const gasUsed = BigInt(call.gasUsed)\n const logs = call.logs?.map((log) => formatLog(log))\n const status = call.status === '0x1' ? 'success' : 'failure'\n\n const result =\n abi && status === 'success' && data !== '0x'\n ? decodeFunctionResult({\n abi,\n data,\n functionName,\n })\n : null\n\n const error = (() => {\n if (status === 'success') return undefined\n\n let error: Error | undefined\n if (data === '0x') error = new AbiDecodingZeroDataError()\n else if (data) error = new RawContractError({ data })\n\n if (!error) return undefined\n return getContractError(error, {\n abi: (abi ?? []) as Abi,\n address: to ?? '0x',\n args,\n functionName: functionName ?? '',\n })\n })()\n\n return {\n data,\n gasUsed,\n logs,\n status,\n ...(status === 'success'\n ? {\n result,\n }\n : {\n error,\n }),\n }\n }),\n })) as unknown as SimulateBlocksReturnType\n } catch (e) {\n const cause = e as BaseError\n const error = getNodeError(cause, {})\n if (error instanceof UnknownNodeError) throw cause\n throw error\n }\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiItem.js'\nimport type { UnionCompute } from './internal/types.js'\n\n/** Root type for an item on an {@link ox#Abi.Abi}. */\nexport type AbiItem = Abi.Abi[number]\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type Foo = AbiItem.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = Extract\n\n/**\n * Extracts the names of all {@link ox#AbiItem.AbiItem} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type names = AbiItem.Name\n * // ^?\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames = Extract<\n abi[number],\n { name: string }\n>['name']\n\n/**\n * Formats an {@link ox#AbiItem.AbiItem} into a **Human Readable ABI Item**.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const formatted = AbiItem.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiItem - The ABI Item to format.\n * @returns The formatted ABI Item .\n */\nexport function format(\n abiItem: abiItem | AbiItem,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiItem) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Item** or **Human Readable ABI Item** into a typed {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from({\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: [{ type: 'bool' }],\n * })\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiItem - The ABI Item to parse.\n * @returns The typed ABI Item.\n */\nexport function from<\n const abiItem extends AbiItem | string | readonly string[],\n>(\n abiItem: (abiItem | AbiItem | string | readonly string[]) &\n (\n | (abiItem extends string ? internal.Signature : never)\n | (abiItem extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiItem\n ),\n options: from.Options = {},\n): from.ReturnType {\n const { prepare = true } = options\n const item = (() => {\n if (Array.isArray(abiItem)) return abitype.parseAbiItem(abiItem)\n if (typeof abiItem === 'string')\n return abitype.parseAbiItem(abiItem as never)\n return abiItem\n })() as AbiItem\n return {\n ...item,\n ...(prepare ? { hash: getSignatureHash(item) } : {}),\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType =\n abiItem extends string\n ? abitype.ParseAbiItem\n : abiItem extends readonly string[]\n ? abitype.ParseAbiItem\n : abiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ABI Items can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiItem.fromAbi(abi, 'Transfer') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Items can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiItem.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Item from an `eth_call` RPC response,\n * a Transaction `input`, or from Event Log `topics`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends internal.ExtractArgs | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: fromAbi.Options,\n): fromAbi.ReturnType {\n const { args = [], prepare = true } = (options ??\n {}) as unknown as fromAbi.Options\n\n const isSelector = Hex.validate(name, { strict: false })\n const abiItems = (abi as Abi.Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function' || abiItem.type === 'error')\n return getSelector(abiItem) === Hex.slice(name, 0, 4)\n if (abiItem.type === 'event') return getSignatureHash(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0) throw new NotFoundError({ name: name as string })\n if (abiItems.length === 1)\n return {\n ...abiItems[0],\n ...(prepare ? { hash: getSignatureHash(abiItems[0]!) } : {}),\n } as never\n\n let matchedAbiItem: AbiItem | 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 {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\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 internal.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 = internal.getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AmbiguityError(\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 const abiItem = (() => {\n if (matchedAbiItem) return matchedAbiItem\n const [abiItem, ...overloads] = abiItems\n return { ...abiItem!, overloads }\n })()\n\n if (!abiItem) throw new NotFoundError({ name: name as string })\n return {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\n}\n\nexport declare namespace fromAbi {\n type Options<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n ///\n allArgs = internal.ExtractArgs,\n > = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n } & UnionCompute<\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.Abi\n ? args extends allArgs\n ? internal.Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (internal.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\n type ReturnType<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n fallback = AbiItem,\n > = abi extends Abi.Abi\n ? Abi.Abi extends abi\n ? fallback\n : internal.ExtractForArgs<\n abi,\n name,\n args extends internal.ExtractArgs\n ? args\n : internal.ExtractArgs\n >\n : fallback\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const selector = AbiItem.getSelector(erc20Abi, 'ownerOf')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for. Can be a signature or an ABI item for an error, event, function, etc.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSelector(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSelector(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n return Hex.slice(getSignatureHash(abiItem), 0, 4)\n}\n\nexport declare namespace getSelector {\n type ErrorType =\n | getSignatureHash.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the stringified signature for a given {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature('function ownerOf(uint256 tokenId)')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const signature = AbiItem.getSignature(erc20Abi, 'ownerOf')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature for.\n * @returns The stringified signature of the ABI Item.\n */\nexport function getSignature<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): string\nexport function getSignature(abiItem: string | AbiItem): string\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignature(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): string {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n const signature = (() => {\n if (typeof abiItem === 'string') return abiItem\n return abitype.formatAbiItem(abiItem)\n })()\n return internal.normalizeSignature(signature)\n}\n\nexport declare namespace getSignature {\n type ErrorType =\n | internal.normalizeSignature.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the signature hash for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing Event Topic values.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash('event Transfer(address indexed from, address indexed to, uint256 amount)')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const hash = AbiItem.getSignatureHash(erc20Abi, 'Transfer')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash({\n * name: 'Transfer',\n * type: 'event',\n * inputs: [\n * { name: 'from', type: 'address', indexed: true },\n * { name: 'to', type: 'address', indexed: true },\n * { name: 'amount', type: 'uint256', indexed: false },\n * ],\n * })\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature hash for.\n * @returns The {@link ox#Hash.(keccak256:function)} hash of the ABI item's signature.\n */\nexport function getSignatureHash<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSignatureHash(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignatureHash(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n if (typeof abiItem !== 'string' && 'hash' in abiItem && abiItem.hash)\n return abiItem.hash as Hex.Hex\n return Hash.keccak256(Hex.fromString(getSignature(abiItem)))\n}\n\nexport declare namespace getSignatureHash {\n type ErrorType =\n | getSignature.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Throws when ambiguous types are found on overloaded ABI items.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from(['function foo(address)', 'function foo(bytes20)'])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n *\n * ### Solution\n *\n * Remove one of the ambiguous types from the ABI.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function foo(bytes20)' // [!code --]\n * ])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n */\nexport class AmbiguityError extends Errors.BaseError {\n override readonly name = 'AbiItem.AmbiguityError'\n constructor(\n x: { abiItem: Abi.Abi[number]; type: string },\n y: { abiItem: Abi.Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI Items.', {\n metaMessages: [\n // TODO: abitype to add support for signature-formatted ABI items.\n `\\`${x.type}\\` in \\`${internal.normalizeSignature(abitype.formatAbiItem(x.abiItem))}\\`, and`,\n `\\`${y.type}\\` in \\`${internal.normalizeSignature(abitype.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 })\n }\n}\n\n/**\n * Throws when an ABI item is not found in the ABI.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * // @error: AbiItem.NotFoundError: ABI function with name \"baz\" not found.\n * ```\n *\n * ### Solution\n *\n * Ensure the ABI item exists on the ABI.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)',\n * 'function baz(bool)' // [!code ++]\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * ```\n */\nexport class NotFoundError extends Errors.BaseError {\n override readonly name = 'AbiItem.NotFoundError'\n constructor({\n name,\n data,\n type = 'item',\n }: {\n name?: string | undefined\n data?: Hex.Hex | undefined\n type?: string | undefined\n }) {\n const selector = (() => {\n if (name) return ` with name \"${name}\"`\n if (data) return ` with data \"${data}\"`\n return ''\n })()\n super(`ABI ${type}${selector} not found.`)\n }\n}\n\n/**\n * Throws when the selector size is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0xaaa')\n * // @error: AbiItem.InvalidSelectorSizeError: Selector size is invalid. Expected 4 bytes. Received 2 bytes (\"0xaaa\").\n * ```\n *\n * ### Solution\n *\n * Ensure the selector size is 4 bytes.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0x7af82b1a')\n * ```\n */\nexport class InvalidSelectorSizeError extends Errors.BaseError {\n override readonly name = 'AbiItem.InvalidSelectorSizeError'\n constructor({ data }: { data: Hex.Hex }) {\n super(\n `Selector size is invalid. Expected 4 bytes. Received ${Hex.size(data)} bytes (\"${data}\").`,\n )\n }\n}\n","import type * as abitype from 'abitype'\nimport type * as Abi from '../Abi.js'\nimport type * as AbiItem from '../AbiItem.js'\nimport type * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Errors from '../Errors.js'\nimport type {\n Compute,\n IsNever,\n IsUnion,\n TypeErrorMessage,\n UnionToTuple,\n} from './types.js'\n\n/** @internal */\nexport type ExtractArgs<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends AbiItem.Name = AbiItem.Name,\n> = abitype.AbiParametersToPrimitiveTypes<\n AbiItem.FromAbi['inputs'],\n 'inputs'\n> extends infer args\n ? [args] extends [never]\n ? readonly unknown[]\n : args\n : readonly unknown[]\n\n/** @internal */\nexport type ExtractForArgs<\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = IsUnion extends true\n ? {\n [key in keyof abi]: abi[key] extends { name: name } ? abi[key] : never\n }[number]\n : AbiItem.FromAbi extends infer abiItem extends AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n }\n ? IsUnion extends true // narrow overloads using `args` by converting to tuple and filtering out overloads that don't match\n ? UnionToTuple extends infer abiItems extends\n readonly (AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n })[]\n ? IsNever> extends true\n ? Compute<\n abiItems[0] & {\n readonly overloads: UnionToTuple<\n Exclude\n >\n }\n >\n : TupleToUnion // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)\n : never\n : abiItem\n : never\n\n/** @internal */\nexport type TupleToUnion<\n abiItems extends readonly {\n inputs: readonly abitype.AbiParameter[]\n }[],\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = {\n [k in keyof abiItems]: (\n readonly [] extends args\n ? readonly [] // fallback to `readonly []` if `args` has no value (e.g. `args` property not provided)\n : args\n ) extends abitype.AbiParametersToPrimitiveTypes<\n abiItems[k]['inputs'],\n 'inputs'\n >\n ? abiItems[k]\n : never\n}[number]\n\n/** @internal */\nexport type ErrorSignature<\n name extends string = string,\n parameters extends string = string,\n> = `error ${name}(${parameters})`\n\n/** @internal */\nexport type IsErrorSignature =\n signature extends ErrorSignature ? IsName : false\n\n/** @internal */\nexport type EventSignature<\n name extends string = string,\n parameters extends string = string,\n> = `event ${name}(${parameters})`\n\n/** @internal */\nexport type IsEventSignature =\n signature extends EventSignature ? IsName : false\n\n/** @internal */\nexport type FunctionSignature<\n name extends string = string,\n tail extends string = string,\n> = `function ${name}(${tail}`\nexport type IsFunctionSignature =\n signature extends FunctionSignature\n ? IsName extends true\n ? signature extends ValidFunctionSignatures\n ? true\n : // Check that `Parameters` is not absorbing other types (e.g. `returns`)\n signature extends `function ${string}(${infer parameters})`\n ? parameters extends InvalidFunctionParameters\n ? false\n : true\n : false\n : false\n : false\n/** @internal */\nexport type Scope = 'public' | 'external' // `internal` or `private` functions wouldn't make it to ABI so can ignore\n\n/** @internal */\nexport type Returns = `returns (${string})` | `returns(${string})`\n\n// Almost all valid function signatures, except `function ${string}(${infer parameters})` since `parameters` can absorb returns\n/** @internal */\nexport type ValidFunctionSignatures =\n | `function ${string}()`\n // basic\n | `function ${string}() ${Returns}`\n | `function ${string}() ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope}`\n // combinations\n | `function ${string}() ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}() ${Scope} ${Returns}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n // Parameters\n | `function ${string}(${string}) ${Returns}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n\n/** @internal */\nexport type StructSignature<\n name extends string = string,\n properties extends string = string,\n> = `struct ${name} {${properties}}`\n\n/** @internal */\nexport type IsStructSignature =\n signature extends StructSignature ? IsName : false\n\n/** @internal */\nexport type ConstructorSignature =\n `constructor(${tail}`\n\n/** @internal */\nexport type IsConstructorSignature =\n signature extends ConstructorSignature\n ? signature extends ValidConstructorSignatures\n ? true\n : false\n : false\n\n/** @internal */\nexport type ValidConstructorSignatures =\n | `constructor(${string})`\n | `constructor(${string}) payable`\n\n/** @internal */\nexport type FallbackSignature =\n `fallback() external${abiStateMutability}`\n\n/** @internal */\nexport type ReceiveSignature = 'receive() external payable'\n\n// TODO: Maybe use this for signature validation one day\n// https://twitter.com/devanshj__/status/1610423724708343808\n/** @internal */\nexport type IsSignature =\n | (IsErrorSignature extends true ? true : never)\n | (IsEventSignature extends true ? true : never)\n | (IsFunctionSignature extends true ? true : never)\n | (IsStructSignature extends true ? true : never)\n | (IsConstructorSignature extends true ? true : never)\n | (type extends FallbackSignature ? true : never)\n | (type extends ReceiveSignature ? true : never) extends infer condition\n ? [condition] extends [never]\n ? false\n : true\n : false\n\n/** @internal */\nexport type Signature<\n string1 extends string,\n string2 extends string | unknown = unknown,\n> = IsSignature extends true\n ? string1\n : string extends string1 // if exactly `string` (not narrowed), then pass through as valid\n ? string1\n : TypeErrorMessage<`Signature \"${string1}\" is invalid${string2 extends string\n ? ` at position ${string2}`\n : ''}.`>\n\n/** @internal */\nexport type Signatures = {\n [key in keyof signatures]: Signature\n}\n\n/** @internal */\nexport type IsName = name extends ''\n ? false\n : ValidateName extends name\n ? true\n : false\n\n/** @internal */\nexport type ValidateName<\n name extends string,\n checkCharacters extends boolean = false,\n> = name extends `${string}${' '}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot contain whitespace.`>\n : IsSolidityKeyword extends true\n ? TypeErrorMessage<`\"${name}\" is a protected Solidity keyword.`>\n : name extends `${number}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot be a number string.`>\n : name extends `${number}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot start with a number.`>\n : checkCharacters extends true\n ? IsValidCharacter extends true\n ? name\n : TypeErrorMessage<`\"${name}\" contains invalid character.`>\n : name\n\n/** @internal */\nexport type IsSolidityKeyword =\n type extends SolidityKeywords ? true : false\n\n/** @internal */\nexport type SolidityKeywords =\n | 'after'\n | 'alias'\n | 'anonymous'\n | 'apply'\n | 'auto'\n | 'byte'\n | 'calldata'\n | 'case'\n | 'catch'\n | 'constant'\n | 'copyof'\n | 'default'\n | 'defined'\n | 'error'\n | 'event'\n | 'external'\n | 'false'\n | 'final'\n | 'function'\n | 'immutable'\n | 'implements'\n | 'in'\n | 'indexed'\n | 'inline'\n | 'internal'\n | 'let'\n | 'mapping'\n | 'match'\n | 'memory'\n | 'mutable'\n | 'null'\n | 'of'\n | 'override'\n | 'partial'\n | 'private'\n | 'promise'\n | 'public'\n | 'pure'\n | 'reference'\n | 'relocatable'\n | 'return'\n | 'returns'\n | 'sizeof'\n | 'static'\n | 'storage'\n | 'struct'\n | 'super'\n | 'supports'\n | 'switch'\n | 'this'\n | 'true'\n | 'try'\n | 'typedef'\n | 'typeof'\n | 'var'\n | 'view'\n | 'virtual'\n | `address${`[${string}]` | ''}`\n | `bool${`[${string}]` | ''}`\n | `string${`[${string}]` | ''}`\n | `tuple${`[${string}]` | ''}`\n | `bytes${number | ''}${`[${string}]` | ''}`\n | `${'u' | ''}int${number | ''}${`[${string}]` | ''}`\n\n/** @internal */\nexport type IsValidCharacter =\n character extends `${ValidCharacters}${infer tail}`\n ? tail extends ''\n ? true\n : IsValidCharacter\n : false\n\n// biome-ignore format: no formatting\n/** @internal */\nexport type ValidCharacters =\n // uppercase letters\n | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'\n // lowercase letters\n | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'\n // numbers\n | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n // special characters\n | '_' | '$'\n\n// Template string inference can absorb `returns`:\n// type Result = `function foo(string) return s (uint256)` extends `function ${string}(${infer Parameters})` ? Parameters : never\n// // ^? type Result = \"string ) return s (uint256\"\n// So we need to validate against `returns` keyword with all combinations of whitespace\n/** @internal */\nexport type InvalidFunctionParameters =\n | `${string}${MangledReturns} (${string}`\n | `${string}) ${MangledReturns}${string}`\n | `${string})${string}${MangledReturns}${string}(${string}`\n\n// r_e_t_u_r_n_s\n/** @internal */\nexport type MangledReturns =\n // Single\n | `r${string}eturns`\n | `re${string}turns`\n | `ret${string}urns`\n | `retu${string}rns`\n | `retur${string}ns`\n | `return${string}s`\n // Double\n // `r_e*`\n | `r${string}e${string}turns`\n | `r${string}et${string}urns`\n | `r${string}etu${string}rns`\n | `r${string}etur${string}ns`\n | `r${string}eturn${string}s`\n // `re_t*`\n | `re${string}t${string}urns`\n | `re${string}tu${string}rns`\n | `re${string}tur${string}ns`\n | `re${string}turn${string}s`\n // `ret_u*`\n | `ret${string}u${string}rns`\n | `ret${string}ur${string}ns`\n | `ret${string}urn${string}s`\n // `retu_r*`\n | `retu${string}r${string}ns`\n | `retu${string}rn${string}s`\n // `retur_n*`\n | `retur${string}n${string}s`\n // Triple\n // `r_e_t*`\n | `r${string}e${string}t${string}urns`\n | `r${string}e${string}tu${string}rns`\n | `r${string}e${string}tur${string}ns`\n | `r${string}e${string}turn${string}s`\n // `re_t_u*`\n | `re${string}t${string}u${string}rns`\n | `re${string}t${string}ur${string}ns`\n | `re${string}t${string}urn${string}s`\n // `ret_u_r*`\n | `ret${string}u${string}r${string}ns`\n | `ret${string}u${string}rn${string}s`\n // `retu_r_n*`\n | `retu${string}r${string}n${string}s`\n // Quadruple\n // `r_e_t_u*`\n | `r${string}e${string}t${string}u${string}rns`\n | `r${string}e${string}t${string}ur${string}ns`\n | `r${string}e${string}t${string}urn${string}s`\n // `re_t_u_r*`\n | `re${string}t${string}u${string}r${string}ns`\n | `re${string}t${string}u${string}rn${string}s`\n // `ret_u_r_n*`\n | `ret${string}u${string}r${string}n${string}s`\n // Quintuple\n // `r_e_t_u_r*`\n | `r${string}e${string}t${string}u${string}r${string}ns`\n | `r${string}e${string}t${string}u${string}rn${string}s`\n // `re_t_u_r_n*`\n | `re${string}t${string}u${string}r${string}n${string}s`\n // Sextuple\n // `r_e_t_u_r_n_s`\n | `r${string}e${string}t${string}u${string}r${string}n${string}s`\n\n/** @internal */\nexport type Widen =\n | ([unknown] extends [type] ? unknown : never)\n | (type extends Function ? type : never)\n | (type extends abitype.ResolvedRegister['bigIntType'] ? bigint : never)\n | (type extends boolean ? boolean : never)\n | (type extends abitype.ResolvedRegister['intType'] ? number : never)\n | (type extends string\n ? type extends abitype.ResolvedRegister['addressType']\n ? abitype.ResolvedRegister['addressType']\n : type extends abitype.ResolvedRegister['bytesType']['inputs']\n ? abitype.ResolvedRegister['bytesType']\n : string\n : never)\n | (type extends readonly [] ? readonly [] : never)\n | (type extends Record\n ? { [K in keyof type]: Widen }\n : never)\n | (type extends { length: number }\n ? {\n [K in keyof type]: Widen\n } extends infer Val extends readonly unknown[]\n ? readonly [...Val]\n : never\n : never)\n\n/** @internal */\nexport function normalizeSignature(signature: string): string {\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', 'error', ''].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 Errors.BaseError('Unable to normalize signature.')\n\n return result\n}\n\n/** @internal */\nexport declare namespace normalizeSignature {\n export type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function isArgOfType(\n arg: unknown,\n abiParameter: AbiParameters.Parameter,\n): boolean {\n const argType = typeof arg\n const abiParameterType = abiParameter.type\n switch (abiParameterType) {\n case 'address':\n return Address.validate(arg as Address.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 AbiParameters.Parameter,\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 AbiParameters.Parameter),\n )\n )\n }\n\n return false\n }\n }\n}\n\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameters.Parameter[],\n targetParameters: readonly AbiParameters.Parameter[],\n args: ExtractArgs,\n): AbiParameters.Parameter['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 Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n if (types.includes('address') && types.includes('bytes'))\n return Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiConstructor.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `constructor` type. */\nexport type AbiConstructor = abitype.AbiConstructor\n\n/**\n * ABI-decodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const bytecode = '0x...'\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode,\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(constructor, { // [!code focus]\n * bytecode, // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.decode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param abiConstructor - The ABI Constructor to decode.\n * @param options - Decoding options.\n * @returns The decoded constructor inputs.\n */\nexport function decode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: decode.Options,\n): decode.ReturnType\nexport function decode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: decode.Options,\n): decode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: decode.Options]\n | [abiConstructor: AbiConstructor, options: decode.Options]\n): decode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n decode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, decode.Options]\n }\n return parameters as [AbiConstructor, decode.Options]\n })()\n\n const { bytecode } = options\n if (abiConstructor.inputs?.length === 0) return undefined\n const data = options.data.replace(bytecode, '0x') as Hex.Hex\n return AbiParameters.decode(abiConstructor.inputs, data)\n}\n\nexport declare namespace decode {\n interface Options {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The encoded constructor. */\n data: Hex.Hex\n }\n\n type ReturnType =\n | (abiConstructor['inputs']['length'] extends 0\n ? undefined\n : abitype.AbiParametersToPrimitiveTypes)\n | (IsNarrowable extends true\n ? never\n : undefined)\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.encode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n], // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiConstructor.encode` to encode the constructor of a contract and deploy it.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { AbiConstructor, Hex } from 'ox'\n *\n * // 1. Instantiate the ABI Constructor.\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner, uint256 amount)',\n * )\n *\n * // 2. Encode the ABI Constructor.\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * // 3. Deploy the contract.\n * const hash = await window.ethereum!.request({\n * method: 'eth_sendTransaction',\n * params: [{ data }],\n * })\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiConstructor - The ABI Constructor to encode.\n * @param options - Encoding options.\n * @returns The encoded constructor.\n */\nexport function encode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: encode.Options,\n): encode.ReturnType\nexport function encode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: encode.Options,\n): encode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: encode.Options]\n | [abiConstructor: AbiConstructor, options: encode.Options]\n): encode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n encode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, encode.Options]\n }\n\n return parameters as [AbiConstructor, encode.Options]\n })()\n\n const { bytecode, args } = options\n return Hex.concat(\n bytecode,\n abiConstructor.inputs?.length && args?.length\n ? AbiParameters.encode(abiConstructor.inputs, args as readonly unknown[])\n : '0x',\n )\n}\n\nexport declare namespace encode {\n type Options<\n abiConstructor extends AbiConstructor = AbiConstructor,\n ///\n args extends abitype.AbiParametersToPrimitiveTypes<\n abiConstructor['inputs']\n > = abitype.AbiParametersToPrimitiveTypes,\n > = {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The constructor arguments to encode. */\n args?: args | undefined\n } & (readonly [] extends args\n ? {}\n : {\n /** The constructor arguments to encode. */\n args: args\n })\n\n type ReturnType = Hex.Hex\n\n type ErrorType =\n | Hex.concat.ErrorType\n | AbiParameters.encode.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function format(\n abiConstructor: abiConstructor,\n): format.ReturnType\n/**\n * Formats an {@link ox#AbiConstructor.AbiConstructor} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const formatted = AbiConstructor.format({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiConstructor - The ABI Constructor to format.\n * @returns The formatted ABI Constructor.\n */\nexport function format(abiConstructor: AbiConstructor): string\n/** @internal */\nexport function format(abiConstructor: AbiConstructor): format.ReturnType {\n return abitype.formatAbiItem(abiConstructor)\n}\n\nexport declare namespace format {\n type ReturnType =\n abitype.FormatAbiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function from<\n const abiConstructor extends AbiConstructor | string | readonly string[],\n>(\n abiConstructor: (abiConstructor | string | readonly string[]) &\n (\n | (abiConstructor extends string\n ? internal.Signature\n : never)\n | (abiConstructor extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiConstructor\n ),\n): from.ReturnType\n/**\n * Parses an arbitrary **JSON ABI Constructor** or **Human Readable ABI Constructor** into a typed {@link ox#AbiConstructor.AbiConstructor}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner)' // [!code hl]\n * )\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from([\n * 'struct Foo { address owner; uint256 amount; }', // [!code hl]\n * 'constructor(Foo foo)',\n * ])\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiConstructor - The ABI Constructor to parse.\n * @returns Typed ABI Constructor.\n */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): AbiConstructor\n/** @internal */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): from.ReturnType {\n return AbiItem.from(abiConstructor as AbiConstructor)\n}\n\nexport declare namespace from {\n type ReturnType<\n abiConstructor extends\n | AbiConstructor\n | string\n | readonly string[] = AbiConstructor,\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function fromAbi(\n abi: abi | Abi.Abi | readonly unknown[],\n): fromAbi.ReturnType\n/**\n * Extracts an {@link ox#AbiConstructor.AbiConstructor} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Events can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([\n * 'constructor(address owner)',\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiConstructor.fromAbi(abi) // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @returns The ABI constructor.\n */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): AbiConstructor\n/** @internal */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): fromAbi.ReturnType {\n const item = (abi as Abi.Abi).find((item) => item.type === 'constructor')\n if (!item) throw new AbiItem.NotFoundError({ name: 'constructor' })\n return item\n}\n\nexport declare namespace fromAbi {\n type ReturnType = Extract<\n abi[number],\n { type: 'constructor' }\n >\n\n type ErrorType = AbiItem.NotFoundError | Errors.GlobalErrorType\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiFunction.js'\nimport type * as AbiItem_internal from './internal/abiItem.js'\nimport type * as AbiParameters_internal from './internal/abiParameters.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `function` type. */\nexport type AbiFunction = abitype.AbiFunction & {\n hash?: Hex.Hex | undefined\n overloads?: readonly AbiFunction[] | undefined\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type Foo = AbiFunction.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = abitype.ExtractAbiFunction\n\n/**\n * Extracts the names of all {@link ox#AbiFunction.AbiFunction} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type names = AbiFunction.Name\n * // ^?\n *\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames<\n abi extends Abi.Abi,\n abiStateMutability extends\n abitype.AbiStateMutability = abitype.AbiStateMutability,\n> = abitype.ExtractAbiFunctionNames\n\n/**\n * ABI-decodes function arguments according to the ABI Item's input types (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n *\n * const input = AbiFunction.decodeData(approve, data) // [!code focus]\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n * const data = '0x...\n *\n * const input = AbiFunction.decodeData(\n * abi, // [!code focus]\n * 'approve', // [!code focus]\n * data\n * )\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @param abiFunction - The ABI Item to decode.\n * @param data - The data to decode.\n */\nexport function decodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n): decodeData.ReturnType\nexport function decodeData(\n abiFunction: abiItem | AbiFunction,\n data: Hex.Hex,\n): decodeData.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeData(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: Hex.Hex | string, data: Hex.Hex]\n | [abiFunction: AbiFunction, data: Hex.Hex]\n) {\n const [abiFunction, data] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n ]\n return [fromAbi(abi, name), data]\n }\n return parameters as [AbiFunction, Hex.Hex]\n })()\n\n const { overloads } = abiFunction\n\n if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })\n if (abiFunction.inputs?.length === 0) return undefined\n\n const item = overloads\n ? fromAbi([abiFunction, ...overloads], data as never)\n : abiFunction\n\n if (Hex.size(data) <= 4) return undefined\n return AbiParameters.decode(item.inputs, Hex.slice(data, 4))\n}\n\nexport declare namespace decodeData {\n type ReturnType = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ? abiFunction['inputs'] extends readonly []\n ? undefined\n :\n | AbiParameters_internal.ToPrimitiveTypes\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? AbiParameters_internal.ToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >\n : never)\n : unknown\n\n type ErrorType =\n | fromAbi.ErrorType\n | AbiParameters.decode.ErrorType\n | Hex.size.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * ABI-decodes a function's result according to the ABI Item's output types (`outputs`).\n *\n * :::tip\n *\n * This function is typically used to decode contract function return values (e.g. the response of an `eth_call` or the `input` property of a Transaction).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply') // [!code hl]\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const output = AbiFunction.decodeResult(\n * erc20Abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * data\n * )\n * // @log: 42n\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.decodeResult` to decode the result of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input.\n * const data = AbiFunction.encodeData(\n * balanceOf,\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B']\n * )\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output. // [!code focus]\n * const balance = AbiFunction.decodeResult(balanceOf, response) // [!code focus]\n * // @log: 42n\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to decode\n * @param data - ABI-encoded function output\n * @param options - Decoding options\n * @returns Decoded function output\n */\nexport function decodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\nexport function decodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, data, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), data, options]\n }\n return parameters as [\n AbiFunction,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n })()\n\n const values = AbiParameters.decode(abiFunction.outputs, data, options)\n if (values && Object.keys(values).length === 0) return undefined\n if (values && Object.keys(values).length === 1) {\n if (Array.isArray(values)) return values[0]\n return Object.values(values)[0]\n }\n return values\n}\n\nexport declare namespace decodeResult {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Array' | 'Object' | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = IsNarrowable extends true\n ? abiFunction['outputs'] extends readonly []\n ? undefined\n : abiFunction['outputs'] extends readonly [\n infer type extends abitype.AbiParameter,\n ]\n ? abitype.AbiParameterToPrimitiveType\n : AbiParameters.decode.ReturnType<\n abiFunction['outputs'],\n as\n > extends infer types\n ? types extends readonly []\n ? undefined\n : types extends readonly [infer type]\n ? type\n : types\n : never\n : unknown\n\n type ErrorType = AbiParameters.decode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes function arguments (`inputs`), prefixed with the 4 byte function selector.\n *\n * :::tip\n *\n * This function is typically used to encode a contract function and its arguments for contract calls (e.g. `data` parameter of an `eth_call` or `eth_sendTransaction`).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData( // [!code focus]\n * approve, // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] // [!code focus]\n * ) // [!code focus]\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const approve = AbiFunction.fromAbi(erc20Abi, 'approve') // [!code hl]\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeData(\n * erc20Abi, // [!code focus]\n * 'approve', // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.encodeData` to encode the input of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input. // [!code focus]\n * const data = AbiFunction.encodeData( // [!code focus]\n * balanceOf, // [!code focus]\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] // [!code focus]\n * ) // [!code focus]\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output.\n * const balance = AbiFunction.decodeResult(balanceOf, response)\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to encode\n * @param args - Function arguments\n * @returns ABI-encoded function name and arguments\n */\nexport function encodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n ...args: encodeData.Args\n): Hex.Hex\nexport function encodeData(\n abiFunction: abiFunction | AbiFunction,\n ...args: encodeData.Args\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeData(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n ...args: readonly unknown[],\n ]\n | [abiFunction: AbiFunction, ...args: readonly unknown[]]\n) {\n const [abiFunction, args = []] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, args] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n readonly unknown[],\n ]\n return [fromAbi(abi, name, { args }), args]\n }\n const [abiFunction, args] = parameters as [AbiFunction, readonly unknown[]]\n return [abiFunction, args]\n })()\n\n const { overloads } = abiFunction\n\n const item = overloads\n ? (fromAbi([abiFunction as AbiFunction, ...overloads], abiFunction.name, {\n args,\n }) as AbiFunction)\n : abiFunction\n\n const selector = getSelector(item)\n\n const data =\n args.length > 0 ? AbiParameters.encode(item.inputs, args) : undefined\n\n return data ? Hex.concat(selector, data) : selector\n}\n\nexport declare namespace encodeData {\n type Args = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ?\n | (abitype.AbiParametersToPrimitiveTypes<\n abiFunction['inputs']\n > extends readonly []\n ? []\n : [abitype.AbiParametersToPrimitiveTypes])\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? [\n abitype.AbiParametersToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >,\n ]\n : [])\n : readonly unknown[]\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes a function's result (`outputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n * const output = AbiFunction.decodeResult(totalSupply, '0x000000000000000000000000000000000000000000000000000000000000002a')\n * // 42n\n *\n * const data = AbiFunction.encodeResult(totalSupply, 42n) // [!code focus]\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeResult(\n * abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * 42n\n * )\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @param abiFunction - The ABI item to encode the function output for.\n * @param output - The function output to encode.\n * @param options - Encoding options.\n * @returns The encoded function output.\n */\nexport function encodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n as extends 'Object' | 'Array' = 'Array',\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\nexport function encodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, output, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, output, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n any,\n encodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), output, options]\n }\n return parameters as [\n AbiFunction,\n any,\n encodeResult.Options | undefined,\n ]\n })()\n\n const { as = 'Array' } = options\n\n const values = (() => {\n if (abiFunction.outputs.length === 1) return [output]\n if (Array.isArray(output)) return output\n if (as === 'Object') return Object.values(output as any)\n return [output]\n })()\n\n return AbiParameters.encode(abiFunction.outputs, values)\n}\n\nexport declare namespace encodeResult {\n type Output<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = abiFunction['outputs'] extends readonly []\n ? never\n : abiFunction['outputs']['length'] extends 1\n ? AbiParameters_internal.ToPrimitiveTypes[0]\n : as extends 'Object'\n ? AbiParameters_internal.ToObject\n : AbiParameters_internal.ToPrimitiveTypes\n\n type Options = {\n as?: as | 'Object' | 'Array' | undefined\n }\n\n type ErrorType = AbiParameters.encode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Formats an {@link ox#AbiFunction.AbiFunction} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const formatted = AbiFunction.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiFunction - The ABI Function to format.\n * @returns The formatted ABI Function.\n */\nexport function format(\n abiFunction: abiFunction | AbiFunction,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiFunction) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Function** or **Human Readable ABI Function** into a typed {@link ox#AbiFunction.AbiFunction}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from({\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: [{ type: 'bool' }],\n * })\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiFunction - The ABI Function to parse.\n * @returns Typed ABI Function.\n */\nexport function from<\n const abiFunction extends AbiFunction | string | readonly string[],\n>(\n abiFunction: (abiFunction | AbiFunction | string | readonly string[]) &\n (\n | (abiFunction extends string ? internal.Signature : never)\n | (abiFunction extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiFunction\n ),\n options: from.Options = {},\n): from.ReturnType {\n return AbiItem.from(abiFunction as AbiFunction, options) as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted function (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction | string | readonly string[],\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Functions can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiFunction.fromAbi(abi, 'foo') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Functions can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiFunction.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Function from an `eth_call` RPC response or\n * from a Transaction `input`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: AbiItem.fromAbi.Options<\n abi,\n name,\n args,\n AbiItem_internal.ExtractArgs\n >,\n): AbiItem.fromAbi.ReturnType {\n const item = AbiItem.fromAbi(abi, name, options as any)\n if (item.type !== 'function')\n throw new AbiItem.NotFoundError({ name, type: 'function' })\n return item as never\n}\n\nexport declare namespace fromAbi {\n type ErrorType = AbiItem.fromAbi.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiFunction.AbiFunction}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector(abiItem: string | AbiFunction): Hex.Hex {\n return AbiItem.getSelector(abiItem)\n}\n\nexport declare namespace getSelector {\n type ErrorType = AbiItem.getSelector.ErrorType | Errors.GlobalErrorType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as AbiConstructor from 'ox/AbiConstructor'\nimport * as AbiFunction from 'ox/AbiFunction'\n\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { ethAddress, zeroAddress } from '../../constants/address.js'\nimport { deploylessCallViaBytecodeBytecode } from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { Mutable } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { hexToBigInt } from '../../utils/index.js'\nimport {\n type CreateAccessListErrorType,\n createAccessList,\n} from './createAccessList.js'\nimport {\n type SimulateBlocksErrorType,\n type SimulateBlocksParameters,\n simulateBlocks,\n} from './simulateBlocks.js'\n\nconst getBalanceCode =\n '0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033'\n\nexport type SimulateCallsParameters<\n calls extends readonly unknown[] = readonly unknown[],\n account extends Account | Address | undefined = Account | Address | undefined,\n> = Omit & {\n /** Account attached to the calls (msg.sender). */\n account?: account | undefined\n /** Calls to simulate. */\n calls: Calls>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n /** Whether to trace asset changes. */\n traceAssetChanges?: boolean | undefined\n}\n\nexport type SimulateCallsReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Asset changes. */\n assetChanges: readonly {\n token: {\n address: Address\n decimals?: number | undefined\n symbol?: string | undefined\n }\n value: { pre: bigint; post: bigint; diff: bigint }\n }[]\n /** Block results. */\n block: Block\n /** Call results. */\n results: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n}\n\nexport type SimulateCallsErrorType =\n | AbiFunction.encodeData.ErrorType\n | AbiFunction.from.ErrorType\n | CreateAccessListErrorType\n | EncodeFunctionDataErrorType\n | SimulateBlocksErrorType\n | ErrorType\n\n/**\n * Simulates execution of a batch of calls.\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateCalls } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulateCalls(client, {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n */\nexport async function simulateCalls<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateCallsParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag,\n calls,\n stateOverrides,\n traceAssetChanges,\n traceTransfers,\n validation,\n } = parameters\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n\n if (traceAssetChanges && !account)\n throw new BaseError(\n '`account` is required when `traceAssetChanges` is true',\n )\n\n // Derive bytecode to extract ETH balance via a contract call.\n const getBalanceData = account\n ? AbiConstructor.encode(AbiConstructor.from('constructor(bytes, bytes)'), {\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [\n getBalanceCode,\n AbiFunction.encodeData(\n AbiFunction.from('function getBalance(address)'),\n [account.address],\n ),\n ],\n })\n : undefined\n\n // Fetch ERC20/721 addresses that were \"touched\" from the calls.\n const assetAddresses = traceAssetChanges\n ? await Promise.all(\n parameters.calls.map(async (call: any) => {\n if (!call.data && !call.abi) return\n const { accessList } = await createAccessList(client, {\n account: account!.address,\n ...call,\n data: call.abi ? encodeFunctionData(call) : call.data,\n })\n return accessList.map(({ address, storageKeys }) =>\n storageKeys.length > 0 ? address : null,\n )\n }),\n ).then((x) => x.flat().filter(Boolean))\n : []\n\n const blocks = await simulateBlocks(client, {\n blockNumber,\n blockTag: blockTag as undefined,\n blocks: [\n ...(traceAssetChanges\n ? [\n // ETH pre balances\n {\n calls: [{ data: getBalanceData }],\n stateOverrides,\n },\n\n // Asset pre balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n\n {\n calls: [...calls, {}].map((call) => ({\n ...(call as Call),\n from: account?.address,\n })) as any,\n stateOverrides,\n },\n\n ...(traceAssetChanges\n ? [\n // ETH post balances\n {\n calls: [{ data: getBalanceData }],\n },\n\n // Asset post balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Decimals\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from('function decimals() returns (uint256)'),\n ],\n functionName: 'decimals',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Token URI\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from(\n 'function tokenURI(uint256) returns (string)',\n ),\n ],\n functionName: 'tokenURI',\n args: [0n],\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Symbols\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [AbiFunction.from('function symbol() returns (string)')],\n functionName: 'symbol',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n ],\n traceTransfers,\n validation,\n })\n\n const block_results = traceAssetChanges ? blocks[2] : blocks[0]\n const [\n block_ethPre,\n block_assetsPre,\n ,\n block_ethPost,\n block_assetsPost,\n block_decimals,\n block_tokenURI,\n block_symbols,\n ] = traceAssetChanges ? blocks : []\n\n // Extract call results from the simulation.\n const { calls: block_calls, ...block } = block_results\n const results = block_calls.slice(0, -1) ?? []\n\n // Extract pre-execution ETH and asset balances.\n const ethPre = block_ethPre?.calls ?? []\n const assetsPre = block_assetsPre?.calls ?? []\n const balancesPre = [...ethPre, ...assetsPre].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract post-execution ETH and asset balances.\n const ethPost = block_ethPost?.calls ?? []\n const assetsPost = block_assetsPost?.calls ?? []\n const balancesPost = [...ethPost, ...assetsPost].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract asset symbols & decimals.\n const decimals = (block_decimals?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (number | null)[]\n const symbols = (block_symbols?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n const tokenURI = (block_tokenURI?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n\n const changes: Mutable['assetChanges']> = []\n for (const [i, balancePost] of balancesPost.entries()) {\n const balancePre = balancesPre[i]\n\n if (typeof balancePost !== 'bigint') continue\n if (typeof balancePre !== 'bigint') continue\n\n const decimals_ = decimals[i - 1]\n const symbol_ = symbols[i - 1]\n const tokenURI_ = tokenURI[i - 1]\n\n const token = (() => {\n if (i === 0)\n return {\n address: ethAddress,\n decimals: 18,\n symbol: 'ETH',\n }\n\n return {\n address: assetAddresses[i - 1]! as Address,\n decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined,\n symbol: symbol_ ?? undefined,\n }\n })()\n\n if (changes.some((change) => change.token.address === token.address))\n continue\n\n changes.push({\n token,\n value: {\n pre: balancePre,\n post: balancePost,\n diff: balancePost - balancePre,\n },\n })\n }\n\n return {\n assetChanges: changes,\n block,\n results,\n } as unknown as SimulateCallsReturnType\n}\n","export const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const\n\nexport const zeroAddress = '0x0000000000000000000000000000000000000000' as const\n","import type * as Abi from '../core/Abi.js'\nimport * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-6492 signature. */\nexport type Unwrapped = {\n /** Calldata to pass to the target address for counterfactual verification. */\n data: Hex.Hex\n /** The original signature. */\n signature: Hex.Hex\n /** The target address to use for counterfactual verification. */\n to: Address.Address\n}\n\n/** Wrapped ERC-6492 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-6492 wrapped signatures.\n */\nexport const magicBytes =\n '0x6492649264926492649264926492649264926492649264926492649264926492' as const\n\n/**\n * Deployless ERC-6492 signature verification bytecode.\n */\nexport const universalSignatureValidatorBytecode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\n/**\n * ABI for the ERC-6492 universal deployless signature validator contract.\n *\n * Constructor return value is `0x1` (valid) or `0x0` (invalid).\n */\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 satisfies Abi.Abi\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * SignatureErc6492.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-6492 wrapped signature.\n * ```\n *\n * @param wrapped - The wrapped signature to assert.\n */\nexport function assert(wrapped: Wrapped) {\n if (Hex.slice(wrapped, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(wrapped)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc6492.from('0x...') // [!code focus]\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc6492.from({ // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * to: '0x...', // [!code focus]\n * })\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', }\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function from(wrapped: Unwrapped | Wrapped): Unwrapped {\n if (typeof wrapped === 'string') return unwrap(wrapped)\n return wrapped\n}\n\nexport declare namespace from {\n type ReturnType = Unwrapped\n\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const { data, signature, to } = SignatureErc6492.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const [to, data, signature] = AbiParameters.decode(\n AbiParameters.from('address, bytes, bytes'),\n wrapped,\n )\n\n return { data, signature, to }\n}\n\nexport declare namespace unwrap {\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc6492.wrap({ // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * to: '0x00000000219ab540356cBB839Cbe05303d7705Fa', // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Wrapped signature to serialize.\n * @returns Serialized wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature, to } = value\n\n return Hex.concat(\n AbiParameters.encode(AbiParameters.from('address, bytes, bytes'), [\n to,\n data,\n signature,\n ]),\n magicBytes,\n )\n}\n\nexport declare namespace wrap {\n type ErrorType =\n | AbiParameters.encode.ErrorType\n | Hex.concat.ErrorType\n | Signature.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const valid = SignatureErc6492.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param wrapped - The wrapped signature to validate.\n * @returns `true` if the wrapped signature is valid, `false` otherwise.\n */\nexport function validate(wrapped: Wrapped): boolean {\n try {\n assert(wrapped)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-6492 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc6492.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-6492 wrapped signature.`)\n }\n}\n","import type { Address } from 'abitype'\nimport { SignatureErc6492 } from 'ox/erc6492'\nimport { SignatureErc8010 } from 'ox/erc8010'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n erc1271Abi,\n erc6492SignatureValidatorAbi,\n multicall3Abi,\n} from '../../constants/abis.js'\nimport {\n erc6492SignatureValidatorByteCode,\n multicall3Bytecode,\n} from '../../constants/contracts.js'\nimport {\n CallExecutionError,\n ContractFunctionExecutionError,\n} from '../../errors/contract.js'\nimport type { InvalidHexBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.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 {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../../utils/address/isAddressEqual.js'\nimport { verifyAuthorization } from '../../utils/authorization/verifyAuthorization.js'\nimport { type ConcatHexErrorType, concatHex } from '../../utils/data/concat.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { hexToBool } from '../../utils/encoding/fromHex.js'\nimport {\n type BytesToHexErrorType,\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../utils/signature/recoverAddress.js'\nimport {\n type SerializeSignatureErrorType,\n serializeSignature,\n} from '../../utils/signature/serializeSignature.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type VerifyHashParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n /** The address that signed the original message. */\n address: Address\n /** The chain to use. */\n chain?: Chain | null | undefined\n /** The address of the ERC-6492 signature verifier contract. */\n erc6492VerifierAddress?: Address | undefined\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n /** @deprecated use `erc6492VerifierAddress` instead. */\n universalSignatureVerifierAddress?: Address | undefined\n} & OneOf<{ factory: Address; factoryData: Hex } | {}>\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n | BytesToHexErrorType\n | CallErrorType\n | ConcatHexErrorType\n | EncodeDeployDataErrorType\n | EncodeFunctionDataErrorType\n | ErrorType\n | GetAddressErrorType\n | GetCodeErrorType\n | InvalidHexBooleanError\n | IsAddressEqualErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ReadContractErrorType\n | RecoverAddressErrorType\n | SerializeSignatureErrorType\n\n/**\n * Verifies a message hash onchain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash(\n client: Client,\n parameters: VerifyHashParameters,\n): Promise {\n const {\n address,\n chain = client.chain,\n hash,\n erc6492VerifierAddress:\n verifierAddress = parameters.universalSignatureVerifierAddress ??\n chain?.contracts?.erc6492Verifier?.address,\n multicallAddress = parameters.multicallAddress ??\n chain?.contracts?.multicall3?.address,\n } = parameters\n\n if (chain?.verifyHash) return await chain.verifyHash(client, parameters)\n\n const signature = (() => {\n const signature = parameters.signature\n if (isHex(signature)) return signature\n if (typeof signature === 'object' && 'r' in signature && 's' in signature)\n return serializeSignature(signature)\n return bytesToHex(signature)\n })()\n\n try {\n if (SignatureErc8010.validate(signature))\n return await verifyErc8010(client, {\n ...parameters,\n multicallAddress,\n signature,\n })\n return await verifyErc6492(client, {\n ...parameters,\n verifierAddress,\n signature,\n })\n } catch (error) {\n // Fallback attempt to verify the signature via ECDSA recovery.\n try {\n const verified = isAddressEqual(\n getAddress(address),\n await recoverAddress({ hash, signature }),\n )\n if (verified) return true\n } catch {}\n\n if (error instanceof VerificationError) {\n // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n // this can happen for many reasons, for example if signer can not be recovered from the signature\n // or if the signature has no valid format\n return false\n }\n\n throw error\n }\n}\n\n/** @internal */\nexport async function verifyErc8010(\n client: Client,\n parameters: verifyErc8010.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, multicallAddress } = parameters\n\n const {\n authorization: authorization_ox,\n data: initData,\n signature,\n to,\n } = SignatureErc8010.unwrap(parameters.signature)\n\n // Check if already delegated\n const code = await getCode(client, {\n address,\n blockNumber,\n blockTag,\n } as never)\n\n // If already delegated, perform standard ERC-1271 verification.\n if (code === concatHex(['0xef0100', authorization_ox.address]))\n return await verifyErc1271(client, {\n address,\n blockNumber,\n blockTag,\n hash,\n signature,\n })\n\n const authorization = {\n address: authorization_ox.address,\n chainId: Number(authorization_ox.chainId),\n nonce: Number(authorization_ox.nonce),\n r: numberToHex(authorization_ox.r, { size: 32 }),\n s: numberToHex(authorization_ox.s, { size: 32 }),\n yParity: authorization_ox.yParity,\n } as const\n\n const valid = await verifyAuthorization({\n address,\n authorization,\n })\n if (!valid) throw new VerificationError()\n\n // Deployless verification.\n const results = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress\n ? { address: multicallAddress }\n : { code: multicall3Bytecode }),\n authorizationList: [authorization],\n abi: multicall3Abi,\n blockNumber,\n blockTag: 'pending',\n functionName: 'aggregate3',\n args: [\n [\n ...(initData\n ? ([\n {\n allowFailure: true,\n target: to ?? address,\n callData: initData,\n },\n ] as const)\n : []),\n {\n allowFailure: true,\n target: address,\n callData: encodeFunctionData({\n abi: erc1271Abi,\n functionName: 'isValidSignature',\n args: [hash, signature],\n }),\n },\n ],\n ],\n })\n\n const data = results[results.length - 1]?.returnData\n\n if (data?.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc8010 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nasync function verifyErc6492(\n client: Client,\n parameters: verifyErc6492.Parameters,\n) {\n const {\n address,\n factory,\n factoryData,\n hash,\n signature,\n verifierAddress,\n ...rest\n } = parameters\n\n const wrappedSignature = await (async () => {\n // If no `factory` or `factoryData` is provided, it is assumed that the\n // address is not a Smart Account, or the Smart Account is already deployed.\n if (!factory && !factoryData) return signature\n\n // If the signature is already wrapped, return the signature.\n if (SignatureErc6492.validate(signature)) return signature\n\n // If the Smart Account is not deployed, wrap the signature with a 6492 wrapper\n // to perform counterfactual validation.\n return SignatureErc6492.wrap({\n data: factoryData!,\n signature,\n to: factory!,\n })\n })()\n\n const args = verifierAddress\n ? ({\n to: verifierAddress,\n data: encodeFunctionData({\n abi: erc6492SignatureValidatorAbi,\n functionName: 'isValidSig',\n args: [address, hash, wrappedSignature],\n }),\n ...rest,\n } as unknown as CallParameters)\n : ({\n data: encodeDeployData({\n abi: erc6492SignatureValidatorAbi,\n args: [address, hash, wrappedSignature],\n bytecode: erc6492SignatureValidatorByteCode,\n }),\n ...rest,\n } as unknown as CallParameters)\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )(args).catch((error) => {\n if (error instanceof CallExecutionError) throw new VerificationError()\n throw error\n })\n\n if (hexToBool(data ?? '0x0')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc6492 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n /** The address of the ERC-6492 signature verifier contract. */\n verifierAddress?: Address | undefined\n } & OneOf<{ factory: Address; factoryData: Hex } | {}>\n}\n\n/** @internal */\nexport async function verifyErc1271(\n client: Client,\n parameters: verifyErc1271.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, signature } = parameters\n\n const result = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address,\n abi: erc1271Abi,\n args: [hash, signature],\n blockNumber,\n blockTag,\n functionName: 'isValidSignature',\n }).catch((error) => {\n if (error instanceof ContractFunctionExecutionError)\n throw new VerificationError()\n throw error\n })\n\n if (result.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc1271 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\nclass VerificationError extends Error {}\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","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ByteArray,\n Hex,\n SignableMessage,\n Signature,\n} from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyMessageParameters = Prettify<\n Omit & {\n /** The address that signed the original message. */\n address: Address\n /** The message to be verified. */\n message: SignableMessage\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n }\n>\n\nexport type VerifyMessageReturnType = boolean\n\nexport type VerifyMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\nexport async function verifyMessage(\n client: Client,\n {\n address,\n message,\n factory,\n factoryData,\n signature,\n ...callRequest\n }: VerifyMessageParameters,\n): Promise {\n const hash = hashMessage(message)\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address, TypedData } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = Omit &\n TypedDataDefinition & {\n /** The address to verify the typed data for. */\n address: Address\n /** The signature to verify */\n signature: Hex | ByteArray | Signature\n }\n\nexport type VerifyTypedDataReturnType = boolean\n\nexport type VerifyTypedDataErrorType =\n | HashTypedDataErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\nexport async function verifyTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: VerifyTypedDataParameters,\n): Promise {\n const {\n address,\n factory,\n factoryData,\n signature,\n message,\n primaryType,\n types,\n domain,\n ...callRequest\n } = parameters as VerifyTypedDataParameters\n const hash = hashTypedData({ message, primaryType, types, domain })\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n TransactionNotFoundError,\n TransactionReceiptNotFoundError,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n type GetTransactionErrorType,\n type GetTransactionReturnType,\n getTransaction,\n} from './getTransaction.js'\nimport {\n type GetTransactionReceiptErrorType,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n type WatchBlockNumberErrorType,\n watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * Whether to check for transaction replacements.\n * @default true\n */\n checkReplacement?: boolean | undefined\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | WaitForTransactionReceiptTimeoutErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: WaitForTransactionReceiptParameters,\n): Promise> {\n const {\n checkReplacement = true,\n confirmations = 1,\n hash,\n onReplaced,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n } = parameters\n\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n const pollingInterval = (() => {\n if (parameters.pollingInterval) return parameters.pollingInterval\n if (client.chain?.experimental_preconfirmationTime)\n return client.chain.experimental_preconfirmationTime\n return client.pollingInterval\n })()\n\n let transaction: GetTransactionReturnType | undefined\n let replacedTransaction: GetTransactionReturnType | undefined\n let receipt: GetTransactionReceiptReturnType | undefined\n let retrying = false\n\n let _unobserve: () => void\n let _unwatch: () => void\n\n const { promise, resolve, reject } =\n withResolvers>()\n\n const timer = timeout\n ? setTimeout(() => {\n _unwatch?.()\n _unobserve?.()\n reject(new WaitForTransactionReceiptTimeoutError({ hash }))\n }, timeout)\n : undefined\n\n _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n async (emit) => {\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash }).catch(() => undefined)\n\n if (receipt && confirmations <= 1) {\n clearTimeout(timer)\n emit.resolve(receipt)\n _unobserve?.()\n return\n }\n\n _unwatch = getAction(\n client,\n watchBlockNumber,\n 'watchBlockNumber',\n )({\n emitMissed: true,\n emitOnBegin: true,\n poll: true,\n pollingInterval,\n async onBlockNumber(blockNumber_) {\n const done = (fn: () => void) => {\n clearTimeout(timer)\n _unwatch?.()\n fn()\n _unobserve?.()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\n\n try {\n // If we already have a valid receipt, let's check if we have enough\n // confirmations. If we do, then we can resolve.\n if (receipt) {\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n return\n }\n\n // Get the transaction to check if it's been replaced.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined transactions.\n if (checkReplacement && !transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\n },\n )\n retrying = false\n }\n\n // Get the receipt to check if it's been processed.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n } catch (err) {\n // If the receipt is not found, the transaction will be pending.\n // We need to check if it has potentially been replaced.\n if (\n err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\n\n try {\n replacedTransaction = transaction\n\n // Let's retrieve the transactions from the current block.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined blocks.\n retrying = true\n const block = await withRetry(\n () =>\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber,\n includeTransactions: true,\n }),\n {\n delay: retryDelay,\n retryCount,\n shouldRetry: ({ error }) =>\n error instanceof BlockNotFoundError,\n },\n )\n retrying = false\n\n const replacementTransaction = (\n block.transactions as {} as Transaction[]\n ).find(\n ({ from, nonce }) =>\n from === replacedTransaction!.from &&\n nonce === replacedTransaction!.nonce,\n )\n\n // If we couldn't find a replacement transaction, continue polling.\n if (!replacementTransaction) return\n\n // If we found a replacement transaction, return it's receipt.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({\n hash: replacementTransaction.hash,\n })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n let reason: ReplacementReason = 'replaced'\n if (\n replacementTransaction.to === replacedTransaction.to &&\n replacementTransaction.value === replacedTransaction.value &&\n replacementTransaction.input === replacedTransaction.input\n ) {\n reason = 'repriced'\n } else if (\n replacementTransaction.from === replacementTransaction.to &&\n replacementTransaction.value === 0n\n ) {\n reason = 'cancelled'\n }\n\n done(() => {\n emit.onReplaced?.({\n reason,\n replacedTransaction: replacedTransaction! as any,\n transaction: replacementTransaction,\n transactionReceipt: receipt!,\n })\n emit.resolve(receipt!)\n })\n } catch (err_) {\n done(() => emit.reject(err_))\n }\n } else {\n done(() => emit.reject(err))\n }\n }\n },\n })\n },\n )\n\n return promise\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n blockNumber: OnBlockNumberParameter,\n prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type WatchBlockNumberParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when a new block number is received. */\n onBlockNumber: OnBlockNumberFn\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n const pollBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) =>\n poll(\n async () => {\n try {\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({ cacheTime: 0 })\n\n if (prevBlockNumber !== undefined) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (blockNumber === prevBlockNumber) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n emit.onBlockNumber(i, prevBlockNumber)\n prevBlockNumber = i\n }\n }\n }\n\n // If the next block number is greater than the previous,\n // it is not in the past, and we can emit the new block number.\n if (\n prevBlockNumber === undefined ||\n blockNumber > prevBlockNumber\n ) {\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockReturnType, getBlock } from './getBlock.js'\n\nexport type OnBlockParameter<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = GetBlockReturnType\n\nexport type OnBlock<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = (\n block: OnBlockParameter,\n prevBlock: OnBlockParameter | undefined,\n) => void\n\nexport type WatchBlocksParameters<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** The callback to call when a new block is received. */\n onBlock: OnBlock\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n blockTag?: undefined\n emitMissed?: undefined\n emitOnBegin?: undefined\n includeTransactions?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** The block tag. Defaults to \"latest\". */\n blockTag?: blockTag | BlockTag | undefined\n /** Whether or not to emit the missed blocks to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the block to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to the client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlocksReturnType = () => void\n\nexport type WatchBlocksErrorType =\n | StringifyErrorType\n | PollErrorType\n | ErrorType\n\n/**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, watchBlocks, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlocks(client, {\n * onBlock: (block) => console.log(block),\n * })\n */\nexport function watchBlocks<\n transport extends Transport,\n chain extends Chain | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockTag = client.experimental_blockTag ?? 'latest',\n emitMissed = false,\n emitOnBegin = false,\n onBlock,\n onError,\n includeTransactions: includeTransactions_,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlocksParameters,\n): WatchBlocksReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const includeTransactions = includeTransactions_ ?? false\n\n let prevBlock:\n | GetBlockReturnType\n | undefined\n\n const pollBlocks = () => {\n const observerId = stringify([\n 'watchBlocks',\n client.uid,\n blockTag,\n emitMissed,\n emitOnBegin,\n includeTransactions,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlock, onError }, (emit) =>\n poll(\n async () => {\n try {\n const block = await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n if (block.number !== null && prevBlock?.number != null) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (block.number === prevBlock.number) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (block.number - prevBlock.number > 1 && emitMissed) {\n for (let i = prevBlock?.number + 1n; i < block.number; i++) {\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: i,\n includeTransactions,\n })) as GetBlockReturnType\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block\n }\n }\n }\n\n if (\n // If no previous block exists, emit.\n prevBlock?.number == null ||\n // If the block tag is \"pending\" with no block number, emit.\n (blockTag === 'pending' && block?.number == null) ||\n // If the next block number is greater than the previous block number, emit.\n // We don't want to emit blocks in the past.\n (block.number !== null && block.number > prevBlock.number)\n ) {\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block as any\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlocks = () => {\n let active = true\n let emitFetched = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n if (emitOnBegin) {\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n .then((block) => {\n if (!active) return\n if (!emitFetched) return\n onBlock(block as any, undefined)\n emitFetched = false\n })\n .catch(onError)\n }\n\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n async onData(data: any) {\n if (!active) return\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: data.result?.number,\n includeTransactions,\n }).catch(() => {})) as GetBlockReturnType\n if (!active) return\n onBlock(block as any, prevBlock as any)\n emitFetched = false\n prevBlock = block\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollBlocks() : subscribeBlocks()\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport {\n type CreateEventFilterParameters,\n createEventFilter,\n} from './createEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { type GetLogsParameters, getLogs } from './getLogs.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchEventOnLogsParameter<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n eventName extends string | undefined = MaybeAbiEventName,\n> = Log[]\nexport type WatchEventOnLogsFn<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = (\n logs: WatchEventOnLogsParameter,\n) => void\n\nexport type WatchEventParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchEventOnLogsFn\n} & GetPollOptions &\n (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: abiEvents | undefined\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n )\n\nexport type WatchEventReturnType = () => void\n\nexport type WatchEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchEvent } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchEvent(client, {\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchEvent<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n _eventName extends string | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n batch = true,\n event,\n events,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n }: WatchEventParameters,\n): WatchEventReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const strict = strict_ ?? false\n\n const pollEvent = () => {\n const observerId = stringify([\n 'watchEvent',\n address,\n args,\n batch,\n client.uid,\n event,\n pollingInterval,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abiEvents, _eventName, any>\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createEventFilter as any,\n 'createEventFilter',\n )({\n address,\n args,\n event: event!,\n events,\n strict,\n fromBlock,\n } as unknown as CreateEventFilterParameters)) as unknown as Filter<\n 'event',\n abiEvents,\n _eventName\n >\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n logs = await getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n event: event!,\n events,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n } as unknown as GetLogsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeEvent = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const events_ = events ?? (event ? [event] : undefined)\n let topics: LogTopic[] = []\n if (events_) {\n const encoded = (events_ as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: events_ ?? [],\n data: log.data,\n topics: log.topics,\n strict,\n })\n const formatted = formatLog(log, { args, eventName })\n onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollEvent() : subscribeEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { createPendingTransactionFilter } from './createPendingTransactionFilter.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type OnTransactionsParameter = Hash[]\nexport type OnTransactionsFn = (transactions: OnTransactionsParameter) => void\n\nexport type WatchPendingTransactionsParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new transactions are received. */\n onTransactions: OnTransactionsFn\n} & GetPollOptions\n\nexport type WatchPendingTransactionsReturnType = () => void\n\nexport type WatchPendingTransactionsErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param client - Client to use\n * @param parameters - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchPendingTransactions } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await watchPendingTransactions(client, {\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\nexport function watchPendingTransactions<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n {\n batch = true,\n onError,\n onTransactions,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchPendingTransactionsParameters,\n) {\n const enablePolling =\n typeof poll_ !== 'undefined'\n ? poll_\n : client.transport.type !== 'webSocket' && client.transport.type !== 'ipc'\n\n const pollPendingTransactions = () => {\n const observerId = stringify([\n 'watchPendingTransactions',\n client.uid,\n batch,\n pollingInterval,\n ])\n return observe(observerId, { onTransactions, onError }, (emit) => {\n let filter: Filter<'transaction'>\n\n const unwatch = poll(\n async () => {\n try {\n if (!filter) {\n try {\n filter = await getAction(\n client,\n createPendingTransactionFilter,\n 'createPendingTransactionFilter',\n )({})\n return\n } catch (err) {\n unwatch()\n throw err\n }\n }\n\n const hashes = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n if (hashes.length === 0) return\n if (batch) emit.onTransactions(hashes)\n else for (const hash of hashes) emit.onTransactions([hash])\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribePendingTransactions = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n params: ['newPendingTransactions'],\n onData(data: any) {\n if (!active) return\n const transaction = data.result\n onTransactions([transaction])\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling\n ? pollPendingTransactions()\n : subscribePendingTransactions()\n}\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\nimport type { SiweMessage } from './types.js'\n\n/**\n * @description Parses EIP-4361 formatted message into message fields object.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n *\n * @returns EIP-4361 fields object\n */\nexport function parseSiweMessage(\n message: string,\n): Prettify> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: Address\n domain: string\n scheme?: string\n statement?: string\n }\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string\n expirationTime?: string\n issuedAt?: string\n nonce: string\n notBefore?: string\n requestId?: string\n uri: string\n version: '1'\n }\n const resources = message.split('Resources:')[1]?.split('\\n- ').slice(1)\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n }\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\\n)(?
0x[a-fA-F0-9]{40})\\n\\n(?:(?.*)\\n\\n)?/\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?.+))\\n(?:Version: (?.+))\\n(?:Chain ID: (?\\d+))\\n(?:Nonce: (?[a-zA-Z0-9]+))\\n(?:Issued At: (?.+))(?:\\nExpiration Time: (?.+))?(?:\\nNot Before: (?.+))?(?:\\nRequest ID: (?.+))?/\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport type { SiweMessage } from './types.js'\n\nexport type ValidateSiweMessageParameters = {\n /**\n * Ethereum address to check against.\n */\n address?: Address | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined\n /**\n * EIP-4361 message fields.\n */\n message: ExactPartial\n /**\n * Random string to check against.\n */\n nonce?: string | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined\n}\n\nexport type ValidateSiweMessageReturnType = boolean\n\n/**\n * @description Validates EIP-4361 message.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n */\nexport function validateSiweMessage(\n parameters: ValidateSiweMessageParameters,\n): ValidateSiweMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters\n\n if (domain && message.domain !== domain) return false\n if (nonce && message.nonce !== nonce) return false\n if (scheme && message.scheme !== scheme) return false\n\n if (message.expirationTime && time >= message.expirationTime) return false\n if (message.notBefore && time < message.notBefore) return false\n\n try {\n if (!message.address) return false\n if (!isAddress(message.address, { strict: false })) return false\n if (address && !isAddressEqual(message.address, address)) return false\n } catch {\n return false\n }\n\n return true\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport { parseSiweMessage } from '../../utils/siwe/parseSiweMessage.js'\nimport {\n type ValidateSiweMessageParameters,\n validateSiweMessage,\n} from '../../utils/siwe/validateSiweMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from '../public/verifyHash.js'\n\nexport type VerifySiweMessageParameters = Prettify<\n Pick &\n Pick<\n ValidateSiweMessageParameters,\n 'address' | 'domain' | 'nonce' | 'scheme' | 'time'\n > & {\n /**\n * EIP-4361 formatted message.\n */\n message: string\n /**\n * Signature to check against.\n */\n signature: Hex\n }\n>\n\nexport type VerifySiweMessageReturnType = boolean\n\nexport type VerifySiweMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\nexport async function verifySiweMessage(\n client: Client,\n parameters: VerifySiweMessageParameters,\n): Promise {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n ...callRequest\n } = parameters\n\n const parsed = parseSiweMessage(message)\n if (!parsed.address) return false\n\n const isValid = validateSiweMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n })\n if (!isValid) return false\n\n const hash = hashMessage(message)\n return verifyHash(client, {\n address: parsed.address,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionReceiptRevertedError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { formatTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport type { FormattedTransactionReceipt } from '../../utils/index.js'\n\nexport type SendRawTransactionSyncParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n /** Whether to throw an error if the transaction was detected as reverted. @default true */\n throwOnReceiptRevert?: boolean | undefined\n /** The timeout for the transaction. */\n timeout?: number | undefined\n}\n\nexport type SendRawTransactionSyncReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type SendRawTransactionSyncErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network synchronously,\n * and waits for the transaction to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await sendRawTransactionSync(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransactionSync(\n client: Client,\n {\n serializedTransaction,\n throwOnReceiptRevert,\n timeout,\n }: SendRawTransactionSyncParameters,\n): Promise> {\n const receipt = await client.request(\n {\n method: 'eth_sendRawTransactionSync',\n params: timeout\n ? [serializedTransaction, timeout]\n : [serializedTransaction],\n },\n { retryCount: 0 },\n )\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n\n const formatted = format(receipt) as SendRawTransactionSyncReturnType\n if (formatted.status === 'reverted' && throwOnReceiptRevert)\n throw new TransactionReceiptRevertedError({ receipt: formatted })\n return formatted\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account, ParseAccount } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { PublicRpcSchema, RpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n} from './createClient.js'\nimport { type PublicActions, publicActions } from './decorators/public.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type PublicClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Pick<\n ClientConfig,\n | 'batch'\n | 'cacheTime'\n | 'ccipRead'\n | 'chain'\n | 'experimental_blockTag'\n | 'key'\n | 'name'\n | 'pollingInterval'\n | 'rpcSchema'\n | 'transport'\n >\n>\n\nexport type PublicClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Client<\n transport,\n chain,\n accountOrAddress,\n rpcSchema extends RpcSchema\n ? [...PublicRpcSchema, ...rpcSchema]\n : PublicRpcSchema,\n PublicActions\n >\n>\n\nexport type CreatePublicClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://viem.sh/docs/clients/public\n *\n * A Public Client is an interface to \"public\" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param config - {@link PublicClientConfig}\n * @returns A Public Client. {@link PublicClient}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: PublicClientConfig,\n): PublicClient, rpcSchema> {\n const { key = 'public', name = 'Public Client' } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n type: 'publicClient',\n })\n return client.extend(publicActions) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { OneOf } from '../../types/utils.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** Methods to include or exclude from executing RPC requests. */\n methods?:\n | OneOf<\n | {\n include?: string[] | undefined\n }\n | {\n exclude?: string[] | undefined\n }\n >\n | undefined\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = ({\n chain,\n}: {\n account?: Account | undefined\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record,\n>(\n {\n key,\n methods,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig,\n value?: rpcAttributes | undefined,\n): ReturnType> {\n const uid = uid_()\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\n value,\n }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { EIP1193RequestFn, RpcSchema } from '../../types/eip1193.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n getHttpRpcClient,\n type HttpRpcClientOptions,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './createTransport.js'\n\nexport type HttpTransportConfig<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** Methods to include or exclude from executing RPC requests. */\n methods?: TransportConfig['methods'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** Whether to return JSON RPC errors as responses instead of throwing. */\n raw?: raw | boolean | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** Typed JSON-RPC schema for the transport. */\n rpcSchema?: rpcSchema | RpcSchema | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n },\n EIP1193RequestFn\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n>(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig = {},\n): HttpTransport {\n const {\n batch,\n fetchFn,\n fetchOptions,\n key = 'http',\n methods,\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n raw,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchFn,\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n methods,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n\n if (raw) return { error, result }\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type AbiParameter,\n type AbiParameterKind,\n type AbiParameterToPrimitiveType,\n type AbiStateMutability,\n type Address,\n CircularReferenceError,\n InvalidAbiItemError,\n InvalidAbiParameterError,\n InvalidAbiParametersError,\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n InvalidParenthesisError,\n InvalidSignatureError,\n InvalidStructSignatureError,\n type Narrow,\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n SolidityProtectedKeywordError,\n type TypedData,\n type TypedDataDomain,\n type TypedDataParameter,\n UnknownSignatureError,\n UnknownTypeError,\n} from 'abitype'\nexport type {\n BlockOverrides,\n Rpc as RpcBlockOverrides,\n} from 'ox/BlockOverrides'\nexport type { EntryPointVersion } from './account-abstraction/types/entryPointVersion.js'\nexport type {\n RpcEstimateUserOperationGasReturnType,\n RpcGetUserOperationByHashReturnType,\n RpcUserOperation,\n RpcUserOperationReceipt,\n RpcUserOperationRequest,\n} from './account-abstraction/types/rpc.js'\nexport type {\n EstimateUserOperationGasReturnType,\n GetUserOperationByHashReturnType,\n PackedUserOperation,\n UserOperation,\n UserOperationReceipt,\n UserOperationRequest,\n} from './account-abstraction/types/userOperation.js'\nexport type {\n Account,\n AccountSource,\n CustomSource,\n HDAccount,\n HDOptions,\n JsonRpcAccount,\n LocalAccount,\n PrivateKeyAccount,\n} from './accounts/types.js'\nexport type {\n GetEnsAddressErrorType,\n GetEnsAddressParameters,\n GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n GetEnsAvatarErrorType,\n GetEnsAvatarParameters,\n GetEnsAvatarReturnType,\n} from './actions/ens/getEnsAvatar.js'\nexport type {\n GetEnsNameErrorType,\n GetEnsNameParameters,\n GetEnsNameReturnType,\n} from './actions/ens/getEnsName.js'\nexport type {\n GetEnsResolverErrorType,\n GetEnsResolverParameters,\n GetEnsResolverReturnType,\n} from './actions/ens/getEnsResolver.js'\nexport type {\n GetEnsTextErrorType,\n GetEnsTextParameters,\n GetEnsTextReturnType,\n} from './actions/ens/getEnsText.js'\nexport {\n type GetContractErrorType,\n type GetContractParameters,\n type GetContractReturnType,\n getContract,\n} from './actions/getContract.js'\nexport type {\n CallErrorType,\n CallParameters,\n CallReturnType,\n} from './actions/public/call.js'\nexport type {\n CreateAccessListErrorType,\n CreateAccessListParameters,\n CreateAccessListReturnType,\n} from './actions/public/createAccessList.js'\nexport type {\n CreateBlockFilterErrorType,\n CreateBlockFilterReturnType,\n} from './actions/public/createBlockFilter.js'\nexport type {\n CreateContractEventFilterErrorType,\n CreateContractEventFilterParameters,\n CreateContractEventFilterReturnType,\n} from './actions/public/createContractEventFilter.js'\nexport type {\n CreateEventFilterErrorType,\n CreateEventFilterParameters,\n CreateEventFilterReturnType,\n} from './actions/public/createEventFilter.js'\nexport type {\n CreatePendingTransactionFilterErrorType,\n CreatePendingTransactionFilterReturnType,\n} from './actions/public/createPendingTransactionFilter.js'\nexport type {\n EstimateContractGasErrorType,\n EstimateContractGasParameters,\n EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n EstimateFeesPerGasErrorType,\n EstimateFeesPerGasParameters,\n EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n EstimateGasErrorType,\n EstimateGasParameters,\n EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n EstimateMaxPriorityFeePerGasErrorType,\n EstimateMaxPriorityFeePerGasParameters,\n EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n FillTransactionErrorType,\n FillTransactionParameters,\n FillTransactionReturnType,\n} from './actions/public/fillTransaction.js'\nexport type {\n GetBalanceErrorType,\n GetBalanceParameters,\n GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n GetBlobBaseFeeErrorType,\n GetBlobBaseFeeReturnType,\n} from './actions/public/getBlobBaseFee.js'\nexport type {\n GetBlockErrorType,\n GetBlockParameters,\n GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n GetBlockNumberErrorType,\n GetBlockNumberParameters,\n GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n GetBlockTransactionCountErrorType,\n GetBlockTransactionCountParameters,\n GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n GetChainIdErrorType,\n GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n /** @deprecated Use `GetCodeErrorType` instead */\n GetCodeErrorType as GetBytecodeErrorType,\n GetCodeErrorType,\n /** @deprecated Use `GetCodeParameters` instead */\n GetCodeParameters as GetBytecodeParameters,\n GetCodeParameters,\n /** @deprecated Use `GetCodeReturnType` instead */\n GetCodeReturnType as GetBytecodeReturnType,\n GetCodeReturnType,\n} from './actions/public/getCode.js'\nexport type {\n GetContractEventsErrorType,\n GetContractEventsParameters,\n GetContractEventsReturnType,\n} from './actions/public/getContractEvents.js'\nexport type {\n GetDelegationErrorType,\n GetDelegationParameters,\n GetDelegationReturnType,\n} from './actions/public/getDelegation.js'\nexport type {\n GetEip712DomainErrorType,\n GetEip712DomainParameters,\n GetEip712DomainReturnType,\n} from './actions/public/getEip712Domain.js'\nexport type {\n GetFeeHistoryErrorType,\n GetFeeHistoryParameters,\n GetFeeHistoryReturnType,\n} from './actions/public/getFeeHistory.js'\nexport type {\n GetFilterChangesErrorType,\n GetFilterChangesParameters,\n GetFilterChangesReturnType,\n} from './actions/public/getFilterChanges.js'\nexport type {\n GetFilterLogsErrorType,\n GetFilterLogsParameters,\n GetFilterLogsReturnType,\n} from './actions/public/getFilterLogs.js'\nexport type {\n GetGasPriceErrorType,\n GetGasPriceReturnType,\n} from './actions/public/getGasPrice.js'\nexport type {\n GetLogsErrorType,\n GetLogsParameters,\n GetLogsReturnType,\n} from './actions/public/getLogs.js'\nexport type {\n GetProofErrorType,\n GetProofParameters,\n GetProofReturnType,\n} from './actions/public/getProof.js'\nexport type {\n GetStorageAtErrorType,\n GetStorageAtParameters,\n GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n GetTransactionErrorType,\n GetTransactionParameters,\n GetTransactionReturnType,\n} from './actions/public/getTransaction.js'\nexport type {\n GetTransactionConfirmationsErrorType,\n GetTransactionConfirmationsParameters,\n GetTransactionConfirmationsReturnType,\n} from './actions/public/getTransactionConfirmations.js'\nexport type {\n GetTransactionCountErrorType,\n GetTransactionCountParameters,\n GetTransactionCountReturnType,\n} from './actions/public/getTransactionCount.js'\nexport type {\n GetTransactionReceiptErrorType,\n GetTransactionReceiptParameters,\n GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n MulticallErrorType,\n MulticallParameters,\n MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n ReadContractErrorType,\n ReadContractParameters,\n ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n SimulateBlocksErrorType,\n SimulateBlocksParameters,\n SimulateBlocksReturnType,\n} from './actions/public/simulateBlocks.js'\nexport type {\n SimulateCallsErrorType,\n SimulateCallsParameters,\n SimulateCallsReturnType,\n} from './actions/public/simulateCalls.js'\nexport type {\n GetMutabilityAwareValue,\n SimulateContractErrorType,\n SimulateContractParameters,\n SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n UninstallFilterErrorType,\n UninstallFilterParameters,\n UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n VerifyHashErrorType as VerifyHashActionErrorType,\n VerifyHashParameters as VerifyHashActionParameters,\n VerifyHashReturnType as VerifyHashActionReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n VerifyMessageErrorType as VerifyMessageActionErrorType,\n VerifyMessageParameters as VerifyMessageActionParameters,\n VerifyMessageReturnType as VerifyMessageActionReturnType,\n} from './actions/public/verifyMessage.js'\nexport type {\n VerifyTypedDataErrorType as VerifyTypedDataActionErrorType,\n VerifyTypedDataParameters as VerifyTypedDataActionParameters,\n VerifyTypedDataReturnType as VerifyTypedDataActionReturnType,\n} from './actions/public/verifyTypedData.js'\nexport type {\n ReplacementReason,\n ReplacementReturnType,\n WaitForTransactionReceiptErrorType,\n WaitForTransactionReceiptParameters,\n WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n OnBlockNumberFn,\n OnBlockNumberParameter,\n WatchBlockNumberErrorType,\n WatchBlockNumberParameters,\n WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n OnBlock,\n OnBlockParameter,\n WatchBlocksErrorType,\n WatchBlocksParameters,\n WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n WatchContractEventErrorType,\n WatchContractEventOnLogsFn,\n WatchContractEventOnLogsParameter,\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n WatchEventErrorType,\n WatchEventOnLogsFn,\n WatchEventOnLogsParameter,\n WatchEventParameters,\n WatchEventReturnType,\n} from './actions/public/watchEvent.js'\nexport type {\n OnTransactionsFn,\n OnTransactionsParameter,\n WatchPendingTransactionsErrorType,\n WatchPendingTransactionsParameters,\n WatchPendingTransactionsReturnType,\n} from './actions/public/watchPendingTransactions.js'\nexport type {\n DropTransactionErrorType,\n DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n DumpStateErrorType,\n DumpStateReturnType,\n} from './actions/test/dumpState.js'\nexport type {\n GetAutomineErrorType,\n GetAutomineReturnType,\n} from './actions/test/getAutomine.js'\nexport type {\n GetTxpoolContentErrorType,\n GetTxpoolContentReturnType,\n} from './actions/test/getTxpoolContent.js'\nexport type {\n GetTxpoolStatusErrorType,\n GetTxpoolStatusReturnType,\n} from './actions/test/getTxpoolStatus.js'\nexport type {\n ImpersonateAccountErrorType,\n ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n IncreaseTimeErrorType,\n IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type {\n InspectTxpoolErrorType,\n InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type {\n LoadStateErrorType,\n LoadStateParameters,\n LoadStateReturnType,\n} from './actions/test/loadState.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type { RemoveBlockTimestampIntervalErrorType } from './actions/test/removeBlockTimestampInterval.js'\nexport type { ResetErrorType, ResetParameters } from './actions/test/reset.js'\nexport type {\n RevertErrorType,\n RevertParameters,\n} from './actions/test/revert.js'\nexport type {\n SendUnsignedTransactionErrorType,\n SendUnsignedTransactionParameters,\n SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type { SetAutomineErrorType } from './actions/test/setAutomine.js'\nexport type {\n SetBalanceErrorType,\n SetBalanceParameters,\n} from './actions/test/setBalance.js'\nexport type {\n SetBlockGasLimitErrorType,\n SetBlockGasLimitParameters,\n} from './actions/test/setBlockGasLimit.js'\nexport type {\n SetBlockTimestampIntervalErrorType,\n SetBlockTimestampIntervalParameters,\n} from './actions/test/setBlockTimestampInterval.js'\nexport type {\n SetCodeErrorType,\n SetCodeParameters,\n} from './actions/test/setCode.js'\nexport type {\n SetCoinbaseErrorType,\n SetCoinbaseParameters,\n} from './actions/test/setCoinbase.js'\nexport type {\n SetIntervalMiningErrorType,\n SetIntervalMiningParameters,\n} from './actions/test/setIntervalMining.js'\nexport type { SetLoggingEnabledErrorType } from './actions/test/setLoggingEnabled.js'\nexport type {\n SetMinGasPriceErrorType,\n SetMinGasPriceParameters,\n} from './actions/test/setMinGasPrice.js'\nexport type {\n SetNextBlockBaseFeePerGasErrorType,\n SetNextBlockBaseFeePerGasParameters,\n} from './actions/test/setNextBlockBaseFeePerGas.js'\nexport type {\n SetNextBlockTimestampErrorType,\n SetNextBlockTimestampParameters,\n} from './actions/test/setNextBlockTimestamp.js'\nexport type {\n SetNonceErrorType,\n SetNonceParameters,\n} from './actions/test/setNonce.js'\nexport type { SetRpcUrlErrorType } from './actions/test/setRpcUrl.js'\nexport type {\n SetStorageAtErrorType,\n SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type { SnapshotErrorType } from './actions/test/snapshot.js'\nexport type {\n StopImpersonatingAccountErrorType,\n StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n AddChainErrorType,\n AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport type {\n DeployContractErrorType,\n DeployContractParameters,\n DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n GetAddressesErrorType,\n GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n GetCallsStatusErrorType,\n GetCallsStatusParameters,\n GetCallsStatusReturnType,\n} from './actions/wallet/getCallsStatus.js'\nexport type {\n GetCapabilitiesErrorType,\n GetCapabilitiesParameters,\n GetCapabilitiesReturnType,\n} from './actions/wallet/getCapabilities.js'\nexport type {\n GetPermissionsErrorType,\n GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n PrepareAuthorizationErrorType,\n PrepareAuthorizationParameters,\n PrepareAuthorizationReturnType,\n} from './actions/wallet/prepareAuthorization.js'\nexport type {\n PrepareTransactionRequestErrorType,\n PrepareTransactionRequestParameters,\n PrepareTransactionRequestParameterType,\n PrepareTransactionRequestRequest,\n PrepareTransactionRequestReturnType,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n RequestAddressesErrorType,\n RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n RequestPermissionsErrorType,\n RequestPermissionsParameters,\n RequestPermissionsReturnType,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n SendCallsErrorType,\n SendCallsParameters,\n SendCallsReturnType,\n} from './actions/wallet/sendCalls.js'\nexport type {\n SendCallsSyncErrorType,\n SendCallsSyncParameters,\n SendCallsSyncReturnType,\n} from './actions/wallet/sendCallsSync.js'\nexport type {\n SendRawTransactionErrorType,\n SendRawTransactionParameters,\n SendRawTransactionReturnType,\n} from './actions/wallet/sendRawTransaction.js'\nexport type {\n SendRawTransactionSyncErrorType,\n SendRawTransactionSyncParameters,\n SendRawTransactionSyncReturnType,\n} from './actions/wallet/sendRawTransactionSync.js'\nexport type {\n SendTransactionErrorType,\n SendTransactionParameters,\n SendTransactionRequest,\n SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n SendTransactionSyncErrorType,\n SendTransactionSyncParameters,\n SendTransactionSyncRequest,\n SendTransactionSyncReturnType,\n} from './actions/wallet/sendTransactionSync.js'\nexport type {\n ShowCallsStatusErrorType,\n ShowCallsStatusParameters,\n ShowCallsStatusReturnType,\n} from './actions/wallet/showCallsStatus.js'\nexport type {\n SignAuthorizationErrorType,\n SignAuthorizationParameters,\n SignAuthorizationReturnType,\n} from './actions/wallet/signAuthorization.js'\nexport type {\n SignMessageErrorType,\n SignMessageParameters,\n SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n SignTransactionErrorType,\n SignTransactionParameters,\n SignTransactionRequest,\n SignTransactionReturnType,\n} from './actions/wallet/signTransaction.js'\nexport type {\n SignTypedDataErrorType,\n SignTypedDataParameters,\n SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n SwitchChainErrorType,\n SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n WaitForCallsStatusErrorType,\n WaitForCallsStatusParameters,\n WaitForCallsStatusReturnType,\n WaitForCallsStatusTimeoutErrorType,\n} from './actions/wallet/waitForCallsStatus.js'\nexport { WaitForCallsStatusTimeoutError } from './actions/wallet/waitForCallsStatus.js'\nexport type {\n WatchAssetErrorType,\n WatchAssetParameters,\n WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n WriteContractErrorType,\n WriteContractParameters,\n WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n WriteContractSyncErrorType,\n WriteContractSyncParameters,\n WriteContractSyncReturnType,\n} from './actions/wallet/writeContractSync.js'\nexport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n type MulticallBatchOptions,\n rpcSchema,\n} from './clients/createClient.js'\nexport {\n type CreatePublicClientErrorType,\n createPublicClient,\n type PublicClient,\n type PublicClientConfig,\n} from './clients/createPublicClient.js'\nexport {\n type CreateTestClientErrorType,\n createTestClient,\n type TestClient,\n type TestClientConfig,\n} from './clients/createTestClient.js'\nexport {\n type CreateWalletClientErrorType,\n createWalletClient,\n type WalletClient,\n type WalletClientConfig,\n} from './clients/createWalletClient.js'\nexport {\n type PublicActions,\n publicActions,\n} from './clients/decorators/public.js'\nexport {\n type TestActions,\n testActions,\n} from './clients/decorators/test.js'\nexport {\n type WalletActions,\n walletActions,\n} from './clients/decorators/wallet.js'\nexport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './clients/transports/createTransport.js'\nexport {\n type CustomTransport,\n type CustomTransportConfig,\n type CustomTransportErrorType,\n custom,\n} from './clients/transports/custom.js'\nexport {\n type FallbackTransport,\n type FallbackTransportConfig,\n type FallbackTransportErrorType,\n fallback,\n shouldThrow,\n} from './clients/transports/fallback.js'\nexport {\n type HttpTransport,\n type HttpTransportConfig,\n type HttpTransportErrorType,\n http,\n} from './clients/transports/http.js'\nexport {\n type WebSocketTransport,\n type WebSocketTransportConfig,\n type WebSocketTransportErrorType,\n webSocket,\n} from './clients/transports/webSocket.js'\nexport {\n erc20Abi,\n erc20Abi_bytes32,\n erc721Abi,\n erc1155Abi,\n erc4626Abi,\n erc6492SignatureValidatorAbi,\n /** @deprecated use `erc6492SignatureValidatorAbi` instead. */\n erc6492SignatureValidatorAbi as universalSignatureValidatorAbi,\n multicall3Abi,\n} from './constants/abis.js'\nexport { ethAddress, zeroAddress } from './constants/address.js'\nexport { zeroHash } from './constants/bytes.js'\nexport {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n erc6492SignatureValidatorByteCode,\n /** @deprecated use `erc6492SignatureValidatorByteCode` instead. */\n erc6492SignatureValidatorByteCode as universalSignatureValidatorByteCode,\n} from './constants/contracts.js'\nexport {\n maxInt8,\n maxInt16,\n maxInt24,\n maxInt32,\n maxInt40,\n maxInt48,\n maxInt56,\n maxInt64,\n maxInt72,\n maxInt80,\n maxInt88,\n maxInt96,\n maxInt104,\n maxInt112,\n maxInt120,\n maxInt128,\n maxInt136,\n maxInt144,\n maxInt152,\n maxInt160,\n maxInt168,\n maxInt176,\n maxInt184,\n maxInt192,\n maxInt200,\n maxInt208,\n maxInt216,\n maxInt224,\n maxInt232,\n maxInt240,\n maxInt248,\n maxInt256,\n maxUint8,\n maxUint16,\n maxUint24,\n maxUint32,\n maxUint40,\n maxUint48,\n maxUint56,\n maxUint64,\n maxUint72,\n maxUint80,\n maxUint88,\n maxUint96,\n maxUint104,\n maxUint112,\n maxUint120,\n maxUint128,\n maxUint136,\n maxUint144,\n maxUint152,\n maxUint160,\n maxUint168,\n maxUint176,\n maxUint184,\n maxUint192,\n maxUint200,\n maxUint208,\n maxUint216,\n maxUint224,\n maxUint232,\n maxUint240,\n maxUint248,\n maxUint256,\n minInt8,\n minInt16,\n minInt24,\n minInt32,\n minInt40,\n minInt48,\n minInt56,\n minInt64,\n minInt72,\n minInt80,\n minInt88,\n minInt96,\n minInt104,\n minInt112,\n minInt120,\n minInt128,\n minInt136,\n minInt144,\n minInt152,\n minInt160,\n minInt168,\n minInt176,\n minInt184,\n minInt192,\n minInt200,\n minInt208,\n minInt216,\n minInt224,\n minInt232,\n minInt240,\n minInt248,\n minInt256,\n} from './constants/number.js'\nexport { presignMessagePrefix } from './constants/strings.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.js'\nexport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n type AbiConstructorParamsNotFoundErrorType,\n AbiDecodingDataSizeInvalidError,\n type AbiDecodingDataSizeInvalidErrorType,\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiDecodingZeroDataError,\n type AbiDecodingZeroDataErrorType,\n AbiEncodingArrayLengthMismatchError,\n type AbiEncodingArrayLengthMismatchErrorType,\n AbiEncodingBytesSizeMismatchError,\n type AbiEncodingBytesSizeMismatchErrorType,\n AbiEncodingLengthMismatchError,\n type AbiEncodingLengthMismatchErrorType,\n AbiErrorInputsNotFoundError,\n type AbiErrorInputsNotFoundErrorType,\n AbiErrorNotFoundError,\n type AbiErrorNotFoundErrorType,\n AbiErrorSignatureNotFoundError,\n type AbiErrorSignatureNotFoundErrorType,\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n AbiFunctionSignatureNotFoundError,\n type AbiFunctionSignatureNotFoundErrorType,\n BytesSizeMismatchError,\n type BytesSizeMismatchErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n InvalidAbiEncodingTypeError,\n type InvalidAbiEncodingTypeErrorType,\n InvalidArrayError,\n type InvalidArrayErrorType,\n InvalidDefinitionTypeError,\n type InvalidDefinitionTypeErrorType,\n UnsupportedPackedAbiType,\n type UnsupportedPackedAbiTypeErrorType,\n} from './errors/abi.js'\nexport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from './errors/address.js'\nexport { BaseError, type BaseErrorType, setErrorConfig } from './errors/base.js'\nexport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n BundleFailedError,\n type BundleFailedErrorType,\n} from './errors/calls.js'\nexport {\n ChainDoesNotSupportContract,\n type ChainDoesNotSupportContractErrorType,\n ChainMismatchError,\n type ChainMismatchErrorType,\n ChainNotFoundError,\n type ChainNotFoundErrorType,\n ClientChainNotConfiguredError,\n type ClientChainNotConfiguredErrorType,\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from './errors/chain.js'\nexport {\n CallExecutionError,\n type CallExecutionErrorType,\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n CounterfactualDeploymentFailedError,\n type CounterfactualDeploymentFailedErrorType,\n RawContractError,\n type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n SliceOffsetOutOfBoundsError,\n type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n InvalidBytesBooleanError,\n type InvalidBytesBooleanErrorType,\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n InvalidHexValueError,\n type InvalidHexValueErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n type EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n EnsInvalidChainIdError,\n type EnsInvalidChainIdErrorType,\n} from './errors/ens.js'\nexport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n MaxFeePerGasTooLowError,\n type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from './errors/log.js'\nexport {\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'\nexport {\n HttpRequestError,\n type HttpRequestErrorType,\n RpcRequestError,\n type RpcRequestErrorType,\n SocketClosedError,\n type SocketClosedErrorType,\n TimeoutError,\n type TimeoutErrorType,\n WebSocketRequestError,\n type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n ProviderRpcError,\n type ProviderRpcErrorCode,\n type ProviderRpcErrorType,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from './errors/stateOverride.js'\nexport {\n FeeConflictError,\n type FeeConflictErrorType,\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n InvalidSerializedTransactionError,\n type InvalidSerializedTransactionErrorType,\n InvalidSerializedTransactionTypeError,\n type InvalidSerializedTransactionTypeErrorType,\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from './errors/transaction.js'\nexport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport {\n InvalidDomainError,\n type InvalidDomainErrorType,\n InvalidPrimaryTypeError,\n type InvalidPrimaryTypeErrorType,\n InvalidStructTypeError,\n type InvalidStructTypeErrorType,\n} from './errors/typedData.js'\nexport {\n InvalidDecimalNumberError,\n type InvalidDecimalNumberErrorType,\n} from './errors/unit.js'\nexport type {\n DeriveAccount,\n HDKey,\n ParseAccount,\n} from './types/account.js'\nexport type {\n Authorization,\n AuthorizationList,\n AuthorizationRequest,\n SerializedAuthorization,\n SerializedAuthorizationList,\n SignedAuthorization,\n SignedAuthorizationList,\n} from './types/authorization.js'\nexport type {\n Block,\n BlockIdentifier,\n BlockNumber,\n BlockTag,\n Uncle,\n} from './types/block.js'\nexport type { Call, Calls } from './types/calls.js'\nexport type {\n Capabilities,\n /** @deprecated Use `Capabilities` instead. */\n Capabilities as WalletCapabilities,\n CapabilitiesSchema,\n /** @deprecated Use `ChainIdToCapabilities` instead. */\n ChainIdToCapabilities as WalletCapabilitiesRecord,\n ChainIdToCapabilities,\n ExtractCapabilities,\n} from './types/capabilities.js'\nexport type {\n Chain,\n ChainConfig,\n ChainContract,\n ChainEstimateFeesPerGasFn,\n ChainEstimateFeesPerGasFnParameters,\n ChainFees,\n ChainFeesFnParameters,\n ChainFormatter,\n ChainFormatters,\n ChainMaxPriorityFeePerGasFn,\n ChainSerializers,\n DeriveChain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterParameters,\n ExtractChainFormatterReturnType,\n GetChainParameter,\n} from './types/chain.js'\nexport type {\n AbiEventParametersToPrimitiveTypes,\n AbiEventParameterToPrimitiveType,\n AbiEventTopicToPrimitiveType,\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ContractConstructorArgs,\n ContractErrorArgs,\n ContractErrorName,\n ContractEventArgs,\n ContractEventArgsFromTopics,\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n EventDefinition,\n ExtractAbiFunctionForArgs,\n ExtractAbiItem,\n ExtractAbiItemForArgs,\n ExtractAbiItemNames,\n GetEventArgs,\n GetValue,\n LogTopicType,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n UnionWiden,\n Widen,\n} from './types/contract.js'\nexport type { DataSuffix } from './types/dataSuffix.js'\nexport type {\n AddEthereumChainParameter,\n BundlerRpcSchema,\n DebugBundlerRpcSchema,\n EIP1193EventMap,\n EIP1193Events,\n EIP1193Parameters,\n EIP1193Provider,\n EIP1193RequestFn,\n EIP1474Methods,\n NetworkSync,\n PaymasterRpcSchema,\n ProviderConnectInfo,\n ProviderMessage,\n ProviderRpcErrorType as EIP1193ProviderRpcErrorType,\n PublicRpcSchema,\n RpcSchema,\n RpcSchemaOverride,\n TestRpcSchema,\n WalletCallReceipt,\n WalletGetAssetsParameters,\n WalletGetAssetsReturnType,\n WalletGetCallsStatusReturnType,\n WalletGrantPermissionsParameters,\n WalletGrantPermissionsReturnType,\n WalletPermission,\n WalletPermissionCaveat,\n WalletRpcSchema,\n WalletSendCallsParameters,\n WalletSendCallsReturnType,\n WatchAssetParams,\n} from './types/eip1193.js'\nexport { ProviderRpcError as EIP1193ProviderRpcError } from './types/eip1193.js'\nexport type { BlobSidecar, BlobSidecars } from './types/eip4844.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n FeeHistory,\n FeeValues,\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n FeeValuesType,\n} from './types/fee.js'\nexport type { Filter, FilterType } from './types/filter.js'\nexport type { GetTransactionRequestKzgParameter, Kzg } from './types/kzg.js'\nexport type { Log } from './types/log.js'\nexport type {\n ByteArray,\n CompactSignature,\n Hash,\n Hex,\n LogTopic,\n SignableMessage,\n Signature,\n} from './types/misc.js'\nexport type {\n MulticallContracts,\n MulticallResponse,\n MulticallResults,\n} from './types/multicall.js'\nexport type { Register, ResolvedRegister } from './types/register.js'\nexport type {\n Index,\n Quantity,\n RpcAccountStateOverride,\n RpcAuthorization,\n RpcAuthorizationList,\n RpcBlock,\n RpcBlockIdentifier,\n RpcBlockNumber,\n RpcFeeHistory,\n RpcFeeValues,\n RpcLog,\n RpcProof,\n RpcStateMapping,\n RpcStateOverride,\n RpcTransaction,\n RpcTransactionReceipt,\n RpcTransactionRequest,\n RpcUncle,\n Status,\n} from './types/rpc.js'\nexport type {\n StateMapping,\n StateOverride,\n} from './types/stateOverride.js'\nexport type {\n AccessList,\n Transaction,\n TransactionBase,\n TransactionEIP1559,\n TransactionEIP2930,\n TransactionEIP4844,\n TransactionEIP7702,\n TransactionLegacy,\n TransactionReceipt,\n TransactionRequest,\n TransactionRequestBase,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestGeneric,\n TransactionRequestLegacy,\n TransactionSerializable,\n TransactionSerializableBase,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionSerializedLegacy,\n TransactionType,\n} from './types/transaction.js'\nexport type { GetPollOptions, GetTransportConfig } from './types/transport.js'\nexport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from './types/typedData.js'\nexport type {\n Assign,\n Branded,\n Evaluate,\n ExactPartial,\n ExactRequired,\n IsNarrowable,\n IsNever,\n IsUndefined,\n IsUnion,\n LooseOmit,\n MaybePartial,\n MaybePromise,\n MaybeRequired,\n Mutable,\n NoInfer,\n NoUndefined,\n Omit,\n OneOf,\n Or,\n PartialBy,\n Prettify,\n RequiredBy,\n Some,\n UnionEvaluate,\n UnionLooseOmit,\n UnionOmit,\n UnionPartialBy,\n UnionPick,\n UnionRequiredBy,\n UnionToTuple,\n ValueOf,\n} from './types/utils.js'\nexport type { Withdrawal } from './types/withdrawal.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './utils/abi/decodeAbiParameters.js'\nexport {\n type DecodeDeployDataErrorType,\n type DecodeDeployDataParameters,\n type DecodeDeployDataReturnType,\n decodeDeployData,\n} from './utils/abi/decodeDeployData.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './utils/abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './utils/abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './utils/abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './utils/abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './utils/abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n type EncodeDeployDataReturnType,\n encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n type EncodeErrorResultReturnType,\n encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n type EncodeFunctionDataReturnType,\n encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n type EncodeFunctionResultReturnType,\n encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n type EncodePackedErrorType,\n encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n type GetAbiItemReturnType,\n getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './utils/abi/parseEventLogs.js'\nexport {\n type PrepareEncodeFunctionDataErrorType,\n type PrepareEncodeFunctionDataParameters,\n type PrepareEncodeFunctionDataReturnType,\n prepareEncodeFunctionData,\n} from './utils/abi/prepareEncodeFunctionData.js'\nexport {\n type ChecksumAddressErrorType,\n checksumAddress,\n type GetAddressErrorType,\n getAddress,\n} from './utils/address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n type IsAddressErrorType,\n type IsAddressOptions,\n isAddress,\n} from './utils/address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n type IsAddressEqualReturnType,\n isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport {\n type BlobsToCommitmentsErrorType,\n type BlobsToCommitmentsParameters,\n type BlobsToCommitmentsReturnType,\n blobsToCommitments,\n} from './utils/blob/blobsToCommitments.js'\nexport {\n blobsToProofs,\n type blobsToProofsErrorType,\n type blobsToProofsParameters,\n type blobsToProofsReturnType,\n} from './utils/blob/blobsToProofs.js'\nexport {\n type CommitmentsToVersionedHashesErrorType,\n type CommitmentsToVersionedHashesParameters,\n type CommitmentsToVersionedHashesReturnType,\n commitmentsToVersionedHashes,\n} from './utils/blob/commitmentsToVersionedHashes.js'\nexport {\n type CommitmentToVersionedHashErrorType,\n type CommitmentToVersionedHashParameters,\n type CommitmentToVersionedHashReturnType,\n commitmentToVersionedHash,\n} from './utils/blob/commitmentToVersionedHash.js'\nexport {\n type FromBlobsErrorType,\n type FromBlobsParameters,\n type FromBlobsReturnType,\n fromBlobs,\n} from './utils/blob/fromBlobs.js'\nexport {\n type SidecarsToVersionedHashesErrorType,\n type SidecarsToVersionedHashesParameters,\n type SidecarsToVersionedHashesReturnType,\n sidecarsToVersionedHashes,\n} from './utils/blob/sidecarsToVersionedHashes.js'\nexport {\n type ToBlobSidecarsErrorType,\n type ToBlobSidecarsParameters,\n type ToBlobSidecarsReturnType,\n toBlobSidecars,\n} from './utils/blob/toBlobSidecars.js'\nexport {\n type ToBlobsErrorType,\n type ToBlobsParameters,\n type ToBlobsReturnType,\n toBlobs,\n} from './utils/blob/toBlobs.js'\nexport {\n type CcipRequestErrorType,\n type CcipRequestParameters,\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport {\n type DefineChainReturnType,\n defineChain,\n extendSchema,\n} from './utils/chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './utils/chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './utils/chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n type ConcatReturnType,\n concat,\n concatBytes,\n concatHex,\n} from './utils/data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n type PadReturnType,\n pad,\n padBytes,\n padHex,\n} from './utils/data/pad.js'\nexport { type SizeErrorType, size } from './utils/data/size.js'\nexport {\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n slice,\n sliceBytes,\n sliceHex,\n} from './utils/data/slice.js'\nexport {\n type TrimErrorType,\n type TrimReturnType,\n trim,\n} from './utils/data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n type FromHexErrorType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBoolErrorType,\n type HexToNumberErrorType,\n type HexToStringErrorType,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './utils/encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n type FromRlpReturnType,\n fromRlp,\n} from './utils/encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './utils/encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './utils/encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n bytesToRlp,\n type HexToRlpErrorType,\n hexToRlp,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './utils/encoding/toRlp.js'\nexport { type LabelhashErrorType, labelhash } from './utils/ens/labelhash.js'\nexport { type NamehashErrorType, namehash } from './utils/ens/namehash.js'\nexport {\n type ToCoinTypeError,\n toCoinType,\n} from './utils/ens/toCoinType.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './utils/formatters/block.js'\nexport { type FormatLogErrorType, formatLog } from './utils/formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport {\n type Keccak256ErrorType,\n type Keccak256Hash,\n keccak256,\n} from './utils/hash/keccak256.js'\nexport {\n type Ripemd160ErrorType,\n type Ripemd160Hash,\n ripemd160,\n} from './utils/hash/ripemd160.js'\nexport {\n type Sha256ErrorType,\n type Sha256Hash,\n sha256,\n} from './utils/hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './utils/hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './utils/hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './utils/hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './utils/hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './utils/hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './utils/hash/toFunctionSignature.js'\nexport {\n type DefineKzgErrorType,\n type DefineKzgParameters,\n type DefineKzgReturnType,\n defineKzg,\n} from './utils/kzg/defineKzg.js'\nexport {\n type SetupKzgErrorType,\n type SetupKzgParameters,\n type SetupKzgReturnType,\n setupKzg,\n} from './utils/kzg/setupKzg.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './utils/nonceManager.js'\nexport { withCache } from './utils/promise/withCache.js'\nexport {\n type WithRetryErrorType,\n withRetry,\n} from './utils/promise/withRetry.js'\nexport {\n type WithTimeoutErrorType,\n withTimeout,\n} from './utils/promise/withTimeout.js'\nexport {\n type CompactSignatureToSignatureErrorType,\n compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n type HashMessageErrorType,\n hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashDomain,\n hashStruct,\n hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './utils/signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './utils/signature/isErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseCompactSignatureErrorType`. */\n type ParseCompactSignatureErrorType as HexToCompactSignatureErrorType,\n type ParseCompactSignatureErrorType,\n /** @deprecated Use `parseCompactSignature`. */\n parseCompactSignature as hexToCompactSignature,\n parseCompactSignature,\n} from './utils/signature/parseCompactSignature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './utils/signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './utils/signature/parseErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseSignatureErrorType`. */\n type ParseSignatureErrorType as HexToSignatureErrorType,\n type ParseSignatureErrorType,\n /** @deprecated Use `parseSignature`. */\n parseSignature as hexToSignature,\n parseSignature,\n} from './utils/signature/parseSignature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './utils/signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './utils/signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './utils/signature/recoverPublicKey.js'\nexport {\n type RecoverTransactionAddressErrorType,\n type RecoverTransactionAddressParameters,\n type RecoverTransactionAddressReturnType,\n recoverTransactionAddress,\n} from './utils/signature/recoverTransactionAddress.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeCompactSignatureErrorType as CompactSignatureToHexErrorType,\n type SerializeCompactSignatureErrorType,\n /** @deprecated Use `serializeCompactSignature` instead. */\n serializeCompactSignature as compactSignatureToHex,\n serializeCompactSignature,\n} from './utils/signature/serializeCompactSignature.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './utils/signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './utils/signature/serializeErc8010Signature.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n type SerializeSignatureParameters,\n type SerializeSignatureReturnType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from './utils/signature/serializeSignature.js'\nexport {\n type SignatureToCompactSignatureErrorType,\n signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n type ToPrefixedMessageErrorType,\n toPrefixedMessage,\n} from './utils/signature/toPrefixedMessage.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './utils/signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './utils/signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './utils/signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n type ParseTransactionReturnType,\n parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n type SerializedTransactionReturnType,\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './utils/transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n domainSeparator,\n type GetTypesForEIP712DomainErrorType,\n getTypesForEIP712Domain,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './utils/typedData.js'\nexport {\n type FormatEtherErrorType,\n formatEther,\n} from './utils/unit/formatEther.js'\nexport {\n type FormatGweiErrorType,\n formatGwei,\n} from './utils/unit/formatGwei.js'\nexport {\n type FormatUnitsErrorType,\n formatUnits,\n} from './utils/unit/formatUnits.js'\nexport {\n type ParseEtherErrorType,\n parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n type ParseUnitsErrorType,\n parseUnits,\n} from './utils/unit/parseUnits.js'\n","import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: Hash,\n PRFSalt: Hash,\n DK: Uint8Array,\n prfW: Hash,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/**\n * Audited & minimal JS implementation of\n * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).\n * @module\n * @example\n```js\nimport * as bip39 from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nconst mn = bip39.generateMnemonic(wordlist);\nconsole.log(mn);\nconst ent = bip39.mnemonicToEntropy(mn, wordlist)\nbip39.entropyToMnemonic(ent, wordlist);\nbip39.validateMnemonic(mn, wordlist);\nawait bip39.mnemonicToSeed(mn, 'password');\nbip39.mnemonicToSeedSync(mn, 'password');\n\n// Wordlists\nimport { wordlist as czech } from '@scure/bip39/wordlists/czech';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { wordlist as french } from '@scure/bip39/wordlists/french';\nimport { wordlist as italian } from '@scure/bip39/wordlists/italian';\nimport { wordlist as japanese } from '@scure/bip39/wordlists/japanese';\nimport { wordlist as korean } from '@scure/bip39/wordlists/korean';\nimport { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';\nimport { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';\nimport { wordlist as spanish } from '@scure/bip39/wordlists/spanish';\nimport { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';\n```\n */\n/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n abytes(ent, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.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 { 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 signAuthorization(authorization) {\n return 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","// 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 type { ErrorType } from '../errors/utils.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.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 signAuthorization: source.signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\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 { type IsHexErrorType, isHex } from '../../utils/data/isHex.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 { 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 =\n | HexToBytesErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | 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 {\n lowS: true,\n extraEntropy: isHex(extraEntropy, { strict: false })\n ? hexToBytes(extraEntropy)\n : extraEntropy,\n },\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 type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../utils/authorization/hashAuthorization.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 AuthorizationRequest & {\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 signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const { chainId, nonce, privateKey, to = 'object' } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n address,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\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 { 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(await serializer(signableTransaction)),\n privateKey,\n })\n return (await serializer(\n transaction,\n signature,\n )) as SignTransactionReturnType\n}\n","import type { TypedData } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\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'\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 [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):\n * `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(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","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","export const x402Version = 2;\n","import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData {\n facilitator: T;\n networks: Set;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = (\n map: Map>,\n network: Network,\n): Map | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = (\n map: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = (\n schemeMap: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record = {};\n Object.keys(obj as Record)\n .sort()\n .forEach(key => {\n const value = (obj as Record)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n","import { x402ResourceServer } from \"../server\";\nimport {\n decodePaymentSignatureHeader,\n encodePaymentRequiredHeader,\n encodePaymentResponseHeader,\n} from \".\";\nimport {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n SettleError,\n Price,\n Network,\n PaymentRequirements,\n} from \"../types\";\nimport { x402Version } from \"..\";\n\n/**\n * Framework-agnostic HTTP adapter interface\n * Implementations provide framework-specific HTTP operations\n */\nexport interface HTTPAdapter {\n getHeader(name: string): string | undefined;\n getMethod(): string;\n getPath(): string;\n getUrl(): string;\n getAcceptHeader(): string;\n getUserAgent(): string;\n\n /**\n * Get query parameters from the request URL\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams?(): Record;\n\n /**\n * Get a specific query parameter by name\n *\n * @param name - The query parameter name\n * @returns The query parameter value(s) or undefined\n */\n getQueryParam?(name: string): string | string[] | undefined;\n\n /**\n * Get the parsed request body\n * Framework adapters should parse JSON/form data appropriately\n *\n * @returns The parsed request body\n */\n getBody?(): unknown;\n}\n\n/**\n * Paywall configuration for HTML responses\n */\nexport interface PaywallConfig {\n appName?: string;\n appLogo?: string;\n sessionTokenEndpoint?: string;\n currentUrl?: string;\n testnet?: boolean;\n}\n\n/**\n * Paywall provider interface for generating HTML\n */\nexport interface PaywallProvider {\n generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;\n}\n\n/**\n * Dynamic payTo function that receives HTTP request context\n */\nexport type DynamicPayTo = (context: HTTPRequestContext) => string | Promise;\n\n/**\n * Dynamic price function that receives HTTP request context\n */\nexport type DynamicPrice = (context: HTTPRequestContext) => Price | Promise;\n\n/**\n * Result of response body callbacks containing content type and body.\n */\nexport interface HTTPResponseBody {\n /**\n * The content type for the response (e.g., 'application/json', 'text/plain').\n */\n contentType: string;\n\n /**\n * The response body to include in the 402 response.\n */\n body: unknown;\n}\n\n/**\n * Dynamic function to generate a custom response for unpaid requests.\n * Receives the HTTP request context and returns the content type and body to include in the 402 response.\n */\nexport type UnpaidResponseBody = (\n context: HTTPRequestContext,\n) => HTTPResponseBody | Promise;\n\n/**\n * Dynamic function to generate a custom response for settlement failures.\n * Receives the HTTP request context and settle failure result, returns the content type and body.\n */\nexport type SettlementFailedResponseBody = (\n context: HTTPRequestContext,\n settleResult: Omit,\n) => HTTPResponseBody | Promise;\n\n/**\n * A single payment option for a route\n * Represents one way a client can pay for access to the resource\n */\nexport interface PaymentOption {\n scheme: string;\n payTo: string | DynamicPayTo;\n price: Price | DynamicPrice;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record;\n}\n\n/**\n * Route configuration for HTTP endpoints\n *\n * The 'accepts' field defines payment options for the route.\n * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.\n */\nexport interface RouteConfig {\n // Payment option(s): single or array\n accepts: PaymentOption | PaymentOption[];\n\n // HTTP-specific metadata\n resource?: string;\n description?: string;\n mimeType?: string;\n customPaywallHtml?: string;\n\n /**\n * Optional callback to generate a custom response for unpaid API requests.\n * This allows servers to return preview data, error messages, or other content\n * when a request lacks payment.\n *\n * For browser requests (Accept: text/html), the paywall HTML takes precedence.\n * This callback is only used for API clients.\n *\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @returns An object containing both contentType and body for the 402 response\n */\n unpaidResponseBody?: UnpaidResponseBody;\n\n /**\n * Optional callback to generate a custom response for settlement failures.\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @param settleResult - The settlement failure result\n * @returns An object containing both contentType and body for the 402 response\n */\n settlementFailedResponseBody?: SettlementFailedResponseBody;\n\n // Extensions\n extensions?: Record;\n}\n\n/**\n * Routes configuration - maps path patterns to route configs\n */\nexport type RoutesConfig = Record | RouteConfig;\n\n/**\n * Hook that runs on every request to a protected route, before payment processing.\n * Can grant access without payment, deny the request, or continue to payment flow.\n *\n * @returns\n * - `void` - Continue to payment processing (default behavior)\n * - `{ grantAccess: true }` - Grant access without requiring payment\n * - `{ abort: true; reason: string }` - Deny the request (returns 403)\n */\nexport type ProtectedRequestHook = (\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n) => Promise;\n\n/**\n * Compiled route for efficient matching\n */\nexport interface CompiledRoute {\n verb: string;\n regex: RegExp;\n config: RouteConfig;\n}\n\n/**\n * HTTP request context that encapsulates all request data\n */\nexport interface HTTPRequestContext {\n adapter: HTTPAdapter;\n path: string;\n method: string;\n paymentHeader?: string;\n}\n\n/**\n * HTTP transport context contains both request context and optional response data.\n */\nexport interface HTTPTransportContext {\n /** The HTTP request context */\n request: HTTPRequestContext;\n /** The response body buffer */\n responseBody?: Buffer;\n}\n\n/**\n * HTTP response instructions for the framework middleware\n */\nexport interface HTTPResponseInstructions {\n status: number;\n headers: Record;\n body?: unknown; // e.g. Paywall for web browser requests, but could be any other type\n isHtml?: boolean; // e.g. if body is a paywall, then isHtml is true\n}\n\n/**\n * Result of processing an HTTP request for payment\n */\nexport type HTTPProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n declaredExtensions?: Record;\n }\n | { type: \"payment-error\"; response: HTTPResponseInstructions };\n\n/**\n * Result of processSettlement\n */\nexport type ProcessSettleSuccessResponse = SettleResponse & {\n success: true;\n headers: Record;\n requirements: PaymentRequirements;\n};\n\nexport type ProcessSettleFailureResponse = SettleResponse & {\n success: false;\n errorReason: string;\n errorMessage?: string;\n headers: Record;\n response: HTTPResponseInstructions;\n};\n\nexport type ProcessSettleResultResponse =\n | ProcessSettleSuccessResponse\n | ProcessSettleFailureResponse;\n\n/**\n * Represents a validation error for a specific route's payment configuration.\n */\nexport interface RouteValidationError {\n /** The route pattern (e.g., \"GET /api/weather\") */\n routePattern: string;\n /** The payment scheme that failed validation */\n scheme: string;\n /** The network that failed validation */\n network: Network;\n /** The type of validation failure */\n reason: \"missing_scheme\" | \"missing_facilitator\";\n /** Human-readable error message */\n message: string;\n}\n\n/**\n * Error thrown when route configuration validation fails.\n */\nexport class RouteConfigurationError extends Error {\n /** The validation errors that caused this exception */\n public readonly errors: RouteValidationError[];\n\n /**\n * Creates a new RouteConfigurationError with the given validation errors.\n *\n * @param errors - The validation errors that caused this exception.\n */\n constructor(errors: RouteValidationError[]) {\n const message = `x402 Route Configuration Errors:\\n${errors.map(e => ` - ${e.message}`).join(\"\\n\")}`;\n super(message);\n this.name = \"RouteConfigurationError\";\n this.errors = errors;\n }\n}\n\n/**\n * HTTP-enhanced x402 resource server\n * Provides framework-agnostic HTTP protocol handling\n */\nexport class x402HTTPResourceServer {\n private ResourceServer: x402ResourceServer;\n private compiledRoutes: CompiledRoute[] = [];\n private routesConfig: RoutesConfig;\n private paywallProvider?: PaywallProvider;\n private protectedRequestHooks: ProtectedRequestHook[] = [];\n\n /**\n * Creates a new x402HTTPResourceServer instance.\n *\n * @param ResourceServer - The core x402ResourceServer instance to use\n * @param routes - Route configuration for payment-protected endpoints\n */\n constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig) {\n this.ResourceServer = ResourceServer;\n this.routesConfig = routes;\n\n // Handle both single route and multiple routes\n const normalizedRoutes =\n typeof routes === \"object\" && !(\"accepts\" in routes)\n ? (routes as Record)\n : { \"*\": routes as RouteConfig };\n\n for (const [pattern, config] of Object.entries(normalizedRoutes)) {\n const parsed = this.parseRoutePattern(pattern);\n this.compiledRoutes.push({\n verb: parsed.verb,\n regex: parsed.regex,\n config,\n });\n }\n }\n\n /**\n * Get the underlying x402ResourceServer instance.\n *\n * @returns The underlying x402ResourceServer instance\n */\n get server(): x402ResourceServer {\n return this.ResourceServer;\n }\n\n /**\n * Get the routes configuration.\n *\n * @returns The routes configuration\n */\n get routes(): RoutesConfig {\n return this.routesConfig;\n }\n\n /**\n * Initialize the HTTP resource server.\n *\n * This method initializes the underlying resource server (fetching facilitator support)\n * and then validates that all route payment configurations have corresponding\n * registered schemes and facilitator support.\n *\n * @throws RouteConfigurationError if any route's payment options don't have\n * corresponding registered schemes or facilitator support\n *\n * @example\n * ```typescript\n * const httpServer = new x402HTTPResourceServer(server, routes);\n * await httpServer.initialize();\n * ```\n */\n async initialize(): Promise {\n // First, initialize the underlying resource server (fetches facilitator support)\n await this.ResourceServer.initialize();\n\n // Then validate route configuration\n const errors = this.validateRouteConfiguration();\n if (errors.length > 0) {\n throw new RouteConfigurationError(errors);\n }\n }\n\n /**\n * Register a custom paywall provider for generating HTML\n *\n * @param provider - PaywallProvider instance\n * @returns This service instance for chaining\n */\n registerPaywallProvider(provider: PaywallProvider): this {\n this.paywallProvider = provider;\n return this;\n }\n\n /**\n * Register a hook that runs on every request to a protected route, before payment processing.\n * Hooks are executed in order of registration. The first hook to return a non-void result wins.\n *\n * @param hook - The request hook function\n * @returns The x402HTTPResourceServer instance for chaining\n */\n onProtectedRequest(hook: ProtectedRequestHook): this {\n this.protectedRequestHooks.push(hook);\n return this;\n }\n\n /**\n * Process HTTP request and return response instructions\n * This is the main entry point for framework middleware\n *\n * @param context - HTTP request context\n * @param paywallConfig - Optional paywall configuration\n * @returns Process result indicating next action for middleware\n */\n async processHTTPRequest(\n context: HTTPRequestContext,\n paywallConfig?: PaywallConfig,\n ): Promise {\n const { adapter, path, method } = context;\n\n // Find matching route\n const routeConfig = this.getRouteConfig(path, method);\n if (!routeConfig) {\n return { type: \"no-payment-required\" }; // No payment required for this route\n }\n\n // Execute request hooks before any payment processing\n for (const hook of this.protectedRequestHooks) {\n const result = await hook(context, routeConfig);\n if (result && \"grantAccess\" in result) {\n return { type: \"no-payment-required\" };\n }\n if (result && \"abort\" in result) {\n return {\n type: \"payment-error\",\n response: {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: result.reason },\n },\n };\n }\n }\n\n // Normalize accepts field to array of payment options\n const paymentOptions = this.normalizePaymentOptions(routeConfig);\n\n // Check for payment header (v1 or v2)\n const paymentPayload = this.extractPayment(adapter);\n\n // Create resource info, using config override if provided\n const resourceInfo = {\n url: routeConfig.resource || context.adapter.getUrl(),\n description: routeConfig.description || \"\",\n mimeType: routeConfig.mimeType || \"\",\n };\n\n // Build requirements from all payment options\n // (this method handles resolving dynamic functions internally)\n let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(\n paymentOptions,\n context,\n );\n\n let extensions = routeConfig.extensions;\n if (extensions) {\n extensions = this.ResourceServer.enrichExtensions(extensions, context);\n }\n\n // createPaymentRequiredResponse already handles extension enrichment in the core layer\n const transportContext: HTTPTransportContext = { request: context };\n const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n !paymentPayload ? \"Payment required\" : undefined,\n extensions,\n transportContext,\n );\n\n // If no payment provided\n if (!paymentPayload) {\n // Resolve custom unpaid response body if provided\n const unpaidBody = routeConfig.unpaidResponseBody\n ? await routeConfig.unpaidResponseBody(context)\n : undefined;\n\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(\n paymentRequired,\n this.isWebBrowser(adapter),\n paywallConfig,\n routeConfig.customPaywallHtml,\n unpaidBody,\n ),\n };\n }\n\n // Verify payment\n try {\n const matchingRequirements = this.ResourceServer.findMatchingRequirements(\n paymentRequired.accepts,\n paymentPayload,\n );\n\n if (!matchingRequirements) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const verifyResult = await this.ResourceServer.verifyPayment(\n paymentPayload,\n matchingRequirements,\n );\n\n if (!verifyResult.isValid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n verifyResult.invalidReason,\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n // Payment is valid, return data needed for settlement\n return {\n type: \"payment-verified\",\n paymentPayload,\n paymentRequirements: matchingRequirements,\n declaredExtensions: routeConfig.extensions,\n };\n } catch (error) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n error instanceof Error ? error.message : \"Payment verification failed\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n }\n\n /**\n * Process settlement after successful response\n *\n * @param paymentPayload - The verified payment payload\n * @param requirements - The matching payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional HTTP transport context\n * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure\n */\n async processSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record,\n transportContext?: HTTPTransportContext,\n ): Promise {\n try {\n const settleResponse = await this.ResourceServer.settlePayment(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n );\n\n if (!settleResponse.success) {\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason: settleResponse.errorReason || \"Settlement failed\",\n errorMessage:\n settleResponse.errorMessage || settleResponse.errorReason || \"Settlement failed\",\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n\n return {\n ...settleResponse,\n success: true,\n headers: this.createSettlementHeaders(settleResponse),\n requirements,\n };\n } catch (error) {\n if (error instanceof SettleError) {\n const errorReason = error.errorReason || error.message;\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: error.errorMessage || errorReason,\n payer: error.payer,\n network: error.network,\n transaction: error.transaction,\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n const errorReason = error instanceof Error ? error.message : \"Settlement failed\";\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: errorReason,\n network: requirements.network as Network,\n transaction: \"\",\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n }\n\n /**\n * Check if a request requires payment based on route configuration\n *\n * @param context - HTTP request context\n * @returns True if the route requires payment, false otherwise\n */\n requiresPayment(context: HTTPRequestContext): boolean {\n const routeConfig = this.getRouteConfig(context.path, context.method);\n return routeConfig !== undefined;\n }\n\n /**\n * Build HTTPResponseInstructions for settlement failure.\n * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.\n *\n * @param failure - Settlement failure result with headers\n * @param transportContext - Optional HTTP transport context for the request\n * @returns HTTP response instructions for the 402 settlement failure response\n */\n private async buildSettlementFailureResponse(\n failure: Omit,\n transportContext?: HTTPTransportContext,\n ): Promise {\n const settlementHeaders = failure.headers;\n const routeConfig = transportContext\n ? this.getRouteConfig(transportContext.request.path, transportContext.request.method)\n : undefined;\n\n const customBody = routeConfig?.settlementFailedResponseBody\n ? await routeConfig.settlementFailedResponseBody(transportContext!.request, failure)\n : undefined;\n\n const contentType = customBody ? customBody.contentType : \"application/json\";\n const body = customBody ? customBody.body : {};\n\n return {\n status: 402,\n headers: {\n \"Content-Type\": contentType,\n ...settlementHeaders,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n };\n }\n\n /**\n * Normalizes a RouteConfig's accepts field into an array of PaymentOptions\n * Handles both single PaymentOption and array formats\n *\n * @param routeConfig - Route configuration\n * @returns Array of payment options\n */\n private normalizePaymentOptions(routeConfig: RouteConfig): PaymentOption[] {\n return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];\n }\n\n /**\n * Validates that all payment options in routes have corresponding registered schemes\n * and facilitator support.\n *\n * @returns Array of validation errors (empty if all routes are valid)\n */\n private validateRouteConfiguration(): RouteValidationError[] {\n const errors: RouteValidationError[] = [];\n\n // Normalize routes to array of [pattern, config] pairs\n const normalizedRoutes =\n typeof this.routesConfig === \"object\" && !(\"accepts\" in this.routesConfig)\n ? Object.entries(this.routesConfig as Record)\n : [[\"*\", this.routesConfig as RouteConfig] as [string, RouteConfig]];\n\n for (const [pattern, config] of normalizedRoutes) {\n const paymentOptions = this.normalizePaymentOptions(config);\n\n for (const option of paymentOptions) {\n // Check 1: Is scheme registered?\n if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_scheme\",\n message: `Route \"${pattern}\": No scheme implementation registered for \"${option.scheme}\" on network \"${option.network}\"`,\n });\n // Skip facilitator check if scheme isn't registered\n continue;\n }\n\n // Check 2: Does facilitator support this scheme/network combination?\n const supportedKind = this.ResourceServer.getSupportedKind(\n x402Version,\n option.network,\n option.scheme,\n );\n\n if (!supportedKind) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_facilitator\",\n message: `Route \"${pattern}\": Facilitator does not support scheme \"${option.scheme}\" on network \"${option.network}\"`,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get route configuration for a request\n *\n * @param path - Request path\n * @param method - HTTP method\n * @returns Route configuration or undefined if no match\n */\n private getRouteConfig(path: string, method: string): RouteConfig | undefined {\n const normalizedPath = this.normalizePath(path);\n const upperMethod = method.toUpperCase();\n\n const matchingRoute = this.compiledRoutes.find(\n route =>\n route.regex.test(normalizedPath) && (route.verb === \"*\" || route.verb === upperMethod),\n );\n\n return matchingRoute?.config;\n }\n\n /**\n * Extract payment from HTTP headers (handles v1 and v2)\n *\n * @param adapter - HTTP adapter\n * @returns Decoded payment payload or null\n */\n private extractPayment(adapter: HTTPAdapter): PaymentPayload | null {\n // Check v2 header first (PAYMENT-SIGNATURE)\n const header = adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"PAYMENT-SIGNATURE\");\n\n if (header) {\n try {\n return decodePaymentSignatureHeader(header);\n } catch (error) {\n console.warn(\"Failed to decode PAYMENT-SIGNATURE header:\", error);\n }\n }\n\n return null;\n }\n\n /**\n * Check if request is from a web browser\n *\n * @param adapter - HTTP adapter\n * @returns True if request appears to be from a browser\n */\n private isWebBrowser(adapter: HTTPAdapter): boolean {\n const accept = adapter.getAcceptHeader();\n const userAgent = adapter.getUserAgent();\n return accept.includes(\"text/html\") && userAgent.includes(\"Mozilla\");\n }\n\n /**\n * Create HTTP response instructions from payment required\n *\n * @param paymentRequired - Payment requirements\n * @param isWebBrowser - Whether request is from browser\n * @param paywallConfig - Paywall configuration\n * @param customHtml - Custom HTML template\n * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests\n * @returns Response instructions\n */\n private createHTTPResponse(\n paymentRequired: PaymentRequired,\n isWebBrowser: boolean,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n unpaidResponse?: HTTPResponseBody,\n ): HTTPResponseInstructions {\n // Use 412 Precondition Failed for permit2_allowance_required error\n // This signals client needs to approve Permit2 before retrying\n const status = paymentRequired.error === \"permit2_allowance_required\" ? 412 : 402;\n\n if (isWebBrowser) {\n const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);\n return {\n status,\n headers: { \"Content-Type\": \"text/html\" },\n body: html,\n isHtml: true,\n };\n }\n\n const response = this.createHTTPPaymentRequiredResponse(paymentRequired);\n\n // Use callback result if provided, otherwise default to JSON with empty object\n const contentType = unpaidResponse ? unpaidResponse.contentType : \"application/json\";\n const body = unpaidResponse ? unpaidResponse.body : {};\n\n return {\n status,\n headers: {\n \"Content-Type\": contentType,\n ...response.headers,\n },\n body,\n };\n }\n\n /**\n * Create HTTP payment required response (v1 puts in body, v2 puts in header)\n *\n * @param paymentRequired - Payment required object\n * @returns Headers and body for the HTTP response\n */\n private createHTTPPaymentRequiredResponse(paymentRequired: PaymentRequired): {\n headers: Record;\n } {\n return {\n headers: {\n \"PAYMENT-REQUIRED\": encodePaymentRequiredHeader(paymentRequired),\n },\n };\n }\n\n /**\n * Create settlement response headers\n *\n * @param settleResponse - Settlement response\n * @returns Headers to add to response\n */\n private createSettlementHeaders(settleResponse: SettleResponse): Record {\n const encoded = encodePaymentResponseHeader(settleResponse);\n return { \"PAYMENT-RESPONSE\": encoded };\n }\n\n /**\n * Parse route pattern into verb and regex\n *\n * @param pattern - Route pattern like \"GET /api/*\", \"/api/[id]\", or \"/api/:id\"\n * @returns Parsed pattern with verb and regex\n */\n private parseRoutePattern(pattern: string): { verb: string; regex: RegExp } {\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n\n const regex = new RegExp(\n `^${\n path\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\") // Escape regex special chars\n .replace(/\\*/g, \".*?\") // Wildcards\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Parameters (Next.js style [param])\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, \"[^/]+\") // Parameters (Express style :param)\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n );\n\n return { verb: verb.toUpperCase(), regex };\n }\n\n /**\n * Normalize path for matching\n *\n * @param path - Raw path from request\n * @returns Normalized path\n */\n private normalizePath(path: string): string {\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n let decodedOrRawPath: string;\n try {\n decodedOrRawPath = decodeURIComponent(pathWithoutQuery);\n } catch {\n decodedOrRawPath = pathWithoutQuery;\n }\n\n return decodedOrRawPath\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/(.+?)\\/+$/, \"$1\");\n }\n\n /**\n * Generate paywall HTML for browser requests\n *\n * @param paymentRequired - Payment required response\n * @param paywallConfig - Optional paywall configuration\n * @param customHtml - Optional custom HTML template\n * @returns HTML string\n */\n private generatePaywallHTML(\n paymentRequired: PaymentRequired,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n ): string {\n if (customHtml) {\n return customHtml;\n }\n\n // Use custom paywall provider if set\n if (this.paywallProvider) {\n return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);\n }\n\n // Try to use @x402/paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@x402/paywall\");\n const displayAmount = this.getDisplayAmount(paymentRequired);\n const resource = paymentRequired.resource;\n\n return paywall.getPaywallHtml({\n amount: displayAmount,\n paymentRequired,\n currentUrl: resource?.url || paywallConfig?.currentUrl || \"\",\n testnet: paywallConfig?.testnet ?? true,\n appName: paywallConfig?.appName,\n appLogo: paywallConfig?.appLogo,\n sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint,\n });\n } catch {\n // @x402/paywall not installed, fall back to basic HTML\n }\n\n // Fallback: Basic HTML paywall\n const resource = paymentRequired.resource;\n const displayAmount = this.getDisplayAmount(paymentRequired);\n\n return `\n \n \n \n Payment Required\n \n \n \n \n
\n ${paywallConfig?.appLogo ? `\"${paywallConfig.appName` : \"\"}\n

Payment Required

\n ${resource ? `

Resource: ${resource.description || resource.url}

` : \"\"}\n

Amount: $${displayAmount.toFixed(2)} USDC

\n
\n \n

\n Note: Install @x402/paywall for full wallet connection and payment UI.\n

\n
\n
\n \n \n `;\n }\n\n /**\n * Extract display amount from payment requirements.\n *\n * @param paymentRequired - The payment required object\n * @returns The display amount in decimal format\n */\n private getDisplayAmount(paymentRequired: PaymentRequired): number {\n const accepts = paymentRequired.accepts;\n if (accepts && accepts.length > 0) {\n const firstReq = accepts[0];\n if (\"amount\" in firstReq) {\n // V2 format\n return parseFloat(firstReq.amount) / 1000000; // Assuming USDC with 6 decimals\n }\n }\n return 0;\n }\n}\n","import { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport {\n VerifyResponse,\n SettleResponse,\n SupportedResponse,\n VerifyError,\n SettleError,\n} from \"../types/facilitator\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://x402.org/facilitator\";\n\nexport interface FacilitatorConfig {\n url?: string;\n createAuthHeaders?: () => Promise<{\n verify: Record;\n settle: Record;\n supported: Record;\n }>;\n}\n\n/**\n * Interface for facilitator clients\n * Can be implemented for HTTP-based or local facilitators\n */\nexport interface FacilitatorClient {\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Get supported payment kinds and extensions from the facilitator\n *\n * @returns Supported payment kinds and extensions\n */\n getSupported(): Promise;\n}\n\n/** Number of retries for getSupported() on 429 rate limit errors */\nconst GET_SUPPORTED_RETRIES = 3;\n/** Base delay in ms for exponential backoff on retries */\nconst GET_SUPPORTED_RETRY_DELAY_MS = 1000;\n\n/**\n * HTTP-based client for interacting with x402 facilitator services\n * Handles HTTP communication with facilitator endpoints\n */\nexport class HTTPFacilitatorClient implements FacilitatorClient {\n readonly url: string;\n private readonly _createAuthHeaders?: FacilitatorConfig[\"createAuthHeaders\"];\n\n /**\n * Creates a new HTTPFacilitatorClient instance.\n *\n * @param config - Configuration options for the facilitator client\n */\n constructor(config?: FacilitatorConfig) {\n this.url = config?.url || DEFAULT_FACILITATOR_URL;\n this._createAuthHeaders = config?.createAuthHeaders;\n }\n\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n async verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"verify\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/verify`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n const verifyResponse = data as VerifyResponse;\n if (!response.ok) {\n throw new VerifyError(response.status, verifyResponse);\n }\n return verifyResponse;\n }\n\n throw new Error(`Facilitator verify failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n async settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"settle\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/settle`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n const settleResponse = data as SettleResponse;\n if (!response.ok) {\n throw new SettleError(response.status, settleResponse);\n }\n return settleResponse;\n }\n\n throw new Error(`Facilitator settle failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Get supported payment kinds and extensions from the facilitator.\n * Retries with exponential backoff on 429 rate limit errors.\n *\n * @returns Supported payment kinds and extensions\n */\n async getSupported(): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"supported\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {\n const response = await fetch(`${this.url}/supported`, {\n method: \"GET\",\n headers,\n });\n\n if (response.ok) {\n return (await response.json()) as SupportedResponse;\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(`Facilitator getSupported failed (${response.status}): ${errorText}`);\n\n // Retry on 429 rate limit errors with exponential backoff\n if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {\n const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n throw lastError;\n }\n\n throw lastError ?? new Error(\"Facilitator getSupported failed after retries\");\n }\n\n /**\n * Creates authentication headers for a specific path.\n *\n * @param path - The path to create authentication headers for (e.g., \"verify\", \"settle\", \"supported\")\n * @returns An object containing the authentication headers for the specified path\n */\n async createAuthHeaders(path: string): Promise<{\n headers: Record;\n }> {\n if (this._createAuthHeaders) {\n const authHeaders = (await this._createAuthHeaders()) as Record<\n string,\n Record\n >;\n return {\n headers: authHeaders[path] ?? {},\n };\n }\n return {\n headers: {},\n };\n }\n\n /**\n * Helper to convert objects to JSON-safe format.\n * Handles BigInt and other non-JSON types.\n *\n * @param obj - The object to convert\n * @returns The JSON-safe representation of the object\n */\n private toJsonSafe(obj: unknown): unknown {\n return JSON.parse(\n JSON.stringify(obj, (_, value) => (typeof value === \"bigint\" ? value.toString() : value)),\n );\n }\n}\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client } from \"../client/x402Client\";\n\n/**\n * Context provided to onPaymentRequired hooks.\n */\nexport interface PaymentRequiredContext {\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return headers to try before payment, or void to proceed directly to payment.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<{ headers: Record } | void>;\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n private paymentRequiredHooks: PaymentRequiredHook[] = [];\n\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Register a hook to handle 402 responses before payment.\n * Hooks run in order; first to return headers wins.\n *\n * @param hook - The hook function to register\n * @returns This instance for chaining\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Run hooks and return headers if any hook provides them.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Headers to use for retry, or null to proceed to payment\n */\n async handlePaymentRequired(\n paymentRequired: PaymentRequired,\n ): Promise | null> {\n for (const hook of this.paymentRequiredHooks) {\n const result = await hook({ paymentRequired });\n if (result?.headers) {\n return result.headers;\n }\n }\n return null;\n }\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequired): Promise {\n return this.client.createPaymentPayload(paymentRequired);\n }\n}\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(paymentResponse: SettleResponse): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPTransportContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n HTTPResponseBody,\n SettlementFailedResponseBody,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n ProtectedRequestHook,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { x402HTTPClient, PaymentRequiredContext, PaymentRequiredHook } from \"./x402HTTPClient\";\n","import { x402Version } from \"..\";\nimport { SchemeNetworkClient } from \"../types/mechanisms\";\nimport { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport { Network, PaymentRequired } from \"../types\";\nimport { findByNetworkAndScheme, findSchemesByNetwork } from \"../utils\";\n\n/**\n * Client Hook Context Interfaces\n */\n\nexport interface PaymentCreationContext {\n paymentRequired: PaymentRequired;\n selectedRequirements: PaymentRequirements;\n}\n\nexport interface PaymentCreatedContext extends PaymentCreationContext {\n paymentPayload: PaymentPayload;\n}\n\nexport interface PaymentCreationFailureContext extends PaymentCreationContext {\n error: Error;\n}\n\n/**\n * Client Hook Type Definitions\n */\n\nexport type BeforePaymentCreationHook = (\n context: PaymentCreationContext,\n) => Promise;\n\nexport type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise;\n\nexport type OnPaymentCreationFailureHook = (\n context: PaymentCreationFailureContext,\n) => Promise;\n\nexport type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;\n\n/**\n * Extension that can enrich payment payloads on the client side.\n *\n * Client extensions are invoked after the scheme creates the base payment payload\n * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612\n * permit signing) to enrich the payload's extensions data.\n */\nexport interface ClientExtension {\n /**\n * Unique key identifying this extension (e.g., \"eip2612GasSponsoring\").\n * Must match the extension key used in PaymentRequired.extensions.\n */\n key: string;\n\n /**\n * Called after payload creation when the extension key is present in\n * paymentRequired.extensions. Allows the extension to enrich the payload\n * with extension-specific data (e.g., signing an EIP-2612 permit).\n *\n * @param paymentPayload - The payment payload to enrich\n * @param paymentRequired - The original PaymentRequired response\n * @returns The enriched payment payload\n */\n enrichPaymentPayload?: (\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ) => Promise;\n}\n\n/**\n * A policy function that filters or transforms payment requirements.\n * Policies are applied in order before the selector chooses the final option.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of payment requirements to filter/transform\n * @returns Filtered array of payment requirements\n */\nexport type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];\n\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme client implementation for this network\n */\n client: SchemeNetworkClient;\n\n /**\n * The x402 protocol version to use for this scheme\n *\n * @default 2\n */\n x402Version?: number;\n}\n\n/**\n * Configuration options for the fetch wrapper\n */\nexport interface x402ClientConfig {\n /**\n * Array of scheme registrations defining which payment methods are supported\n */\n schemes: SchemeRegistration[];\n\n /**\n * Policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Custom payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n}\n\n/**\n * Core client for managing x402 payment schemes and creating payment payloads.\n *\n * Handles registration of payment schemes, policy-based filtering of payment requirements,\n * and creation of payment payloads based on server requirements.\n */\nexport class x402Client {\n private readonly paymentRequirementsSelector: SelectPaymentRequirements;\n private readonly registeredClientSchemes: Map>> = new Map();\n private readonly policies: PaymentPolicy[] = [];\n private readonly registeredExtensions: Map = new Map();\n\n private beforePaymentCreationHooks: BeforePaymentCreationHook[] = [];\n private afterPaymentCreationHooks: AfterPaymentCreationHook[] = [];\n private onPaymentCreationFailureHooks: OnPaymentCreationFailureHook[] = [];\n\n /**\n * Creates a new x402Client instance.\n *\n * @param paymentRequirementsSelector - Function to select payment requirements from available options\n */\n constructor(paymentRequirementsSelector?: SelectPaymentRequirements) {\n this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version, accepts) => accepts[0]);\n }\n\n /**\n * Creates a new x402Client instance from a configuration object.\n *\n * @param config - The client configuration including schemes, policies, and payment requirements selector\n * @returns A configured x402Client instance\n */\n static fromConfig(config: x402ClientConfig): x402Client {\n const client = new x402Client(config.paymentRequirementsSelector);\n config.schemes.forEach(scheme => {\n if (scheme.x402Version === 1) {\n client.registerV1(scheme.network, scheme.client);\n } else {\n client.register(scheme.network, scheme.client);\n }\n });\n config.policies?.forEach(policy => {\n client.registerPolicy(policy);\n });\n return client;\n }\n\n /**\n * Registers a scheme client for the current x402 version.\n *\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n register(network: Network, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(x402Version, network, client);\n }\n\n /**\n * Registers a scheme client for x402 version 1.\n *\n * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n registerV1(network: string, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(1, network as Network, client);\n }\n\n /**\n * Registers a policy to filter or transform payment requirements.\n *\n * Policies are applied in order after filtering by registered schemes\n * and before the selector chooses the final payment requirement.\n *\n * @param policy - Function to filter/transform payment requirements\n * @returns The x402Client instance for chaining\n *\n * @example\n * ```typescript\n * // Prefer cheaper options\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))\n * );\n *\n * // Prefer specific networks\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => r.network.startsWith('eip155:'))\n * );\n * ```\n */\n registerPolicy(policy: PaymentPolicy): x402Client {\n this.policies.push(policy);\n return this;\n }\n\n /**\n * Registers a client extension that can enrich payment payloads.\n *\n * Extensions are invoked after the scheme creates the base payload and the\n * payload is wrapped with extensions/resource/accepted data. If the extension's\n * key is present in `paymentRequired.extensions`, the extension's\n * `enrichPaymentPayload` hook is called to modify the payload.\n *\n * @param extension - The client extension to register\n * @returns The x402Client instance for chaining\n */\n registerExtension(extension: ClientExtension): x402Client {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Register a hook to execute before payment payload creation.\n * Can abort creation by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client {\n this.beforePaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment payload creation.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client {\n this.afterPaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment payload creation fails.\n * Can recover from failure by returning { recovered: true, payload: PaymentPayload }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client {\n this.onPaymentCreationFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Creates a payment payload based on a PaymentRequired response.\n *\n * Automatically extracts x402Version, resource, and extensions from the PaymentRequired\n * response and constructs a complete PaymentPayload with the accepted requirements.\n *\n * @param paymentRequired - The PaymentRequired response from the server\n * @returns Promise resolving to the complete payment payload\n */\n async createPaymentPayload(\n paymentRequired: PaymentRequired,\n ): Promise {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);\n }\n\n const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);\n\n const context: PaymentCreationContext = {\n paymentRequired,\n selectedRequirements: requirements,\n };\n\n // Execute beforePaymentCreation hooks\n for (const hook of this.beforePaymentCreationHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Payment creation aborted: ${result.reason}`);\n }\n }\n\n try {\n const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);\n if (!schemeNetworkClient) {\n throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);\n }\n\n const partialPayload = await schemeNetworkClient.createPaymentPayload(\n paymentRequired.x402Version,\n requirements,\n { extensions: paymentRequired.extensions },\n );\n\n let paymentPayload: PaymentPayload;\n if (partialPayload.x402Version == 1) {\n paymentPayload = partialPayload as PaymentPayload;\n } else {\n // Merge server-declared extensions with any scheme-provided extensions.\n // Scheme extensions overlay on top (e.g., EIP-2612 info enriches server declaration).\n const mergedExtensions = this.mergeExtensions(\n paymentRequired.extensions,\n partialPayload.extensions,\n );\n\n paymentPayload = {\n x402Version: partialPayload.x402Version,\n payload: partialPayload.payload,\n extensions: mergedExtensions,\n resource: paymentRequired.resource,\n accepted: requirements,\n };\n }\n\n // Enrich payload via registered client extensions (for non-scheme extensions)\n paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);\n\n // Execute afterPaymentCreation hooks\n const createdContext: PaymentCreatedContext = {\n ...context,\n paymentPayload,\n };\n\n for (const hook of this.afterPaymentCreationHooks) {\n await hook(createdContext);\n }\n\n return paymentPayload;\n } catch (error) {\n const failureContext: PaymentCreationFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onPaymentCreationFailure hooks\n for (const hook of this.onPaymentCreationFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.payload;\n }\n }\n\n throw error;\n }\n }\n\n\n\n /**\n * Merges server-declared extensions with scheme-provided extensions.\n * Scheme extensions overlay on top of server extensions at each key,\n * preserving server-provided schema while overlaying scheme-provided info.\n *\n * @param serverExtensions - Extensions declared by the server in the 402 response\n * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)\n * @returns The merged extensions object, or undefined if both inputs are undefined\n */\n private mergeExtensions(\n serverExtensions?: Record,\n schemeExtensions?: Record,\n ): Record | undefined {\n if (!schemeExtensions) return serverExtensions;\n if (!serverExtensions) return schemeExtensions;\n\n const merged = { ...serverExtensions };\n for (const [key, schemeValue] of Object.entries(schemeExtensions)) {\n const serverValue = merged[key];\n if (\n serverValue &&\n typeof serverValue === \"object\" &&\n schemeValue &&\n typeof schemeValue === \"object\"\n ) {\n // Deep merge: scheme info overlays server info, schema preserved\n merged[key] = { ...serverValue as Record, ...schemeValue as Record };\n } else {\n merged[key] = schemeValue;\n }\n }\n return merged;\n }\n\n /**\n * Enriches a payment payload by calling registered extension hooks.\n * For each extension key present in the PaymentRequired response,\n * invokes the corresponding extension's enrichPaymentPayload callback.\n *\n * @param paymentPayload - The payment payload to enrich with extension data\n * @param paymentRequired - The PaymentRequired response containing extension declarations\n * @returns The enriched payment payload with extension data applied\n */\n private async enrichPaymentPayloadWithExtensions(\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ): Promise {\n if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {\n return paymentPayload;\n }\n\n let enriched = paymentPayload;\n for (const [key, extension] of this.registeredExtensions) {\n if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {\n enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);\n }\n }\n\n return enriched;\n }\n\n /**\n * Selects appropriate payment requirements based on registered clients and policies.\n *\n * Selection process:\n * 1. Filter by registered schemes (network + scheme support)\n * 2. Apply all registered policies in order\n * 3. Use selector to choose final requirement\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of available payment requirements\n * @returns The selected payment requirements\n */\n private selectPaymentRequirements(x402Version: number, paymentRequirements: PaymentRequirements[]): PaymentRequirements {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${x402Version}`);\n }\n\n // Step 1: Filter by registered schemes\n const supportedPaymentRequirements = paymentRequirements.filter(requirement => {\n let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);\n if (!clientSchemes) {\n return false;\n }\n\n return clientSchemes.has(requirement.scheme);\n })\n\n if (supportedPaymentRequirements.length === 0) {\n throw new Error(`No network/scheme registered for x402 version: ${x402Version} which comply with the payment requirements. ${JSON.stringify({\n x402Version,\n paymentRequirements,\n x402Versions: Array.from(this.registeredClientSchemes.keys()),\n networks: Array.from(clientSchemesByNetwork.keys()),\n schemes: Array.from(clientSchemesByNetwork.values()).map(schemes => Array.from(schemes.keys())).flat(),\n })}`);\n }\n\n // Step 2: Apply all policies in order\n let filteredRequirements = supportedPaymentRequirements;\n for (const policy of this.policies) {\n filteredRequirements = policy(x402Version, filteredRequirements);\n\n if (filteredRequirements.length === 0) {\n throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version}`);\n }\n }\n\n // Step 3: Use selector to choose final requirement\n return this.paymentRequirementsSelector(x402Version, filteredRequirements);\n }\n\n /**\n * Internal method to register a scheme client.\n *\n * @param x402Version - The x402 protocol version\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n private _registerScheme(x402Version: number, network: Network, client: SchemeNetworkClient): x402Client {\n if (!this.registeredClientSchemes.has(x402Version)) {\n this.registeredClientSchemes.set(x402Version, new Map());\n }\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version)!;\n if (!clientSchemesByNetwork.has(network)) {\n clientSchemesByNetwork.set(network, new Map());\n }\n\n const clientByScheme = clientSchemesByNetwork.get(network)!;\n if (!clientByScheme.has(client.scheme)) {\n clientByScheme.set(client.scheme, client);\n }\n\n return this;\n }\n}\n","import { x402Client, x402ClientConfig, x402HTTPClient } from \"@x402/core/client\";\nimport { type PaymentRequired } from \"@x402/core/types\";\n\n/**\n * Enables the payment of APIs using the x402 payment protocol v2.\n *\n * This function wraps the native fetch API to automatically handle 402 Payment Required responses\n * by creating and sending payment headers. It will:\n * 1. Make the initial request\n * 2. If a 402 response is received, parse the payment requirements\n * 3. Create a payment header using the configured x402HTTPClient\n * 4. Retry the request with the payment header\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param client - Configured x402Client or x402HTTPClient instance for handling payments\n * @returns A wrapped fetch function that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * import { wrapFetchWithPayment, x402Client } from '@x402/fetch';\n * import { ExactEvmScheme } from '@x402/evm';\n * import { ExactSvmScheme } from '@x402/svm';\n *\n * const client = new x402Client()\n * .register('eip155:8453', new ExactEvmScheme(evmSigner))\n * .register('solana:mainnet', new ExactSvmScheme(svmSigner))\n * .register('eip155:1', new ExactEvmScheme(evmSigner), 1); // v1 protocol\n *\n * const fetchWithPay = wrapFetchWithPayment(fetch, client);\n *\n * // Make a request that may require payment\n * const response = await fetchWithPay('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If no schemes are provided\n * @throws {Error} If the request configuration is missing\n * @throws {Error} If a payment has already been attempted for this request\n * @throws {Error} If there's an error creating the payment header\n */\nexport function wrapFetchWithPayment(\n fetch: typeof globalThis.fetch,\n client: x402Client | x402HTTPClient,\n) {\n const httpClient = client instanceof x402HTTPClient ? client : new x402HTTPClient(client);\n\n return async (input: RequestInfo | URL, init?: RequestInit) => {\n const request = new Request(input, init);\n const clonedRequest = request.clone();\n\n const response = await fetch(request);\n\n if (response.status !== 402) {\n return response;\n }\n\n // Parse payment requirements from response\n let paymentRequired: PaymentRequired;\n try {\n // Create getHeader function for case-insensitive header lookup\n const getHeader = (name: string) => response.headers.get(name);\n\n // Try to get from headers first (v2), then from body (v1)\n let body: PaymentRequired | undefined;\n try {\n const responseText = await response.text();\n if (responseText) {\n body = JSON.parse(responseText) as PaymentRequired;\n }\n } catch {\n // Ignore JSON parse errors - might be header-only response\n }\n\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n } catch (error) {\n throw new Error(\n `Failed to parse payment requirements: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Run payment required hooks\n const hookHeaders = await httpClient.handlePaymentRequired(paymentRequired);\n if (hookHeaders) {\n const hookRequest = clonedRequest.clone();\n for (const [key, value] of Object.entries(hookHeaders)) {\n hookRequest.headers.set(key, value);\n }\n const hookResponse = await fetch(hookRequest);\n if (hookResponse.status !== 402) {\n return hookResponse; // Hook succeeded\n }\n // Hook's retry got 402, fall through to payment\n }\n\n // Create payment payload (copy extensions from PaymentRequired)\n let paymentPayload;\n try {\n paymentPayload = await client.createPaymentPayload(paymentRequired);\n } catch (error) {\n throw new Error(\n `Failed to create payment payload: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Encode payment header\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);\n\n // Check if this is already a retry to prevent infinite loops\n if (clonedRequest.headers.has(\"PAYMENT-SIGNATURE\") || clonedRequest.headers.has(\"X-PAYMENT\")) {\n throw new Error(\"Payment already attempted\");\n }\n\n // Add payment headers to cloned request\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n clonedRequest.headers.set(\n \"Access-Control-Expose-Headers\",\n \"PAYMENT-RESPONSE,X-PAYMENT-RESPONSE\",\n );\n\n // Retry the request with payment\n const secondResponse = await fetch(clonedRequest);\n return secondResponse;\n };\n}\n\n/**\n * Creates a payment-enabled fetch function from a configuration object.\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param config - Configuration options including scheme registrations and selectors\n * @returns A wrapped fetch function that handles 402 responses automatically\n */\nexport function wrapFetchWithPaymentFromConfig(\n fetch: typeof globalThis.fetch,\n config: x402ClientConfig,\n) {\n const client = x402Client.fromConfig(config);\n return wrapFetchWithPayment(fetch, client);\n}\n\n// Re-export types and utilities for convenience\nexport { x402Client, x402HTTPClient } from \"@x402/core/client\";\nexport type {\n PaymentPolicy,\n SchemeRegistration,\n SelectPaymentRequirements,\n x402ClientConfig,\n} from \"@x402/core/client\";\nexport { decodePaymentResponseHeader } from \"@x402/core/http\";\nexport type {\n Network,\n PaymentPayload,\n PaymentRequired,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\n","/**\n * Payment Pre-Auth Cache\n *\n * Wraps the @x402/fetch SDK with pre-authorization caching.\n * After the first 402 response, caches payment requirements per endpoint.\n * On subsequent requests, pre-signs payment and attaches it to the first\n * request, skipping the 402 round trip (~200ms savings per request).\n *\n * Falls back to normal 402 flow if pre-signed payment is rejected.\n */\n\nimport type { x402Client } from \"@x402/fetch\";\nimport { x402HTTPClient } from \"@x402/fetch\";\n\ntype PaymentRequired = Parameters[\"createPaymentPayload\"]>[0];\n\ninterface CachedEntry {\n paymentRequired: PaymentRequired;\n cachedAt: number;\n}\n\nconst DEFAULT_TTL_MS = 3_600_000; // 1 hour\n\ntype FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise;\n\nexport function createPayFetchWithPreAuth(\n baseFetch: FetchFn,\n client: x402Client,\n ttlMs = DEFAULT_TTL_MS,\n options?: { skipPreAuth?: boolean },\n): FetchFn {\n const httpClient = new x402HTTPClient(client);\n const cache = new Map();\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise => {\n const request = new Request(input, init);\n const urlPath = new URL(request.url).pathname;\n\n // Extract model from request body to create model-specific cache keys.\n // Without this, a cached payment from a paid model (e.g. sonnet) would be\n // incorrectly applied to a free model (nvidia/gpt-oss-120b), causing\n // payment errors even when the server wouldn't charge for the request.\n let requestModel = \"\";\n if (init?.body) {\n try {\n const bodyStr =\n init.body instanceof Uint8Array\n ? new TextDecoder().decode(init.body)\n : typeof init.body === \"string\"\n ? init.body\n : \"\";\n if (bodyStr) {\n const parsed = JSON.parse(bodyStr) as { model?: string };\n requestModel = parsed.model ?? \"\";\n }\n } catch {\n /* not JSON, use empty model */\n }\n }\n const cacheKey = `${urlPath}:${requestModel}`;\n\n // Try pre-auth if we have cached payment requirements\n // Skip for Solana: payments use per-tx blockhashes that expire ~60-90s,\n // making cached requirements useless and causing double charges.\n const cached = !options?.skipPreAuth ? cache.get(cacheKey) : undefined;\n if (cached && Date.now() - cached.cachedAt < ttlMs) {\n try {\n const payload = await client.createPaymentPayload(cached.paymentRequired);\n const headers = httpClient.encodePaymentSignatureHeader(payload);\n const preAuthRequest = request.clone();\n for (const [key, value] of Object.entries(headers)) {\n preAuthRequest.headers.set(key, value);\n }\n const response = await baseFetch(preAuthRequest);\n if (response.status !== 402) {\n return response; // Pre-auth worked — saved ~200ms\n }\n // Pre-auth rejected (params may have changed) — invalidate and fall through\n cache.delete(cacheKey);\n } catch {\n // Pre-auth signing failed — invalidate and fall through\n cache.delete(cacheKey);\n }\n }\n\n // Normal flow: make request, handle 402 if needed\n const clonedRequest = request.clone();\n const response = await baseFetch(request);\n if (response.status !== 402) {\n return response;\n }\n\n // Parse 402 response and cache for future pre-auth\n let paymentRequired: PaymentRequired;\n try {\n const getHeader = (name: string) => response.headers.get(name);\n let body: unknown;\n try {\n const responseText = await Promise.race([\n response.text(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Body read timeout\")), 30_000),\n ),\n ]);\n if (responseText) body = JSON.parse(responseText);\n } catch {\n /* empty body is fine */\n }\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n cache.set(cacheKey, { paymentRequired, cachedAt: Date.now() });\n } catch (error) {\n throw new Error(\n `Failed to parse payment requirements: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n { cause: error },\n );\n }\n\n // Sign payment and retry\n const payload = await client.createPaymentPayload(paymentRequired);\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(payload);\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n return baseFetch(clonedRequest);\n };\n}\n","import type { PaymentPayload } from \"@x402/core/types\";\nimport type { FacilitatorEvmSigner } from \"../signer\";\n\nexport const EIP2612_GAS_SPONSORING_KEY = \"eip2612GasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_KEY = \"erc20ApprovalGasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_VERSION = \"1\" as const;\n\nexport interface Eip2612GasSponsoringInfo {\n [key: string]: unknown;\n from: string;\n asset: string;\n spender: string;\n amount: string;\n nonce: string;\n deadline: string;\n signature: string;\n version: string;\n}\n\nexport interface Erc20ApprovalGasSponsoringInfo {\n [key: string]: unknown;\n from: `0x${string}`;\n asset: `0x${string}`;\n spender: `0x${string}`;\n amount: string;\n signedTransaction: `0x${string}`;\n version: string;\n}\n\n/**\n * A single transaction to be executed by the signer.\n * - `0x${string}`: a pre-signed serialized transaction (broadcast as-is via sendRawTransaction)\n * - `{ to, data, gas? }`: an unsigned call intent (signer signs and broadcasts)\n */\nexport type TransactionRequest =\n | `0x${string}`\n | { to: `0x${string}`; data: `0x${string}`; gas?: bigint };\n\nexport type Erc20ApprovalGasSponsoringSigner = FacilitatorEvmSigner & {\n sendTransactions(transactions: TransactionRequest[]): Promise<`0x${string}`[]>;\n simulateTransactions?(transactions: TransactionRequest[]): Promise;\n};\n\nexport interface Erc20ApprovalGasSponsoringFacilitatorExtension {\n key: typeof ERC20_APPROVAL_GAS_SPONSORING_KEY;\n signer?: Erc20ApprovalGasSponsoringSigner;\n signerForNetwork?: (network: string) => Erc20ApprovalGasSponsoringSigner | undefined;\n}\n\n/**\n * Extracts a typed `info` payload from an extension entry.\n *\n * @param payload - Payment payload containing optional extensions.\n * @param extensionKey - Extension key to extract.\n * @returns The extension `info` object when present; otherwise null.\n */\nfunction _extractInfo(\n payload: PaymentPayload,\n extensionKey: string,\n): Record | null {\n const extensions = payload.extensions;\n if (!extensions) return null;\n const extension = extensions[extensionKey] as { info?: Record } | undefined;\n if (!extension?.info) return null;\n return extension.info;\n}\n\n/**\n * Extracts and validates required EIP-2612 gas sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed EIP-2612 gas sponsoring info when available and complete.\n */\nexport function extractEip2612GasSponsoringInfo(\n payload: PaymentPayload,\n): Eip2612GasSponsoringInfo | null {\n const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.nonce ||\n !info.deadline ||\n !info.signature ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Eip2612GasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of EIP-2612 sponsoring info.\n *\n * @param info - EIP-2612 extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateEip2612GasSponsoringInfo(info: Eip2612GasSponsoringInfo): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n numericPattern.test(info.nonce) &&\n numericPattern.test(info.deadline) &&\n hexPattern.test(info.signature) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Extracts and validates required ERC-20 approval sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed ERC-20 approval sponsoring info when available and complete.\n */\nexport function extractErc20ApprovalGasSponsoringInfo(\n payload: PaymentPayload,\n): Erc20ApprovalGasSponsoringInfo | null {\n const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.signedTransaction ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Erc20ApprovalGasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of ERC-20 approval sponsoring info.\n *\n * @param info - ERC-20 approval extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateErc20ApprovalGasSponsoringInfo(\n info: Erc20ApprovalGasSponsoringInfo,\n): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n hexPattern.test(info.signedTransaction) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Resolves the ERC-20 approval extension signer for a specific network.\n *\n * @param extension - Optional facilitator extension config.\n * @param network - CAIP-2 network identifier.\n * @returns A network-specific signer when available, else the default signer.\n */\nexport function resolveErc20ApprovalExtensionSigner(\n extension: Erc20ApprovalGasSponsoringFacilitatorExtension | undefined,\n network: string,\n): Erc20ApprovalGasSponsoringSigner | undefined {\n if (!extension) return undefined;\n return extension.signerForNetwork?.(network) ?? extension.signer;\n}\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce } from \"../../../utils\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainIdV1(requirements.network as EvmNetworkV1);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Permit2 EIP-712 types for signing PermitWitnessTransferFrom.\n * Must match the exact format expected by the Permit2 contract.\n * Note: Types must be in ALPHABETICAL order after the primary type (TokenPermissions < Witness).\n */\nexport const permit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"Witness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n Witness: [\n { name: \"to\", type: \"address\" },\n { name: \"validAfter\", type: \"uint256\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"name\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"authorizer\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n name: \"authorizationState\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/**\n * EIP-2612 Permit EIP-712 types for signing token.permit().\n */\nexport const eip2612PermitTypes = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * EIP-2612 nonces ABI for querying current nonce.\n */\nexport const eip2612NoncesAbi = [\n {\n type: \"function\",\n name: \"nonces\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** ERC-20 approve(address,uint256) ABI for encoding/decoding approval calldata. */\nexport const erc20ApproveAbi = [\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n] as const;\n\n/** ERC-20 allowance(address,address) ABI for checking spender approval. */\nexport const erc20AllowanceAbi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** Gas limit for a standard ERC-20 approve() transaction. */\nexport const ERC20_APPROVE_GAS_LIMIT = 70_000n;\n\n/** Fallback max fee per gas (1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_FEE_PER_GAS = 1_000_000_000n;\n\n/** Fallback max priority fee per gas (0.1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100_000_000n;\n\n/**\n * Canonical Permit2 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/Uniswap/permit2\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\" as const;\n\n/**\n * x402ExactPermit2Proxy contract address.\n * Vanity address: 0x4020...0001 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0001\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402ExactPermit2ProxyAddress = \"0x402085c248EeA27D92E8b30b2C58ed07f9E20001\" as const;\n\n/**\n * x402UptoPermit2Proxy contract address.\n * Vanity address: 0x4020...0002 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0002\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402UptoPermit2ProxyAddress = \"0x402039b3d6E6BEC5A02c2C9fd937ac17A6940002\" as const;\n\n/**\n * Shared ABI components for the Permit2 witness tuple.\n * Used in both x402ExactPermit2ProxyABI and x402UptoPermit2ProxyABI to keep them in sync.\n * The upto contract's witness struct is identical to exact (both remove 'extra' post-audit).\n */\nconst permit2WitnessABIComponents = [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"validAfter\", type: \"uint256\", internalType: \"uint256\" },\n] as const;\n\n/**\n * x402UptoPermit2Proxy ABI - settle function for upto payment scheme (variable amounts).\n * Updated post-audit: 'extra' removed from witness struct, 'initialize()' removed (now\n * a constructor arg), and error names aligned with x402ExactPermit2Proxy.\n */\nexport const x402UptoPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n\n/**\n * x402ExactPermit2Proxy ABI - settle function for exact payment scheme.\n */\nexport const x402ExactPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n","import { toHex } from \"viem\";\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (network.startsWith(\"eip155:\")) {\n const idStr = network.split(\":\")[1];\n const chainId = parseInt(idStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n return chainId;\n }\n\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\nimport * as Errors from \"../../facilitator/errors\";\nimport {\n diagnoseEip3009SimulationFailure,\n executeTransferWithAuthorization,\n simulateEip3009Transfer,\n} from \"../../facilitator/eip3009-utils\";\n\nexport interface VerifyV1Options {\n /** Run onchain simulation. Defaults to true. */\n simulate?: boolean;\n}\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * If enabled, the facilitator will deploy ERC-4337 smart wallets\n * via EIP-6492 when encountering undeployed contract signatures.\n *\n * @default false\n */\n deployERC4337WithEIP6492?: boolean;\n /**\n * If enabled, simulates transaction before settling. Defaults to false, ie only simulate during verify.\n *\n * @default false\n */\n simulateInSettle?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n deployERC4337WithEIP6492: config?.deployERC4337WithEIP6492 ?? false,\n simulateInSettle: config?.simulateInSettle ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n return this._verify(payload, requirements);\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this._verify(payload, requirements, {\n simulate: this.config.simulateInSettle ?? false,\n });\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? Errors.ErrInvalidScheme,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable (for optional deployment)\n const { address: factoryAddress, data: factoryCalldata } = parseErc6492Signature(\n exactEvmPayload.signature!,\n );\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if configured and needed\n if (\n this.config.deployERC4337WithEIP6492 &&\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment transaction\n await this.signer.waitForTransactionReceipt({ hash: deployTx });\n }\n }\n\n const tx = await executeTransferWithAuthorization(\n this.signer,\n getAddress(requirements.asset),\n exactEvmPayload,\n );\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: Errors.ErrTransactionFailed,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n return {\n success: false,\n errorReason: error instanceof Error ? error.message : Errors.ErrTransactionFailed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n /**\n * Internal verify with optional simulation control.\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @param options - Verification options (e.g. simulate)\n * @returns Promise resolving to verification response\n */\n private async _verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n options?: VerifyV1Options,\n ): Promise {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n const payer = exactEvmPayload.authorization.from;\n let eip6492Deployment:\n | { factoryAddress: `0x${string}`; factoryCalldata: `0x${string}` }\n | undefined;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidScheme,\n payer,\n };\n }\n\n // Get chain configuration\n let chainId: number;\n try {\n chainId = getEvmChainIdV1(payloadV1.network as EvmNetworkV1);\n } catch {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: Errors.ErrMissingEip712Domain,\n payer,\n };\n }\n\n const { name, version } = requirements.extra;\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n // Verify signature (flatten EIP-6492 handling out of catch block)\n let isValid = false;\n try {\n isValid = await this.signer.verifyTypedData({\n address: payer,\n ...permitTypedData,\n signature: exactEvmPayload.signature!,\n });\n } catch {\n isValid = false;\n }\n\n const signature = exactEvmPayload.signature!;\n const sigLen = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n\n // Extract EIP-6492 deployment info (factory address + calldata) if present\n const erc6492Data = parseErc6492Signature(signature);\n const hasDeploymentInfo =\n erc6492Data.address &&\n erc6492Data.data &&\n !isAddressEqual(erc6492Data.address, \"0x0000000000000000000000000000000000000000\");\n\n if (hasDeploymentInfo) {\n eip6492Deployment = {\n factoryAddress: erc6492Data.address!,\n factoryCalldata: erc6492Data.data!,\n };\n }\n\n if (!isValid) {\n const isSmartWallet = sigLen > 130; // 65 bytes = 130 hex chars for EOA\n\n if (!isSmartWallet) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidSignature,\n payer,\n };\n }\n\n const bytecode = await this.signer.getCode({ address: payer });\n const isDeployed = bytecode && bytecode !== \"0x\";\n\n if (!isDeployed && !hasDeploymentInfo) {\n return {\n isValid: false,\n invalidReason: Errors.ErrUndeployedSmartWallet,\n payer,\n };\n }\n }\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrRecipientMismatch,\n payer,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidBeforeExpired,\n payer,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidAfterInFuture,\n payer,\n };\n }\n\n // Verify amount exactly matches requirements\n if (BigInt(exactEvmPayload.authorization.value) !== BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidAuthorizationValue,\n payer,\n };\n }\n\n // Transaction simulation\n if (options?.simulate !== false) {\n const simulationSucceeded = await simulateEip3009Transfer(\n this.signer,\n erc20Address,\n exactEvmPayload,\n eip6492Deployment,\n );\n if (!simulationSucceeded) {\n return diagnoseEip3009SimulationFailure(\n this.signer,\n erc20Address,\n exactEvmPayload,\n requirements,\n requirementsV1.maxAmountRequired,\n );\n }\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n }\n}\n","/**\n * Named error reason constants for the exact EVM facilitator.\n *\n * These strings must be character-for-character identical to the Go constants in\n * go/mechanisms/evm/exact/facilitator/errors.go to maintain cross-SDK parity.\n */\n\nexport const ErrInvalidScheme = \"invalid_exact_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_exact_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_exact_evm_missing_eip712_domain\";\nexport const ErrRecipientMismatch = \"invalid_exact_evm_recipient_mismatch\";\nexport const ErrInvalidSignature = \"invalid_exact_evm_signature\";\nexport const ErrValidBeforeExpired = \"invalid_exact_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture = \"invalid_exact_evm_payload_authorization_valid_after\";\nexport const ErrInvalidAuthorizationValue = \"invalid_exact_evm_authorization_value\";\nexport const ErrUndeployedSmartWallet = \"invalid_exact_evm_payload_undeployed_smart_wallet\";\nexport const ErrTransactionFailed = \"invalid_exact_evm_transaction_failed\";\n\n// EIP-3009 verify errors\nexport const ErrEip3009TokenNameMismatch = \"invalid_exact_evm_token_name_mismatch\";\nexport const ErrEip3009TokenVersionMismatch = \"invalid_exact_evm_token_version_mismatch\";\nexport const ErrEip3009NotSupported = \"invalid_exact_evm_eip3009_not_supported\";\nexport const ErrEip3009NonceAlreadyUsed = \"invalid_exact_evm_nonce_already_used\";\nexport const ErrEip3009InsufficientBalance = \"invalid_exact_evm_insufficient_balance\";\nexport const ErrEip3009SimulationFailed = \"invalid_exact_evm_transaction_simulation_failed\";\n\n// Permit2 verify errors\nexport const ErrPermit2InvalidSpender = \"invalid_permit2_spender\";\nexport const ErrPermit2RecipientMismatch = \"invalid_permit2_recipient_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"permit2_deadline_expired\";\nexport const ErrPermit2NotYetValid = \"permit2_not_yet_valid\";\nexport const ErrPermit2AmountMismatch = \"permit2_amount_mismatch\";\nexport const ErrPermit2TokenMismatch = \"permit2_token_mismatch\";\nexport const ErrPermit2InvalidSignature = \"invalid_permit2_signature\";\nexport const ErrPermit2AllowanceRequired = \"permit2_allowance_required\";\nexport const ErrPermit2SimulationFailed = \"permit2_simulation_failed\";\nexport const ErrPermit2InsufficientBalance = \"permit2_insufficient_balance\";\nexport const ErrPermit2ProxyNotDeployed = \"permit2_proxy_not_deployed\";\n\n// Permit2 settle errors (from contract reverts)\nexport const ErrPermit2InvalidAmount = \"permit2_invalid_amount\";\nexport const ErrPermit2InvalidDestination = \"permit2_invalid_destination\";\nexport const ErrPermit2InvalidOwner = \"permit2_invalid_owner\";\nexport const ErrPermit2PaymentTooEarly = \"permit2_payment_too_early\";\nexport const ErrPermit2InvalidNonce = \"permit2_invalid_nonce\";\nexport const ErrPermit2612AmountMismatch = \"permit2_2612_amount_mismatch\";\n\n// ERC-20 approval gas sponsoring verify errors\nexport const ErrErc20ApprovalInsufficientEthForGas = \"erc20_approval_insufficient_eth_for_gas\";\nexport const ErrErc20ApprovalInvalidFormat = \"invalid_erc20_approval_extension_format\";\nexport const ErrErc20ApprovalFromMismatch = \"erc20_approval_from_mismatch\";\nexport const ErrErc20ApprovalAssetMismatch = \"erc20_approval_asset_mismatch\";\nexport const ErrErc20ApprovalSpenderNotPermit2 = \"erc20_approval_spender_not_permit2\";\nexport const ErrErc20ApprovalTxWrongTarget = \"erc20_approval_tx_wrong_target\";\nexport const ErrErc20ApprovalTxWrongSelector = \"erc20_approval_tx_wrong_selector\";\nexport const ErrErc20ApprovalTxWrongSpender = \"erc20_approval_tx_wrong_spender\";\nexport const ErrErc20ApprovalTxInvalidCalldata = \"erc20_approval_tx_invalid_calldata\";\nexport const ErrErc20ApprovalTxSignerMismatch = \"erc20_approval_tx_signer_mismatch\";\nexport const ErrErc20ApprovalTxInvalidSignature = \"erc20_approval_tx_invalid_signature\";\nexport const ErrErc20ApprovalTxParseFailed = \"erc20_approval_tx_parse_failed\";\nexport const ErrErc20ApprovalTxFailed = \"erc20_approval_tx_failed\";\n\n// EIP-2612 gas sponsoring verify errors\nexport const ErrInvalidEip2612ExtensionFormat = \"invalid_eip2612_extension_format\";\nexport const ErrEip2612FromMismatch = \"eip2612_from_mismatch\";\nexport const ErrEip2612AssetMismatch = \"eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderNotPermit2 = \"eip2612_spender_not_permit2\";\nexport const ErrEip2612DeadlineExpired = \"eip2612_deadline_expired\";\n\n// Shared settle errors\nexport const ErrUnsupportedPayloadType = \"unsupported_payload_type\";\nexport const ErrInvalidTransactionState = \"invalid_transaction_state\";\n","import { PaymentRequirements, VerifyResponse } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress, Hex, parseErc6492Signature, parseSignature } from \"viem\";\nimport { eip3009ABI } from \"../../constants\";\nimport { multicall, ContractCall, RawContractCall } from \"../../multicall\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport * as Errors from \"./errors\";\n\nexport interface Eip6492Deployment {\n factoryAddress: `0x${string}`;\n factoryCalldata: `0x${string}`;\n}\n\n/**\n * Simulates transferWithAuthorization via eth_call.\n * Returns true if simulation succeeded, false if it failed.\n *\n * @param signer - EVM signer for contract reads\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param eip6492Deployment - Optional EIP-6492 factory info for undeployed smart wallets\n *\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulateEip3009Transfer(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n eip6492Deployment?: Eip6492Deployment,\n): Promise {\n const auth = payload.authorization;\n const transferArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (eip6492Deployment) {\n const { signature: innerSignature } = parseErc6492Signature(payload.signature!);\n const transferCalldata = encodeFunctionData({\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, innerSignature],\n });\n\n try {\n const results = await multicall(signer.readContract.bind(signer), [\n {\n address: getAddress(eip6492Deployment.factoryAddress),\n callData: eip6492Deployment.factoryCalldata,\n } satisfies RawContractCall,\n {\n address: erc20Address,\n callData: transferCalldata,\n } satisfies RawContractCall,\n ]);\n\n return results[1]?.status === \"success\";\n } catch {\n return false;\n }\n }\n\n const sig = payload.signature!;\n const sigLength = sig.startsWith(\"0x\") ? sig.length - 2 : sig.length;\n const isECDSA = sigLength === 130;\n\n try {\n if (isECDSA) {\n const parsedSig = parseSignature(sig);\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...transferArgs,\n (parsedSig.v as number | undefined) ?? parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, sig],\n });\n }\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * After simulation fails, runs a single diagnostic multicall to determine the most specific error reason.\n * Checks balanceOf, name, version and authorizationState in one RPC round-trip.\n *\n * @param signer - EVM signer used for the payment\n * @param erc20Address - Address of the ERC-20 token contract\n * @param payload - The EIP-3009 transfer authorization payload\n * @param requirements - Payment requirements to validate against\n * @param amountRequired - Required amount for the payment (balance check)\n *\n * @returns Promise resolving to the verification result with validity and optional invalid reason\n */\nexport async function diagnoseEip3009SimulationFailure(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n requirements: PaymentRequirements,\n amountRequired: string,\n): Promise {\n const payer = payload.authorization.from;\n\n const diagnosticCalls: ContractCall[] = [\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payload.authorization.from],\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"name\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"version\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"authorizationState\",\n args: [payload.authorization.from, payload.authorization.nonce],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [balanceResult, nameResult, versionResult, authStateResult] = results;\n\n if (authStateResult.status === \"failure\") {\n return { isValid: false, invalidReason: Errors.ErrEip3009NotSupported, payer };\n }\n\n if (authStateResult.status === \"success\" && authStateResult.result === true) {\n return { isValid: false, invalidReason: Errors.ErrEip3009NonceAlreadyUsed, payer };\n }\n\n if (\n nameResult.status === \"success\" &&\n requirements.extra?.name &&\n nameResult.result !== requirements.extra.name\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenNameMismatch, payer };\n }\n\n if (\n versionResult.status === \"success\" &&\n requirements.extra?.version &&\n versionResult.result !== requirements.extra.version\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenVersionMismatch, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrEip3009InsufficientBalance,\n payer,\n };\n }\n }\n } catch {\n // Diagnostic multicall failed — fall through to generic error\n }\n\n return { isValid: false, invalidReason: Errors.ErrEip3009SimulationFailed, payer };\n}\n\n/**\n * Executes transferWithAuthorization onchain.\n *\n * @param signer - EVM signer for contract writes\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n *\n * @returns Transaction hash\n */\nexport async function executeTransferWithAuthorization(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n): Promise {\n const { signature } = parseErc6492Signature(payload.signature!);\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n const auth = payload.authorization;\n const baseArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (isECDSA) {\n const parsedSig = parseSignature(signature);\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...baseArgs,\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n }\n\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...baseArgs, signature],\n });\n}\n","import { encodeFunctionData, decodeFunctionResult } from \"viem\";\n\n/**\n * Multicall3 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/mds1/multicall\n */\nexport const MULTICALL3_ADDRESS = \"0xcA11bde05977b3631167028862bE2a173976CA11\" as const;\n\n/** Multicall3 getEthBalance ABI for querying native token balance. */\nexport const multicall3GetEthBalanceAbi = [\n {\n name: \"getEthBalance\",\n inputs: [{ name: \"addr\", type: \"address\" }],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/** Multicall3 tryAggregate ABI for batching calls. */\nconst multicall3ABI = [\n {\n inputs: [\n { name: \"requireSuccess\", type: \"bool\" },\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n name: \"tryAggregate\",\n outputs: [\n {\n name: \"returnData\",\n type: \"tuple[]\",\n components: [\n { name: \"success\", type: \"bool\" },\n { name: \"returnData\", type: \"bytes\" },\n ],\n },\n ],\n stateMutability: \"payable\",\n type: \"function\",\n },\n] as const;\n\nexport type ContractCall = {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n};\n\nexport type RawContractCall = {\n address: `0x${string}`;\n callData: `0x${string}`;\n};\n\nexport type MulticallSuccess = { status: \"success\"; result: unknown };\nexport type MulticallFailure = { status: \"failure\"; error: Error };\nexport type MulticallResult = MulticallSuccess | MulticallFailure;\n\n/**\n * Batches contract calls via Multicall3 `tryAggregate(false, ...)`.\n *\n * Accepts a mix of typed ContractCall (ABI-encoded + decoded) and\n * RawContractCall (pre-encoded calldata, no decoding) entries.\n * Raw calls are useful for the EIP-6492 factory deployment case\n * where calldata is pre-encoded with no ABI available.\n */\ntype ReadContractFn = (args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n}) => Promise;\n\n/**\n * Executes multiple contract read calls in a single RPC round-trip using Multicall3.\n *\n * @param readContract - Function that performs a single contract read (e.g. viem readContract)\n * @param calls - Array of contract calls to batch (ContractCall or RawContractCall)\n * @returns A promise that resolves to an array of decoded results, one per call\n */\nexport async function multicall(\n readContract: ReadContractFn,\n calls: ReadonlyArray,\n): Promise {\n const aggregateCalls = calls.map(call => {\n if (\"callData\" in call) {\n return { target: call.address, callData: call.callData };\n }\n const callData = encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args as unknown[],\n });\n return { target: call.address, callData };\n });\n\n const rawResults = (await readContract({\n address: MULTICALL3_ADDRESS,\n abi: multicall3ABI,\n functionName: \"tryAggregate\",\n args: [false, aggregateCalls],\n })) as { success: boolean; returnData: `0x${string}` }[];\n\n return rawResults.map((raw, i) => {\n if (!raw.success) {\n return {\n status: \"failure\" as const,\n error: new Error(`multicall: call reverted (returnData: ${raw.returnData})`),\n };\n }\n\n const call = calls[i];\n if (\"callData\" in call) {\n return { status: \"success\" as const, result: undefined };\n }\n\n try {\n const decoded = decodeFunctionResult({\n abi: call.abi,\n functionName: call.functionName,\n data: raw.returnData,\n });\n return { status: \"success\" as const, result: decoded };\n } catch (err) {\n return {\n status: \"failure\" as const,\n error: err instanceof Error ? err : new Error(String(err)),\n };\n }\n });\n}\n","export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const EVM_NETWORK_CHAIN_ID_MAP = {\n ethereum: 1,\n sepolia: 11155111,\n abstract: 2741,\n \"abstract-testnet\": 11124,\n \"base-sepolia\": 84532,\n base: 8453,\n \"avalanche-fuji\": 43113,\n avalanche: 43114,\n iotex: 4689,\n sei: 1329,\n \"sei-testnet\": 1328,\n polygon: 137,\n \"polygon-amoy\": 80002,\n peaq: 3338,\n story: 1514,\n educhain: 41923,\n \"skale-base-sepolia\": 324705682,\n megaeth: 4326,\n monad: 143,\n} as const;\n\nexport type EvmNetworkV1 = keyof typeof EVM_NETWORK_CHAIN_ID_MAP;\n\nexport const NETWORKS: string[] = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);\n\n/**\n * Extract chain ID from a v1 legacy network name.\n *\n * @param network - The v1 network name (e.g., \"base-sepolia\", \"polygon\")\n * @returns The numeric chain ID\n * @throws Error if the network name is not a known v1 network\n */\nexport function getEvmChainIdV1(network: string): number {\n const chainId = EVM_NETWORK_CHAIN_ID_MAP[network as EvmNetworkV1];\n if (!chainId) {\n throw new Error(`Unsupported v1 network: ${network}`);\n }\n return chainId;\n}\n","import {\n SchemeNetworkClient,\n PaymentRequirements,\n PaymentPayloadResult,\n PaymentPayloadContext,\n} from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { AssetTransferMethod } from \"../../types\";\nimport { PERMIT2_ADDRESS, erc20AllowanceAbi } from \"../../constants\";\nimport { getAddress } from \"viem\";\nimport { getEvmChainId } from \"../../utils\";\nimport { EIP2612_GAS_SPONSORING_KEY, ERC20_APPROVAL_GAS_SPONSORING_KEY } from \"../extensions\";\nimport { createEIP3009Payload } from \"./eip3009\";\nimport { createPermit2Payload } from \"./permit2\";\nimport { signEip2612Permit } from \"./eip2612\";\nimport { signErc20ApprovalTransaction } from \"./erc20approval\";\nimport { ExactEvmSchemeOptions, resolveExtensionRpcCapabilities } from \"./rpc\";\n\n/**\n * EVM client implementation for the Exact payment scheme.\n * Supports both EIP-3009 (transferWithAuthorization) and Permit2 flows.\n *\n * Routes to the appropriate authorization method based on\n * `requirements.extra.assetTransferMethod`. Defaults to EIP-3009\n * for backward compatibility with older facilitators.\n *\n * When the server advertises `eip2612GasSponsoring` and the asset transfer\n * method is `permit2`, the scheme automatically signs an EIP-2612 permit\n * if the user lacks Permit2 approval. This requires `readContract` on the signer.\n */\nexport class ExactEvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClient instance.\n *\n * @param signer - The EVM signer for client operations.\n * Base flow only requires `address` + `signTypedData`.\n * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally\n * requires optional capabilities like `readContract` and tx signing helpers.\n * @param options - Optional RPC configuration used to backfill extension capabilities.\n */\n constructor(\n private readonly signer: ClientEvmSigner,\n private readonly options?: ExactEvmSchemeOptions,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.\n *\n * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the\n * signer supports `readContract`, automatically signs an EIP-2612 permit\n * when Permit2 allowance is insufficient.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @param context - Optional context with server-declared extensions\n * @returns Promise resolving to a payment payload result (with optional extensions)\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n context?: PaymentPayloadContext,\n ): Promise {\n const assetTransferMethod =\n (paymentRequirements.extra?.assetTransferMethod as AssetTransferMethod) ?? \"eip3009\";\n\n if (assetTransferMethod === \"permit2\") {\n const result = await createPermit2Payload(this.signer, x402Version, paymentRequirements);\n\n const eip2612Extensions = await this.trySignEip2612Permit(\n paymentRequirements,\n result,\n context,\n );\n\n if (eip2612Extensions) {\n return {\n ...result,\n extensions: eip2612Extensions,\n };\n }\n\n const erc20Extensions = await this.trySignErc20Approval(paymentRequirements, result, context);\n if (erc20Extensions) {\n return {\n ...result,\n extensions: erc20Extensions,\n };\n }\n\n return result;\n }\n\n return createEIP3009Payload(this.signer, x402Version, paymentRequirements);\n }\n\n /**\n * Attempts to sign an EIP-2612 permit for gasless Permit2 approval.\n *\n * Returns extension data if:\n * 1. Server advertises eip2612GasSponsoring\n * 2. Signer has readContract capability\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param result - The payment payload result from the scheme\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for EIP-2612 gas sponsoring, or undefined if not applicable\n */\n private async trySignEip2612Permit(\n requirements: PaymentRequirements,\n result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n const tokenName = requirements.extra?.name as string | undefined;\n const tokenVersion = requirements.extra?.version as string | undefined;\n if (!tokenName || !tokenVersion) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const permit2Auth = result.payload?.permit2Authorization as Record | undefined;\n const deadline =\n (permit2Auth?.deadline as string) ??\n Math.floor(Date.now() / 1000 + requirements.maxTimeoutSeconds).toString();\n\n const info = await signEip2612Permit(\n {\n address: this.signer.address,\n signTypedData: msg => this.signer.signTypedData(msg),\n readContract: capabilities.readContract,\n },\n tokenAddress,\n tokenName,\n tokenVersion,\n chainId,\n deadline,\n requirements.amount,\n );\n\n return {\n [EIP2612_GAS_SPONSORING_KEY]: { info },\n };\n }\n\n /**\n * Attempts to sign an ERC-20 approval transaction for gasless Permit2 approval.\n *\n * This is the fallback path when the token does not support EIP-2612. The client\n * signs (but does not broadcast) a raw `approve(Permit2, MaxUint256)` transaction.\n * The facilitator broadcasts it atomically before settling.\n *\n * Returns extension data if:\n * 1. Server advertises erc20ApprovalGasSponsoring\n * 2. Signer has signTransaction + getTransactionCount capabilities\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param _result - The payment payload result from the scheme (unused)\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for ERC-20 approval gas sponsoring, or undefined if not applicable\n */\n private async trySignErc20Approval(\n requirements: PaymentRequirements,\n _result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n if (!capabilities.signTransaction || !capabilities.getTransactionCount) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const info = await signErc20ApprovalTransaction(\n {\n address: this.signer.address,\n signTransaction: capabilities.signTransaction,\n getTransactionCount: capabilities.getTransactionCount,\n estimateFeesPerGas: capabilities.estimateFeesPerGas,\n },\n tokenAddress,\n chainId,\n );\n\n return {\n [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info },\n };\n }\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport { createNonce, getEvmChainId } from \"../../utils\";\n\n/**\n * Creates an EIP-3009 (transferWithAuthorization) payload.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createEIP3009Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEIP3009Payload[\"authorization\"] = {\n from: signer.address,\n to: getAddress(paymentRequirements.payTo),\n value: paymentRequirements.amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n const signature = await signEIP3009Authorization(signer, authorization, paymentRequirements);\n\n const payload: ExactEIP3009Payload = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the EIP-3009 authorization using EIP-712.\n *\n * @param signer - The EVM signer\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signEIP3009Authorization(\n signer: ClientEvmSigner,\n authorization: ExactEIP3009Payload[\"authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress } from \"viem\";\nimport {\n permit2WitnessTypes,\n PERMIT2_ADDRESS,\n x402ExactPermit2ProxyAddress,\n erc20ApproveAbi,\n erc20AllowanceAbi,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactPermit2Payload } from \"../../types\";\nimport { createPermit2Nonce, getEvmChainId } from \"../../utils\";\n\n/** Maximum uint256 value for unlimited approval. */\nconst MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\n/**\n * Creates a Permit2 payload using the x402Permit2Proxy witness pattern.\n * The spender is set to x402Permit2Proxy, which enforces that funds\n * can only be sent to the witness.to address.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createPermit2Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const now = Math.floor(Date.now() / 1000);\n const nonce = createPermit2Nonce();\n\n // Lower time bound - allow some clock skew\n const validAfter = (now - 600).toString();\n // Upper time bound is enforced by Permit2's deadline field\n const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();\n\n const permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"] = {\n from: signer.address,\n permitted: {\n token: getAddress(paymentRequirements.asset),\n amount: paymentRequirements.amount,\n },\n spender: x402ExactPermit2ProxyAddress,\n nonce,\n deadline,\n witness: {\n to: getAddress(paymentRequirements.payTo),\n validAfter,\n },\n };\n\n const signature = await signPermit2Authorization(\n signer,\n permit2Authorization,\n paymentRequirements,\n );\n\n const payload: ExactPermit2Payload = {\n signature,\n permit2Authorization,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the Permit2 authorization using EIP-712 with witness data.\n * The signature authorizes the x402Permit2Proxy to transfer tokens on behalf of the signer.\n *\n * @param signer - The EVM signer\n * @param permit2Authorization - The Permit2 authorization parameters\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signPermit2Authorization(\n signer: ClientEvmSigner,\n permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n const domain = {\n name: \"Permit2\",\n chainId,\n verifyingContract: PERMIT2_ADDRESS,\n };\n\n const message = {\n permitted: {\n token: getAddress(permit2Authorization.permitted.token),\n amount: BigInt(permit2Authorization.permitted.amount),\n },\n spender: getAddress(permit2Authorization.spender),\n nonce: BigInt(permit2Authorization.nonce),\n deadline: BigInt(permit2Authorization.deadline),\n witness: {\n to: getAddress(permit2Authorization.witness.to),\n validAfter: BigInt(permit2Authorization.witness.validAfter),\n },\n };\n\n return await signer.signTypedData({\n domain,\n types: permit2WitnessTypes,\n primaryType: \"PermitWitnessTransferFrom\",\n message,\n });\n}\n\n/**\n * Creates transaction data to approve Permit2 to spend tokens.\n * The user sends this transaction (paying gas) before using Permit2 flow.\n *\n * @param tokenAddress - The ERC20 token contract address\n * @returns Transaction data to send for approval\n *\n * @example\n * ```typescript\n * const tx = createPermit2ApprovalTx(\"0x...\");\n * await walletClient.sendTransaction({\n * to: tx.to,\n * data: tx.data,\n * });\n * ```\n */\nexport function createPermit2ApprovalTx(tokenAddress: `0x${string}`): {\n to: `0x${string}`;\n data: `0x${string}`;\n} {\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [PERMIT2_ADDRESS, MAX_UINT256],\n });\n\n return {\n to: getAddress(tokenAddress),\n data,\n };\n}\n\n/**\n * Parameters for checking Permit2 allowance.\n * Application provides these to check if approval is needed.\n */\nexport interface Permit2AllowanceParams {\n tokenAddress: `0x${string}`;\n ownerAddress: `0x${string}`;\n}\n\n/**\n * Returns contract read parameters for checking Permit2 allowance.\n * Use with a public client to check if the user has approved Permit2.\n *\n * @param params - The allowance check parameters\n * @returns Contract read parameters for checking allowance\n *\n * @example\n * ```typescript\n * const readParams = getPermit2AllowanceReadParams({\n * tokenAddress: \"0x...\",\n * ownerAddress: \"0x...\",\n * });\n *\n * const allowance = await publicClient.readContract(readParams);\n * const needsApproval = allowance < requiredAmount;\n * ```\n */\nexport function getPermit2AllowanceReadParams(params: Permit2AllowanceParams): {\n address: `0x${string}`;\n abi: typeof erc20AllowanceAbi;\n functionName: \"allowance\";\n args: [`0x${string}`, `0x${string}`];\n} {\n return {\n address: getAddress(params.tokenAddress),\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [getAddress(params.ownerAddress), PERMIT2_ADDRESS],\n };\n}\n","import { getAddress } from \"viem\";\nimport { eip2612PermitTypes, eip2612NoncesAbi, PERMIT2_ADDRESS } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport type { Eip2612GasSponsoringInfo } from \"../extensions\";\n\nexport type Eip2612PermitSigner = Pick & {\n readContract: NonNullable;\n};\n\n/**\n * Signs an EIP-2612 permit authorizing the Permit2 contract to spend tokens.\n *\n * This creates a gasless off-chain signature that the facilitator can submit\n * on-chain via `x402Permit2Proxy.settleWithPermit()`.\n *\n * The `permittedAmount` must match the Permit2 `permitted.amount` exactly, as the\n * proxy contract enforces `permit2612.value == permittedAmount`.\n *\n * @param signer - The client EVM signer (must support readContract for nonce query)\n * @param tokenAddress - The ERC-20 token contract address\n * @param tokenName - The token name (from paymentRequirements.extra.name)\n * @param tokenVersion - The token version (from paymentRequirements.extra.version)\n * @param chainId - The chain ID\n * @param deadline - The deadline for the permit (unix timestamp as string)\n * @param permittedAmount - The Permit2 permitted amount (must match exactly)\n * @returns The EIP-2612 gas sponsoring info object\n */\nexport async function signEip2612Permit(\n signer: Eip2612PermitSigner,\n tokenAddress: `0x${string}`,\n tokenName: string,\n tokenVersion: string,\n chainId: number,\n deadline: string,\n permittedAmount: string,\n): Promise {\n const owner = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Query the current EIP-2612 nonce from the token contract\n const nonce = (await signer.readContract({\n address: tokenAddress,\n abi: eip2612NoncesAbi,\n functionName: \"nonces\",\n args: [owner],\n })) as bigint;\n\n // Construct EIP-712 domain for the token's permit function\n const domain = {\n name: tokenName,\n version: tokenVersion,\n chainId,\n verifyingContract: tokenAddress,\n };\n\n const approvalAmount = BigInt(permittedAmount);\n\n const message = {\n owner,\n spender,\n value: approvalAmount,\n nonce,\n deadline: BigInt(deadline),\n };\n\n // Sign the EIP-2612 permit\n const signature = await signer.signTypedData({\n domain,\n types: eip2612PermitTypes,\n primaryType: \"Permit\",\n message,\n });\n\n return {\n from: owner,\n asset: tokenAddress,\n spender,\n amount: approvalAmount.toString(),\n nonce: nonce.toString(),\n deadline,\n signature,\n version: \"1\",\n };\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport {\n PERMIT2_ADDRESS,\n erc20ApproveAbi,\n ERC20_APPROVE_GAS_LIMIT,\n DEFAULT_MAX_FEE_PER_GAS,\n DEFAULT_MAX_PRIORITY_FEE_PER_GAS,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport {\n ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n type Erc20ApprovalGasSponsoringInfo,\n} from \"../extensions\";\n\nexport type Erc20ApprovalTxSigner = Pick & {\n signTransaction: NonNullable;\n getTransactionCount: NonNullable;\n estimateFeesPerGas?: NonNullable;\n};\n\n/**\n * Signs an EIP-1559 `approve(Permit2, MaxUint256)` transaction for the given token.\n *\n * The signed transaction is NOT broadcast here — the facilitator broadcasts it\n * atomically before settling the Permit2 payment. This enables Permit2 payments\n * for generic ERC-20 tokens that do NOT implement EIP-2612.\n *\n * Always approves MaxUint256 regardless of the payment amount.\n *\n * @param signer - The client EVM signer (must support signTransaction, getTransactionCount)\n * @param tokenAddress - The ERC-20 token contract address\n * @param chainId - The chain ID\n * @returns The ERC-20 approval gas sponsoring info object\n */\nexport async function signErc20ApprovalTransaction(\n signer: Erc20ApprovalTxSigner,\n tokenAddress: `0x${string}`,\n chainId: number,\n): Promise {\n const from = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Encode approve(PERMIT2_ADDRESS, MaxUint256) calldata\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [spender, maxUint256],\n });\n\n // Get current nonce for the sender\n const nonce = await signer.getTransactionCount({ address: from });\n\n // Get current fee estimates, with fallback values\n let maxFeePerGas: bigint;\n let maxPriorityFeePerGas: bigint;\n try {\n const fees = await signer.estimateFeesPerGas?.();\n if (!fees) {\n throw new Error(\"no fee estimates available\");\n }\n maxFeePerGas = fees.maxFeePerGas;\n maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n } catch {\n maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;\n maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;\n }\n\n // Sign the EIP-1559 transaction (not broadcast)\n const signedTransaction = await signer.signTransaction({\n to: tokenAddress,\n data,\n nonce,\n gas: ERC20_APPROVE_GAS_LIMIT,\n maxFeePerGas,\n maxPriorityFeePerGas,\n chainId,\n });\n\n return {\n from,\n asset: tokenAddress,\n spender,\n amount: maxUint256.toString(),\n signedTransaction,\n version: ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n };\n}\n","import { createPublicClient, http } from \"viem\";\nimport type { ClientEvmSigner } from \"../../signer\";\nimport { getEvmChainId } from \"../../utils\";\n\nexport type ExactEvmSchemeConfig = {\n rpcUrl?: string;\n};\n\nexport type ExactEvmSchemeConfigByChainId = Record;\n\nexport type ExactEvmSchemeOptions = ExactEvmSchemeConfig | ExactEvmSchemeConfigByChainId;\n\ntype ExtensionRpcCapabilities = Pick<\n ClientEvmSigner,\n \"readContract\" | \"signTransaction\" | \"getTransactionCount\" | \"estimateFeesPerGas\"\n>;\n\nconst rpcClientCache = new Map>();\n\n/**\n * Determines whether scheme options are keyed by numeric chain id.\n *\n * @param options - Exact EVM scheme options provided by the client.\n * @returns True when options are a chainId-to-config mapping.\n */\nfunction isConfigByChainId(\n options: ExactEvmSchemeOptions,\n): options is ExactEvmSchemeConfigByChainId {\n const keys = Object.keys(options);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n\n/**\n * Returns a cached viem public client for a specific RPC URL.\n *\n * @param rpcUrl - The RPC endpoint URL used to construct the client.\n * @returns A cached or newly created viem public client instance.\n */\nfunction getRpcClient(rpcUrl: string): ReturnType {\n const existing = rpcClientCache.get(rpcUrl);\n if (existing) {\n return existing;\n }\n\n const client = createPublicClient({\n transport: http(rpcUrl),\n });\n rpcClientCache.set(rpcUrl, client);\n return client;\n}\n\n/**\n * Resolves the RPC URL for a given CAIP-2 network from scheme options.\n *\n * @param network - CAIP-2 network identifier.\n * @param options - Optional scheme configuration (single config or chain map).\n * @returns The configured RPC URL for the network, if available.\n */\nexport function resolveRpcUrl(\n network: string,\n options?: ExactEvmSchemeOptions,\n): string | undefined {\n if (!options) {\n return undefined;\n }\n\n if (isConfigByChainId(options)) {\n const chainId = getEvmChainId(network);\n const optionsByChainId = options as ExactEvmSchemeConfigByChainId;\n return optionsByChainId[chainId]?.rpcUrl;\n }\n\n return (options as ExactEvmSchemeConfig).rpcUrl;\n}\n\n/**\n * Resolves extension RPC capabilities from signer methods and optional RPC backfill.\n *\n * @param network - CAIP-2 network identifier for chain resolution.\n * @param signer - Client signer with optional RPC-like methods.\n * @param options - Optional scheme configuration used for RPC backfill.\n * @returns The best available capability set for extension enrichment flows.\n */\nexport function resolveExtensionRpcCapabilities(\n network: string,\n signer: ClientEvmSigner,\n options?: ExactEvmSchemeOptions,\n): ExtensionRpcCapabilities {\n const capabilities: ExtensionRpcCapabilities = {\n signTransaction: signer.signTransaction,\n readContract: signer.readContract,\n getTransactionCount: signer.getTransactionCount,\n estimateFeesPerGas: signer.estimateFeesPerGas,\n };\n\n const needsRpcBackfill =\n !capabilities.readContract ||\n !capabilities.getTransactionCount ||\n !capabilities.estimateFeesPerGas;\n if (!needsRpcBackfill) {\n return capabilities;\n }\n\n const rpcUrl = resolveRpcUrl(network, options);\n if (!rpcUrl) {\n return capabilities;\n }\n const rpcClient = getRpcClient(rpcUrl);\n if (!capabilities.readContract) {\n capabilities.readContract = args => rpcClient.readContract(args as never) as Promise;\n }\n if (!capabilities.getTransactionCount) {\n capabilities.getTransactionCount = async args =>\n rpcClient.getTransactionCount({ address: args.address });\n }\n if (!capabilities.estimateFeesPerGas) {\n capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();\n }\n\n return capabilities;\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeOptions } from \"./rpc\";\nimport { ExactEvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Client\n */\nexport interface EvmClientConfig {\n /**\n * The EVM signer to use for creating payment payloads\n */\n signer: ClientEvmSigner;\n\n /**\n * Optional payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional Exact EVM client scheme options.\n * Supports either a single config ({ rpcUrl }) or per-chain configs\n * keyed by EVM chain ID ({ 8453: { rpcUrl: \"...\" } }).\n */\n schemeOptions?: ExactEvmSchemeOptions;\n\n /**\n * Optional specific networks to register.\n * If not provided, registers wildcard support (eip155:*).\n */\n networks?: Network[];\n}\n\n/**\n * Registers EVM exact payment schemes to an x402Client instance.\n *\n * This function registers:\n * - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for EVM client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@x402/evm/exact/client/register\";\n * import { x402Client } from \"@x402/core/client\";\n * import { privateKeyToAccount } from \"viem/accounts\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const client = new x402Client();\n * registerExactEvmScheme(client, { signer: account });\n * ```\n */\nexport function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client {\n const evmScheme = new ExactEvmScheme(config.signer, config.schemeOptions);\n\n // Register V2 scheme\n // EIP-2612 gas sponsoring is handled internally by the scheme when the\n // server advertises support - no separate extension registration needed.\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach(network => {\n client.register(network, evmScheme);\n });\n } else {\n // Register wildcard for all EVM chains\n client.register(\"eip155:*\", evmScheme);\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactEvmSchemeV1(config.signer));\n });\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * ClientEvmSigner - Used by x402 clients to sign payment authorizations.\n *\n * Typically a viem WalletClient extended with publicActions:\n * ```typescript\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * Or composed via `toClientEvmSigner(account, publicClient)`.\n */\nexport type ClientEvmSigner = {\n readonly address: `0x${string}`;\n signTypedData(message: {\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n }): Promise<`0x${string}`>;\n /**\n * Optional on-chain reads.\n * Required only for extension enrichment (EIP-2612 / ERC-20 approval).\n */\n readContract?(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n /**\n * Optional: Signs a raw EIP-1559 transaction without broadcasting.\n * Required for ERC-20 approval gas sponsoring when the token lacks EIP-2612.\n */\n signTransaction?(args: {\n to: `0x${string}`;\n data: `0x${string}`;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n chainId: number;\n }): Promise<`0x${string}`>;\n /**\n * Optional: Gets the current transaction count (nonce) for an address.\n * Required for ERC-20 approval gas sponsoring.\n */\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n /**\n * Optional: Estimates current gas fees per gas.\n * Required for ERC-20 approval gas sponsoring.\n */\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n};\n\n/**\n * FacilitatorEvmSigner - Used by x402 facilitators to verify and settle payments\n * This is typically a viem PublicClient + WalletClient combination that can\n * read contract state, verify signatures, write transactions, and wait for receipts\n *\n * Supports multiple addresses for load balancing, key rotation, and high availability\n */\nexport type FacilitatorEvmSigner = {\n /**\n * Get all addresses this facilitator can use for signing\n * Enables dynamic address selection for load balancing and key rotation\n */\n getAddresses(): readonly `0x${string}`[];\n\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n verifyTypedData(args: {\n address: `0x${string}`;\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n signature: `0x${string}`;\n }): Promise;\n writeContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n /** Optional gas limit. When provided, skips eth_estimateGas simulation. */\n gas?: bigint;\n }): Promise<`0x${string}`>;\n sendTransaction(args: { to: `0x${string}`; data: `0x${string}` }): Promise<`0x${string}`>;\n waitForTransactionReceipt(args: { hash: `0x${string}` }): Promise<{ status: string }>;\n getCode(args: { address: `0x${string}` }): Promise<`0x${string}` | undefined>;\n};\n\n/**\n * Composes a ClientEvmSigner from a local account and a public client.\n *\n * Use this when your signer (e.g., `privateKeyToAccount`) doesn't have\n * `readContract`. The `publicClient` provides the on-chain read capability.\n *\n * Alternatively, use a WalletClient extended with publicActions directly:\n * ```typescript\n * const signer = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * @param signer - A signer with `address` and `signTypedData` (and optionally `readContract`)\n * @param publicClient - A client with optional read/nonce/fee helpers\n * @param publicClient.readContract - The readContract method from the public client\n * @param publicClient.getTransactionCount - Optional getTransactionCount for ERC-20 approval\n * @param publicClient.estimateFeesPerGas - Optional estimateFeesPerGas for ERC-20 approval\n * @returns A ClientEvmSigner with any available optional capabilities\n *\n * @example\n * ```typescript\n * const account = privateKeyToAccount(\"0x...\");\n * const publicClient = createPublicClient({ chain: baseSepolia, transport: http() });\n * const signer = toClientEvmSigner(account, publicClient);\n * ```\n */\nexport function toClientEvmSigner(\n signer: Omit & {\n readContract?: ClientEvmSigner[\"readContract\"];\n },\n publicClient?: {\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n },\n): ClientEvmSigner {\n const readContract = signer.readContract ?? publicClient?.readContract.bind(publicClient);\n\n const result: ClientEvmSigner = {\n address: signer.address,\n signTypedData: msg => signer.signTypedData(msg),\n };\n\n if (readContract) {\n result.readContract = readContract;\n }\n\n // Forward optional capabilities from signer or publicClient\n const signTransaction = signer.signTransaction;\n if (signTransaction) {\n result.signTransaction = args => signTransaction(args);\n }\n\n const getTransactionCount =\n signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);\n if (getTransactionCount) {\n result.getTransactionCount = args => getTransactionCount(args);\n }\n\n const estimateFeesPerGas =\n signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);\n if (estimateFeesPerGas) {\n result.estimateFeesPerGas = () => estimateFeesPerGas();\n }\n\n return result;\n}\n\n/**\n * Converts a viem client with single address to a FacilitatorEvmSigner\n * Wraps the single address in a getAddresses() function for compatibility\n *\n * @param client - The client to convert (must have 'address' property)\n * @returns FacilitatorEvmSigner with getAddresses() support\n */\nexport function toFacilitatorEvmSigner(\n client: Omit & { address: `0x${string}` },\n): FacilitatorEvmSigner {\n return {\n ...client,\n getAddresses: () => [client.address],\n };\n}\n","/**\n * Rule-Based Classifier (v2 — Weighted Scoring)\n *\n * Scores a request across 14 weighted dimensions and maps the aggregate\n * score to a tier using configurable boundaries. Confidence is calibrated\n * via sigmoid — low confidence triggers the fallback classifier.\n *\n * Handles 70-80% of requests in < 1ms with zero cost.\n */\n\nimport type { Tier, ScoringResult, ScoringConfig } from \"./types.js\";\n\ntype DimensionScore = { name: string; score: number; signal: string | null };\n\n// ─── Dimension Scorers ───\n// Each returns a score in [-1, 1] and an optional signal string.\n\nfunction scoreTokenCount(\n estimatedTokens: number,\n thresholds: { simple: number; complex: number },\n): DimensionScore {\n if (estimatedTokens < thresholds.simple) {\n return { name: \"tokenCount\", score: -1.0, signal: `short (${estimatedTokens} tokens)` };\n }\n if (estimatedTokens > thresholds.complex) {\n return { name: \"tokenCount\", score: 1.0, signal: `long (${estimatedTokens} tokens)` };\n }\n return { name: \"tokenCount\", score: 0, signal: null };\n}\n\nfunction scoreKeywordMatch(\n text: string,\n keywords: string[],\n name: string,\n signalLabel: string,\n thresholds: { low: number; high: number },\n scores: { none: number; low: number; high: number },\n): DimensionScore {\n const matches = keywords.filter((kw) => text.includes(kw.toLowerCase()));\n if (matches.length >= thresholds.high) {\n return {\n name,\n score: scores.high,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n if (matches.length >= thresholds.low) {\n return {\n name,\n score: scores.low,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n return { name, score: scores.none, signal: null };\n}\n\nfunction scoreMultiStep(text: string): DimensionScore {\n const patterns = [/first.*then/i, /step \\d/i, /\\d\\.\\s/];\n const hits = patterns.filter((p) => p.test(text));\n if (hits.length > 0) {\n return { name: \"multiStepPatterns\", score: 0.5, signal: \"multi-step\" };\n }\n return { name: \"multiStepPatterns\", score: 0, signal: null };\n}\n\nfunction scoreQuestionComplexity(prompt: string): DimensionScore {\n const count = (prompt.match(/\\?/g) || []).length;\n if (count > 3) {\n return { name: \"questionComplexity\", score: 0.5, signal: `${count} questions` };\n }\n return { name: \"questionComplexity\", score: 0, signal: null };\n}\n\n/**\n * Score agentic task indicators.\n * Returns agenticScore (0-1) based on keyword matches:\n * - 4+ matches = 1.0 (high agentic)\n * - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)\n * - 1-2 matches = 0.2 (low agentic)\n *\n * Thresholds raised because common keywords were pruned from the list.\n */\nfunction scoreAgenticTask(\n text: string,\n keywords: string[],\n): { dimensionScore: DimensionScore; agenticScore: number } {\n let matchCount = 0;\n const signals: string[] = [];\n\n for (const keyword of keywords) {\n if (text.includes(keyword.toLowerCase())) {\n matchCount++;\n if (signals.length < 3) {\n signals.push(keyword);\n }\n }\n }\n\n // Threshold-based scoring (raised thresholds after keyword pruning)\n if (matchCount >= 4) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 1.0,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 1.0,\n };\n } else if (matchCount >= 3) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.6,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 0.6,\n };\n } else if (matchCount >= 1) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.2,\n signal: `agentic-light (${signals.join(\", \")})`,\n },\n agenticScore: 0.2,\n };\n }\n\n return {\n dimensionScore: { name: \"agenticTask\", score: 0, signal: null },\n agenticScore: 0,\n };\n}\n\n// ─── Main Classifier ───\n\nexport function classifyByRules(\n prompt: string,\n systemPrompt: string | undefined,\n estimatedTokens: number,\n config: ScoringConfig,\n): ScoringResult {\n // Score against user prompt only — system prompts contain boilerplate keywords\n // (tool definitions, skill descriptions, behavioral rules) that dominate scoring\n // and make every request score identically. See GitHub issue #50.\n const userText = prompt.toLowerCase();\n\n // Score all 14 dimensions against user text only\n const dimensions: DimensionScore[] = [\n // Token count uses total estimated tokens (system + user) — context size matters for model selection\n scoreTokenCount(estimatedTokens, config.tokenCountThresholds),\n scoreKeywordMatch(\n userText,\n config.codeKeywords,\n \"codePresence\",\n \"code\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.reasoningKeywords,\n \"reasoningMarkers\",\n \"reasoning\",\n { low: 1, high: 2 },\n { none: 0, low: 0.7, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.technicalKeywords,\n \"technicalTerms\",\n \"technical\",\n { low: 2, high: 4 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.creativeKeywords,\n \"creativeMarkers\",\n \"creative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.simpleKeywords,\n \"simpleIndicators\",\n \"simple\",\n { low: 1, high: 2 },\n { none: 0, low: -1.0, high: -1.0 },\n ),\n scoreMultiStep(userText),\n scoreQuestionComplexity(prompt),\n\n // 6 new dimensions\n scoreKeywordMatch(\n userText,\n config.imperativeVerbs,\n \"imperativeVerbs\",\n \"imperative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.constraintIndicators,\n \"constraintCount\",\n \"constraints\",\n { low: 1, high: 3 },\n { none: 0, low: 0.3, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.outputFormatKeywords,\n \"outputFormat\",\n \"format\",\n { low: 1, high: 2 },\n { none: 0, low: 0.4, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.referenceKeywords,\n \"referenceComplexity\",\n \"references\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.negationKeywords,\n \"negationComplexity\",\n \"negation\",\n { low: 2, high: 3 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.domainSpecificKeywords,\n \"domainSpecificity\",\n \"domain-specific\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.8 },\n ),\n ];\n\n // Score agentic task indicators — user prompt only\n // System prompt describes assistant behavior, not user's intent.\n // e.g. a coding assistant system prompt with \"edit files\" / \"fix bugs\" should NOT\n // force every request into agentic mode.\n const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);\n dimensions.push(agenticResult.dimensionScore);\n const agenticScore = agenticResult.agenticScore;\n\n // Collect signals\n const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);\n\n // Compute weighted score\n const weights = config.dimensionWeights;\n let weightedScore = 0;\n for (const d of dimensions) {\n const w = weights[d.name] ?? 0;\n weightedScore += d.score * w;\n }\n\n // Count reasoning markers for override — only check USER prompt, not system prompt\n // This prevents system prompts with \"step by step\" from triggering REASONING for simple queries\n const reasoningMatches = config.reasoningKeywords.filter((kw) =>\n userText.includes(kw.toLowerCase()),\n );\n\n // Direct reasoning override: 2+ reasoning markers = high confidence REASONING\n if (reasoningMatches.length >= 2) {\n const confidence = calibrateConfidence(\n Math.max(weightedScore, 0.3), // ensure positive for confidence calc\n config.confidenceSteepness,\n );\n return {\n score: weightedScore,\n tier: \"REASONING\",\n confidence: Math.max(confidence, 0.85),\n signals,\n agenticScore,\n dimensions,\n };\n }\n\n // Map weighted score to tier using boundaries\n const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;\n let tier: Tier;\n let distanceFromBoundary: number;\n\n if (weightedScore < simpleMedium) {\n tier = \"SIMPLE\";\n distanceFromBoundary = simpleMedium - weightedScore;\n } else if (weightedScore < mediumComplex) {\n tier = \"MEDIUM\";\n distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);\n } else if (weightedScore < complexReasoning) {\n tier = \"COMPLEX\";\n distanceFromBoundary = Math.min(\n weightedScore - mediumComplex,\n complexReasoning - weightedScore,\n );\n } else {\n tier = \"REASONING\";\n distanceFromBoundary = weightedScore - complexReasoning;\n }\n\n // Calibrate confidence via sigmoid of distance from nearest boundary\n const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);\n\n // If confidence is below threshold → ambiguous\n if (confidence < config.confidenceThreshold) {\n return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };\n }\n\n return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };\n}\n\n/**\n * Sigmoid confidence calibration.\n * Maps distance from tier boundary to [0.5, 1.0] confidence range.\n */\nfunction calibrateConfidence(distance: number, steepness: number): number {\n return 1 / (1 + Math.exp(-steepness * distance));\n}\n","/**\n * Tier → Model Selection\n *\n * Maps a classification tier to the cheapest capable model.\n * Builds RoutingDecision metadata with cost estimates and savings.\n */\n\nimport type { Tier, TierConfig, RoutingDecision } from \"./types.js\";\n\nexport type ModelPricing = {\n inputPrice: number; // per 1M tokens\n outputPrice: number; // per 1M tokens\n};\n\nconst BASELINE_MODEL_ID = \"anthropic/claude-opus-4.6\";\n\n// Hardcoded fallback: Claude Opus 4.6 pricing (per 1M tokens)\n// Used when baseline model not found in dynamic pricing map\nconst BASELINE_INPUT_PRICE = 5.0;\nconst BASELINE_OUTPUT_PRICE = 25.0;\n\n/**\n * Select the primary model for a tier and build the RoutingDecision.\n */\nexport function selectModel(\n tier: Tier,\n confidence: number,\n method: \"rules\" | \"llm\",\n reasoning: string,\n tierConfigs: Record,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n agenticScore?: number,\n): RoutingDecision {\n const tierConfig = tierConfigs[tier];\n const model = tierConfig.primary;\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n const costEstimate = inputCost + outputCost;\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return {\n model,\n tier,\n confidence,\n method,\n reasoning,\n costEstimate,\n baselineCost,\n savings,\n ...(agenticScore !== undefined && { agenticScore }),\n };\n}\n\n/**\n * Get the ordered fallback chain for a tier: [primary, ...fallbacks].\n */\nexport function getFallbackChain(tier: Tier, tierConfigs: Record): string[] {\n const config = tierConfigs[tier];\n return [config.primary, ...config.fallback];\n}\n\n/**\n * Calculate cost for a specific model (used when fallback model is used).\n * Returns updated cost fields for RoutingDecision.\n */\n// Server-side margin applied to all x402 payments (must match blockrun server's MARGIN_PERCENT)\nconst SERVER_MARGIN_PERCENT = 5;\n// Minimum payment enforced by CDP Facilitator (must match blockrun server's MIN_PAYMENT_USD)\nconst MIN_PAYMENT_USD = 0.001;\n\nexport function calculateModelCost(\n model: string,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n): { costEstimate: number; baselineCost: number; savings: number } {\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n // Include server margin + minimum payment to match actual x402 charge\n const costEstimate = Math.max(\n (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100),\n MIN_PAYMENT_USD,\n );\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return { costEstimate, baselineCost, savings };\n}\n\n/**\n * Filter a model list to only those that support tool calling.\n * When hasTools is false, returns the list unchanged.\n * When all models lack tool calling support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByToolCalling(\n models: string[],\n hasTools: boolean,\n supportsToolCalling: (modelId: string) => boolean,\n): string[] {\n if (!hasTools) return models;\n const filtered = models.filter(supportsToolCalling);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to only those that support vision (image inputs).\n * When hasVision is false, returns the list unchanged.\n * When all models lack vision support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByVision(\n models: string[],\n hasVision: boolean,\n supportsVision: (modelId: string) => boolean,\n): string[] {\n if (!hasVision) return models;\n const filtered = models.filter(supportsVision);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to remove user-excluded models.\n * When all models are excluded, returns the full list as a fallback\n * (same safety pattern as filterByToolCalling/filterByVision).\n */\nexport function filterByExcludeList(models: string[], excludeList: Set): string[] {\n if (excludeList.size === 0) return models;\n const filtered = models.filter((m) => !excludeList.has(m));\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Get the fallback chain filtered by context length.\n * Only returns models that can handle the estimated total context.\n *\n * @param tier - The tier to get fallback chain for\n * @param tierConfigs - Tier configurations\n * @param estimatedTotalTokens - Estimated total context (input + output)\n * @param getContextWindow - Function to get context window for a model ID\n * @returns Filtered list of models that can handle the context\n */\nexport function getFallbackChainFiltered(\n tier: Tier,\n tierConfigs: Record,\n estimatedTotalTokens: number,\n getContextWindow: (modelId: string) => number | undefined,\n): string[] {\n const fullChain = getFallbackChain(tier, tierConfigs);\n\n // Filter to models that can handle the context\n const filtered = fullChain.filter((modelId) => {\n const contextWindow = getContextWindow(modelId);\n if (contextWindow === undefined) {\n // Unknown model - include it (let API reject if needed)\n return true;\n }\n // Add 10% buffer for safety\n return contextWindow >= estimatedTotalTokens * 1.1;\n });\n\n // If all models filtered out, return the original chain\n // (let the API error out - better than no options)\n if (filtered.length === 0) {\n return fullChain;\n }\n\n return filtered;\n}\n","/**\n * Router Strategy Registry\n *\n * Pluggable strategy system for request routing.\n * Default: RulesStrategy — identical to the original inline route() logic, <1ms.\n */\n\nimport type { Tier, RoutingDecision, RouterStrategy, RouterOptions } from \"./types.js\";\nimport { classifyByRules } from \"./rules.js\";\nimport { selectModel } from \"./selector.js\";\n\n/**\n * Rules-based routing strategy.\n * Extracted from the original route() in index.ts — logic is identical.\n * Attaches tierConfigs and profile to the decision for downstream use.\n */\nexport class RulesStrategy implements RouterStrategy {\n readonly name = \"rules\";\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ): RoutingDecision {\n const { config, modelPricing } = options;\n\n // Estimate input tokens (~4 chars per token)\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // --- Rule-based classification (runs first to get agenticScore) ---\n const ruleResult = classifyByRules(prompt, systemPrompt, estimatedTokens, config.scoring);\n\n // --- Select tier configs based on routing profile ---\n const { routingProfile } = options;\n let tierConfigs: Record;\n let profileSuffix: string;\n let profile: RoutingDecision[\"profile\"];\n\n if (routingProfile === \"eco\" && config.ecoTiers) {\n tierConfigs = config.ecoTiers;\n profileSuffix = \" | eco\";\n profile = \"eco\";\n } else if (routingProfile === \"premium\" && config.premiumTiers) {\n tierConfigs = config.premiumTiers;\n profileSuffix = \" | premium\";\n profile = \"premium\";\n } else {\n // Auto profile (or undefined): intelligent routing with agentic detection\n const agenticScore = ruleResult.agenticScore ?? 0;\n const isAutoAgentic = agenticScore >= 0.5;\n const isExplicitAgentic = config.overrides.agenticMode ?? false;\n const hasToolsInRequest = options.hasTools ?? false;\n const useAgenticTiers =\n (hasToolsInRequest || isAutoAgentic || isExplicitAgentic) && config.agenticTiers != null;\n tierConfigs = useAgenticTiers ? config.agenticTiers! : config.tiers;\n profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? \" (tools)\" : \"\"}` : \"\";\n profile = useAgenticTiers ? \"agentic\" : \"auto\";\n }\n\n const agenticScoreValue = ruleResult.agenticScore;\n\n // --- Override: large context → force COMPLEX ---\n if (estimatedTokens > config.overrides.maxTokensForceComplex) {\n const decision = selectModel(\n \"COMPLEX\",\n 0.95,\n \"rules\",\n `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n\n // Structured output detection\n const hasStructuredOutput = systemPrompt ? /json|structured|schema/i.test(systemPrompt) : false;\n\n let tier: Tier;\n let confidence: number;\n const method: \"rules\" | \"llm\" = \"rules\";\n let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(\", \")}`;\n\n if (ruleResult.tier !== null) {\n tier = ruleResult.tier;\n confidence = ruleResult.confidence;\n } else {\n // Ambiguous — default to configurable tier (no external API call)\n tier = config.overrides.ambiguousDefaultTier;\n confidence = 0.5;\n reasoning += ` | ambiguous -> default: ${tier}`;\n }\n\n // Apply structured output minimum tier\n if (hasStructuredOutput) {\n const tierRank: Record = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };\n const minTier = config.overrides.structuredOutputMinTier;\n if (tierRank[tier] < tierRank[minTier]) {\n reasoning += ` | upgraded to ${minTier} (structured output)`;\n tier = minTier;\n }\n }\n\n // Add routing profile suffix to reasoning\n reasoning += profileSuffix;\n\n const decision = selectModel(\n tier,\n confidence,\n method,\n reasoning,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n}\n\n// --- Strategy Registry ---\n\nconst registry = new Map();\nregistry.set(\"rules\", new RulesStrategy());\n\nexport function getStrategy(name: string): RouterStrategy {\n const strategy = registry.get(name);\n if (!strategy) {\n throw new Error(`Unknown routing strategy: ${name}`);\n }\n return strategy;\n}\n\nexport function registerStrategy(strategy: RouterStrategy): void {\n registry.set(strategy.name, strategy);\n}\n","/**\n * Default Routing Config\n *\n * All routing parameters as a TypeScript constant.\n * Operators override via openclaw.yaml plugin config.\n *\n * Scoring uses 14 weighted dimensions with sigmoid confidence calibration.\n */\n\nimport type { RoutingConfig } from \"./types.js\";\n\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n version: \"2.0\",\n\n classifier: {\n llmModel: \"google/gemini-2.5-flash\",\n llmMaxTokens: 10,\n llmTemperature: 0,\n promptTruncationChars: 500,\n cacheTtlMs: 3_600_000, // 1 hour\n },\n\n scoring: {\n tokenCountThresholds: { simple: 50, complex: 500 },\n\n // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR\n codeKeywords: [\n // English\n \"function\",\n \"class\",\n \"import\",\n \"def\",\n \"SELECT\",\n \"async\",\n \"await\",\n \"const\",\n \"let\",\n \"var\",\n \"return\",\n \"```\",\n // Chinese\n \"函数\",\n \"类\",\n \"导入\",\n \"定义\",\n \"查询\",\n \"异步\",\n \"等待\",\n \"常量\",\n \"变量\",\n \"返回\",\n // Japanese\n \"関数\",\n \"クラス\",\n \"インポート\",\n \"非同期\",\n \"定数\",\n \"変数\",\n // Russian\n \"функция\",\n \"класс\",\n \"импорт\",\n \"определ\",\n \"запрос\",\n \"асинхронный\",\n \"ожидать\",\n \"константа\",\n \"переменная\",\n \"вернуть\",\n // German\n \"funktion\",\n \"klasse\",\n \"importieren\",\n \"definieren\",\n \"abfrage\",\n \"asynchron\",\n \"erwarten\",\n \"konstante\",\n \"variable\",\n \"zurückgeben\",\n // Spanish\n \"función\",\n \"clase\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"asíncrono\",\n \"esperar\",\n \"constante\",\n \"variable\",\n \"retornar\",\n // Portuguese\n \"função\",\n \"classe\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"assíncrono\",\n \"aguardar\",\n \"constante\",\n \"variável\",\n \"retornar\",\n // Korean\n \"함수\",\n \"클래스\",\n \"가져오기\",\n \"정의\",\n \"쿼리\",\n \"비동기\",\n \"대기\",\n \"상수\",\n \"변수\",\n \"반환\",\n // Arabic\n \"دالة\",\n \"فئة\",\n \"استيراد\",\n \"تعريف\",\n \"استعلام\",\n \"غير متزامن\",\n \"انتظار\",\n \"ثابت\",\n \"متغير\",\n \"إرجاع\",\n ],\n reasoningKeywords: [\n // English\n \"prove\",\n \"theorem\",\n \"derive\",\n \"step by step\",\n \"chain of thought\",\n \"formally\",\n \"mathematical\",\n \"proof\",\n \"logically\",\n // Chinese\n \"证明\",\n \"定理\",\n \"推导\",\n \"逐步\",\n \"思维链\",\n \"形式化\",\n \"数学\",\n \"逻辑\",\n // Japanese\n \"証明\",\n \"定理\",\n \"導出\",\n \"ステップバイステップ\",\n \"論理的\",\n // Russian\n \"доказать\",\n \"докажи\",\n \"доказательств\",\n \"теорема\",\n \"вывести\",\n \"шаг за шагом\",\n \"пошагово\",\n \"поэтапно\",\n \"цепочка рассуждений\",\n \"рассуждени\",\n \"формально\",\n \"математически\",\n \"логически\",\n // German\n \"beweisen\",\n \"beweis\",\n \"theorem\",\n \"ableiten\",\n \"schritt für schritt\",\n \"gedankenkette\",\n \"formal\",\n \"mathematisch\",\n \"logisch\",\n // Spanish\n \"demostrar\",\n \"teorema\",\n \"derivar\",\n \"paso a paso\",\n \"cadena de pensamiento\",\n \"formalmente\",\n \"matemático\",\n \"prueba\",\n \"lógicamente\",\n // Portuguese\n \"provar\",\n \"teorema\",\n \"derivar\",\n \"passo a passo\",\n \"cadeia de pensamento\",\n \"formalmente\",\n \"matemático\",\n \"prova\",\n \"logicamente\",\n // Korean\n \"증명\",\n \"정리\",\n \"도출\",\n \"단계별\",\n \"사고의 연쇄\",\n \"형식적\",\n \"수학적\",\n \"논리적\",\n // Arabic\n \"إثبات\",\n \"نظرية\",\n \"اشتقاق\",\n \"خطوة بخطوة\",\n \"سلسلة التفكير\",\n \"رسمياً\",\n \"رياضي\",\n \"برهان\",\n \"منطقياً\",\n ],\n simpleKeywords: [\n // English\n \"what is\",\n \"define\",\n \"translate\",\n \"hello\",\n \"yes or no\",\n \"capital of\",\n \"how old\",\n \"who is\",\n \"when was\",\n // Chinese\n \"什么是\",\n \"定义\",\n \"翻译\",\n \"你好\",\n \"是否\",\n \"首都\",\n \"多大\",\n \"谁是\",\n \"何时\",\n // Japanese\n \"とは\",\n \"定義\",\n \"翻訳\",\n \"こんにちは\",\n \"はいかいいえ\",\n \"首都\",\n \"誰\",\n // Russian\n \"что такое\",\n \"определение\",\n \"перевести\",\n \"переведи\",\n \"привет\",\n \"да или нет\",\n \"столица\",\n \"сколько лет\",\n \"кто такой\",\n \"когда\",\n \"объясни\",\n // German\n \"was ist\",\n \"definiere\",\n \"übersetze\",\n \"hallo\",\n \"ja oder nein\",\n \"hauptstadt\",\n \"wie alt\",\n \"wer ist\",\n \"wann\",\n \"erkläre\",\n // Spanish\n \"qué es\",\n \"definir\",\n \"traducir\",\n \"hola\",\n \"sí o no\",\n \"capital de\",\n \"cuántos años\",\n \"quién es\",\n \"cuándo\",\n // Portuguese\n \"o que é\",\n \"definir\",\n \"traduzir\",\n \"olá\",\n \"sim ou não\",\n \"capital de\",\n \"quantos anos\",\n \"quem é\",\n \"quando\",\n // Korean\n \"무엇\",\n \"정의\",\n \"번역\",\n \"안녕하세요\",\n \"예 또는 아니오\",\n \"수도\",\n \"누구\",\n \"언제\",\n // Arabic\n \"ما هو\",\n \"تعريف\",\n \"ترجم\",\n \"مرحبا\",\n \"نعم أو لا\",\n \"عاصمة\",\n \"من هو\",\n \"متى\",\n ],\n technicalKeywords: [\n // English\n \"algorithm\",\n \"optimize\",\n \"architecture\",\n \"distributed\",\n \"kubernetes\",\n \"microservice\",\n \"database\",\n \"infrastructure\",\n // Chinese\n \"算法\",\n \"优化\",\n \"架构\",\n \"分布式\",\n \"微服务\",\n \"数据库\",\n \"基础设施\",\n // Japanese\n \"アルゴリズム\",\n \"最適化\",\n \"アーキテクチャ\",\n \"分散\",\n \"マイクロサービス\",\n \"データベース\",\n // Russian\n \"алгоритм\",\n \"оптимизировать\",\n \"оптимизаци\",\n \"оптимизируй\",\n \"архитектура\",\n \"распределённый\",\n \"микросервис\",\n \"база данных\",\n \"инфраструктура\",\n // German\n \"algorithmus\",\n \"optimieren\",\n \"architektur\",\n \"verteilt\",\n \"kubernetes\",\n \"mikroservice\",\n \"datenbank\",\n \"infrastruktur\",\n // Spanish\n \"algoritmo\",\n \"optimizar\",\n \"arquitectura\",\n \"distribuido\",\n \"microservicio\",\n \"base de datos\",\n \"infraestructura\",\n // Portuguese\n \"algoritmo\",\n \"otimizar\",\n \"arquitetura\",\n \"distribuído\",\n \"microsserviço\",\n \"banco de dados\",\n \"infraestrutura\",\n // Korean\n \"알고리즘\",\n \"최적화\",\n \"아키텍처\",\n \"분산\",\n \"마이크로서비스\",\n \"데이터베이스\",\n \"인프라\",\n // Arabic\n \"خوارزمية\",\n \"تحسين\",\n \"بنية\",\n \"موزع\",\n \"خدمة مصغرة\",\n \"قاعدة بيانات\",\n \"بنية تحتية\",\n ],\n creativeKeywords: [\n // English\n \"story\",\n \"poem\",\n \"compose\",\n \"brainstorm\",\n \"creative\",\n \"imagine\",\n \"write a\",\n // Chinese\n \"故事\",\n \"诗\",\n \"创作\",\n \"头脑风暴\",\n \"创意\",\n \"想象\",\n \"写一个\",\n // Japanese\n \"物語\",\n \"詩\",\n \"作曲\",\n \"ブレインストーム\",\n \"創造的\",\n \"想像\",\n // Russian\n \"история\",\n \"рассказ\",\n \"стихотворение\",\n \"сочинить\",\n \"сочини\",\n \"мозговой штурм\",\n \"творческий\",\n \"представить\",\n \"придумай\",\n \"напиши\",\n // German\n \"geschichte\",\n \"gedicht\",\n \"komponieren\",\n \"brainstorming\",\n \"kreativ\",\n \"vorstellen\",\n \"schreibe\",\n \"erzählung\",\n // Spanish\n \"historia\",\n \"poema\",\n \"componer\",\n \"lluvia de ideas\",\n \"creativo\",\n \"imaginar\",\n \"escribe\",\n // Portuguese\n \"história\",\n \"poema\",\n \"compor\",\n \"criativo\",\n \"imaginar\",\n \"escreva\",\n // Korean\n \"이야기\",\n \"시\",\n \"작곡\",\n \"브레인스토밍\",\n \"창의적\",\n \"상상\",\n \"작성\",\n // Arabic\n \"قصة\",\n \"قصيدة\",\n \"تأليف\",\n \"عصف ذهني\",\n \"إبداعي\",\n \"تخيل\",\n \"اكتب\",\n ],\n\n // New dimension keyword lists (multilingual)\n imperativeVerbs: [\n // English\n \"build\",\n \"create\",\n \"implement\",\n \"design\",\n \"develop\",\n \"construct\",\n \"generate\",\n \"deploy\",\n \"configure\",\n \"set up\",\n // Chinese\n \"构建\",\n \"创建\",\n \"实现\",\n \"设计\",\n \"开发\",\n \"生成\",\n \"部署\",\n \"配置\",\n \"设置\",\n // Japanese\n \"構築\",\n \"作成\",\n \"実装\",\n \"設計\",\n \"開発\",\n \"生成\",\n \"デプロイ\",\n \"設定\",\n // Russian\n \"построить\",\n \"построй\",\n \"создать\",\n \"создай\",\n \"реализовать\",\n \"реализуй\",\n \"спроектировать\",\n \"разработать\",\n \"разработай\",\n \"сконструировать\",\n \"сгенерировать\",\n \"сгенерируй\",\n \"развернуть\",\n \"разверни\",\n \"настроить\",\n \"настрой\",\n // German\n \"erstellen\",\n \"bauen\",\n \"implementieren\",\n \"entwerfen\",\n \"entwickeln\",\n \"konstruieren\",\n \"generieren\",\n \"bereitstellen\",\n \"konfigurieren\",\n \"einrichten\",\n // Spanish\n \"construir\",\n \"crear\",\n \"implementar\",\n \"diseñar\",\n \"desarrollar\",\n \"generar\",\n \"desplegar\",\n \"configurar\",\n // Portuguese\n \"construir\",\n \"criar\",\n \"implementar\",\n \"projetar\",\n \"desenvolver\",\n \"gerar\",\n \"implantar\",\n \"configurar\",\n // Korean\n \"구축\",\n \"생성\",\n \"구현\",\n \"설계\",\n \"개발\",\n \"배포\",\n \"설정\",\n // Arabic\n \"بناء\",\n \"إنشاء\",\n \"تنفيذ\",\n \"تصميم\",\n \"تطوير\",\n \"توليد\",\n \"نشر\",\n \"إعداد\",\n ],\n constraintIndicators: [\n // English\n \"under\",\n \"at most\",\n \"at least\",\n \"within\",\n \"no more than\",\n \"o(\",\n \"maximum\",\n \"minimum\",\n \"limit\",\n \"budget\",\n // Chinese\n \"不超过\",\n \"至少\",\n \"最多\",\n \"在内\",\n \"最大\",\n \"最小\",\n \"限制\",\n \"预算\",\n // Japanese\n \"以下\",\n \"最大\",\n \"最小\",\n \"制限\",\n \"予算\",\n // Russian\n \"не более\",\n \"не менее\",\n \"как минимум\",\n \"в пределах\",\n \"максимум\",\n \"минимум\",\n \"ограничение\",\n \"бюджет\",\n // German\n \"höchstens\",\n \"mindestens\",\n \"innerhalb\",\n \"nicht mehr als\",\n \"maximal\",\n \"minimal\",\n \"grenze\",\n \"budget\",\n // Spanish\n \"como máximo\",\n \"al menos\",\n \"dentro de\",\n \"no más de\",\n \"máximo\",\n \"mínimo\",\n \"límite\",\n \"presupuesto\",\n // Portuguese\n \"no máximo\",\n \"pelo menos\",\n \"dentro de\",\n \"não mais que\",\n \"máximo\",\n \"mínimo\",\n \"limite\",\n \"orçamento\",\n // Korean\n \"이하\",\n \"이상\",\n \"최대\",\n \"최소\",\n \"제한\",\n \"예산\",\n // Arabic\n \"على الأكثر\",\n \"على الأقل\",\n \"ضمن\",\n \"لا يزيد عن\",\n \"أقصى\",\n \"أدنى\",\n \"حد\",\n \"ميزانية\",\n ],\n outputFormatKeywords: [\n // English\n \"json\",\n \"yaml\",\n \"xml\",\n \"table\",\n \"csv\",\n \"markdown\",\n \"schema\",\n \"format as\",\n \"structured\",\n // Chinese\n \"表格\",\n \"格式化为\",\n \"结构化\",\n // Japanese\n \"テーブル\",\n \"フォーマット\",\n \"構造化\",\n // Russian\n \"таблица\",\n \"форматировать как\",\n \"структурированный\",\n // German\n \"tabelle\",\n \"formatieren als\",\n \"strukturiert\",\n // Spanish\n \"tabla\",\n \"formatear como\",\n \"estructurado\",\n // Portuguese\n \"tabela\",\n \"formatar como\",\n \"estruturado\",\n // Korean\n \"테이블\",\n \"형식\",\n \"구조화\",\n // Arabic\n \"جدول\",\n \"تنسيق\",\n \"منظم\",\n ],\n referenceKeywords: [\n // English\n \"above\",\n \"below\",\n \"previous\",\n \"following\",\n \"the docs\",\n \"the api\",\n \"the code\",\n \"earlier\",\n \"attached\",\n // Chinese\n \"上面\",\n \"下面\",\n \"之前\",\n \"接下来\",\n \"文档\",\n \"代码\",\n \"附件\",\n // Japanese\n \"上記\",\n \"下記\",\n \"前の\",\n \"次の\",\n \"ドキュメント\",\n \"コード\",\n // Russian\n \"выше\",\n \"ниже\",\n \"предыдущий\",\n \"следующий\",\n \"документация\",\n \"код\",\n \"ранее\",\n \"вложение\",\n // German\n \"oben\",\n \"unten\",\n \"vorherige\",\n \"folgende\",\n \"dokumentation\",\n \"der code\",\n \"früher\",\n \"anhang\",\n // Spanish\n \"arriba\",\n \"abajo\",\n \"anterior\",\n \"siguiente\",\n \"documentación\",\n \"el código\",\n \"adjunto\",\n // Portuguese\n \"acima\",\n \"abaixo\",\n \"anterior\",\n \"seguinte\",\n \"documentação\",\n \"o código\",\n \"anexo\",\n // Korean\n \"위\",\n \"아래\",\n \"이전\",\n \"다음\",\n \"문서\",\n \"코드\",\n \"첨부\",\n // Arabic\n \"أعلاه\",\n \"أدناه\",\n \"السابق\",\n \"التالي\",\n \"الوثائق\",\n \"الكود\",\n \"مرفق\",\n ],\n negationKeywords: [\n // English\n \"don't\",\n \"do not\",\n \"avoid\",\n \"never\",\n \"without\",\n \"except\",\n \"exclude\",\n \"no longer\",\n // Chinese\n \"不要\",\n \"避免\",\n \"从不\",\n \"没有\",\n \"除了\",\n \"排除\",\n // Japanese\n \"しないで\",\n \"避ける\",\n \"決して\",\n \"なしで\",\n \"除く\",\n // Russian\n \"не делай\",\n \"не надо\",\n \"нельзя\",\n \"избегать\",\n \"никогда\",\n \"без\",\n \"кроме\",\n \"исключить\",\n \"больше не\",\n // German\n \"nicht\",\n \"vermeide\",\n \"niemals\",\n \"ohne\",\n \"außer\",\n \"ausschließen\",\n \"nicht mehr\",\n // Spanish\n \"no hagas\",\n \"evitar\",\n \"nunca\",\n \"sin\",\n \"excepto\",\n \"excluir\",\n // Portuguese\n \"não faça\",\n \"evitar\",\n \"nunca\",\n \"sem\",\n \"exceto\",\n \"excluir\",\n // Korean\n \"하지 마\",\n \"피하다\",\n \"절대\",\n \"없이\",\n \"제외\",\n // Arabic\n \"لا تفعل\",\n \"تجنب\",\n \"أبداً\",\n \"بدون\",\n \"باستثناء\",\n \"استبعاد\",\n ],\n domainSpecificKeywords: [\n // English\n \"quantum\",\n \"fpga\",\n \"vlsi\",\n \"risc-v\",\n \"asic\",\n \"photonics\",\n \"genomics\",\n \"proteomics\",\n \"topological\",\n \"homomorphic\",\n \"zero-knowledge\",\n \"lattice-based\",\n // Chinese\n \"量子\",\n \"光子学\",\n \"基因组学\",\n \"蛋白质组学\",\n \"拓扑\",\n \"同态\",\n \"零知识\",\n \"格密码\",\n // Japanese\n \"量子\",\n \"フォトニクス\",\n \"ゲノミクス\",\n \"トポロジカル\",\n // Russian\n \"квантовый\",\n \"фотоника\",\n \"геномика\",\n \"протеомика\",\n \"топологический\",\n \"гомоморфный\",\n \"с нулевым разглашением\",\n \"на основе решёток\",\n // German\n \"quanten\",\n \"photonik\",\n \"genomik\",\n \"proteomik\",\n \"topologisch\",\n \"homomorph\",\n \"zero-knowledge\",\n \"gitterbasiert\",\n // Spanish\n \"cuántico\",\n \"fotónica\",\n \"genómica\",\n \"proteómica\",\n \"topológico\",\n \"homomórfico\",\n // Portuguese\n \"quântico\",\n \"fotônica\",\n \"genômica\",\n \"proteômica\",\n \"topológico\",\n \"homomórfico\",\n // Korean\n \"양자\",\n \"포토닉스\",\n \"유전체학\",\n \"위상\",\n \"동형\",\n // Arabic\n \"كمي\",\n \"ضوئيات\",\n \"جينوميات\",\n \"طوبولوجي\",\n \"تماثلي\",\n ],\n\n // Agentic task keywords - file ops, execution, multi-step, iterative work\n // Pruned: removed overly common words like \"then\", \"first\", \"run\", \"test\", \"build\"\n agenticTaskKeywords: [\n // English - File operations (clearly agentic)\n \"read file\",\n \"read the file\",\n \"look at\",\n \"check the\",\n \"open the\",\n \"edit\",\n \"modify\",\n \"update the\",\n \"change the\",\n \"write to\",\n \"create file\",\n // English - Execution (specific commands only)\n \"execute\",\n \"deploy\",\n \"install\",\n \"npm\",\n \"pip\",\n \"compile\",\n // English - Multi-step patterns (specific only)\n \"after that\",\n \"and also\",\n \"once done\",\n \"step 1\",\n \"step 2\",\n // English - Iterative work\n \"fix\",\n \"debug\",\n \"until it works\",\n \"keep trying\",\n \"iterate\",\n \"make sure\",\n \"verify\",\n \"confirm\",\n // Chinese (keep specific ones)\n \"读取文件\",\n \"查看\",\n \"打开\",\n \"编辑\",\n \"修改\",\n \"更新\",\n \"创建\",\n \"执行\",\n \"部署\",\n \"安装\",\n \"第一步\",\n \"第二步\",\n \"修复\",\n \"调试\",\n \"直到\",\n \"确认\",\n \"验证\",\n // Spanish\n \"leer archivo\",\n \"editar\",\n \"modificar\",\n \"actualizar\",\n \"ejecutar\",\n \"desplegar\",\n \"instalar\",\n \"paso 1\",\n \"paso 2\",\n \"arreglar\",\n \"depurar\",\n \"verificar\",\n // Portuguese\n \"ler arquivo\",\n \"editar\",\n \"modificar\",\n \"atualizar\",\n \"executar\",\n \"implantar\",\n \"instalar\",\n \"passo 1\",\n \"passo 2\",\n \"corrigir\",\n \"depurar\",\n \"verificar\",\n // Korean\n \"파일 읽기\",\n \"편집\",\n \"수정\",\n \"업데이트\",\n \"실행\",\n \"배포\",\n \"설치\",\n \"단계 1\",\n \"단계 2\",\n \"디버그\",\n \"확인\",\n // Arabic\n \"قراءة ملف\",\n \"تحرير\",\n \"تعديل\",\n \"تحديث\",\n \"تنفيذ\",\n \"نشر\",\n \"تثبيت\",\n \"الخطوة 1\",\n \"الخطوة 2\",\n \"إصلاح\",\n \"تصحيح\",\n \"تحقق\",\n ],\n\n // Dimension weights (sum to 1.0)\n dimensionWeights: {\n tokenCount: 0.08,\n codePresence: 0.15,\n reasoningMarkers: 0.18,\n technicalTerms: 0.1,\n creativeMarkers: 0.05,\n simpleIndicators: 0.02, // Reduced from 0.12 to make room for agenticTask\n multiStepPatterns: 0.12,\n questionComplexity: 0.05,\n imperativeVerbs: 0.03,\n constraintCount: 0.04,\n outputFormat: 0.03,\n referenceComplexity: 0.02,\n negationComplexity: 0.01,\n domainSpecificity: 0.02,\n agenticTask: 0.04, // Reduced - agentic signals influence tier selection, not dominate it\n },\n\n // Tier boundaries on weighted score axis\n tierBoundaries: {\n simpleMedium: 0.0,\n mediumComplex: 0.3, // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier\n complexReasoning: 0.5, // Raised from 0.4 - reserve for true reasoning tasks\n },\n\n // Sigmoid steepness for confidence calibration\n confidenceSteepness: 12,\n // Below this confidence → ambiguous (null tier)\n confidenceThreshold: 0.7,\n },\n\n // Auto (balanced) tier configs - current default smart routing\n // Benchmark-tuned 2026-03-16: balancing quality (retention) + latency\n tiers: {\n SIMPLE: {\n primary: \"google/gemini-2.5-flash\", // 1,238ms, IQ 20, 60% retention (best) — fast AND quality\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — smarter fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, strong quality\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context — newest flash-lite\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"openai/gpt-5.4-nano\", // $0.20/$1.25, 1M context\n \"xai/grok-4-fast-non-reasoning\", // 1,143ms, $0.20/$0.50 — fast fallback\n \"free/gpt-oss-120b\", // 1,252ms, FREE fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, $0.60/$3.00 — strong tool use, quality output\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — nearly same IQ, faster + cheaper\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"google/gemini-2.5-flash\", // 1,238ms, 60% retention\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"xai/grok-3-mini\", // 1,202ms, $0.30/$0.50\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-pro\", // 1,609ms, IQ 57 — fast flagship quality\n fallback: [\n \"google/gemini-3-pro-preview\", // 1,352ms, IQ 48 — quality-first fallback\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — fast + smart\n \"xai/grok-4-0709\", // 1,348ms, IQ 41\n \"google/gemini-2.5-pro\", // 1,294ms\n \"anthropic/claude-sonnet-4.6\", // 2,110ms, IQ 52 — quality fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32\n \"google/gemini-2.5-flash\", // 1,238ms, IQ 20 — cheap last resort\n \"openai/gpt-5.4\", // 6,213ms, IQ 57 — slowest but highest quality\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // 1,454ms, $0.20/$0.50\n fallback: [\n \"xai/grok-4-fast-reasoning\", // 1,298ms, $0.20/$0.50\n \"deepseek/deepseek-reasoner\", // 1,454ms, cheap reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Eco tier configs - absolute cheapest (blockrun/eco)\n ecoTiers: {\n SIMPLE: {\n primary: \"free/gpt-oss-120b\", // FREE! $0.00/$0.00\n fallback: [\n \"free/gpt-oss-20b\", // FREE — smaller, faster\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n \"openai/gpt-5.4-nano\", // $0.20/$1.25 — fast nano\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\", // $0.20/$0.50\n ],\n },\n MEDIUM: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n fallback: [\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\",\n \"google/gemini-2.5-flash\",\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n fallback: [\n \"google/gemini-2.5-flash-lite\",\n \"xai/grok-4-0709\",\n \"google/gemini-2.5-flash\",\n \"deepseek/deepseek-chat\",\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // $0.20/$0.50\n fallback: [\"xai/grok-4-fast-reasoning\", \"deepseek/deepseek-reasoner\"],\n },\n },\n\n // Premium tier configs - best quality (blockrun/premium)\n // codex=complex coding, kimi=simple coding, sonnet=reasoning/instructions, opus=architecture/PM/audits\n premiumTiers: {\n SIMPLE: {\n primary: \"moonshot/kimi-k2.5\", // $0.60/$3.00 - good for simple coding\n fallback: [\n \"google/gemini-2.5-flash\", // 60% retention, fast growth\n \"anthropic/claude-haiku-4.5\",\n \"google/gemini-2.5-flash-lite\",\n \"deepseek/deepseek-chat\",\n ],\n },\n MEDIUM: {\n primary: \"openai/gpt-5.3-codex\", // $1.75/$14 - 400K context, 128K output, replaces 5.2\n fallback: [\n \"moonshot/kimi-k2.5\",\n \"google/gemini-2.5-flash\", // 60% retention, good coding capability\n \"google/gemini-2.5-pro\",\n \"xai/grok-4-0709\",\n \"anthropic/claude-sonnet-4.6\",\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-opus-4.6\", // Best quality for complex tasks\n fallback: [\n \"openai/gpt-5.4\", // Newest flagship\n \"openai/gpt-5.3-codex\",\n \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-sonnet-4.6\",\n \"google/gemini-3.1-pro\", // Newest Gemini\n \"google/gemini-3-pro-preview\",\n \"moonshot/kimi-k2.5\",\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms, $3/$15 - best for reasoning/instructions\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms, cheap fast reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Agentic tier configs - models that excel at multi-step autonomous tasks\n agenticTiers: {\n SIMPLE: {\n primary: \"openai/gpt-4o-mini\", // $0.15/$0.60 - best tool compliance at lowest cost\n fallback: [\n \"moonshot/kimi-k2.5\", // 1,646ms, strong tool use quality\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, $0.60/$3.00 - strong tool use, proper function calls\n fallback: [\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"openai/gpt-4o-mini\", // 2,764ms, reliable tool calling\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"deepseek/deepseek-chat\", // 1,431ms\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — best agentic quality\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms — top quality\n \"google/gemini-3.1-pro\", // 1,609ms\n \"xai/grok-4-0709\", // 1,348ms\n \"openai/gpt-5.4\", // 6,213ms — slow but highest quality fallback\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — strong tool use + reasoning\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms\n \"deepseek/deepseek-reasoner\", // 1,454ms\n ],\n },\n },\n\n overrides: {\n maxTokensForceComplex: 100_000,\n structuredOutputMinTier: \"MEDIUM\",\n ambiguousDefaultTier: \"MEDIUM\",\n agenticMode: false,\n },\n};\n","/**\n * Smart Router Entry Point\n *\n * Classifies requests and routes to the cheapest capable model.\n * Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).\n */\n\nimport type { RoutingDecision, RouterOptions } from \"./types.js\";\nimport { getStrategy } from \"./strategy.js\";\n\n/**\n * Route a request to the cheapest capable model.\n * Delegates to the registered \"rules\" strategy by default.\n */\nexport function route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n): RoutingDecision {\n const strategy = getStrategy(\"rules\");\n return strategy.route(prompt, systemPrompt, maxOutputTokens, options);\n}\n\nexport { getStrategy, registerStrategy } from \"./strategy.js\";\nexport {\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n} from \"./selector.js\";\nexport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nexport type {\n RoutingDecision,\n Tier,\n RoutingConfig,\n RouterOptions,\n RouterStrategy,\n} from \"./types.js\";\nexport type { ModelPricing } from \"./selector.js\";\n","/**\n * BlockRun Model Definitions for OpenClaw\n *\n * Maps BlockRun's 55+ AI models to OpenClaw's ModelDefinitionConfig format.\n * All models use the \"openai-completions\" API since BlockRun is OpenAI-compatible.\n *\n * Pricing is in USD per 1M tokens. Operators pay these rates via x402;\n * they set their own markup when reselling to end users (Phase 2).\n */\n\nimport type { ModelDefinitionConfig, ModelProviderConfig } from \"./types.js\";\n\n/**\n * Model aliases for convenient shorthand access.\n * Users can type `/model claude` instead of `/model blockrun/anthropic/claude-sonnet-4-6`.\n */\nexport const MODEL_ALIASES: Record = {\n // Claude - use newest versions (4.6)\n claude: \"anthropic/claude-sonnet-4.6\",\n sonnet: \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4.6\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n opus: \"anthropic/claude-opus-4.6\",\n \"opus-4\": \"anthropic/claude-opus-4.6\",\n \"opus-4.6\": \"anthropic/claude-opus-4.6\",\n \"opus-4-6\": \"anthropic/claude-opus-4.6\",\n haiku: \"anthropic/claude-haiku-4.5\",\n // Claude - provider/shortname patterns (common in agent frameworks)\n \"anthropic/sonnet\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/opus\": \"anthropic/claude-opus-4.6\",\n \"anthropic/haiku\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude\": \"anthropic/claude-sonnet-4.6\",\n // Backward compatibility - map all variants to 4.6\n \"anthropic/claude-sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-opus-4\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4-6\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4.5\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-haiku-4\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude-haiku-4-5\": \"anthropic/claude-haiku-4.5\",\n\n // OpenAI\n gpt: \"openai/gpt-4o\",\n gpt4: \"openai/gpt-4o\",\n gpt5: \"openai/gpt-5.4\",\n \"gpt-5.4\": \"openai/gpt-5.4\",\n \"gpt-5.4-pro\": \"openai/gpt-5.4-pro\",\n \"gpt-5.4-nano\": \"openai/gpt-5.4-nano\",\n nano: \"openai/gpt-5.4-nano\",\n \"gpt-5-nano\": \"openai/gpt-5.4-nano\",\n codex: \"openai/gpt-5.3-codex\",\n mini: \"openai/gpt-4o-mini\",\n o1: \"openai/o1\",\n o3: \"openai/o3\",\n\n // DeepSeek\n deepseek: \"deepseek/deepseek-chat\",\n \"deepseek-chat\": \"deepseek/deepseek-chat\",\n reasoner: \"deepseek/deepseek-reasoner\",\n\n // Kimi / Moonshot\n kimi: \"moonshot/kimi-k2.5\",\n moonshot: \"moonshot/kimi-k2.5\",\n \"kimi-k2.5\": \"moonshot/kimi-k2.5\",\n\n // Google\n gemini: \"google/gemini-2.5-pro\",\n flash: \"google/gemini-2.5-flash\",\n \"gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"google/gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"gemini-3.1-flash-lite\": \"google/gemini-3.1-flash-lite\",\n\n // xAI\n grok: \"xai/grok-3\",\n \"grok-fast\": \"xai/grok-4-fast-reasoning\",\n \"grok-code\": \"deepseek/deepseek-chat\", // was grok-code-fast-1, delisted due to poor retention\n // Delisted model redirects — full model IDs that were previously valid but removed\n \"grok-code-fast-1\": \"deepseek/deepseek-chat\", // bare alias\n \"xai/grok-code-fast-1\": \"deepseek/deepseek-chat\", // delisted 2026-03-12\n \"xai/grok-3-fast\": \"xai/grok-4-fast-reasoning\", // delisted (too expensive)\n\n // NVIDIA — backward compat aliases (nvidia/xxx → free/xxx)\n nvidia: \"free/gpt-oss-120b\",\n \"gpt-120b\": \"free/gpt-oss-120b\",\n \"gpt-20b\": \"free/gpt-oss-20b\",\n \"nvidia/gpt-oss-120b\": \"free/gpt-oss-120b\",\n \"nvidia/gpt-oss-20b\": \"free/gpt-oss-20b\",\n \"nvidia/nemotron-ultra-253b\": \"free/nemotron-ultra-253b\",\n \"nvidia/nemotron-3-super-120b\": \"free/nemotron-3-super-120b\",\n \"nvidia/nemotron-super-49b\": \"free/nemotron-super-49b\",\n \"nvidia/deepseek-v3.2\": \"free/deepseek-v3.2\",\n \"nvidia/mistral-large-3-675b\": \"free/mistral-large-3-675b\",\n \"nvidia/qwen3-coder-480b\": \"free/qwen3-coder-480b\",\n \"nvidia/devstral-2-123b\": \"free/devstral-2-123b\",\n \"nvidia/glm-4.7\": \"free/glm-4.7\",\n \"nvidia/llama-4-maverick\": \"free/llama-4-maverick\",\n // Free model shorthand aliases\n \"deepseek-free\": \"free/deepseek-v3.2\",\n \"mistral-free\": \"free/mistral-large-3-675b\",\n \"glm-free\": \"free/glm-4.7\",\n \"llama-free\": \"free/llama-4-maverick\",\n nemotron: \"free/nemotron-ultra-253b\",\n \"nemotron-ultra\": \"free/nemotron-ultra-253b\",\n \"nemotron-253b\": \"free/nemotron-ultra-253b\",\n \"nemotron-super\": \"free/nemotron-super-49b\",\n \"nemotron-49b\": \"free/nemotron-super-49b\",\n \"nemotron-120b\": \"free/nemotron-3-super-120b\",\n devstral: \"free/devstral-2-123b\",\n \"devstral-2\": \"free/devstral-2-123b\",\n \"qwen-coder\": \"free/qwen3-coder-480b\",\n \"qwen-coder-free\": \"free/qwen3-coder-480b\",\n maverick: \"free/llama-4-maverick\",\n free: \"free/nemotron-ultra-253b\",\n\n // MiniMax\n minimax: \"minimax/minimax-m2.7\",\n \"minimax-m2.7\": \"minimax/minimax-m2.7\",\n \"minimax-m2.5\": \"minimax/minimax-m2.5\",\n\n // Z.AI GLM-5\n glm: \"zai/glm-5\",\n \"glm-5\": \"zai/glm-5\",\n \"glm-5-turbo\": \"zai/glm-5-turbo\",\n\n // Routing profile aliases (common variations)\n \"auto-router\": \"auto\",\n router: \"auto\",\n\n // Note: auto, eco, premium are virtual routing profiles registered in BLOCKRUN_MODELS\n // They don't need aliases since they're already top-level model IDs\n};\n\n/**\n * Resolve a model alias to its full model ID.\n * Also strips \"blockrun/\" prefix for direct model paths.\n * Examples:\n * - \"claude\" -> \"anthropic/claude-sonnet-4-6\" (alias)\n * - \"blockrun/claude\" -> \"anthropic/claude-sonnet-4-6\" (alias with prefix)\n * - \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\" (prefix stripped)\n * - \"openai/gpt-4o\" -> \"openai/gpt-4o\" (unchanged)\n */\nexport function resolveModelAlias(model: string): string {\n const normalized = model.trim().toLowerCase();\n const resolved = MODEL_ALIASES[normalized];\n if (resolved) return resolved;\n\n // Check with \"blockrun/\" prefix stripped\n if (normalized.startsWith(\"blockrun/\")) {\n const withoutPrefix = normalized.slice(\"blockrun/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // Even if not an alias, strip the prefix for direct model paths\n // e.g., \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\"\n return withoutPrefix;\n }\n\n // Strip \"openai/\" prefix when it wraps a virtual routing profile or alias.\n // OpenClaw sends virtual models as \"openai/eco\", \"openai/auto\", etc. because\n // the provider uses the openai-completions API type.\n if (normalized.startsWith(\"openai/\")) {\n const withoutPrefix = normalized.slice(\"openai/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // If it's a known BlockRun virtual profile (eco, auto, premium), return bare id\n const isVirtualProfile = BLOCKRUN_MODELS.some((m) => m.id === withoutPrefix);\n if (isVirtualProfile) return withoutPrefix;\n }\n\n return model;\n}\n\ntype BlockRunModel = {\n id: string;\n name: string;\n /** Model version (e.g., \"4.6\", \"3.1\", \"5.2\") for tracking updates */\n version?: string;\n inputPrice: number;\n outputPrice: number;\n contextWindow: number;\n maxOutput: number;\n reasoning?: boolean;\n vision?: boolean;\n /** Models optimized for agentic workflows (multi-step autonomous tasks) */\n agentic?: boolean;\n /**\n * Model supports OpenAI-compatible structured function/tool calling.\n * Models without this flag output tool invocations as plain text JSON,\n * which leaks raw {\"command\":\"...\"} into visible chat messages.\n * Default: false (must opt-in to prevent silent regressions on new models).\n */\n toolCalling?: boolean;\n /** Model is deprecated — will be routed to fallbackModel if set */\n deprecated?: boolean;\n /** Model ID to route to when this model is deprecated */\n fallbackModel?: string;\n};\n\nexport const BLOCKRUN_MODELS: BlockRunModel[] = [\n // Smart routing meta-models — proxy replaces with actual model\n // NOTE: Model IDs are WITHOUT provider prefix (OpenClaw adds \"blockrun/\" automatically)\n {\n id: \"auto\",\n name: \"Auto (Smart Router - Balanced)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"free\",\n name: \"Free → Nemotron Ultra 253B\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131_072,\n maxOutput: 16_384,\n reasoning: true,\n },\n {\n id: \"eco\",\n name: \"Eco (Smart Router - Cost Optimized)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"premium\",\n name: \"Premium (Smart Router - Best Quality)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 2_000_000,\n maxOutput: 200_000,\n },\n\n // OpenAI GPT-5 Family\n {\n id: \"openai/gpt-5.2\",\n name: \"GPT-5.2\",\n version: \"5.2\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-mini\",\n name: \"GPT-5 Mini\",\n version: \"5.0\",\n inputPrice: 0.25,\n outputPrice: 2.0,\n contextWindow: 200000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-nano\",\n name: \"GPT-5 Nano\",\n version: \"5.0\",\n inputPrice: 0.05,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 32768,\n toolCalling: true,\n deprecated: true,\n fallbackModel: \"openai/gpt-5.4-nano\",\n },\n {\n id: \"openai/gpt-5.2-pro\",\n name: \"GPT-5.2 Pro\",\n version: \"5.2\",\n inputPrice: 21.0,\n outputPrice: 168.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n // GPT-5.4 — newest flagship, same input price as 4o but much more capable\n {\n id: \"openai/gpt-5.4\",\n name: \"GPT-5.4\",\n version: \"5.4\",\n inputPrice: 2.5,\n outputPrice: 15.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-pro\",\n name: \"GPT-5.4 Pro\",\n version: \"5.4\",\n inputPrice: 30.0,\n outputPrice: 180.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-nano\",\n name: \"GPT-5.4 Nano\",\n version: \"5.4\",\n inputPrice: 0.2,\n outputPrice: 1.25,\n contextWindow: 1050000,\n maxOutput: 32768,\n toolCalling: true,\n },\n\n // OpenAI GPT-5.3 Family\n {\n id: \"openai/gpt-5.3\",\n name: \"GPT-5.3\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 128000,\n maxOutput: 16000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI Codex Family\n {\n id: \"openai/gpt-5.3-codex\",\n name: \"GPT-5.3 Codex\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI GPT-4 Family\n {\n id: \"openai/gpt-4.1\",\n name: \"GPT-4.1\",\n version: \"4.1\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-mini\",\n name: \"GPT-4.1 Mini\",\n version: \"4.1\",\n inputPrice: 0.4,\n outputPrice: 1.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-nano\",\n name: \"GPT-4.1 Nano\",\n version: \"4.1\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o\",\n name: \"GPT-4o\",\n version: \"4o\",\n inputPrice: 2.5,\n outputPrice: 10.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o-mini\",\n name: \"GPT-4o Mini\",\n version: \"4o-mini\",\n inputPrice: 0.15,\n outputPrice: 0.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // OpenAI O-series (Reasoning)\n {\n id: \"openai/o1\",\n name: \"o1\",\n version: \"1\",\n inputPrice: 15.0,\n outputPrice: 60.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o1-mini\",\n name: \"o1-mini\",\n version: \"1-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3\",\n name: \"o3\",\n version: \"3\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3-mini\",\n name: \"o3-mini\",\n version: \"3-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o4-mini\",\n name: \"o4-mini\",\n version: \"4-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n\n // Anthropic - all Claude models excel at agentic workflows\n // Use newest versions (4.6) with full provider prefix\n {\n id: \"anthropic/claude-haiku-4.5\",\n name: \"Claude Haiku 4.5\",\n version: \"4.5\",\n inputPrice: 1.0,\n outputPrice: 5.0,\n contextWindow: 200000,\n maxOutput: 8192,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-sonnet-4.6\",\n name: \"Claude Sonnet 4.6\",\n version: \"4.6\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 200000,\n maxOutput: 64000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-opus-4.6\",\n name: \"Claude Opus 4.6\",\n version: \"4.6\",\n inputPrice: 5.0,\n outputPrice: 25.0,\n contextWindow: 200000,\n maxOutput: 32000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Google\n {\n id: \"google/gemini-3.1-pro\",\n name: \"Gemini 3.1 Pro\",\n version: \"3.1\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-pro-preview\",\n name: \"Gemini 3 Pro Preview\",\n version: \"3.0\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-flash-preview\",\n name: \"Gemini 3 Flash Preview\",\n version: \"3.0\",\n inputPrice: 0.5,\n outputPrice: 3.0,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n },\n {\n id: \"google/gemini-2.5-pro\",\n name: \"Gemini 2.5 Pro\",\n version: \"2.5\",\n inputPrice: 1.25,\n outputPrice: 10.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash\",\n name: \"Gemini 2.5 Flash\",\n version: \"2.5\",\n inputPrice: 0.3,\n outputPrice: 2.5,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash-lite\",\n name: \"Gemini 2.5 Flash Lite\",\n version: \"2.5\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 1000000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3.1-flash-lite\",\n name: \"Gemini 3.1 Flash Lite\",\n version: \"3.1\",\n inputPrice: 0.25,\n outputPrice: 1.5,\n contextWindow: 1000000,\n maxOutput: 8192,\n toolCalling: true,\n },\n\n // DeepSeek\n {\n id: \"deepseek/deepseek-chat\",\n name: \"DeepSeek V3.2 Chat\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n toolCalling: true,\n },\n {\n id: \"deepseek/deepseek-reasoner\",\n name: \"DeepSeek V3.2 Reasoner\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n reasoning: true,\n toolCalling: true,\n },\n\n // Moonshot / Kimi - optimized for agentic workflows\n {\n id: \"moonshot/kimi-k2.5\",\n name: \"Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 8192,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // xAI / Grok\n {\n id: \"xai/grok-3\",\n name: \"Grok 3\",\n version: \"3\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n // grok-3-fast removed - too expensive ($5/$25), use grok-4-fast instead\n {\n id: \"xai/grok-3-mini\",\n name: \"Grok 3 Mini\",\n version: \"3-mini\",\n inputPrice: 0.3,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // xAI Grok 4 Family - Ultra-cheap fast models\n {\n id: \"xai/grok-4-fast-reasoning\",\n name: \"Grok 4 Fast Reasoning\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-fast-non-reasoning\",\n name: \"Grok 4 Fast\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-reasoning\",\n name: \"Grok 4.1 Fast Reasoning\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-non-reasoning\",\n name: \"Grok 4.1 Fast\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n // xai/grok-code-fast-1 delisted 2026-03-12: poor retention (coding users churn),\n // no structured tool calling, alias \"grok-code\" redirected to deepseek-chat\n {\n id: \"xai/grok-4-0709\",\n name: \"Grok 4 (0709)\",\n version: \"4-0709\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-2-vision\",\n name: \"Grok 2 Vision\",\n version: \"2\",\n inputPrice: 2.0,\n outputPrice: 10.0,\n contextWindow: 131072,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n\n // MiniMax\n {\n id: \"minimax/minimax-m2.7\",\n name: \"MiniMax M2.7\",\n version: \"m2.7\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"minimax/minimax-m2.5\",\n name: \"MiniMax M2.5\",\n version: \"m2.5\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Free models (hosted by NVIDIA, billingMode: \"free\" on server)\n // IDs use \"free/\" prefix so users see them as free in the /model picker.\n // ClawRouter maps free/xxx → nvidia/xxx before sending to BlockRun upstream.\n // toolCalling intentionally omitted: structured function calling unverified.\n {\n id: \"free/gpt-oss-120b\",\n name: \"[Free] GPT-OSS 120B\",\n version: \"120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/gpt-oss-20b\",\n name: \"[Free] GPT-OSS 20B\",\n version: \"20b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/nemotron-ultra-253b\",\n name: \"[Free] Nemotron Ultra 253B\",\n version: \"253b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-3-super-120b\",\n name: \"[Free] Nemotron 3 Super 120B\",\n version: \"3-super-120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-super-49b\",\n name: \"[Free] Nemotron Super 49B\",\n version: \"super-49b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/deepseek-v3.2\",\n name: \"[Free] DeepSeek V3.2\",\n version: \"v3.2\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/mistral-large-3-675b\",\n name: \"[Free] Mistral Large 675B\",\n version: \"3-675b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/qwen3-coder-480b\",\n name: \"[Free] Qwen3 Coder 480B\",\n version: \"480b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/devstral-2-123b\",\n name: \"[Free] Devstral 2 123B\",\n version: \"2-123b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/glm-4.7\",\n name: \"[Free] GLM-4.7\",\n version: \"4.7\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/llama-4-maverick\",\n name: \"[Free] Llama 4 Maverick\",\n version: \"4-maverick\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n\n // NVIDIA - Paid models\n {\n id: \"nvidia/kimi-k2.5\",\n name: \"NVIDIA Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // Z.AI GLM-5 Models\n {\n id: \"zai/glm-5\",\n name: \"GLM-5\",\n version: \"5\",\n inputPrice: 1.0,\n outputPrice: 3.2,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n {\n id: \"zai/glm-5-turbo\",\n name: \"GLM-5 Turbo\",\n version: \"5-turbo\",\n inputPrice: 1.2,\n outputPrice: 4.0,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n];\n\n/**\n * Convert BlockRun model definitions to OpenClaw ModelDefinitionConfig format.\n */\nfunction toOpenClawModel(m: BlockRunModel): ModelDefinitionConfig {\n return {\n id: m.id,\n name: m.name,\n api: \"openai-completions\",\n reasoning: m.reasoning ?? false,\n input: m.vision ? [\"text\", \"image\"] : [\"text\"],\n cost: {\n input: m.inputPrice,\n output: m.outputPrice,\n cacheRead: 0,\n cacheWrite: 0,\n },\n contextWindow: m.contextWindow,\n maxTokens: m.maxOutput,\n };\n}\n\n/**\n * Alias models that map to real models.\n * These allow users to use friendly names like \"free\" or \"gpt-120b\".\n */\nconst ALIAS_MODELS: ModelDefinitionConfig[] = Object.entries(MODEL_ALIASES)\n .map(([alias, targetId]) => {\n const target = BLOCKRUN_MODELS.find((m) => m.id === targetId);\n if (!target) return null;\n return toOpenClawModel({ ...target, id: alias, name: `${alias} → ${target.name}` });\n })\n .filter((m): m is ModelDefinitionConfig => m !== null);\n\n/**\n * All BlockRun models in OpenClaw format (including aliases).\n */\nexport const OPENCLAW_MODELS: ModelDefinitionConfig[] = [\n ...BLOCKRUN_MODELS.map(toOpenClawModel),\n ...ALIAS_MODELS,\n];\n\n/**\n * Build a ModelProviderConfig for BlockRun.\n *\n * @param baseUrl - The proxy's local base URL (e.g., \"http://127.0.0.1:12345\")\n */\nexport function buildProviderModels(baseUrl: string): ModelProviderConfig {\n return {\n baseUrl: `${baseUrl}/v1`,\n api: \"openai-completions\",\n models: OPENCLAW_MODELS,\n };\n}\n\n/**\n * Check if a model is optimized for agentic workflows.\n * Agentic models continue autonomously with multi-step tasks\n * instead of stopping and waiting for user input.\n */\nexport function isAgenticModel(modelId: string): boolean {\n const model = BLOCKRUN_MODELS.find(\n (m) => m.id === modelId || m.id === modelId.replace(\"blockrun/\", \"\"),\n );\n return model?.agentic ?? false;\n}\n\n/**\n * Get all agentic-capable models.\n */\nexport function getAgenticModels(): string[] {\n return BLOCKRUN_MODELS.filter((m) => m.agentic).map((m) => m.id);\n}\n\n/**\n * Check if a model supports OpenAI-compatible structured tool/function calling.\n * Models without this flag (e.g. grok-code-fast-1) output tool invocations as\n * plain text JSON, which leaks {\"command\":\"...\"} into visible chat messages.\n */\nexport function supportsToolCalling(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.toolCalling ?? false;\n}\n\n/**\n * Check if a model supports vision (image inputs).\n * Models without this flag cannot process image_url content parts.\n */\nexport function supportsVision(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.vision ?? false;\n}\n\n/**\n * Get context window size for a model.\n * Returns undefined if model not found.\n */\nexport function getModelContextWindow(modelId: string): number | undefined {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.contextWindow;\n}\n\n/**\n * Check if a model has reasoning/thinking capabilities.\n * Reasoning models may require reasoning_content in assistant tool_call messages.\n */\nexport function isReasoningModel(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.reasoning ?? false;\n}\n","/**\n * Usage Logger\n *\n * Logs every LLM request as a JSON line to a daily log file.\n * Files: ~/.openclaw/blockrun/logs/usage-YYYY-MM-DD.jsonl\n *\n * MVP: append-only JSON lines. No rotation, no cleanup.\n * Logging never breaks the request flow — all errors are swallowed.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport type UsageEntry = {\n timestamp: string;\n model: string;\n tier: string;\n cost: number;\n baselineCost: number;\n savings: number; // 0-1 percentage\n latencyMs: number;\n /** Input (prompt) tokens reported by the provider */\n inputTokens?: number;\n /** Output (completion) tokens reported by the provider */\n outputTokens?: number;\n /** Partner service ID (e.g., \"x_users_lookup\") — only set for partner API calls */\n partnerId?: string;\n /** Partner service name (e.g., \"AttentionVC\") — only set for partner API calls */\n service?: string;\n};\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\nlet dirReady = false;\n\nasync function ensureDir(): Promise {\n if (dirReady) return;\n await mkdir(LOG_DIR, { recursive: true });\n dirReady = true;\n}\n\n/**\n * Log a usage entry as a JSON line.\n */\nexport async function logUsage(entry: UsageEntry): Promise {\n try {\n await ensureDir();\n const date = entry.timestamp.slice(0, 10); // YYYY-MM-DD\n const file = join(LOG_DIR, `usage-${date}.jsonl`);\n await appendFile(file, JSON.stringify(entry) + \"\\n\");\n } catch {\n // Never break the request flow\n }\n}\n","/**\n * Usage Statistics Aggregator\n *\n * Reads usage log files and aggregates statistics for terminal display.\n * Supports filtering by date range and provides multiple aggregation views.\n */\n\nimport { readdir, unlink } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type { UsageEntry } from \"./logger.js\";\nimport { VERSION } from \"./version.js\";\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\n\nexport type DailyStats = {\n date: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n avgLatencyMs: number;\n byTier: Record;\n byModel: Record;\n};\n\nexport type AggregatedStats = {\n period: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n savingsPercentage: number;\n avgLatencyMs: number;\n avgCostPerRequest: number;\n byTier: Record;\n byModel: Record;\n dailyBreakdown: DailyStats[];\n entriesWithBaseline: number; // Entries with valid baseline tracking\n};\n\n/**\n * Parse a JSONL log file into usage entries.\n * Handles both old format (without tier/baselineCost) and new format.\n */\nasync function parseLogFile(filePath: string): Promise {\n try {\n const content = await readTextFile(filePath);\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n const entries: UsageEntry[] = [];\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Partial;\n entries.push({\n timestamp: entry.timestamp || new Date().toISOString(),\n model: entry.model || \"unknown\",\n tier: entry.tier || \"UNKNOWN\",\n cost: entry.cost || 0,\n baselineCost: entry.baselineCost || entry.cost || 0,\n savings: entry.savings || 0,\n latencyMs: entry.latencyMs || 0,\n });\n } catch {\n // Skip malformed lines, keep valid ones\n }\n }\n return entries;\n } catch {\n return [];\n }\n}\n\n/**\n * Get list of available log files sorted by date (newest first).\n */\nasync function getLogFiles(): Promise {\n try {\n const files = await readdir(LOG_DIR);\n return files\n .filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\n/**\n * Aggregate stats for a single day.\n */\nfunction aggregateDay(date: string, entries: UsageEntry[]): DailyStats {\n const byTier: Record = {};\n const byModel: Record = {};\n let totalLatency = 0;\n\n for (const entry of entries) {\n // By tier\n if (!byTier[entry.tier]) byTier[entry.tier] = { count: 0, cost: 0 };\n byTier[entry.tier].count++;\n byTier[entry.tier].cost += entry.cost;\n\n // By model\n if (!byModel[entry.model]) byModel[entry.model] = { count: 0, cost: 0 };\n byModel[entry.model].count++;\n byModel[entry.model].cost += entry.cost;\n\n totalLatency += entry.latencyMs;\n }\n\n const totalCost = entries.reduce((sum, e) => sum + e.cost, 0);\n const totalBaselineCost = entries.reduce((sum, e) => sum + e.baselineCost, 0);\n\n return {\n date,\n totalRequests: entries.length,\n totalCost,\n totalBaselineCost,\n totalSavings: totalBaselineCost - totalCost,\n avgLatencyMs: entries.length > 0 ? totalLatency / entries.length : 0,\n byTier,\n byModel,\n };\n}\n\n/**\n * Get aggregated statistics for the last N days.\n */\nexport async function getStats(days: number = 7): Promise {\n const logFiles = await getLogFiles();\n const filesToRead = logFiles.slice(0, days);\n\n const dailyBreakdown: DailyStats[] = [];\n const allByTier: Record = {};\n const allByModel: Record = {};\n let totalRequests = 0;\n let totalCost = 0;\n let totalBaselineCost = 0;\n let totalLatency = 0;\n\n for (const file of filesToRead) {\n const date = file.replace(\"usage-\", \"\").replace(\".jsonl\", \"\");\n const filePath = join(LOG_DIR, file);\n const entries = await parseLogFile(filePath);\n\n if (entries.length === 0) continue;\n\n const dayStats = aggregateDay(date, entries);\n dailyBreakdown.push(dayStats);\n\n totalRequests += dayStats.totalRequests;\n totalCost += dayStats.totalCost;\n totalBaselineCost += dayStats.totalBaselineCost;\n totalLatency += dayStats.avgLatencyMs * dayStats.totalRequests;\n\n // Merge tier stats\n for (const [tier, stats] of Object.entries(dayStats.byTier)) {\n if (!allByTier[tier]) allByTier[tier] = { count: 0, cost: 0 };\n allByTier[tier].count += stats.count;\n allByTier[tier].cost += stats.cost;\n }\n\n // Merge model stats\n for (const [model, stats] of Object.entries(dayStats.byModel)) {\n if (!allByModel[model]) allByModel[model] = { count: 0, cost: 0 };\n allByModel[model].count += stats.count;\n allByModel[model].cost += stats.cost;\n }\n }\n\n // Calculate percentages\n const byTierWithPercentage: Record =\n {};\n for (const [tier, stats] of Object.entries(allByTier)) {\n byTierWithPercentage[tier] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const byModelWithPercentage: Record =\n {};\n for (const [model, stats] of Object.entries(allByModel)) {\n byModelWithPercentage[model] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const totalSavings = totalBaselineCost - totalCost;\n const savingsPercentage = totalBaselineCost > 0 ? (totalSavings / totalBaselineCost) * 100 : 0;\n\n // Count entries with valid baseline tracking (baseline != cost means tracking was active)\n let entriesWithBaseline = 0;\n for (const day of dailyBreakdown) {\n if (day.totalBaselineCost !== day.totalCost) {\n entriesWithBaseline += day.totalRequests;\n }\n }\n\n return {\n period: days === 1 ? \"today\" : `last ${days} days`,\n totalRequests,\n totalCost,\n totalBaselineCost,\n totalSavings,\n savingsPercentage,\n avgLatencyMs: totalRequests > 0 ? totalLatency / totalRequests : 0,\n avgCostPerRequest: totalRequests > 0 ? totalCost / totalRequests : 0,\n byTier: byTierWithPercentage,\n byModel: byModelWithPercentage,\n dailyBreakdown: dailyBreakdown.reverse(), // Oldest first for charts\n entriesWithBaseline, // How many entries have valid baseline tracking\n };\n}\n\n/**\n * Format stats as ASCII table for terminal display.\n */\nexport function formatStatsAscii(stats: AggregatedStats): string {\n const lines: string[] = [];\n\n // Header\n lines.push(\"╔════════════════════════════════════════════════════════════╗\");\n lines.push(`║ ClawRouter by BlockRun v${VERSION}`.padEnd(61) + \"║\");\n lines.push(\"║ Usage Statistics ║\");\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n\n // Summary\n lines.push(`║ Period: ${stats.period.padEnd(49)}║`);\n lines.push(`║ Total Requests: ${stats.totalRequests.toString().padEnd(41)}║`);\n lines.push(`║ Total Cost: $${stats.totalCost.toFixed(4).padEnd(43)}║`);\n lines.push(`║ Baseline Cost (Opus 4.5): $${stats.totalBaselineCost.toFixed(4).padEnd(30)}║`);\n\n // Show savings with note if some entries lack baseline tracking\n const savingsLine = `║ 💰 Total Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(1)}%)`;\n if (stats.entriesWithBaseline < stats.totalRequests && stats.entriesWithBaseline > 0) {\n lines.push(savingsLine.padEnd(61) + \"║\");\n const note = `║ (based on ${stats.entriesWithBaseline}/${stats.totalRequests} tracked requests)`;\n lines.push(note.padEnd(61) + \"║\");\n } else {\n lines.push(savingsLine.padEnd(61) + \"║\");\n }\n lines.push(`║ Avg Latency: ${stats.avgLatencyMs.toFixed(0)}ms`.padEnd(61) + \"║\");\n\n // Tier breakdown\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Routing by Tier: ║\");\n\n // Show all tiers found in data, ordered by known tiers first then others\n const knownTiers = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\", \"DIRECT\"];\n const allTiers = Object.keys(stats.byTier);\n const otherTiers = allTiers.filter((t) => !knownTiers.includes(t));\n const tierOrder = [...knownTiers.filter((t) => stats.byTier[t]), ...otherTiers];\n\n for (const tier of tierOrder) {\n const data = stats.byTier[tier];\n if (data) {\n const bar = \"█\".repeat(Math.min(20, Math.round(data.percentage / 5)));\n const displayTier = tier === \"UNKNOWN\" ? \"OTHER\" : tier;\n const line = `║ ${displayTier.padEnd(10)} ${bar.padEnd(20)} ${data.percentage.toFixed(1).padStart(5)}% (${data.count})`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n // Top models\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Top Models: ║\");\n\n const sortedModels = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 5);\n\n for (const [model, data] of sortedModels) {\n const shortModel = model.length > 25 ? model.slice(0, 22) + \"...\" : model;\n const line = `║ ${shortModel.padEnd(25)} ${data.count.toString().padStart(5)} reqs $${data.cost.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n\n // Daily breakdown (last 7 days)\n if (stats.dailyBreakdown.length > 0) {\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Daily Breakdown: ║\");\n lines.push(\"║ Date Requests Cost Saved ║\");\n\n for (const day of stats.dailyBreakdown.slice(-7)) {\n const saved = day.totalBaselineCost - day.totalCost;\n const line = `║ ${day.date} ${day.totalRequests.toString().padStart(6)} $${day.totalCost.toFixed(4).padStart(8)} $${saved.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n lines.push(\"╚════════════════════════════════════════════════════════════╝\");\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Delete all usage log files, resetting stats to zero.\n */\nexport async function clearStats(): Promise<{ deletedFiles: number }> {\n try {\n const files = await readdir(LOG_DIR);\n const logFiles = files.filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"));\n\n await Promise.all(logFiles.map((f) => unlink(join(LOG_DIR, f))));\n\n return { deletedFiles: logFiles.length };\n } catch {\n return { deletedFiles: 0 };\n }\n}\n","/**\n * Scanner-safe file reading utilities.\n *\n * Uses open() + read() to avoid false positives from openclaw's\n * potential-exfiltration heuristic in bundled output.\n */\n\nimport { open } from \"node:fs/promises\";\nimport { openSync, readSync, closeSync, fstatSync } from \"node:fs\";\n\n/** Read file contents as UTF-8 string (async). */\nexport async function readTextFile(filePath: string): Promise {\n const fh = await open(filePath, \"r\");\n try {\n const size = (await fh.stat()).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const { bytesRead } = await fh.read(buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n await fh.close();\n }\n}\n\n/** Read file contents as UTF-8 string (sync). */\nexport function readTextFileSync(filePath: string): string {\n const fd = openSync(filePath, \"r\");\n try {\n const size = fstatSync(fd).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const bytesRead = readSync(fd, buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n closeSync(fd);\n }\n}\n","/**\n * Single source of truth for version.\n * Reads from package.json at build time via tsup's define.\n */\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\n\n// Read package.json at runtime\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// In dist/, go up one level to find package.json\nconst require = createRequire(import.meta.url);\nconst pkg = require(join(__dirname, \"..\", \"package.json\")) as { version: string };\n\nexport const VERSION = pkg.version;\nexport const USER_AGENT = `clawrouter/${VERSION}`;\n","/**\n * Request Deduplication\n *\n * Prevents double-charging when OpenClaw retries a request after timeout.\n * Tracks in-flight requests and caches completed responses for a short TTL.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedResponse = {\n status: number;\n headers: Record;\n body: Buffer;\n completedAt: number;\n};\n\ntype InflightEntry = {\n resolvers: Array<(result: CachedResponse) => void>;\n};\n\nconst DEFAULT_TTL_MS = 30_000; // 30 seconds\nconst MAX_BODY_SIZE = 1_048_576; // 1MB\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical string regardless of field order.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip OpenClaw-injected timestamps from message content.\n * Format: [DAY YYYY-MM-DD HH:MM TZ] at the start of messages.\n * Example: [SUN 2026-02-07 13:30 PST] Hello world\n *\n * This ensures requests with different timestamps but same content hash identically.\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction stripTimestamps(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stripTimestamps);\n }\n const result: Record = {};\n for (const [key, value] of Object.entries(obj as Record)) {\n if (key === \"content\" && typeof value === \"string\") {\n // Strip timestamp prefix from message content\n result[key] = value.replace(TIMESTAMP_PATTERN, \"\");\n } else {\n result[key] = stripTimestamps(value);\n }\n }\n return result;\n}\n\nexport class RequestDeduplicator {\n private inflight = new Map();\n private completed = new Map();\n private ttlMs: number;\n\n constructor(ttlMs = DEFAULT_TTL_MS) {\n this.ttlMs = ttlMs;\n }\n\n /** Hash request body to create a dedup key. */\n static hash(body: Buffer): string {\n // Canonicalize JSON to ensure consistent hashing regardless of field order.\n // Also strip OpenClaw-injected timestamps so retries with different timestamps\n // still match the same dedup key.\n let content = body;\n try {\n const parsed = JSON.parse(body.toString());\n const stripped = stripTimestamps(parsed);\n const canonical = canonicalize(stripped);\n content = Buffer.from(JSON.stringify(canonical));\n } catch {\n // Not valid JSON, use raw bytes\n }\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 16);\n }\n\n /** Check if a response is cached for this key. */\n getCached(key: string): CachedResponse | undefined {\n const entry = this.completed.get(key);\n if (!entry) return undefined;\n if (Date.now() - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n return undefined;\n }\n return entry;\n }\n\n /** Check if a request with this key is currently in-flight. Returns a promise to wait on. */\n getInflight(key: string): Promise | undefined {\n const entry = this.inflight.get(key);\n if (!entry) return undefined;\n return new Promise((resolve) => {\n entry.resolvers.push(resolve);\n });\n }\n\n /** Mark a request as in-flight. */\n markInflight(key: string): void {\n this.inflight.set(key, {\n resolvers: [],\n });\n }\n\n /** Complete an in-flight request — cache result and notify waiters. */\n complete(key: string, result: CachedResponse): void {\n // Only cache responses within size limit\n if (result.body.length <= MAX_BODY_SIZE) {\n this.completed.set(key, result);\n }\n\n const entry = this.inflight.get(key);\n if (entry) {\n for (const resolve of entry.resolvers) {\n resolve(result);\n }\n this.inflight.delete(key);\n }\n\n this.prune();\n }\n\n /** Remove an in-flight entry on error (don't cache failures).\n * Also rejects any waiters so they can retry independently. */\n removeInflight(key: string): void {\n const entry = this.inflight.get(key);\n if (entry) {\n // Resolve waiters with a sentinel error response so they don't hang forever.\n // Waiters will see a 503 and can retry on their own.\n const errorBody = Buffer.from(\n JSON.stringify({\n error: { message: \"Original request failed, please retry\", type: \"dedup_origin_failed\" },\n }),\n );\n for (const resolve of entry.resolvers) {\n resolve({\n status: 503,\n headers: { \"content-type\": \"application/json\" },\n body: errorBody,\n completedAt: Date.now(),\n });\n }\n this.inflight.delete(key);\n }\n }\n\n /** Prune expired completed entries. */\n private prune(): void {\n const now = Date.now();\n for (const [key, entry] of this.completed) {\n if (now - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n }\n }\n }\n}\n","/**\n * Response Cache for LLM Completions\n *\n * Caches LLM responses by request hash (model + messages + params).\n * Inspired by LiteLLM's caching system. Returns cached responses for\n * identical requests, saving both cost and latency.\n *\n * Features:\n * - TTL-based expiration (default 10 minutes)\n * - LRU eviction when cache is full\n * - Size limits per item (1MB max)\n * - Heap-based expiration tracking for efficient pruning\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedLLMResponse = {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n cachedAt: number;\n expiresAt: number;\n};\n\nexport type ResponseCacheConfig = {\n /** Maximum number of cached responses. Default: 200 */\n maxSize?: number;\n /** Default TTL in seconds. Default: 600 (10 minutes) */\n defaultTTL?: number;\n /** Maximum size per cached item in bytes. Default: 1MB */\n maxItemSize?: number;\n /** Enable/disable cache. Default: true */\n enabled?: boolean;\n};\n\nconst DEFAULT_CONFIG: Required = {\n maxSize: 200,\n defaultTTL: 600,\n maxItemSize: 1_048_576, // 1MB\n enabled: true,\n};\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical hash.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip fields that shouldn't affect cache key:\n * - stream (we handle streaming separately)\n * - timestamps injected by OpenClaw\n * - request IDs\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction normalizeForCache(obj: Record): Record {\n const result: Record = {};\n\n for (const [key, value] of Object.entries(obj)) {\n // Skip fields that don't affect response content\n if ([\"stream\", \"user\", \"request_id\", \"x-request-id\"].includes(key)) {\n continue;\n }\n\n if (key === \"messages\" && Array.isArray(value)) {\n // Strip timestamps from message content\n result[key] = value.map((msg: unknown) => {\n if (typeof msg === \"object\" && msg !== null) {\n const m = msg as Record;\n if (typeof m.content === \"string\") {\n return { ...m, content: m.content.replace(TIMESTAMP_PATTERN, \"\") };\n }\n }\n return msg;\n });\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nexport class ResponseCache {\n private cache = new Map();\n private expirationHeap: Array<{ expiresAt: number; key: string }> = [];\n private config: Required;\n\n // Stats for monitoring\n private stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n };\n\n constructor(config: ResponseCacheConfig = {}) {\n // Filter out undefined values so they don't override defaults\n const filtered = Object.fromEntries(\n Object.entries(config).filter(([, v]) => v !== undefined),\n ) as ResponseCacheConfig;\n this.config = { ...DEFAULT_CONFIG, ...filtered };\n }\n\n /**\n * Generate cache key from request body.\n * Hashes: model + messages + temperature + max_tokens + other params\n */\n static generateKey(body: Buffer | string): string {\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n const normalized = normalizeForCache(parsed);\n const canonical = canonicalize(normalized);\n const keyContent = JSON.stringify(canonical);\n return createHash(\"sha256\").update(keyContent).digest(\"hex\").slice(0, 32);\n } catch {\n // Fallback: hash raw body\n const content = typeof body === \"string\" ? body : body.toString();\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 32);\n }\n }\n\n /**\n * Check if caching is enabled for this request.\n * Respects cache control headers and request params.\n */\n shouldCache(body: Buffer | string, headers?: Record): boolean {\n if (!this.config.enabled) return false;\n\n // Respect Cache-Control: no-cache header\n if (headers?.[\"cache-control\"]?.includes(\"no-cache\")) {\n return false;\n }\n\n // Check for explicit cache disable in body\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n if (parsed.cache === false || parsed.no_cache === true) {\n return false;\n }\n } catch {\n // Not JSON, allow caching\n }\n\n return true;\n }\n\n /**\n * Get cached response if available and not expired.\n */\n get(key: string): CachedLLMResponse | undefined {\n const entry = this.cache.get(key);\n if (!entry) {\n this.stats.misses++;\n return undefined;\n }\n\n // Check expiration\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n this.stats.misses++;\n return undefined;\n }\n\n this.stats.hits++;\n return entry;\n }\n\n /**\n * Cache a response with optional custom TTL.\n */\n set(\n key: string,\n response: {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n },\n ttlSeconds?: number,\n ): void {\n // Don't cache if disabled or maxSize is 0\n if (!this.config.enabled || this.config.maxSize <= 0) return;\n\n // Don't cache if item too large\n if (response.body.length > this.config.maxItemSize) {\n console.log(`[ResponseCache] Skipping cache - item too large: ${response.body.length} bytes`);\n return;\n }\n\n // Don't cache error responses\n if (response.status >= 400) {\n return;\n }\n\n // Evict if at capacity\n if (this.cache.size >= this.config.maxSize) {\n this.evict();\n }\n\n const now = Date.now();\n const ttl = ttlSeconds ?? this.config.defaultTTL;\n const expiresAt = now + ttl * 1000;\n\n const entry: CachedLLMResponse = {\n ...response,\n cachedAt: now,\n expiresAt,\n };\n\n this.cache.set(key, entry);\n this.expirationHeap.push({ expiresAt, key });\n }\n\n /**\n * Evict expired and oldest entries to make room.\n */\n private evict(): void {\n const now = Date.now();\n\n // First pass: remove expired entries\n this.expirationHeap.sort((a, b) => a.expiresAt - b.expiresAt);\n\n while (this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap[0];\n\n // Check if entry still exists and matches\n const entry = this.cache.get(oldest.key);\n if (!entry || entry.expiresAt !== oldest.expiresAt) {\n // Stale heap entry, remove it\n this.expirationHeap.shift();\n continue;\n }\n\n if (oldest.expiresAt <= now) {\n // Expired, remove both\n this.cache.delete(oldest.key);\n this.expirationHeap.shift();\n this.stats.evictions++;\n } else {\n // Not expired, stop\n break;\n }\n }\n\n // Second pass: if still at capacity, evict oldest\n while (this.cache.size >= this.config.maxSize && this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap.shift()!;\n if (this.cache.has(oldest.key)) {\n this.cache.delete(oldest.key);\n this.stats.evictions++;\n }\n }\n }\n\n /**\n * Get cache statistics.\n */\n getStats(): {\n size: number;\n maxSize: number;\n hits: number;\n misses: number;\n evictions: number;\n hitRate: string;\n } {\n const total = this.stats.hits + this.stats.misses;\n const hitRate = total > 0 ? ((this.stats.hits / total) * 100).toFixed(1) + \"%\" : \"0%\";\n\n return {\n size: this.cache.size,\n maxSize: this.config.maxSize,\n hits: this.stats.hits,\n misses: this.stats.misses,\n evictions: this.stats.evictions,\n hitRate,\n };\n }\n\n /**\n * Clear all cached entries.\n */\n clear(): void {\n this.cache.clear();\n this.expirationHeap = [];\n }\n\n /**\n * Check if cache is enabled.\n */\n isEnabled(): boolean {\n return this.config.enabled;\n }\n}\n","/**\n * Typed Error Classes for ClawRouter\n *\n * Provides structured errors for balance-related failures with\n * all necessary information for user-friendly error messages.\n */\n\n/**\n * Thrown when wallet has insufficient USDC balance for a request.\n */\nexport class InsufficientFundsError extends Error {\n readonly code = \"INSUFFICIENT_FUNDS\" as const;\n readonly currentBalanceUSD: string;\n readonly requiredUSD: string;\n readonly walletAddress: string;\n\n constructor(opts: { currentBalanceUSD: string; requiredUSD: string; walletAddress: string }) {\n const msg = [\n `Insufficient balance. Current: ${opts.currentBalanceUSD}, Required: ${opts.requiredUSD}`,\n `Options:`,\n ` 1. Fund wallet: ${opts.walletAddress}`,\n ` 2. Use free model: /model free`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"InsufficientFundsError\";\n this.currentBalanceUSD = opts.currentBalanceUSD;\n this.requiredUSD = opts.requiredUSD;\n this.walletAddress = opts.walletAddress;\n }\n}\n\n/**\n * Thrown when wallet has no USDC balance (or effectively zero).\n */\nexport class EmptyWalletError extends Error {\n readonly code = \"EMPTY_WALLET\" as const;\n readonly walletAddress: string;\n\n constructor(walletAddress: string) {\n const msg = [\n `No USDC balance.`,\n `Options:`,\n ` 1. Fund wallet: ${walletAddress}`,\n ` 2. Use free model: /model free`,\n ` 3. Uninstall: bash ~/.openclaw/extensions/clawrouter/scripts/uninstall.sh`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"EmptyWalletError\";\n this.walletAddress = walletAddress;\n }\n}\n\n/**\n * Type guard to check if an error is InsufficientFundsError.\n */\nexport function isInsufficientFundsError(error: unknown): error is InsufficientFundsError {\n return error instanceof Error && (error as InsufficientFundsError).code === \"INSUFFICIENT_FUNDS\";\n}\n\n/**\n * Type guard to check if an error is EmptyWalletError.\n */\nexport function isEmptyWalletError(error: unknown): error is EmptyWalletError {\n return error instanceof Error && (error as EmptyWalletError).code === \"EMPTY_WALLET\";\n}\n\n/**\n * Type guard to check if an error is a balance-related error.\n */\nexport function isBalanceError(error: unknown): error is InsufficientFundsError | EmptyWalletError {\n return isInsufficientFundsError(error) || isEmptyWalletError(error);\n}\n\n/**\n * Thrown when RPC call fails (network error, node down, etc).\n * Distinguishes infrastructure failures from actual empty wallets.\n */\nexport class RpcError extends Error {\n readonly code = \"RPC_ERROR\" as const;\n readonly originalError: unknown;\n\n constructor(message: string, originalError?: unknown) {\n super(`RPC error: ${message}. Check network connectivity.`);\n this.name = \"RpcError\";\n this.originalError = originalError;\n }\n}\n\n/**\n * Type guard to check if an error is RpcError.\n */\nexport function isRpcError(error: unknown): error is RpcError {\n return error instanceof Error && (error as RpcError).code === \"RPC_ERROR\";\n}\n","/**\n * Balance Monitor for ClawRouter\n *\n * Monitors USDC balance on Base network with intelligent caching.\n * Provides pre-request balance checks to prevent failed payments.\n *\n * Caching Strategy:\n * - TTL: 30 seconds (balance is cached to avoid excessive RPC calls)\n * - Optimistic deduction: after successful payment, subtract estimated cost from cache\n * - Invalidation: on payment failure, immediately refresh from RPC\n */\n\nimport { createPublicClient, http, erc20Abi } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { RpcError } from \"./errors.js\";\n\n/** USDC contract address on Base mainnet */\nconst USDC_BASE = \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\" as const;\n\n/** Cache TTL in milliseconds (30 seconds) */\nconst CACHE_TTL_MS = 30_000;\n\n/** Balance thresholds in USDC smallest unit (6 decimals) */\nexport const BALANCE_THRESHOLDS = {\n /** Low balance warning threshold: $1.00 */\n LOW_BALANCE_MICROS: 1_000_000n,\n /** Effectively zero threshold: $0.0001 (covers dust/rounding) */\n ZERO_THRESHOLD: 100n,\n} as const;\n\n/** Balance information returned by checkBalance() */\nexport type BalanceInfo = {\n /** Raw balance in USDC smallest unit (6 decimals) */\n balance: bigint;\n /** Formatted balance as \"$X.XX\" */\n balanceUSD: string;\n /** True if balance < $1.00 */\n isLow: boolean;\n /** True if balance < $0.0001 (effectively zero) */\n isEmpty: boolean;\n /** Wallet address for funding instructions */\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SufficiencyResult = {\n /** True if balance >= estimated cost */\n sufficient: boolean;\n /** Current balance info */\n info: BalanceInfo;\n /** If insufficient, the shortfall as \"$X.XX\" */\n shortfall?: string;\n};\n\n/**\n * Monitors USDC balance on Base network.\n *\n * Usage:\n * const monitor = new BalanceMonitor(\"0x...\");\n * const info = await monitor.checkBalance();\n * if (info.isLow) console.warn(\"Low balance!\");\n */\nexport class BalanceMonitor {\n private readonly client;\n private readonly walletAddress: `0x${string}`;\n\n /** Cached balance (null = not yet fetched) */\n private cachedBalance: bigint | null = null;\n /** Timestamp when cache was last updated */\n private cachedAt = 0;\n\n constructor(walletAddress: string) {\n this.walletAddress = walletAddress as `0x${string}`;\n this.client = createPublicClient({\n chain: base,\n transport: http(undefined, {\n timeout: 10_000, // 10 second timeout to prevent hanging on slow RPC\n }),\n });\n }\n\n /**\n * Check current USDC balance.\n * Uses cache if valid, otherwise fetches from RPC.\n */\n async checkBalance(): Promise {\n const now = Date.now();\n\n // Use cache only when balance is positive and still fresh.\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n if (\n this.cachedBalance !== null &&\n this.cachedBalance > 0n &&\n now - this.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(this.cachedBalance);\n }\n\n // Fetch from RPC\n const balance = await this.fetchBalance();\n if (balance > 0n) {\n this.cachedBalance = balance;\n this.cachedAt = now;\n }\n\n return this.buildInfo(balance);\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n *\n * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals)\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSDC(shortfall),\n };\n }\n\n /**\n * Optimistically deduct estimated cost from cached balance.\n * Call this after a successful payment to keep cache accurate.\n *\n * @param amountMicros - Amount to deduct in USDC smallest unit\n */\n deductEstimated(amountMicros: bigint): void {\n if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {\n this.cachedBalance -= amountMicros;\n }\n }\n\n /**\n * Invalidate cache, forcing next checkBalance() to fetch from RPC.\n * Call this after a payment failure to get accurate balance.\n */\n invalidate(): void {\n this.cachedBalance = null;\n this.cachedAt = 0;\n }\n\n /**\n * Force refresh balance from RPC (ignores cache).\n */\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n /**\n * Format USDC amount (in micros) as \"$X.XX\".\n */\n formatUSDC(amountMicros: bigint): string {\n // USDC has 6 decimals\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n /**\n * Get the wallet address being monitored.\n */\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n /** Fetch balance from RPC */\n private async fetchBalance(): Promise {\n try {\n const balance = await this.client.readContract({\n address: USDC_BASE,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [this.walletAddress],\n });\n return balance;\n } catch (error) {\n // Throw typed error instead of silently returning 0\n // This allows callers to distinguish \"node down\" from \"wallet empty\"\n throw new RpcError(error instanceof Error ? error.message : \"Unknown error\", error);\n }\n }\n\n /** Build BalanceInfo from raw balance */\n private buildInfo(balance: bigint): BalanceInfo {\n return {\n balance,\n balanceUSD: this.formatUSDC(balance),\n isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,\n isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD,\n walletAddress: this.walletAddress,\n };\n }\n}\n","/**\n * BlockRun Auth Methods for OpenClaw\n *\n * Provides wallet-based authentication for the BlockRun provider.\n * Operators configure their wallet private key, which is used to\n * sign x402 micropayments for LLM inference.\n *\n * Three methods:\n * 1. Auto-generate — create a new wallet on first run, save to ~/.openclaw/blockrun/wallet.key\n * 2. Environment variable — read from BLOCKRUN_WALLET_KEY\n * 3. Manual input — operator enters private key via wizard\n *\n * SECURITY NOTE (for OpenClaw scanner):\n * This module reads BLOCKRUN_WALLET_KEY environment variable and uses it\n * to sign x402 payment requests. This is INTENTIONAL and REQUIRED behavior:\n * - The wallet key signs USDC payments on Base L2 for each LLM API call\n * - Without the key, ClawRouter cannot authorize payments to BlockRun\n * - The key is NEVER transmitted over the network, only used locally for signing\n * - This is standard x402 payment flow, not credential harvesting\n *\n * @see https://x402.org - x402 payment protocol specification\n * @see https://blockrun.ai/docs - BlockRun API documentation\n * @openclaw-security env-access=BLOCKRUN_WALLET_KEY purpose=x402-payment-signing\n */\n\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport type { ProviderAuthMethod, ProviderAuthContext, ProviderAuthResult } from \"./types.js\";\nimport {\n generateWalletMnemonic,\n isValidMnemonic,\n deriveSolanaKeyBytes,\n deriveAllKeys,\n getSolanaAddress,\n} from \"./wallet.js\";\n\nconst WALLET_DIR = join(homedir(), \".openclaw\", \"blockrun\");\nconst WALLET_FILE = join(WALLET_DIR, \"wallet.key\");\nconst MNEMONIC_FILE = join(WALLET_DIR, \"mnemonic\");\nconst CHAIN_FILE = join(WALLET_DIR, \"payment-chain\");\n\n// Export for use by wallet command and index.ts\nexport { WALLET_FILE, MNEMONIC_FILE, CHAIN_FILE };\n\n/**\n * Try to load a previously auto-generated wallet key from disk.\n */\nasync function loadSavedWallet(): Promise {\n try {\n const key = (await readTextFile(WALLET_FILE)).trim();\n if (key.startsWith(\"0x\") && key.length === 66) {\n console.log(`[ClawRouter] ✓ Loaded existing wallet from ${WALLET_FILE}`);\n return key;\n }\n // File exists but content is wrong — do NOT silently fall through to generate a new wallet.\n // This would silently replace a funded wallet with an empty one.\n console.error(`[ClawRouter] ✗ CRITICAL: Wallet file exists but has invalid format!`);\n console.error(`[ClawRouter] File: ${WALLET_FILE}`);\n console.error(`[ClawRouter] Expected: 0x followed by 64 hex characters (66 chars total)`);\n console.error(\n `[ClawRouter] To fix: restore your backup key or set BLOCKRUN_WALLET_KEY env var`,\n );\n throw new Error(\n `Wallet file at ${WALLET_FILE} is corrupted or has wrong format. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Restore your backup key or set BLOCKRUN_WALLET_KEY environment variable.`,\n );\n } catch (err) {\n // Re-throw corruption errors (not ENOENT)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n // If it's our own thrown error, re-throw as-is\n if (err instanceof Error && err.message.includes(\"Refusing to auto-generate\")) {\n throw err;\n }\n console.error(\n `[ClawRouter] ✗ Failed to read wallet file: ${err instanceof Error ? err.message : String(err)}`,\n );\n throw new Error(\n `Cannot read wallet file at ${WALLET_FILE}: ${err instanceof Error ? err.message : String(err)}. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Fix file permissions or set BLOCKRUN_WALLET_KEY environment variable.`,\n { cause: err },\n );\n }\n }\n return undefined;\n}\n\n/**\n * Load mnemonic from disk if it exists.\n * Warns on corruption but never throws — callers handle missing mnemonic gracefully.\n */\nasync function loadMnemonic(): Promise {\n try {\n const mnemonic = (await readTextFile(MNEMONIC_FILE)).trim();\n if (mnemonic && isValidMnemonic(mnemonic)) {\n return mnemonic;\n }\n // File exists but content is invalid — warn but continue.\n console.warn(`[ClawRouter] ⚠ Mnemonic file exists but has invalid format — ignoring`);\n return undefined;\n } catch (err) {\n // Only swallow ENOENT (file not found)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n console.warn(`[ClawRouter] ⚠ Cannot read mnemonic file — ignoring`);\n }\n }\n return undefined;\n}\n\n/**\n * Save mnemonic to disk.\n */\nasync function saveMnemonic(mnemonic: string): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Generate a new wallet with BIP-39 mnemonic, save to disk.\n * New users get both EVM and Solana keys derived from the same mnemonic.\n * CRITICAL: Verifies the file was actually written after generation.\n */\nasync function generateAndSaveWallet(): Promise<{\n key: string;\n address: string;\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: if a mnemonic file already exists, a Solana wallet was derived from it.\n // Generating a new wallet would overwrite the mnemonic and lose Solana funds.\n const existingMnemonic = await loadMnemonic();\n if (existingMnemonic) {\n throw new Error(\n `Mnemonic file exists at ${MNEMONIC_FILE} but wallet.key is missing.\\n` +\n `Refusing to generate a new wallet to protect existing funds.\\n\\n` +\n `Restore your EVM private key using one of:\\n` +\n ` Windows: set BLOCKRUN_WALLET_KEY=0x\\n` +\n ` Mac/Linux: export BLOCKRUN_WALLET_KEY=0x\\n\\n` +\n `Then run: npx @blockrun/clawrouter`,\n );\n }\n\n const mnemonic = generateWalletMnemonic();\n const derived = deriveAllKeys(mnemonic);\n\n // Create directory\n await mkdir(WALLET_DIR, { recursive: true });\n\n // Write wallet key file (EVM private key)\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n // Write mnemonic file\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n\n // CRITICAL: Verify the file was actually written\n try {\n const verification = (await readTextFile(WALLET_FILE)).trim();\n if (verification !== derived.evmPrivateKey) {\n throw new Error(\"Wallet file verification failed - content mismatch\");\n }\n console.log(`[ClawRouter] Wallet saved and verified at ${WALLET_FILE}`);\n } catch (err) {\n throw new Error(\n `Failed to verify wallet file after creation: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n // Derive Solana address for display\n let solanaAddress: string | undefined;\n try {\n solanaAddress = await getSolanaAddress(derived.solanaPrivateKeyBytes);\n } catch {\n // Non-fatal — Solana address display is best-effort\n }\n\n // Print prominent backup reminder after generating a new wallet\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] NEW WALLET GENERATED — BACK UP YOUR KEY NOW`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter] Key file : ${WALLET_FILE}`);\n console.log(`[ClawRouter] Mnemonic : ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Both EVM (Base) and Solana wallets are ready.`);\n console.log(`[ClawRouter] To back up, run in OpenClaw:`);\n console.log(`[ClawRouter] /wallet export`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] To restore on another machine:`);\n console.log(`[ClawRouter] export BLOCKRUN_WALLET_KEY=`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n return {\n key: derived.evmPrivateKey,\n address: derived.evmAddress,\n mnemonic,\n solanaPrivateKeyBytes: derived.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Resolve wallet key: load saved → env var → auto-generate.\n * Also loads mnemonic if available for Solana key derivation.\n * Called by index.ts before the auth wizard runs.\n */\nexport type WalletResolution = {\n key: string;\n address: string;\n source: \"saved\" | \"env\" | \"generated\";\n mnemonic?: string;\n solanaPrivateKeyBytes?: Uint8Array;\n};\n\nexport async function resolveOrGenerateWalletKey(): Promise {\n // 1. Previously saved wallet\n const saved = await loadSavedWallet();\n if (saved) {\n const account = privateKeyToAccount(saved as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: saved,\n address: account.address,\n source: \"saved\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: saved, address: account.address, source: \"saved\" };\n }\n\n // 2. Environment variable\n const envKey = process[\"env\"].BLOCKRUN_WALLET_KEY;\n if (typeof envKey === \"string\" && envKey.startsWith(\"0x\") && envKey.length === 66) {\n const account = privateKeyToAccount(envKey as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: envKey,\n address: account.address,\n source: \"env\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: envKey, address: account.address, source: \"env\" };\n }\n\n // 3. Auto-generate with BIP-39 mnemonic (new users get both chains)\n const result = await generateAndSaveWallet();\n return {\n key: result.key,\n address: result.address,\n source: \"generated\",\n mnemonic: result.mnemonic,\n solanaPrivateKeyBytes: result.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Recover wallet.key from existing mnemonic.\n *\n * ONLY works when the mnemonic was originally generated by ClawRouter\n * (i.e., both mnemonic and EVM key were derived from the same seed).\n * If the EVM key was set independently (manually or via env), the derived\n * key will be different — do NOT use this in that case.\n */\nexport async function recoverWalletFromMnemonic(): Promise {\n const mnemonic = await loadMnemonic();\n if (!mnemonic) {\n console.error(`[ClawRouter] No mnemonic found at ${MNEMONIC_FILE}`);\n console.error(`[ClawRouter] Cannot recover — no mnemonic to derive from.`);\n process.exit(1);\n }\n\n // Safety: if wallet.key already exists, refuse to overwrite\n const existing = await loadSavedWallet().catch(() => undefined);\n if (existing) {\n console.error(`[ClawRouter] wallet.key already exists at ${WALLET_FILE}`);\n console.error(`[ClawRouter] Recovery not needed.`);\n process.exit(1);\n }\n\n const derived = deriveAllKeys(mnemonic);\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const solanaAddress = await getSolanaAddress(solanaKeyBytes).catch(() => undefined);\n\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ⚠ WALLET RECOVERY FROM MNEMONIC`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] This only works if your mnemonic was originally`);\n console.log(`[ClawRouter] generated by ClawRouter (not set manually).`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Derived EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Derived Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] If the Solana address above matches your funded`);\n console.log(`[ClawRouter] wallet, recovery is safe to proceed.`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n console.log(`[ClawRouter] ✓ wallet.key restored at ${WALLET_FILE}`);\n console.log(`[ClawRouter] Run: npx @blockrun/clawrouter`);\n console.log(`[ClawRouter]`);\n}\n\n/**\n * Set up Solana wallet for existing EVM-only users.\n * Generates a new mnemonic for Solana key derivation.\n * NEVER touches the existing wallet.key file.\n */\nexport async function setupSolana(): Promise<{\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: mnemonic must not already exist\n const existing = await loadMnemonic();\n if (existing) {\n throw new Error(\"Solana wallet already set up. Mnemonic file exists at \" + MNEMONIC_FILE);\n }\n\n // Safety: wallet.key must exist (can't set up Solana without EVM wallet)\n const savedKey = await loadSavedWallet();\n if (!savedKey) {\n throw new Error(\n \"No EVM wallet found. Run ClawRouter first to generate a wallet before setting up Solana.\",\n );\n }\n\n // Generate new mnemonic for Solana derivation\n const mnemonic = generateWalletMnemonic();\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n\n // Save mnemonic (wallet.key untouched)\n await saveMnemonic(mnemonic);\n\n console.log(`[ClawRouter] Solana wallet set up successfully.`);\n console.log(`[ClawRouter] Mnemonic saved to ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter] Existing EVM wallet unchanged.`);\n\n return { mnemonic, solanaPrivateKeyBytes: solanaKeyBytes };\n}\n\n/**\n * Persist the user's payment chain selection to disk.\n */\nexport async function savePaymentChain(chain: \"base\" | \"solana\"): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(CHAIN_FILE, chain + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Load the persisted payment chain selection from disk.\n * Returns \"base\" if no file exists or the file is invalid.\n */\nexport async function loadPaymentChain(): Promise<\"base\" | \"solana\"> {\n try {\n const content = (await readTextFile(CHAIN_FILE)).trim();\n if (content === \"solana\") return \"solana\";\n return \"base\";\n } catch {\n return \"base\";\n }\n}\n\n/**\n * Resolve payment chain: env var first → persisted file second → default \"base\".\n */\nexport async function resolvePaymentChain(): Promise<\"base\" | \"solana\"> {\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"solana\") return \"solana\";\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"base\") return \"base\";\n return loadPaymentChain();\n}\n\n/**\n * Auth method: operator enters their wallet private key directly.\n */\nexport const walletKeyAuth: ProviderAuthMethod = {\n id: \"wallet-key\",\n label: \"Wallet Private Key\",\n hint: \"Enter your EVM wallet private key (0x...) for x402 payments to BlockRun\",\n kind: \"api_key\",\n run: async (ctx: ProviderAuthContext): Promise => {\n const key = await ctx.prompter.text({\n message: \"Enter your wallet private key (0x...)\",\n validate: (value: string) => {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"0x\")) return \"Key must start with 0x\";\n if (trimmed.length !== 66) return \"Key must be 66 characters (0x + 64 hex)\";\n if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) return \"Key must be valid hex\";\n return undefined;\n },\n });\n\n if (!key || typeof key !== \"string\") {\n throw new Error(\"Wallet key is required\");\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\n \"Wallet key stored securely in OpenClaw credentials.\",\n \"Your wallet signs x402 USDC payments on Base for each LLM call.\",\n \"Fund your wallet with USDC on Base to start using BlockRun models.\",\n ],\n };\n },\n};\n\n/**\n * Auth method: read wallet key from BLOCKRUN_WALLET_KEY environment variable.\n */\nexport const envKeyAuth: ProviderAuthMethod = {\n id: \"env-key\",\n label: \"Environment Variable\",\n hint: \"Use BLOCKRUN_WALLET_KEY environment variable\",\n kind: \"api_key\",\n run: async (): Promise => {\n const key = process[\"env\"].BLOCKRUN_WALLET_KEY;\n\n if (!key) {\n throw new Error(\n \"BLOCKRUN_WALLET_KEY environment variable is not set. \" +\n \"Set it to your EVM wallet private key (0x...).\",\n );\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\"Using wallet key from BLOCKRUN_WALLET_KEY environment variable.\"],\n };\n },\n};\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(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// 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 return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\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(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\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, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\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 = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, 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++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\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\nexport function validateObject(\n object: Record,\n fields: Record = {},\n optFields: Record = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _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 */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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\nfunction assertIsSquare(Fp: IField, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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 assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): (Fp: IField, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return (Fp: IField, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // 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): boolean =>\n (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 isLE: boolean;\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 isValidNot0: (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 invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): 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): IField {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security 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're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 * 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.Point.Fn.ORDER)\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 abytes(key);\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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons

> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns Fp type from Point (P_F

== P.F) */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns Fp type from PointCons (PC_F == PC.P.F) */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P == PC.P) */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper = (i: T[]) => T[];\n\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport function normalizeZ

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\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\n/** Internal wNAF opts for specific W and scalarBits */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = 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 point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\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 * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\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 const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\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 acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, 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 createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 than 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 secret keys / bigints)\n */\nexport function pippenger

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\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 const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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 P;\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

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\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 const fieldN = c.Fn;\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 = bitMask(windowSize);\n const tables = points.map((p: P) => {\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[]): P => {\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\nexport type ValidCurveParams = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: IField, isLE?: boolean): IField {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField;\n }\n}\nexport type FpFn = { Fp: IField; Fn: IField };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: Partial> = {},\n FpFnLE?: boolean\n): FpFn & { CURVE: ValidCurveParams } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abool,\n abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n memoized,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * https://paulmillr.com/posts/deterministic-signatures/\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates sigs with increased security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): Required {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n CURVE(): WeierstrassOpts;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\nexport type WeierstrassExtraOpts = Partial<{\n Fp: IField;\n Fn: IField;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n fromBytes: (bytes: Uint8Array) => AffinePoint;\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: (key: Uint8Array, message: Uint8Array) => Uint8Array;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed?: boolean\n ) => Uint8Array;\n Point: WeierstrassPointCons;\n utils: {\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Uint8Array, secretKey: Uint8Array, opts?: ECDSASignOpts) => Uint8Array;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(data);\n },\n },\n toSig(bytes: Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\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\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\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 { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: 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 x = Fp.mul(X, iz);\n const y = 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, y };\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 (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) 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 if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) 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 function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\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 WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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 // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\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 *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\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) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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(): boolean {\n return this.equals(Point.ZERO);\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 } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n hasHighS(): boolean;\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n}\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASignatureFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\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, 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, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, 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, 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, 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: IField, Fn: IField) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: Uint8Array) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey: Uint8Array, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(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: Uint8Array): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item)) return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey) return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed = true\n ): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor(): void {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: Uint8Array,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\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 toBytes(format: ECDSASignatureFormat = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\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 ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\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 *\n * Warning: we cannot assume here that message 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 */\n function prepSig(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\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 function k2sig(kBytes: Uint8Array): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\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 = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts = {}): Uint8Array {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n }) satisfies Signer;\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\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 = secp256k1_CURVE.p;\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(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\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\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(asciiToBytes(tag));\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.toBytes(true).slice(1);\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: Uint8Array) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { 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 const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\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 Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Uint8Array): Uint8Array {\n return schnorrGetExtPubKey(secretKey).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: Uint8Array,\n secretKey: Uint8Array,\n auxRand: Uint8Array = randomBytes(32)\n): Uint8Array {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(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 // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\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(Fn.toBytes(Fn.create(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: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\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 (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!Fn.isValidNot0(s)) return false;\n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\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 }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\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 ))();\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl } from './utils.ts';\n\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\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 }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1: CHash = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\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 this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5: CHash = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * const hdkey1 = HDKey.fromMasterSeed(seed);\n * const hdkey2 = HDKey.fromExtendedKey(base58key);\n * const hdkey3 = HDKey.fromJSON({ xpriv: string });\n *\n * // props\n * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];\n * console.log(hdkey2.privateKey, hdkey2.publicKey);\n * console.log(hdkey3.derive(\"m/0/2147483647'/1\"));\n * const sig = hdkey3.sign(hash);\n * hdkey3.verify(hash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.Point;\nconst { Fn } = Point;\nconst base58check = createBase58check(sha256);\n\nconst MASTER_SECRET = Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n\n/** Network-specific versioning. */\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened offset from Bitcoin, default */\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number): Uint8Array => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array;\n}\n\n/**\n * HDKey from BIP32\n * @example\n```js\nconst hdkey1 = HDKey.fromMasterSeed(seed);\nconst hdkey2 = HDKey.fromExtendedKey(base58key);\nconst hdkey3 = HDKey.fromJSON({ xpriv: string });\n```\n */\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this._privateKey || null;\n }\n get publicKey(): Uint8Array | null {\n return this._publicKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n\n static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n\n static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n readonly versions: Versions;\n readonly depth: number = 0;\n readonly index: number = 0;\n readonly chainCode: Uint8Array | null = null;\n readonly parentFingerprint: number = 0;\n private _privateKey?: Uint8Array;\n private _publicKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key');\n this._privateKey = opt.privateKey;\n this._publicKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n\n derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n deriveChild(index: number): HDKey {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = I.slice(0, 32);\n const chainCode = I.slice(32);\n if (!secp.utils.isValidSecretKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n const ctweak = Fn.fromBytes(childTweak);\n try {\n // Private parent key -> private child key\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n } else {\n const added = Point.fromBytes(this._publicKey).add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n sign(hash: Uint8Array): Uint8Array {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n\n verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n\n wipePrivateData(): this {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n","/**\n * Wallet Key Derivation\n *\n * BIP-39 mnemonic generation + BIP-44 HD key derivation for EVM and Solana.\n * Absorbed from @blockrun/clawwallet. No file I/O here - auth.ts handles persistence.\n *\n * Solana uses SLIP-10 Ed25519 derivation (Phantom/Solflare/Backpack compatible).\n * EVM uses standard BIP-32 secp256k1 derivation.\n */\n\nimport { HDKey } from \"@scure/bip32\";\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from \"@scure/bip39\";\nimport { wordlist as english } from \"@scure/bip39/wordlists/english\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha512 } from \"@noble/hashes/sha512\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst ETH_DERIVATION_PATH = \"m/44'/60'/0'/0/0\";\nconst SOLANA_HARDENED_INDICES = [44 + 0x80000000, 501 + 0x80000000, 0 + 0x80000000, 0 + 0x80000000]; // m/44'/501'/0'/0'\n\nexport interface DerivedKeys {\n mnemonic: string;\n evmPrivateKey: `0x${string}`;\n evmAddress: string;\n solanaPrivateKeyBytes: Uint8Array; // 32 bytes\n}\n\n/**\n * Generate a 24-word BIP-39 mnemonic.\n */\nexport function generateWalletMnemonic(): string {\n return generateMnemonic(english, 256);\n}\n\n/**\n * Validate a BIP-39 mnemonic.\n */\nexport function isValidMnemonic(mnemonic: string): boolean {\n return validateMnemonic(mnemonic, english);\n}\n\n/**\n * Derive EVM private key and address from a BIP-39 mnemonic.\n * Path: m/44'/60'/0'/0/0 (standard Ethereum derivation)\n */\nexport function deriveEvmKey(mnemonic: string): { privateKey: `0x${string}`; address: string } {\n const seed = mnemonicToSeedSync(mnemonic);\n const hdKey = HDKey.fromMasterSeed(seed);\n const derived = hdKey.derive(ETH_DERIVATION_PATH);\n if (!derived.privateKey) throw new Error(\"Failed to derive EVM private key\");\n const hex = `0x${Buffer.from(derived.privateKey).toString(\"hex\")}` as `0x${string}`;\n const account = privateKeyToAccount(hex);\n return { privateKey: hex, address: account.address };\n}\n\n/**\n * Derive 32-byte Solana private key using SLIP-10 Ed25519 derivation.\n * Path: m/44'/501'/0'/0' (Phantom / Solflare / Backpack compatible)\n *\n * Algorithm (SLIP-0010 for Ed25519):\n * 1. Master: HMAC-SHA512(key=\"ed25519 seed\", data=bip39_seed) → IL=key, IR=chainCode\n * 2. For each hardened child index:\n * HMAC-SHA512(key=chainCode, data=0x00 || key || ser32(index)) → split again\n * 3. Final IL (32 bytes) = Ed25519 private key seed\n */\nexport function deriveSolanaKeyBytes(mnemonic: string): Uint8Array {\n const seed = mnemonicToSeedSync(mnemonic);\n\n // Master key from SLIP-10\n let I = hmac(sha512, \"ed25519 seed\", seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n // Derive each hardened child: m/44'/501'/0'/0'\n for (const index of SOLANA_HARDENED_INDICES) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n // ser32 big-endian\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n return new Uint8Array(key);\n}\n\n/**\n * Derive both EVM and Solana keys from a single mnemonic.\n */\nexport function deriveAllKeys(mnemonic: string): DerivedKeys {\n const { privateKey: evmPrivateKey, address: evmAddress } = deriveEvmKey(mnemonic);\n const solanaPrivateKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return { mnemonic, evmPrivateKey, evmAddress, solanaPrivateKeyBytes };\n}\n\n/**\n * Get the Solana address from 32-byte private key bytes.\n * Uses @solana/kit's createKeyPairSignerFromPrivateKeyBytes (dynamic import).\n */\nexport async function getSolanaAddress(privateKeyBytes: Uint8Array): Promise {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(privateKeyBytes);\n return signer.address;\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA384 as SHA384n,\n sha384 as sha384n,\n sha512_224 as sha512_224n,\n SHA512_224 as SHA512_224n,\n sha512_256 as sha512_256n,\n SHA512_256 as SHA512_256n,\n SHA512 as SHA512n,\n sha512 as sha512n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512: typeof SHA512n = SHA512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512: typeof sha512n = sha512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA384: typeof SHA384n = SHA384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha384: typeof sha384n = sha384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_224: typeof SHA512_224n = SHA512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_224: typeof sha512_224n = sha512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_256: typeof SHA512_256n = SHA512_256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_256: typeof sha512_256n = sha512_256n;\n","/**\n * LLM-Safe Context Compression Types\n *\n * Types for the 7-layer compression system that reduces token usage\n * while preserving semantic meaning for LLM queries.\n */\n\n// Content part for multimodal messages (images, etc.)\nexport interface ContentPart {\n type: \"text\" | \"image_url\";\n text?: string;\n image_url?: {\n url: string;\n detail?: \"low\" | \"high\" | \"auto\";\n };\n}\n\n// Normalized message structure (matches OpenAI format)\n// Note: content can be an array for multimodal messages (images, etc.)\nexport interface NormalizedMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | ContentPart[] | null;\n tool_call_id?: string;\n tool_calls?: ToolCall[];\n name?: string;\n}\n\nexport interface ToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\n// Compression configuration\nexport interface CompressionConfig {\n enabled: boolean;\n preserveRaw: boolean; // Keep original for logging\n\n // Per-layer toggles\n layers: {\n deduplication: boolean;\n whitespace: boolean;\n dictionary: boolean;\n paths: boolean;\n jsonCompact: boolean;\n observation: boolean; // L6: Compress tool results (BIG WIN)\n dynamicCodebook: boolean; // L7: Build codebook from content\n };\n\n // Dictionary settings\n dictionary: {\n maxEntries: number;\n minPhraseLength: number;\n includeCodebookHeader: boolean; // Include codebook in system message\n };\n}\n\n// Compression statistics\nexport interface CompressionStats {\n duplicatesRemoved: number;\n whitespaceSavedChars: number;\n dictionarySubstitutions: number;\n pathsShortened: number;\n jsonCompactedChars: number;\n observationsCompressed: number; // L6: Tool results compressed\n observationCharsSaved: number; // L6: Chars saved from observations\n dynamicSubstitutions: number; // L7: Dynamic codebook substitutions\n dynamicCharsSaved: number; // L7: Chars saved from dynamic codebook\n}\n\n// Result from compression\nexport interface CompressionResult {\n messages: NormalizedMessage[];\n originalMessages: NormalizedMessage[]; // For logging\n\n // Token estimates\n originalChars: number;\n compressedChars: number;\n compressionRatio: number; // 0.85 = 15% reduction\n\n // Per-layer stats\n stats: CompressionStats;\n\n // Codebook used (for decompression in logs)\n codebook: Record;\n pathMap: Record;\n dynamicCodes: Record; // L7: Dynamic codebook\n}\n\n// Log data extension for compression metrics\nexport interface CompressionLogData {\n enabled: boolean;\n ratio: number;\n original_chars: number;\n compressed_chars: number;\n stats: {\n duplicates_removed: number;\n whitespace_saved: number;\n dictionary_subs: number;\n paths_shortened: number;\n json_compacted: number;\n };\n}\n\n// Default configuration - CONSERVATIVE settings for model compatibility\n// Only enable layers that don't require the model to decode anything\nexport const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {\n enabled: true,\n preserveRaw: true,\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // DISABLED: requires model to understand codebook\n paths: false, // DISABLED: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // DISABLED: may lose important context\n dynamicCodebook: false, // DISABLED: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false, // No codebook header needed\n },\n};\n","/**\n * Layer 1: Message Deduplication\n *\n * Removes exact duplicate messages from conversation history.\n * Common in heartbeat patterns and repeated tool calls.\n *\n * Safe for LLM: Identical messages add no new information.\n * Expected savings: 2-5%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport crypto from \"crypto\";\n\nexport interface DeduplicationResult {\n messages: NormalizedMessage[];\n duplicatesRemoved: number;\n originalCount: number;\n}\n\n/**\n * Generate a hash for a message based on its semantic content.\n * Uses role + content + tool_call_id to identify duplicates.\n */\nfunction hashMessage(message: NormalizedMessage): string {\n // Handle content - stringify arrays (multimodal), use string directly, or empty string\n let contentStr = \"\";\n if (typeof message.content === \"string\") {\n contentStr = message.content;\n } else if (Array.isArray(message.content)) {\n contentStr = JSON.stringify(message.content);\n }\n\n const parts = [message.role, contentStr, message.tool_call_id || \"\", message.name || \"\"];\n\n // Include tool_calls if present\n if (message.tool_calls) {\n parts.push(\n JSON.stringify(\n message.tool_calls.map((tc) => ({\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n ),\n );\n }\n\n const content = parts.join(\"|\");\n return crypto.createHash(\"md5\").update(content).digest(\"hex\");\n}\n\n/**\n * Remove exact duplicate messages from the conversation.\n *\n * Strategy:\n * - Keep first occurrence of each unique message\n * - Preserve order for semantic coherence\n * - Never dedupe system messages (they set context)\n * - Allow duplicate user messages (user might repeat intentionally)\n * - CRITICAL: Never dedupe assistant messages with tool_calls that are\n * referenced by subsequent tool messages (breaks Anthropic tool_use/tool_result pairing)\n */\nexport function deduplicateMessages(messages: NormalizedMessage[]): DeduplicationResult {\n const seen = new Set();\n const result: NormalizedMessage[] = [];\n let duplicatesRemoved = 0;\n\n // First pass: collect all tool_call_ids that are referenced by tool messages\n // These tool_calls MUST be preserved to maintain tool_use/tool_result pairing\n const referencedToolCallIds = new Set();\n for (const message of messages) {\n if (message.role === \"tool\" && message.tool_call_id) {\n referencedToolCallIds.add(message.tool_call_id);\n }\n }\n\n for (const message of messages) {\n // Always keep system messages (they set important context)\n if (message.role === \"system\") {\n result.push(message);\n continue;\n }\n\n // Always keep user messages (user might repeat intentionally)\n if (message.role === \"user\") {\n result.push(message);\n continue;\n }\n\n // Always keep tool messages (they are results of tool calls)\n // Removing them would break the tool_use/tool_result pairing\n if (message.role === \"tool\") {\n result.push(message);\n continue;\n }\n\n // For assistant messages with tool_calls, check if any are referenced\n // by subsequent tool messages - if so, we MUST keep this message\n if (message.role === \"assistant\" && message.tool_calls) {\n const hasReferencedToolCall = message.tool_calls.some((tc) =>\n referencedToolCallIds.has(tc.id),\n );\n if (hasReferencedToolCall) {\n // This assistant message has tool_calls that are referenced - keep it\n result.push(message);\n continue;\n }\n }\n\n // For other assistant messages, check for duplicates\n const hash = hashMessage(message);\n\n if (!seen.has(hash)) {\n seen.add(hash);\n result.push(message);\n } else {\n duplicatesRemoved++;\n }\n }\n\n return {\n messages: result,\n duplicatesRemoved,\n originalCount: messages.length,\n };\n}\n","/**\n * Layer 2: Whitespace Normalization\n *\n * Reduces excessive whitespace without changing semantic meaning.\n *\n * Safe for LLM: Tokenizers normalize whitespace anyway.\n * Expected savings: 3-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface WhitespaceResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Normalize whitespace in a string.\n *\n * - Max 2 consecutive newlines\n * - Remove trailing whitespace from lines\n * - Normalize tabs to spaces\n * - Trim start/end\n */\nexport function normalizeWhitespace(content: string): string {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") return content as string;\n\n return (\n content\n // Normalize line endings\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n // Max 2 consecutive newlines (preserve paragraph breaks)\n .replace(/\\n{3,}/g, \"\\n\\n\")\n // Remove trailing whitespace from each line\n .replace(/[ \\t]+$/gm, \"\")\n // Normalize multiple spaces to single (except at line start for indentation)\n .replace(/([^\\n]) {2,}/g, \"$1 \")\n // Reduce excessive indentation (more than 8 spaces → 2 spaces per level)\n .replace(/^[ ]{8,}/gm, (match) => \" \".repeat(Math.ceil(match.length / 4)))\n // Normalize tabs to 2 spaces\n .replace(/\\t/g, \" \")\n // Trim\n .trim()\n );\n}\n\n/**\n * Apply whitespace normalization to all messages.\n */\nexport function normalizeMessagesWhitespace(messages: NormalizedMessage[]): WhitespaceResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const originalLength = message.content.length;\n const normalizedContent = normalizeWhitespace(message.content);\n charsSaved += originalLength - normalizedContent.length;\n\n return {\n ...message,\n content: normalizedContent,\n };\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * Dictionary Codebook\n *\n * Static dictionary of frequently repeated phrases observed in LLM prompts.\n * Built from analysis of BlockRun production logs.\n *\n * Format: Short code ($XX) -> Long phrase\n * The LLM receives a codebook header and decodes in-context.\n */\n\n// Static codebook - common patterns from system prompts\n// Ordered by expected frequency and impact\nexport const STATIC_CODEBOOK: Record = {\n // High-impact: OpenClaw/Agent system prompt patterns (very common)\n $OC01: \"unbrowse_\", // Common prefix in tool names\n $OC02: \"\",\n $OC03: \"\",\n $OC04: \"\",\n $OC05: \"\",\n $OC06: \"\",\n $OC07: \"\",\n $OC08: \"(may need login)\",\n $OC09: \"API skill for OpenClaw\",\n $OC10: \"endpoints\",\n\n // Skill/tool markers\n $SK01: \"\",\n $SK02: \"\",\n $SK03: \"\",\n $SK04: \"\",\n\n // Schema patterns (very common in tool definitions)\n $T01: 'type: \"function\"',\n $T02: '\"type\": \"function\"',\n $T03: '\"type\": \"string\"',\n $T04: '\"type\": \"object\"',\n $T05: '\"type\": \"array\"',\n $T06: '\"type\": \"boolean\"',\n $T07: '\"type\": \"number\"',\n\n // Common descriptions\n $D01: \"description:\",\n $D02: '\"description\":',\n\n // Common instructions\n $I01: \"You are a personal assistant\",\n $I02: \"Tool names are case-sensitive\",\n $I03: \"Call tools exactly as listed\",\n $I04: \"Use when\",\n $I05: \"without asking\",\n\n // Safety phrases\n $S01: \"Do not manipulate or persuade\",\n $S02: \"Prioritize safety and human oversight\",\n $S03: \"unless explicitly requested\",\n\n // JSON patterns\n $J01: '\"required\": [\"',\n $J02: '\"properties\": {',\n $J03: '\"additionalProperties\": false',\n\n // Heartbeat patterns\n $H01: \"HEARTBEAT_OK\",\n $H02: \"Read HEARTBEAT.md if it exists\",\n\n // Role markers\n $R01: '\"role\": \"system\"',\n $R02: '\"role\": \"user\"',\n $R03: '\"role\": \"assistant\"',\n $R04: '\"role\": \"tool\"',\n\n // Common endings/phrases\n $E01: \"would you like to\",\n $E02: \"Let me know if you\",\n $E03: \"internal APIs\",\n $E04: \"session cookies\",\n\n // BlockRun model aliases (common in prompts)\n $M01: \"blockrun/\",\n $M02: \"openai/\",\n $M03: \"anthropic/\",\n $M04: \"google/\",\n $M05: \"xai/\",\n};\n\n/**\n * Get the inverse codebook for decompression.\n */\nexport function getInverseCodebook(): Record {\n const inverse: Record = {};\n for (const [code, phrase] of Object.entries(STATIC_CODEBOOK)) {\n inverse[phrase] = code;\n }\n return inverse;\n}\n\n/**\n * Generate the codebook header for inclusion in system message.\n * LLMs can decode in-context using this header.\n */\nexport function generateCodebookHeader(\n usedCodes: Set,\n pathMap: Record = {},\n): string {\n if (usedCodes.size === 0 && Object.keys(pathMap).length === 0) {\n return \"\";\n }\n\n const parts: string[] = [];\n\n // Add used dictionary codes\n if (usedCodes.size > 0) {\n const codeEntries = Array.from(usedCodes)\n .map((code) => `${code}=${STATIC_CODEBOOK[code]}`)\n .join(\", \");\n parts.push(`[Dict: ${codeEntries}]`);\n }\n\n // Add path map\n if (Object.keys(pathMap).length > 0) {\n const pathEntries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n parts.push(`[Paths: ${pathEntries}]`);\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Decompress a string using the codebook (for logging).\n */\nexport function decompressContent(\n content: string,\n codebook: Record = STATIC_CODEBOOK,\n): string {\n let result = content;\n for (const [code, phrase] of Object.entries(codebook)) {\n result = result.split(code).join(phrase);\n }\n return result;\n}\n","/**\n * Layer 3: Dictionary Encoding\n *\n * Replaces frequently repeated long phrases with short codes.\n * Uses a static codebook of common patterns from production logs.\n *\n * Safe for LLM: Reversible substitution with codebook header.\n * Expected savings: 4-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport { getInverseCodebook } from \"../codebook\";\n\nexport interface DictionaryResult {\n messages: NormalizedMessage[];\n substitutionCount: number;\n usedCodes: Set;\n charsSaved: number;\n}\n\n/**\n * Apply dictionary encoding to a string.\n * Returns the encoded string and stats.\n */\nfunction encodeContent(\n content: string,\n inverseCodebook: Record,\n): { encoded: string; substitutions: number; codes: Set; charsSaved: number } {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") {\n return { encoded: content, substitutions: 0, codes: new Set(), charsSaved: 0 };\n }\n let encoded = content;\n let substitutions = 0;\n let charsSaved = 0;\n const codes = new Set();\n\n // Sort phrases by length (longest first) to avoid partial matches\n const phrases = Object.keys(inverseCodebook).sort((a, b) => b.length - a.length);\n\n for (const phrase of phrases) {\n const code = inverseCodebook[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = encoded.match(regex);\n\n if (matches && matches.length > 0) {\n encoded = encoded.replace(regex, code);\n substitutions += matches.length;\n charsSaved += matches.length * (phrase.length - code.length);\n codes.add(code);\n }\n }\n\n return { encoded, substitutions, codes, charsSaved };\n}\n\n/**\n * Escape special regex characters in a string.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dictionary encoding to all messages.\n */\nexport function encodeMessages(messages: NormalizedMessage[]): DictionaryResult {\n const inverseCodebook = getInverseCodebook();\n let totalSubstitutions = 0;\n let totalCharsSaved = 0;\n const allUsedCodes = new Set();\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const { encoded, substitutions, codes, charsSaved } = encodeContent(\n message.content,\n inverseCodebook,\n );\n\n totalSubstitutions += substitutions;\n totalCharsSaved += charsSaved;\n codes.forEach((code) => allUsedCodes.add(code));\n\n return {\n ...message,\n content: encoded,\n };\n });\n\n return {\n messages: result,\n substitutionCount: totalSubstitutions,\n usedCodes: allUsedCodes,\n charsSaved: totalCharsSaved,\n };\n}\n","/**\n * Layer 4: Path Shortening\n *\n * Detects common filesystem path prefixes and replaces them with short codes.\n * Common in coding assistant contexts with repeated file paths.\n *\n * Safe for LLM: Lossless abbreviation with path map header.\n * Expected savings: 1-3%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface PathShorteningResult {\n messages: NormalizedMessage[];\n pathMap: Record; // $P1 -> /home/user/project/\n charsSaved: number;\n}\n\n// Regex to match filesystem paths\nconst PATH_REGEX = /(?:\\/[\\w.-]+){3,}/g;\n\n/**\n * Extract all paths from messages and find common prefixes.\n */\nfunction extractPaths(messages: NormalizedMessage[]): string[] {\n const paths: string[] = [];\n\n for (const message of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") continue;\n const matches = message.content.match(PATH_REGEX);\n if (matches) {\n paths.push(...matches);\n }\n }\n\n return paths;\n}\n\n/**\n * Group paths by their common prefixes.\n * Returns prefixes that appear at least 3 times.\n */\nfunction findFrequentPrefixes(paths: string[]): string[] {\n const prefixCounts = new Map();\n\n for (const path of paths) {\n const parts = path.split(\"/\").filter(Boolean);\n\n // Try prefixes of different lengths\n for (let i = 2; i < parts.length; i++) {\n const prefix = \"/\" + parts.slice(0, i).join(\"/\") + \"/\";\n prefixCounts.set(prefix, (prefixCounts.get(prefix) || 0) + 1);\n }\n }\n\n // Return prefixes that appear 3+ times, sorted by length (longest first)\n return Array.from(prefixCounts.entries())\n .filter(([, count]) => count >= 3)\n .sort((a, b) => b[0].length - a[0].length)\n .slice(0, 5) // Max 5 path codes\n .map(([prefix]) => prefix);\n}\n\n/**\n * Apply path shortening to all messages.\n */\nexport function shortenPaths(messages: NormalizedMessage[]): PathShorteningResult {\n const allPaths = extractPaths(messages);\n\n if (allPaths.length < 5) {\n // Not enough paths to benefit from shortening\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n const prefixes = findFrequentPrefixes(allPaths);\n\n if (prefixes.length === 0) {\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n // Create path map\n const pathMap: Record = {};\n prefixes.forEach((prefix, i) => {\n pathMap[`$P${i + 1}`] = prefix;\n });\n\n // Replace paths in messages\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n let content = message.content;\n const originalLength = content.length;\n\n // Replace prefixes (longest first to avoid partial replacements)\n for (const [code, prefix] of Object.entries(pathMap)) {\n content = content.split(prefix).join(code + \"/\");\n }\n\n charsSaved += originalLength - content.length;\n\n return {\n ...message,\n content,\n };\n });\n\n return {\n messages: result,\n pathMap,\n charsSaved,\n };\n}\n\n/**\n * Generate the path map header for the codebook.\n */\nexport function generatePathMapHeader(pathMap: Record): string {\n if (Object.keys(pathMap).length === 0) return \"\";\n\n const entries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n\n return `[Paths: ${entries}]`;\n}\n","/**\n * Layer 5: JSON Compaction\n *\n * Minifies JSON in tool_call arguments and tool results.\n * Removes pretty-print whitespace from JSON strings.\n *\n * Safe for LLM: JSON semantics unchanged.\n * Expected savings: 2-4%\n */\n\nimport { NormalizedMessage, ToolCall } from \"../types\";\n\nexport interface JsonCompactResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Compact a JSON string by parsing and re-stringifying without formatting.\n */\nfunction compactJson(jsonString: string): string {\n try {\n const parsed = JSON.parse(jsonString);\n return JSON.stringify(parsed);\n } catch {\n // Not valid JSON, return as-is\n return jsonString;\n }\n}\n\n/**\n * Check if a string looks like JSON (starts with { or [).\n */\nfunction looksLikeJson(str: string): boolean {\n const trimmed = str.trim();\n return (\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) ||\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\"))\n );\n}\n\n/**\n * Compact tool_call arguments in a message.\n */\nfunction compactToolCalls(toolCalls: ToolCall[]): ToolCall[] {\n return toolCalls.map((tc) => ({\n ...tc,\n function: {\n ...tc.function,\n arguments: compactJson(tc.function.arguments),\n },\n }));\n}\n\n/**\n * Apply JSON compaction to all messages.\n *\n * Targets:\n * - tool_call arguments (in assistant messages)\n * - tool message content (often JSON)\n */\nexport function compactMessagesJson(messages: NormalizedMessage[]): JsonCompactResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n const newMessage = { ...message };\n\n // Compact tool_calls arguments\n if (message.tool_calls && message.tool_calls.length > 0) {\n const originalLength = JSON.stringify(message.tool_calls).length;\n newMessage.tool_calls = compactToolCalls(message.tool_calls);\n const newLength = JSON.stringify(newMessage.tool_calls).length;\n charsSaved += originalLength - newLength;\n }\n\n // Compact tool message content if it looks like JSON\n // Only process string content (skip arrays for multimodal messages)\n if (\n message.role === \"tool\" &&\n message.content &&\n typeof message.content === \"string\" &&\n looksLikeJson(message.content)\n ) {\n const originalLength = message.content.length;\n const compacted = compactJson(message.content);\n charsSaved += originalLength - compacted.length;\n newMessage.content = compacted;\n }\n\n return newMessage;\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * L6: Observation Compression (AGGRESSIVE)\n *\n * Inspired by claw-compactor's 97% compression on tool results.\n * Tool call results (especially large ones) are summarized to key info only.\n *\n * This is the biggest compression win - tool outputs can be 10KB+ but\n * only ~200 chars of actual useful information.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface ObservationResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n observationsCompressed: number;\n}\n\n// Max length for tool results before compression kicks in\nconst TOOL_RESULT_THRESHOLD = 500;\n\n// Max length to compress tool results down to\nconst COMPRESSED_RESULT_MAX = 300;\n\n/**\n * Extract key information from tool result.\n * Keeps: errors, key values, status, first/last important lines.\n */\nfunction compressToolResult(content: string): string {\n if (!content || content.length <= TOOL_RESULT_THRESHOLD) {\n return content;\n }\n\n const lines = content\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter(Boolean);\n\n // Priority 1: Error messages (always keep)\n const errorLines = lines.filter(\n (l) => /error|exception|failed|denied|refused|timeout|invalid/i.test(l) && l.length < 200,\n );\n\n // Priority 2: Status/result lines\n const statusLines = lines.filter(\n (l) =>\n /success|complete|created|updated|found|result|status|total|count/i.test(l) && l.length < 150,\n );\n\n // Priority 3: Key JSON fields (extract important values)\n const jsonMatches: string[] = [];\n const jsonPattern = /\"(id|name|status|error|message|count|total|url|path)\":\\s*\"?([^\",}\\n]+)\"?/gi;\n let match;\n while ((match = jsonPattern.exec(content)) !== null) {\n jsonMatches.push(`${match[1]}: ${match[2].slice(0, 50)}`);\n }\n\n // Priority 4: First and last meaningful lines\n const firstLine = lines[0]?.slice(0, 100);\n const lastLine = lines.length > 1 ? lines[lines.length - 1]?.slice(0, 100) : \"\";\n\n // Build compressed observation\n const parts: string[] = [];\n\n if (errorLines.length > 0) {\n parts.push(\"[ERR] \" + errorLines.slice(0, 3).join(\" | \"));\n }\n\n if (statusLines.length > 0) {\n parts.push(statusLines.slice(0, 3).join(\" | \"));\n }\n\n if (jsonMatches.length > 0) {\n parts.push(jsonMatches.slice(0, 5).join(\", \"));\n }\n\n if (parts.length === 0) {\n // Fallback: keep first/last lines with truncation marker\n parts.push(firstLine || \"\");\n if (lines.length > 2) {\n parts.push(`[...${lines.length - 2} lines...]`);\n }\n if (lastLine && lastLine !== firstLine) {\n parts.push(lastLine);\n }\n }\n\n let result = parts.join(\"\\n\");\n\n // Final length cap\n if (result.length > COMPRESSED_RESULT_MAX) {\n result = result.slice(0, COMPRESSED_RESULT_MAX - 20) + \"\\n[...truncated]\";\n }\n\n return result;\n}\n\n/**\n * Compress large repeated content blocks.\n * Detects when same large block appears multiple times.\n */\nfunction deduplicateLargeBlocks(messages: NormalizedMessage[]): {\n messages: NormalizedMessage[];\n charsSaved: number;\n} {\n const blockHashes = new Map(); // hash -> first occurrence index\n let charsSaved = 0;\n\n const result = messages.map((msg, idx) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\" || msg.content.length < 500) {\n return msg;\n }\n\n // Hash first 200 chars as block identifier\n const blockKey = msg.content.slice(0, 200);\n\n if (blockHashes.has(blockKey)) {\n const firstIdx = blockHashes.get(blockKey)!;\n const original = msg.content;\n const compressed = `[See message #${firstIdx + 1} - same content]`;\n charsSaved += original.length - compressed.length;\n return { ...msg, content: compressed };\n }\n\n blockHashes.set(blockKey, idx);\n return msg;\n });\n\n return { messages: result, charsSaved };\n}\n\n/**\n * Compress tool results in messages.\n */\nexport function compressObservations(messages: NormalizedMessage[]): ObservationResult {\n let charsSaved = 0;\n let observationsCompressed = 0;\n\n // First pass: compress individual tool results\n let result = messages.map((msg) => {\n // Only compress tool role messages (these are tool call results)\n // Only process string content (skip arrays for multimodal messages)\n if (msg.role !== \"tool\" || !msg.content || typeof msg.content !== \"string\") {\n return msg;\n }\n\n const original = msg.content;\n if (original.length <= TOOL_RESULT_THRESHOLD) {\n return msg;\n }\n\n const compressed = compressToolResult(original);\n const saved = original.length - compressed.length;\n\n if (saved > 50) {\n charsSaved += saved;\n observationsCompressed++;\n return { ...msg, content: compressed };\n }\n\n return msg;\n });\n\n // Second pass: deduplicate large repeated blocks\n const dedupResult = deduplicateLargeBlocks(result);\n result = dedupResult.messages;\n charsSaved += dedupResult.charsSaved;\n\n return {\n messages: result,\n charsSaved,\n observationsCompressed,\n };\n}\n","/**\n * L7: Dynamic Codebook Builder\n *\n * Inspired by claw-compactor's frequency-based codebook.\n * Builds codebook from actual content being compressed,\n * rather than relying on static patterns.\n *\n * Finds phrases that appear 3+ times and replaces with short codes.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface DynamicCodebookResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n dynamicCodes: Record; // code -> phrase\n substitutions: number;\n}\n\n// Config\nconst MIN_PHRASE_LENGTH = 20;\nconst MAX_PHRASE_LENGTH = 200;\nconst MIN_FREQUENCY = 3;\nconst MAX_ENTRIES = 100;\nconst CODE_PREFIX = \"$D\"; // Dynamic codes: $D01, $D02, etc.\n\n/**\n * Find repeated phrases in content.\n */\nfunction findRepeatedPhrases(allContent: string): Map {\n const phrases = new Map();\n\n // Split by sentence-like boundaries\n const segments = allContent.split(/(?<=[.!?\\n])\\s+/);\n\n for (const segment of segments) {\n const trimmed = segment.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n // Also find repeated lines\n const lines = allContent.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n return phrases;\n}\n\n/**\n * Build dynamic codebook from message content.\n */\nfunction buildDynamicCodebook(messages: NormalizedMessage[]): Record {\n // Combine all content\n let allContent = \"\";\n for (const msg of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (msg.content && typeof msg.content === \"string\") {\n allContent += msg.content + \"\\n\";\n }\n }\n\n // Find repeated phrases\n const phrases = findRepeatedPhrases(allContent);\n\n // Filter by frequency and sort by savings potential\n const candidates: Array<{ phrase: string; count: number; savings: number }> = [];\n for (const [phrase, count] of phrases.entries()) {\n if (count >= MIN_FREQUENCY) {\n // Savings = (phrase length - code length) * occurrences\n const codeLength = 4; // e.g., \"$D01\"\n const savings = (phrase.length - codeLength) * count;\n if (savings > 50) {\n candidates.push({ phrase, count, savings });\n }\n }\n }\n\n // Sort by savings (descending) and take top entries\n candidates.sort((a, b) => b.savings - a.savings);\n const topCandidates = candidates.slice(0, MAX_ENTRIES);\n\n // Build codebook\n const codebook: Record = {};\n topCandidates.forEach((c, i) => {\n const code = `${CODE_PREFIX}${String(i + 1).padStart(2, \"0\")}`;\n codebook[code] = c.phrase;\n });\n\n return codebook;\n}\n\n/**\n * Escape special regex characters.\n */\nfunction escapeRegex(str: string): string {\n // Defensive type check\n if (!str || typeof str !== \"string\") return \"\";\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dynamic codebook to messages.\n */\nexport function applyDynamicCodebook(messages: NormalizedMessage[]): DynamicCodebookResult {\n // Build codebook from content\n const codebook = buildDynamicCodebook(messages);\n\n if (Object.keys(codebook).length === 0) {\n return {\n messages,\n charsSaved: 0,\n dynamicCodes: {},\n substitutions: 0,\n };\n }\n\n // Create inverse map for replacement\n const phraseToCode: Record = {};\n for (const [code, phrase] of Object.entries(codebook)) {\n phraseToCode[phrase] = code;\n }\n\n // Sort phrases by length (longest first) to avoid partial replacements\n const sortedPhrases = Object.keys(phraseToCode).sort((a, b) => b.length - a.length);\n\n let charsSaved = 0;\n let substitutions = 0;\n\n // Apply replacements\n const result = messages.map((msg) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n for (const phrase of sortedPhrases) {\n const code = phraseToCode[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = content.match(regex);\n if (matches) {\n content = content.replace(regex, code);\n charsSaved += (phrase.length - code.length) * matches.length;\n substitutions += matches.length;\n }\n }\n\n return { ...msg, content };\n });\n\n return {\n messages: result,\n charsSaved,\n dynamicCodes: codebook,\n substitutions,\n };\n}\n\n/**\n * Generate header for dynamic codes (to include in system message).\n */\nexport function generateDynamicCodebookHeader(codebook: Record): string {\n if (Object.keys(codebook).length === 0) return \"\";\n\n const entries = Object.entries(codebook)\n .slice(0, 20) // Limit header size\n .map(([code, phrase]) => {\n // Truncate long phrases in header\n const displayPhrase = phrase.length > 40 ? phrase.slice(0, 37) + \"...\" : phrase;\n return `${code}=${displayPhrase}`;\n })\n .join(\", \");\n\n return `[DynDict: ${entries}]`;\n}\n","/**\n * LLM-Safe Context Compression\n *\n * Reduces token usage by 15-40% while preserving semantic meaning.\n * Implements 7 compression layers inspired by claw-compactor.\n *\n * Usage:\n * const result = await compressContext(messages);\n * // result.messages -> compressed version to send to provider\n * // result.originalMessages -> original for logging\n */\n\nimport {\n NormalizedMessage,\n CompressionConfig,\n CompressionResult,\n CompressionStats,\n DEFAULT_COMPRESSION_CONFIG,\n} from \"./types\";\nimport { deduplicateMessages } from \"./layers/deduplication\";\nimport { normalizeMessagesWhitespace } from \"./layers/whitespace\";\nimport { encodeMessages } from \"./layers/dictionary\";\nimport { shortenPaths } from \"./layers/paths\";\nimport { compactMessagesJson } from \"./layers/json-compact\";\nimport { compressObservations } from \"./layers/observation\";\nimport { applyDynamicCodebook, generateDynamicCodebookHeader } from \"./layers/dynamic-codebook\";\nimport { generateCodebookHeader, STATIC_CODEBOOK } from \"./codebook\";\n\nexport * from \"./types\";\nexport { STATIC_CODEBOOK } from \"./codebook\";\n\n/**\n * Calculate total character count for messages.\n */\nfunction calculateTotalChars(messages: NormalizedMessage[]): number {\n return messages.reduce((total, msg) => {\n let chars = 0;\n if (typeof msg.content === \"string\") {\n chars = msg.content.length;\n } else if (Array.isArray(msg.content)) {\n // For multimodal content, stringify to get approximate size\n chars = JSON.stringify(msg.content).length;\n }\n if (msg.tool_calls) {\n chars += JSON.stringify(msg.tool_calls).length;\n }\n return total + chars;\n }, 0);\n}\n\n/**\n * Deep clone messages to preserve originals.\n */\nfunction cloneMessages(messages: NormalizedMessage[]): NormalizedMessage[] {\n return JSON.parse(JSON.stringify(messages));\n}\n\n/**\n * Prepend codebook header to the first USER message (not system).\n *\n * Why not system message?\n * - Google Gemini uses systemInstruction which doesn't support codebook format\n * - The codebook header in user message is still visible to all LLMs\n * - This ensures compatibility across all providers\n */\nfunction prependCodebookHeader(\n messages: NormalizedMessage[],\n usedCodes: Set,\n pathMap: Record,\n): NormalizedMessage[] {\n const header = generateCodebookHeader(usedCodes, pathMap);\n if (!header) return messages;\n\n // Find first user message (not system - Google's systemInstruction doesn't support codebook)\n const userIndex = messages.findIndex((m) => m.role === \"user\");\n\n if (userIndex === -1) {\n // No user message, add codebook as system (fallback)\n return [{ role: \"system\", content: header }, ...messages];\n }\n\n // Prepend to first user message (only if content is a string)\n return messages.map((msg, i) => {\n if (i === userIndex) {\n // Only prepend to string content - skip arrays (multimodal messages)\n if (typeof msg.content === \"string\") {\n return {\n ...msg,\n content: `${header}\\n\\n${msg.content}`,\n };\n }\n // For non-string content, don't modify the message\n // The codebook header would corrupt array content\n }\n return msg;\n });\n}\n\n/**\n * Main compression function.\n *\n * Applies 5 layers in sequence:\n * 1. Deduplication - Remove exact duplicate messages\n * 2. Whitespace - Normalize excessive whitespace\n * 3. Dictionary - Replace common phrases with codes\n * 4. Paths - Shorten repeated file paths\n * 5. JSON - Compact JSON in tool calls\n *\n * Then prepends a codebook header for the LLM to decode in-context.\n */\nexport async function compressContext(\n messages: NormalizedMessage[],\n config: Partial = {},\n): Promise {\n const fullConfig: CompressionConfig = {\n ...DEFAULT_COMPRESSION_CONFIG,\n ...config,\n layers: {\n ...DEFAULT_COMPRESSION_CONFIG.layers,\n ...config.layers,\n },\n dictionary: {\n ...DEFAULT_COMPRESSION_CONFIG.dictionary,\n ...config.dictionary,\n },\n };\n\n // If compression disabled, return as-is\n if (!fullConfig.enabled) {\n const originalChars = calculateTotalChars(messages);\n return {\n messages,\n originalMessages: messages,\n originalChars,\n compressedChars: originalChars,\n compressionRatio: 1,\n stats: {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n },\n codebook: {},\n pathMap: {},\n dynamicCodes: {},\n };\n }\n\n // Preserve originals for logging\n const originalMessages = fullConfig.preserveRaw ? cloneMessages(messages) : messages;\n const originalChars = calculateTotalChars(messages);\n\n // Initialize stats\n const stats: CompressionStats = {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n };\n\n let result = cloneMessages(messages);\n let usedCodes = new Set();\n let pathMap: Record = {};\n let dynamicCodes: Record = {};\n\n // Layer 1: Deduplication\n if (fullConfig.layers.deduplication) {\n const dedupResult = deduplicateMessages(result);\n result = dedupResult.messages;\n stats.duplicatesRemoved = dedupResult.duplicatesRemoved;\n }\n\n // Layer 2: Whitespace normalization\n if (fullConfig.layers.whitespace) {\n const wsResult = normalizeMessagesWhitespace(result);\n result = wsResult.messages;\n stats.whitespaceSavedChars = wsResult.charsSaved;\n }\n\n // Layer 3: Dictionary encoding\n if (fullConfig.layers.dictionary) {\n const dictResult = encodeMessages(result);\n result = dictResult.messages;\n stats.dictionarySubstitutions = dictResult.substitutionCount;\n usedCodes = dictResult.usedCodes;\n }\n\n // Layer 4: Path shortening\n if (fullConfig.layers.paths) {\n const pathResult = shortenPaths(result);\n result = pathResult.messages;\n pathMap = pathResult.pathMap;\n stats.pathsShortened = Object.keys(pathMap).length;\n }\n\n // Layer 5: JSON compaction\n if (fullConfig.layers.jsonCompact) {\n const jsonResult = compactMessagesJson(result);\n result = jsonResult.messages;\n stats.jsonCompactedChars = jsonResult.charsSaved;\n }\n\n // Layer 6: Observation compression (BIG WIN - 97% on tool results)\n if (fullConfig.layers.observation) {\n const obsResult = compressObservations(result);\n result = obsResult.messages;\n stats.observationsCompressed = obsResult.observationsCompressed;\n stats.observationCharsSaved = obsResult.charsSaved;\n }\n\n // Layer 7: Dynamic codebook (learns from actual content)\n if (fullConfig.layers.dynamicCodebook) {\n const dynResult = applyDynamicCodebook(result);\n result = dynResult.messages;\n stats.dynamicSubstitutions = dynResult.substitutions;\n stats.dynamicCharsSaved = dynResult.charsSaved;\n dynamicCodes = dynResult.dynamicCodes;\n }\n\n // Add codebook header if enabled and we have codes to include\n if (\n fullConfig.dictionary.includeCodebookHeader &&\n (usedCodes.size > 0 || Object.keys(pathMap).length > 0 || Object.keys(dynamicCodes).length > 0)\n ) {\n result = prependCodebookHeader(result, usedCodes, pathMap);\n // Also add dynamic codebook header if we have dynamic codes\n if (Object.keys(dynamicCodes).length > 0) {\n const dynHeader = generateDynamicCodebookHeader(dynamicCodes);\n if (dynHeader) {\n const systemIndex = result.findIndex((m) => m.role === \"system\");\n // Only prepend to string content - skip arrays (multimodal messages)\n if (systemIndex >= 0 && typeof result[systemIndex].content === \"string\") {\n result[systemIndex] = {\n ...result[systemIndex],\n content: `${dynHeader}\\n${result[systemIndex].content}`,\n };\n }\n }\n }\n }\n\n // Calculate final stats\n const compressedChars = calculateTotalChars(result);\n const compressionRatio = compressedChars / originalChars;\n\n // Build used codebook for logging\n const usedCodebook: Record = {};\n usedCodes.forEach((code) => {\n usedCodebook[code] = STATIC_CODEBOOK[code];\n });\n\n return {\n messages: result,\n originalMessages,\n originalChars,\n compressedChars,\n compressionRatio,\n stats,\n codebook: usedCodebook,\n pathMap,\n dynamicCodes,\n };\n}\n\n/**\n * Quick check if compression would benefit these messages.\n * Returns true if messages are large enough to warrant compression.\n */\nexport function shouldCompress(messages: NormalizedMessage[]): boolean {\n const chars = calculateTotalChars(messages);\n // Only compress if > 5000 chars (roughly 1000 tokens)\n return chars > 5000;\n}\n","/**\n * Session Persistence Store\n *\n * Tracks model selections per session to prevent model switching mid-task.\n * When a session is active, the router will continue using the same model\n * instead of re-routing each request.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type SessionEntry = {\n model: string;\n tier: string;\n createdAt: number;\n lastUsedAt: number;\n requestCount: number;\n // --- Three-strike escalation ---\n recentHashes: string[]; // Sliding window of last 3 request content fingerprints\n strikes: number; // Consecutive similar request count\n escalated: boolean; // Whether session was already escalated via three-strike\n // --- Cost accumulation for maxCostPerRun ---\n sessionCostMicros: bigint; // Total estimated cost for this session run (USDC 6-decimal)\n};\n\nexport type SessionConfig = {\n /** Enable session persistence (default: false) */\n enabled: boolean;\n /** Session timeout in ms (default: 30 minutes) */\n timeoutMs: number;\n /** Header name for session ID (default: X-Session-ID) */\n headerName: string;\n};\n\nexport const DEFAULT_SESSION_CONFIG: SessionConfig = {\n enabled: true,\n timeoutMs: 30 * 60 * 1000, // 30 minutes\n headerName: \"x-session-id\",\n};\n\n/**\n * Session persistence store for maintaining model selections.\n */\nexport class SessionStore {\n private sessions: Map = new Map();\n private config: SessionConfig;\n private cleanupInterval: ReturnType | null = null;\n\n constructor(config: Partial = {}) {\n this.config = { ...DEFAULT_SESSION_CONFIG, ...config };\n\n // Start cleanup interval (every 5 minutes)\n if (this.config.enabled) {\n this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1000);\n }\n }\n\n /**\n * Get the pinned model for a session, if any.\n */\n getSession(sessionId: string): SessionEntry | undefined {\n if (!this.config.enabled || !sessionId) {\n return undefined;\n }\n\n const entry = this.sessions.get(sessionId);\n if (!entry) {\n return undefined;\n }\n\n // Check if session has expired\n const now = Date.now();\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(sessionId);\n return undefined;\n }\n\n return entry;\n }\n\n /**\n * Pin a model to a session.\n */\n setSession(sessionId: string, model: string, tier: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const existing = this.sessions.get(sessionId);\n const now = Date.now();\n\n if (existing) {\n existing.lastUsedAt = now;\n existing.requestCount++;\n // Update model if different (e.g., fallback)\n if (existing.model !== model) {\n existing.model = model;\n existing.tier = tier;\n }\n } else {\n this.sessions.set(sessionId, {\n model,\n tier,\n createdAt: now,\n lastUsedAt: now,\n requestCount: 1,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n });\n }\n }\n\n /**\n * Touch a session to extend its timeout.\n */\n touchSession(sessionId: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const entry = this.sessions.get(sessionId);\n if (entry) {\n entry.lastUsedAt = Date.now();\n entry.requestCount++;\n }\n }\n\n /**\n * Clear a specific session.\n */\n clearSession(sessionId: string): void {\n this.sessions.delete(sessionId);\n }\n\n /**\n * Clear all sessions.\n */\n clearAll(): void {\n this.sessions.clear();\n }\n\n /**\n * Get session stats for debugging.\n */\n getStats(): { count: number; sessions: Array<{ id: string; model: string; age: number }> } {\n const now = Date.now();\n const sessions = Array.from(this.sessions.entries()).map(([id, entry]) => ({\n id: id.slice(0, 8) + \"...\",\n model: entry.model,\n age: Math.round((now - entry.createdAt) / 1000),\n }));\n return { count: this.sessions.size, sessions };\n }\n\n /**\n * Clean up expired sessions.\n */\n private cleanup(): void {\n const now = Date.now();\n for (const [id, entry] of this.sessions) {\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(id);\n }\n }\n }\n\n /**\n * Record a request content hash and detect repetitive patterns.\n * Returns true if escalation should be triggered (3+ consecutive similar requests).\n */\n recordRequestHash(sessionId: string, hash: string): boolean {\n const entry = this.sessions.get(sessionId);\n if (!entry) return false;\n\n const prev = entry.recentHashes;\n if (prev.length > 0 && prev[prev.length - 1] === hash) {\n entry.strikes++;\n } else {\n entry.strikes = 0;\n }\n\n entry.recentHashes.push(hash);\n if (entry.recentHashes.length > 3) {\n entry.recentHashes.shift();\n }\n\n return entry.strikes >= 2 && !entry.escalated;\n }\n\n /**\n * Escalate session to next tier. Returns the new model/tier or null if already at max.\n */\n escalateSession(\n sessionId: string,\n tierConfigs: Record,\n ): { model: string; tier: string } | null {\n const entry = this.sessions.get(sessionId);\n if (!entry) return null;\n\n const TIER_ORDER = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\"];\n const currentIdx = TIER_ORDER.indexOf(entry.tier);\n if (currentIdx < 0 || currentIdx >= TIER_ORDER.length - 1) return null;\n\n const nextTier = TIER_ORDER[currentIdx + 1];\n const nextConfig = tierConfigs[nextTier];\n if (!nextConfig) return null;\n\n entry.model = nextConfig.primary;\n entry.tier = nextTier;\n entry.strikes = 0;\n entry.escalated = true;\n\n return { model: nextConfig.primary, tier: nextTier };\n }\n\n /**\n * Add cost to a session's running total for maxCostPerRun tracking.\n * Cost is in USDC 6-decimal units (micros).\n * Creates a cost-tracking-only entry if none exists (e.g., explicit model requests\n * that never go through the routing path).\n */\n addSessionCost(sessionId: string, additionalMicros: bigint): void {\n let entry = this.sessions.get(sessionId);\n if (!entry) {\n const now = Date.now();\n entry = {\n model: \"\",\n tier: \"DIRECT\",\n createdAt: now,\n lastUsedAt: now,\n requestCount: 0,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n };\n this.sessions.set(sessionId, entry);\n }\n entry.sessionCostMicros += additionalMicros;\n }\n\n /**\n * Get the total accumulated cost for a session in USD.\n */\n getSessionCostUsd(sessionId: string): number {\n const entry = this.sessions.get(sessionId);\n if (!entry) return 0;\n return Number(entry.sessionCostMicros) / 1_000_000;\n }\n\n /**\n * Stop the cleanup interval.\n */\n close(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n}\n\n/**\n * Generate a session ID from request headers or create a default.\n */\nexport function getSessionId(\n headers: Record,\n headerName: string = DEFAULT_SESSION_CONFIG.headerName,\n): string | undefined {\n const value = headers[headerName] || headers[headerName.toLowerCase()];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n if (Array.isArray(value) && value.length > 0) {\n return value[0];\n }\n return undefined;\n}\n\n/**\n * Derive a stable session ID from message content when no explicit session\n * header is provided. Uses the first user message as the conversation anchor —\n * same opening message = same session ID across all subsequent turns.\n *\n * This prevents model-switching mid-conversation even when OpenClaw doesn't\n * send an x-session-id header (which is the default OpenClaw behaviour).\n */\nexport function deriveSessionId(\n messages: Array<{ role: string; content: unknown }>,\n): string | undefined {\n const firstUser = messages.find((m) => m.role === \"user\");\n if (!firstUser) return undefined;\n\n const content =\n typeof firstUser.content === \"string\" ? firstUser.content : JSON.stringify(firstUser.content);\n\n // 8-char hex prefix of SHA-256 — short enough for logs, collision-resistant\n // enough for session tracking within a single gateway instance.\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 8);\n}\n\n/**\n * Generate a short hash fingerprint from request content.\n * Captures: last user message text + tool call names (if any).\n * Normalizes whitespace to avoid false negatives from minor formatting diffs.\n */\nexport function hashRequestContent(lastUserContent: string, toolCallNames?: string[]): string {\n const normalized = lastUserContent.replace(/\\s+/g, \" \").trim().slice(0, 500);\n const toolSuffix = toolCallNames?.length ? `|tools:${toolCallNames.sort().join(\",\")}` : \"\";\n return createHash(\"sha256\")\n .update(normalized + toolSuffix)\n .digest(\"hex\")\n .slice(0, 12);\n}\n","/**\n * Auto-update checker for ClawRouter.\n * Checks npm registry on startup and notifies user if update available.\n */\n\nimport { VERSION } from \"./version.js\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org/@blockrun/clawrouter/latest\";\nconst CHECK_TIMEOUT_MS = 5_000; // Don't block startup for more than 5s\n\n/**\n * Compare semver versions. Returns:\n * 1 if a > b\n * 0 if a === b\n * -1 if a < b\n */\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split(\".\").map(Number);\n const pb = b.split(\".\").map(Number);\n for (let i = 0; i < 3; i++) {\n if ((pa[i] || 0) > (pb[i] || 0)) return 1;\n if ((pa[i] || 0) < (pb[i] || 0)) return -1;\n }\n return 0;\n}\n\n/**\n * Check npm registry for latest version.\n * Non-blocking, silent on errors.\n */\nexport async function checkForUpdates(): Promise {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);\n\n const res = await fetch(NPM_REGISTRY, {\n signal: controller.signal,\n headers: { Accept: \"application/json\" },\n });\n clearTimeout(timeout);\n\n if (!res.ok) return;\n\n const data = (await res.json()) as { version?: string };\n const latest = data.version;\n\n if (!latest) return;\n\n if (compareSemver(latest, VERSION) > 0) {\n console.log(\"\");\n console.log(`\\x1b[33m⬆️ ClawRouter ${latest} available (you have ${VERSION})\\x1b[0m`);\n console.log(` Run: \\x1b[36mnpx @blockrun/clawrouter@latest\\x1b[0m`);\n console.log(\"\");\n }\n } catch {\n // Silent fail - don't disrupt startup\n }\n}\n","/**\n * Exclude-models persistence module.\n *\n * Manages a user-configurable list of model IDs that the smart router\n * should never select. Stored as a sorted JSON array on disk.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { resolveModelAlias } from \"./models.js\";\n\nconst DEFAULT_FILE_PATH = join(homedir(), \".openclaw\", \"blockrun\", \"exclude-models.json\");\n\n/**\n * Load the exclude list from disk.\n * Returns an empty set if the file does not exist.\n */\nexport function loadExcludeList(filePath: string = DEFAULT_FILE_PATH): Set {\n try {\n const raw = readFileSync(filePath, \"utf-8\");\n const arr: unknown = JSON.parse(raw);\n if (Array.isArray(arr)) {\n return new Set(arr.filter((x): x is string => typeof x === \"string\"));\n }\n return new Set();\n } catch {\n return new Set();\n }\n}\n\n/**\n * Save a set of model IDs to disk as a sorted JSON array.\n */\nfunction saveExcludeList(set: Set, filePath: string): void {\n const sorted = [...set].sort();\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n writeFileSync(filePath, JSON.stringify(sorted, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Add a model to the exclude list.\n * Resolves aliases before persisting.\n * @returns The resolved model ID.\n */\nexport function addExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): string {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n set.add(resolved);\n saveExcludeList(set, filePath);\n return resolved;\n}\n\n/**\n * Remove a model from the exclude list.\n * Resolves aliases before removing.\n * @returns true if the model was present and removed, false otherwise.\n */\nexport function removeExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): boolean {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n const had = set.delete(resolved);\n if (had) {\n saveExcludeList(set, filePath);\n }\n return had;\n}\n\n/**\n * Clear the entire exclude list.\n */\nexport function clearExclusions(filePath: string = DEFAULT_FILE_PATH): void {\n saveExcludeList(new Set(), filePath);\n}\n","/**\n * Configuration Module\n *\n * Reads environment variables at module load time.\n * Separated from network code to avoid security scanner false positives.\n */\n\nconst DEFAULT_PORT = 8402;\n\n/**\n * Proxy port configuration - resolved once at module load.\n * Reads BLOCKRUN_PROXY_PORT env var or defaults to 8402.\n */\nexport const PROXY_PORT = (() => {\n const envPort = process[\"env\"].BLOCKRUN_PROXY_PORT;\n if (envPort) {\n const parsed = parseInt(envPort, 10);\n if (!isNaN(parsed) && parsed > 0 && parsed < 65536) {\n return parsed;\n }\n }\n return DEFAULT_PORT;\n})();\n","/**\n * Session Journal - Memory layer for ClawRouter\n *\n * Maintains a compact record of key actions per session, enabling agents\n * to recall earlier work even when OpenClaw's sessions_history is truncated.\n *\n * How it works:\n * 1. As LLM responses flow through, extracts key actions (\"I created X\", \"I fixed Y\")\n * 2. Stores them in a compact journal per session\n * 3. When a request mentions past work (\"what did you do today?\"), injects the journal\n */\n\nexport interface JournalEntry {\n timestamp: number;\n action: string; // Compact description: \"Created login component\"\n model?: string;\n}\n\nexport interface SessionJournalConfig {\n /** Maximum entries per session (default: 100) */\n maxEntries?: number;\n /** Maximum age of entries in ms (default: 24 hours) */\n maxAgeMs?: number;\n /** Maximum events to extract per response (default: 5) */\n maxEventsPerResponse?: number;\n}\n\nconst DEFAULT_CONFIG: Required = {\n maxEntries: 100,\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxEventsPerResponse: 5,\n};\n\nexport class SessionJournal {\n private journals: Map = new Map();\n private config: Required;\n\n constructor(config?: SessionJournalConfig) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Extract key events from assistant response content.\n * Looks for patterns like \"I created...\", \"I fixed...\", \"Successfully...\"\n */\n extractEvents(content: string): string[] {\n if (!content || typeof content !== \"string\") {\n return [];\n }\n\n const events: string[] = [];\n const seen = new Set();\n\n // Patterns for identifying key actions\n // Note: Patterns allow optional words like \"also\", \"then\", \"have\" between \"I\" and verb\n const patterns = [\n // Creation patterns\n /I (?:also |then |have |)?(?:created|implemented|added|wrote|built|generated|set up|initialized) ([^.!?\\n]{10,150})/gi,\n // Fix patterns\n /I (?:also |then |have |)?(?:fixed|resolved|solved|patched|corrected|addressed|debugged) ([^.!?\\n]{10,150})/gi,\n // Completion patterns\n /I (?:also |then |have |)?(?:completed|finished|done with|wrapped up) ([^.!?\\n]{10,150})/gi,\n // Update patterns\n /I (?:also |then |have |)?(?:updated|modified|changed|refactored|improved|enhanced|optimized) ([^.!?\\n]{10,150})/gi,\n // Success patterns\n /Successfully ([^.!?\\n]{10,150})/gi,\n // Tool usage patterns (when agent uses tools)\n /I (?:also |then |have |)?(?:ran|executed|called|invoked) ([^.!?\\n]{10,100})/gi,\n ];\n\n for (const pattern of patterns) {\n // Reset pattern lastIndex for each iteration\n pattern.lastIndex = 0;\n\n let match;\n while ((match = pattern.exec(content)) !== null) {\n const action = match[0].trim();\n\n // Skip if already seen (dedup)\n const normalized = action.toLowerCase();\n if (seen.has(normalized)) {\n continue;\n }\n\n // Validate length (not too short or too long)\n if (action.length >= 15 && action.length <= 200) {\n events.push(action);\n seen.add(normalized);\n }\n\n // Stop if we have enough events\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n return events;\n }\n\n /**\n * Record events to the session journal.\n */\n record(sessionId: string, events: string[], model?: string): void {\n if (!sessionId || !events.length) {\n return;\n }\n\n const journal = this.journals.get(sessionId) || [];\n const now = Date.now();\n\n for (const action of events) {\n journal.push({\n timestamp: now,\n action,\n model,\n });\n }\n\n // Trim old entries and enforce max count\n const cutoff = now - this.config.maxAgeMs;\n const trimmed = journal.filter((e) => e.timestamp > cutoff).slice(-this.config.maxEntries);\n\n this.journals.set(sessionId, trimmed);\n }\n\n /**\n * Check if the user message indicates a need for historical context.\n */\n needsContext(lastUserMessage: string): boolean {\n if (!lastUserMessage || typeof lastUserMessage !== \"string\") {\n return false;\n }\n\n const lower = lastUserMessage.toLowerCase();\n\n // Trigger phrases that indicate user wants to recall past work\n const triggers = [\n // Direct questions about past work\n \"what did you do\",\n \"what have you done\",\n \"what did we do\",\n \"what have we done\",\n // Temporal references\n \"earlier\",\n \"before\",\n \"previously\",\n \"this session\",\n \"today\",\n \"so far\",\n // Summary requests\n \"remind me\",\n \"summarize\",\n \"summary of\",\n \"recap\",\n // Progress inquiries\n \"your work\",\n \"your progress\",\n \"accomplished\",\n \"achievements\",\n \"completed tasks\",\n ];\n\n return triggers.some((t) => lower.includes(t));\n }\n\n /**\n * Format the journal for injection into system message.\n * Returns null if journal is empty.\n */\n format(sessionId: string): string | null {\n const journal = this.journals.get(sessionId);\n if (!journal?.length) {\n return null;\n }\n\n const lines = journal.map((e) => {\n const time = new Date(e.timestamp).toLocaleTimeString(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n });\n return `- ${time}: ${e.action}`;\n });\n\n return `[Session Memory - Key Actions]\\n${lines.join(\"\\n\")}`;\n }\n\n /**\n * Get the raw journal entries for a session (for debugging/testing).\n */\n getEntries(sessionId: string): JournalEntry[] {\n return this.journals.get(sessionId) || [];\n }\n\n /**\n * Clear journal for a specific session.\n */\n clear(sessionId: string): void {\n this.journals.delete(sessionId);\n }\n\n /**\n * Clear all journals.\n */\n clearAll(): void {\n this.journals.clear();\n }\n\n /**\n * Get stats about the journal.\n */\n getStats(): { sessions: number; totalEntries: number } {\n let totalEntries = 0;\n for (const entries of this.journals.values()) {\n totalEntries += entries.length;\n }\n return {\n sessions: this.journals.size,\n totalEntries,\n };\n }\n}\n","/**\n * Cost Report Generator\n */\n\nimport { getStats } from \"./stats.js\";\nimport type { AggregatedStats } from \"./stats.js\";\n\nexport type ReportPeriod = \"daily\" | \"weekly\" | \"monthly\";\n\nexport async function generateReport(period: ReportPeriod, json: boolean = false): Promise {\n const days = period === \"daily\" ? 1 : period === \"weekly\" ? 7 : 30;\n const stats = await getStats(days);\n\n if (json) {\n return JSON.stringify(stats, null, 2);\n }\n\n return formatMarkdownReport(period, days, stats);\n}\n\nfunction formatMarkdownReport(period: ReportPeriod, days: number, stats: AggregatedStats): string {\n const lines: string[] = [];\n\n lines.push(`# ClawRouter ${capitalize(period)} Report`);\n lines.push(`**Period:** Last ${days} day${days > 1 ? \"s\" : \"\"}`);\n lines.push(`**Generated:** ${new Date().toISOString()}`);\n lines.push(\"\");\n\n lines.push(\"## 📊 Usage Summary\");\n lines.push(\"\");\n lines.push(`| Metric | Value |`);\n lines.push(`|--------|-------|`);\n lines.push(`| Total Requests | ${stats.totalRequests} |`);\n lines.push(`| Total Cost | $${stats.totalCost.toFixed(4)} |`);\n lines.push(`| Baseline Cost | $${stats.totalBaselineCost.toFixed(4)} |`);\n lines.push(`| **Savings** | **$${stats.totalSavings.toFixed(4)}** |`);\n lines.push(`| Savings % | ${stats.savingsPercentage.toFixed(1)}% |`);\n lines.push(`| Avg Latency | ${stats.avgLatencyMs.toFixed(0)}ms |`);\n lines.push(\"\");\n\n lines.push(\"## 🤖 Model Distribution\");\n lines.push(\"\");\n const sortedModels = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 10);\n for (const [model, data] of sortedModels) {\n lines.push(`- ${model}: ${data.count} reqs, $${data.cost.toFixed(4)}`);\n }\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\nfunction capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n","/**\n * BlockRun Doctor - AI-Powered Diagnostics\n *\n * Collects system diagnostics and sends to Claude Opus 4.6 for analysis.\n * Works independently of OpenClaw - direct x402 payment to BlockRun API.\n */\n\nimport { platform, arch, freemem, totalmem } from \"node:os\";\nimport { createPublicClient, http } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { wrapFetchWithPayment, x402Client } from \"@x402/fetch\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { toClientEvmSigner } from \"@x402/evm\";\nimport { resolveOrGenerateWalletKey, resolvePaymentChain, WALLET_FILE } from \"./auth.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport { getSolanaAddress } from \"./wallet.js\";\nimport { getStats } from \"./stats.js\";\nimport { getProxyPort } from \"./proxy.js\";\nimport { VERSION } from \"./version.js\";\n\n// Types\ninterface SystemInfo {\n os: string;\n arch: string;\n nodeVersion: string;\n memoryFree: string;\n memoryTotal: string;\n}\n\ninterface WalletInfo {\n exists: boolean;\n valid: boolean;\n address: string | null;\n solanaAddress: string | null;\n balance: string | null;\n isLow: boolean;\n isEmpty: boolean;\n source: \"saved\" | \"env\" | \"generated\" | null;\n paymentChain: \"base\" | \"solana\";\n}\n\ninterface NetworkInfo {\n blockrunApi: { reachable: boolean; latencyMs: number | null };\n localProxy: { running: boolean; port: number };\n}\n\ninterface LogInfo {\n requestsLast24h: number;\n costLast24h: string;\n errorsFound: number;\n}\n\ninterface DiagnosticResult {\n version: string;\n timestamp: string;\n system: SystemInfo;\n wallet: WalletInfo;\n network: NetworkInfo;\n logs: LogInfo;\n issues: string[];\n}\n\n// Helpers\nfunction formatBytes(bytes: number): string {\n const gb = bytes / (1024 * 1024 * 1024);\n return `${gb.toFixed(1)}GB`;\n}\n\nfunction green(text: string): string {\n return `\\x1b[32m✓\\x1b[0m ${text}`;\n}\n\nfunction red(text: string): string {\n return `\\x1b[31m✗\\x1b[0m ${text}`;\n}\n\nfunction yellow(text: string): string {\n return `\\x1b[33m⚠\\x1b[0m ${text}`;\n}\n\n// Collect system info\nfunction collectSystemInfo(): SystemInfo {\n return {\n os: `${platform()} ${arch()}`,\n arch: arch(),\n nodeVersion: process.version,\n memoryFree: formatBytes(freemem()),\n memoryTotal: formatBytes(totalmem()),\n };\n}\n\n// Collect wallet info\nasync function collectWalletInfo(): Promise {\n try {\n const { key, address, source, solanaPrivateKeyBytes } = await resolveOrGenerateWalletKey();\n\n if (!key || !address) {\n return {\n exists: false,\n valid: false,\n address: null,\n solanaAddress: null,\n balance: null,\n isLow: false,\n isEmpty: true,\n source: null,\n paymentChain: \"base\",\n };\n }\n\n // Derive Solana address if mnemonic-based wallet\n let solanaAddress: string | null = null;\n if (solanaPrivateKeyBytes) {\n try {\n solanaAddress = await getSolanaAddress(solanaPrivateKeyBytes);\n } catch {\n // Non-fatal\n }\n }\n\n // Check balance on the active payment chain\n const paymentChain = await resolvePaymentChain();\n try {\n let balanceInfo: { balanceUSD: string; isLow: boolean; isEmpty: boolean };\n if (paymentChain === \"solana\" && solanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n const monitor = new SolanaBalanceMonitor(solanaAddress);\n balanceInfo = await monitor.checkBalance();\n } else {\n const monitor = new BalanceMonitor(address);\n balanceInfo = await monitor.checkBalance();\n }\n return {\n exists: true,\n valid: true,\n address,\n solanaAddress,\n balance: balanceInfo.balanceUSD,\n isLow: balanceInfo.isLow,\n isEmpty: balanceInfo.isEmpty,\n source,\n paymentChain,\n };\n } catch {\n return {\n exists: true,\n valid: true,\n address,\n solanaAddress,\n balance: null,\n isLow: false,\n isEmpty: false,\n source,\n paymentChain,\n };\n }\n } catch {\n return {\n exists: false,\n valid: false,\n address: null,\n solanaAddress: null,\n balance: null,\n isLow: false,\n isEmpty: true,\n source: null,\n paymentChain: \"base\",\n };\n }\n}\n\n// Collect network info\nasync function collectNetworkInfo(): Promise {\n const port = getProxyPort();\n\n // Check BlockRun API\n let blockrunReachable = false;\n let blockrunLatency: number | null = null;\n try {\n const start = Date.now();\n const response = await fetch(\"https://blockrun.ai/api/v1/models\", {\n method: \"GET\",\n signal: AbortSignal.timeout(10000),\n });\n blockrunLatency = Date.now() - start;\n blockrunReachable = response.ok || response.status === 402;\n } catch {\n // blockrunReachable already false\n }\n\n // Check local proxy\n let proxyRunning = false;\n try {\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n method: \"GET\",\n signal: AbortSignal.timeout(3000),\n });\n proxyRunning = response.ok;\n } catch {\n // proxyRunning already false\n }\n\n return {\n blockrunApi: { reachable: blockrunReachable, latencyMs: blockrunLatency },\n localProxy: { running: proxyRunning, port },\n };\n}\n\n// Collect log info\nasync function collectLogInfo(): Promise {\n try {\n const stats = await getStats(1); // Last 1 day\n return {\n requestsLast24h: stats.totalRequests,\n costLast24h: `$${stats.totalCost.toFixed(4)}`,\n errorsFound: 0, // TODO: parse error logs\n };\n } catch {\n return {\n requestsLast24h: 0,\n costLast24h: \"$0.00\",\n errorsFound: 0,\n };\n }\n}\n\n// Identify issues\nfunction identifyIssues(result: DiagnosticResult): string[] {\n const issues: string[] = [];\n\n if (!result.wallet.exists) {\n issues.push(\"No wallet found\");\n }\n if (result.wallet.isEmpty) {\n const chain = result.wallet.paymentChain === \"solana\" ? \"Solana\" : \"Base\";\n issues.push(`Wallet is empty - need to fund with USDC on ${chain}`);\n if (result.wallet.paymentChain === \"base\" && result.wallet.solanaAddress) {\n issues.push(\"Tip: if you funded Solana, run /wallet solana to switch chains\");\n }\n } else if (result.wallet.isLow) {\n issues.push(\"Wallet balance is low (< $1.00)\");\n }\n if (!result.network.blockrunApi.reachable) {\n issues.push(\"Cannot reach BlockRun API - check internet connection\");\n }\n if (!result.network.localProxy.running) {\n issues.push(`Local proxy not running on port ${result.network.localProxy.port}`);\n }\n\n return issues;\n}\n\n// Print diagnostics to terminal\nfunction printDiagnostics(result: DiagnosticResult): void {\n console.log(\"\\n🔍 Collecting diagnostics...\\n\");\n\n // System\n console.log(\"System\");\n console.log(` ${green(`OS: ${result.system.os}`)}`);\n console.log(` ${green(`Node: ${result.system.nodeVersion}`)}`);\n console.log(\n ` ${green(`Memory: ${result.system.memoryFree} free / ${result.system.memoryTotal}`)}`,\n );\n\n // Wallet\n console.log(\"\\nWallet\");\n if (result.wallet.exists && result.wallet.valid) {\n console.log(` ${green(`Key: ${WALLET_FILE} (${result.wallet.source})`)}`);\n console.log(` ${green(`EVM Address: ${result.wallet.address}`)}`);\n if (result.wallet.solanaAddress) {\n console.log(` ${green(`Solana Address: ${result.wallet.solanaAddress}`)}`);\n }\n const chainLabel = result.wallet.paymentChain === \"solana\" ? \"Solana\" : \"Base\";\n console.log(` ${green(`Chain: ${chainLabel}`)}`);\n if (result.wallet.isEmpty) {\n console.log(` ${red(`Balance: $0.00 - NEED TO FUND WITH USDC ON ${chainLabel.toUpperCase()}!`)}`);\n if (result.wallet.paymentChain === \"base\" && result.wallet.solanaAddress) {\n console.log(` ${yellow(`Tip: funded Solana instead? Run /wallet solana to switch`)}`);\n }\n } else if (result.wallet.isLow) {\n console.log(` ${yellow(`Balance: ${result.wallet.balance} (low)`)}`);\n } else if (result.wallet.balance) {\n console.log(` ${green(`Balance: ${result.wallet.balance}`)}`);\n } else {\n console.log(` ${yellow(`Balance: checking...`)}`);\n }\n } else {\n console.log(` ${red(\"No wallet found\")}`);\n }\n\n // Network\n console.log(\"\\nNetwork\");\n if (result.network.blockrunApi.reachable) {\n console.log(\n ` ${green(`BlockRun API: reachable (${result.network.blockrunApi.latencyMs}ms)`)}`,\n );\n } else {\n console.log(` ${red(\"BlockRun API: unreachable\")}`);\n }\n if (result.network.localProxy.running) {\n console.log(` ${green(`Local proxy: running on :${result.network.localProxy.port}`)}`);\n } else {\n console.log(` ${red(`Local proxy: not running on :${result.network.localProxy.port}`)}`);\n }\n\n // Logs\n console.log(\"\\nLogs\");\n console.log(\n ` ${green(`Last 24h: ${result.logs.requestsLast24h} requests, ${result.logs.costLast24h} spent`)}`,\n );\n if (result.logs.errorsFound > 0) {\n console.log(` ${yellow(`${result.logs.errorsFound} errors found in logs`)}`);\n }\n\n // Issues summary\n if (result.issues.length > 0) {\n console.log(\"\\n⚠️ Issues Found:\");\n for (const issue of result.issues) {\n console.log(` • ${issue}`);\n }\n }\n}\n\n// Model options for doctor command\ntype DoctorModel = \"sonnet\" | \"opus\";\n\nconst DOCTOR_MODELS: Record = {\n sonnet: {\n id: \"anthropic/claude-sonnet-4.6\",\n name: \"Claude Sonnet 4.6\",\n cost: \"~$0.003\",\n },\n opus: {\n id: \"anthropic/claude-opus-4.6\",\n name: \"Claude Opus 4.6\",\n cost: \"~$0.01\",\n },\n};\n\n// Send to AI for analysis\nasync function analyzeWithAI(\n diagnostics: DiagnosticResult,\n userQuestion?: string,\n model: DoctorModel = \"sonnet\",\n): Promise {\n // Check if wallet has funds\n if (diagnostics.wallet.isEmpty) {\n console.log(\"\\n💳 Wallet is empty - cannot call AI for analysis.\");\n console.log(` Fund your EVM wallet with USDC on Base: ${diagnostics.wallet.address}`);\n if (diagnostics.wallet.solanaAddress) {\n console.log(` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress}`);\n }\n console.log(\" Get USDC: https://www.coinbase.com/price/usd-coin\");\n console.log(\" Bridge to Base: https://bridge.base.org\\n\");\n return;\n }\n\n const modelConfig = DOCTOR_MODELS[model];\n console.log(`\\n📤 Sending to ${modelConfig.name} (${modelConfig.cost})...\\n`);\n\n try {\n const { key } = await resolveOrGenerateWalletKey();\n const account = privateKeyToAccount(key as `0x${string}`);\n const publicClient = createPublicClient({ chain: base, transport: http() });\n const evmSigner = toClientEvmSigner(account, publicClient);\n const x402 = new x402Client();\n registerExactEvmScheme(x402, { signer: evmSigner });\n const paymentFetch = wrapFetchWithPayment(fetch, x402);\n\n const response = await paymentFetch(\"https://blockrun.ai/api/v1/chat/completions\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: modelConfig.id,\n stream: false,\n messages: [\n {\n role: \"system\",\n content: `You are a technical support expert for BlockRun and ClawRouter.\nAnalyze the diagnostics and:\n1. Identify the root cause of any issues\n2. Provide specific, actionable fix commands (bash)\n3. Explain why the issue occurred briefly\n4. Be concise but thorough\n5. Format commands in code blocks`,\n },\n {\n role: \"user\",\n content: userQuestion\n ? `Here are my system diagnostics:\\n\\n${JSON.stringify(diagnostics, null, 2)}\\n\\nUser's question: ${userQuestion}`\n : `Here are my system diagnostics:\\n\\n${JSON.stringify(diagnostics, null, 2)}\\n\\nPlease analyze and help me fix any issues.`,\n },\n ],\n max_tokens: 1000,\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n console.log(`Error: ${response.status} - ${text}`);\n return;\n }\n\n const data = await response.json();\n const content = data.choices?.[0]?.message?.content;\n\n if (content) {\n console.log(\"🤖 AI Analysis:\\n\");\n console.log(content);\n console.log();\n } else {\n console.log(\"Error: No response from AI\");\n }\n } catch (err) {\n console.log(`\\nError calling AI: ${err instanceof Error ? err.message : String(err)}`);\n console.log(\"Try again or check your wallet balance.\\n\");\n }\n}\n\n// Main entry point\nexport async function runDoctor(\n userQuestion?: string,\n model: \"sonnet\" | \"opus\" = \"sonnet\",\n): Promise {\n console.log(`\\n🩺 BlockRun Doctor v${VERSION}\\n`);\n\n // Collect all diagnostics\n const [system, wallet, network, logs] = await Promise.all([\n collectSystemInfo(),\n collectWalletInfo(),\n collectNetworkInfo(),\n collectLogInfo(),\n ]);\n\n const result: DiagnosticResult = {\n version: VERSION,\n timestamp: new Date().toISOString(),\n system,\n wallet,\n network,\n logs,\n issues: [],\n };\n\n // Identify issues\n result.issues = identifyIssues(result);\n\n // Print to terminal\n printDiagnostics(result);\n\n // Send to AI for analysis\n await analyzeWithAI(result, userQuestion, model);\n}\n","/**\n * Partner Service Registry\n *\n * Defines available partner APIs that can be called through ClawRouter's proxy.\n * Partners provide specialized data (Twitter/X, etc.) via x402 micropayments.\n * The same wallet used for LLM calls pays for partner API calls — zero extra setup.\n */\n\nexport type PartnerServiceParam = {\n name: string;\n type: \"string\" | \"string[]\" | \"number\";\n description: string;\n required: boolean;\n};\n\nexport type PartnerServiceDefinition = {\n /** Unique service ID used in tool names: blockrun_{id} */\n id: string;\n /** Human-readable name */\n name: string;\n /** Partner providing this service */\n partner: string;\n /** Short description for tool listing */\n description: string;\n /** Proxy path (relative to /v1) */\n proxyPath: string;\n /** HTTP method */\n method: \"GET\" | \"POST\";\n /** Parameters for the tool's JSON Schema */\n params: PartnerServiceParam[];\n /** Pricing info for display */\n pricing: {\n perUnit: string;\n unit: string;\n minimum: string;\n maximum: string;\n };\n /** Example usage for help text */\n example: {\n input: Record;\n description: string;\n };\n};\n\n/**\n * All registered partner services.\n * New partners are added here — the rest of the system picks them up automatically.\n */\nexport const PARTNER_SERVICES: PartnerServiceDefinition[] = [\n {\n id: \"x_users_lookup\",\n name: \"Twitter/X User Lookup\",\n partner: \"AttentionVC\",\n description:\n \"Look up real-time Twitter/X user profiles by username. \" +\n \"Call this ONLY when the user explicitly asks to look up, check, or get information about a specific Twitter/X user's profile (follower count, bio, verification status, etc.). \" +\n \"Do NOT call this for messages that merely contain x.com or twitter.com URLs — only invoke when the user is asking for profile information about a specific account. \" +\n \"Returns: follower count, verification badge, bio, location, join date. \" +\n \"Accepts up to 100 usernames per request (without @ prefix).\",\n proxyPath: \"/x/users/lookup\",\n method: \"POST\",\n params: [\n {\n name: \"usernames\",\n type: \"string[]\",\n description:\n 'Array of Twitter/X usernames to look up (without @ prefix). Example: [\"elonmusk\", \"naval\"]',\n required: true,\n },\n ],\n pricing: {\n perUnit: \"$0.001\",\n unit: \"user\",\n minimum: \"$0.01 (10 users)\",\n maximum: \"$0.10 (100 users)\",\n },\n example: {\n input: { usernames: [\"elonmusk\", \"naval\", \"balaboris\"] },\n description: \"Look up 3 Twitter/X user profiles\",\n },\n },\n];\n\n/**\n * Get a partner service by ID.\n */\nexport function getPartnerService(id: string): PartnerServiceDefinition | undefined {\n return PARTNER_SERVICES.find((s) => s.id === id);\n}\n","#!/usr/bin/env node\n/**\n * ClawRouter CLI\n *\n * Standalone proxy for deployed setups where the proxy needs to survive gateway restarts.\n *\n * Usage:\n * npx @blockrun/clawrouter # Start standalone proxy\n * npx @blockrun/clawrouter --version # Show version\n * npx @blockrun/clawrouter --port 8402 # Custom port\n *\n * For production deployments, use with PM2:\n * pm2 start \"npx @blockrun/clawrouter\" --name clawrouter\n */\n\nimport { startProxy, getProxyPort } from \"./proxy.js\";\nimport { VERSION } from \"./version.js\";\nimport {\n resolveOrGenerateWalletKey,\n resolvePaymentChain,\n recoverWalletFromMnemonic,\n savePaymentChain,\n} from \"./auth.js\";\nimport { getSolanaAddress } from \"./wallet.js\";\nimport { generateReport } from \"./report.js\";\nimport { runDoctor } from \"./doctor.js\";\nimport { PARTNER_SERVICES } from \"./partners/index.js\";\n\nfunction printHelp(): void {\n console.log(`\nClawRouter v${VERSION} - Smart LLM Router\n\nUsage:\n clawrouter [options]\n clawrouter doctor [opus] [question]\n clawrouter partners [test]\n clawrouter report [daily|weekly|monthly] [--json]\n\nOptions:\n --version, -v Show version number\n --help, -h Show this help message\n --port Port to listen on (default: ${getProxyPort()})\n\nCommands:\n doctor AI-powered diagnostics (default: Sonnet ~$0.003)\n doctor opus Use Opus for deeper analysis (~$0.01)\n partners List available partner APIs with pricing\n partners test Test partner API endpoints (expect 402 = alive)\n wallet recover Restore wallet.key from mnemonic (if generated by ClawRouter)\n chain solana Switch to Solana (persists). Aliases: /wallet solana, wallet solana\n chain base Switch to Base EVM (persists). Aliases: /wallet base, wallet base\n\nExamples:\n # Start standalone proxy\n npx @blockrun/clawrouter\n\n # Run diagnostics (uses Sonnet by default)\n npx @blockrun/clawrouter doctor\n\n # Use Opus for complex issues\n npx @blockrun/clawrouter doctor opus\n\n # Ask a specific question\n npx @blockrun/clawrouter doctor \"why is my request failing?\"\n\n # Opus + question\n npx @blockrun/clawrouter doctor opus \"深度分析我的配置问题\"\n\nEnvironment Variables:\n BLOCKRUN_WALLET_KEY Private key for x402 payments (auto-generated if not set)\n BLOCKRUN_PROXY_PORT Default proxy port (default: 8402)\n\nFor more info: https://github.com/BlockRunAI/ClawRouter\n`);\n}\n\nfunction parseArgs(args: string[]): {\n version: boolean;\n help: boolean;\n doctor: boolean;\n partners: boolean;\n partnersTest: boolean;\n report: boolean;\n reportPeriod: \"daily\" | \"weekly\" | \"monthly\";\n reportJson: boolean;\n walletRecover: boolean;\n chain?: \"solana\" | \"base\";\n port?: number;\n} {\n const result = {\n version: false,\n help: false,\n doctor: false,\n partners: false,\n partnersTest: false,\n report: false,\n reportPeriod: \"daily\" as \"daily\" | \"weekly\" | \"monthly\",\n reportJson: false,\n walletRecover: false,\n chain: undefined as \"solana\" | \"base\" | undefined,\n port: undefined as number | undefined,\n };\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"--version\" || arg === \"-v\") {\n result.version = true;\n } else if (arg === \"--help\" || arg === \"-h\") {\n result.help = true;\n } else if (arg === \"doctor\" || arg === \"--doctor\") {\n result.doctor = true;\n } else if (arg === \"partners\") {\n result.partners = true;\n // Check for \"test\" subcommand\n if (args[i + 1] === \"test\") {\n result.partnersTest = true;\n i++;\n }\n } else if (arg === \"report\") {\n result.report = true;\n const next = args[i + 1];\n if (next && [\"daily\", \"weekly\", \"monthly\"].includes(next)) {\n result.reportPeriod = next as \"daily\" | \"weekly\" | \"monthly\";\n i++;\n if (args[i + 1] === \"--json\") {\n result.reportJson = true;\n i++;\n }\n } else if (next === \"--json\") {\n result.reportJson = true;\n i++;\n }\n } else if (arg === \"wallet\" && args[i + 1] === \"recover\") {\n result.walletRecover = true;\n i++;\n } else if (\n (arg === \"chain\" || arg === \"/wallet\" || arg === \"wallet\") &&\n (args[i + 1] === \"solana\" || args[i + 1] === \"base\")\n ) {\n result.chain = args[i + 1] as \"solana\" | \"base\";\n i++;\n } else if (arg === \"--port\" && args[i + 1]) {\n result.port = parseInt(args[i + 1], 10);\n i++; // Skip next arg\n }\n }\n\n return result;\n}\n\nasync function main(): Promise {\n const args = parseArgs(process.argv.slice(2));\n\n if (args.version) {\n console.log(VERSION);\n process.exit(0);\n }\n\n if (args.help) {\n printHelp();\n process.exit(0);\n }\n\n if (args.doctor) {\n // Parse: doctor [opus|sonnet] [question...]\n const rawArgs = process.argv.slice(2);\n const doctorIndex = rawArgs.findIndex((a) => a === \"doctor\" || a === \"--doctor\");\n const afterDoctor = rawArgs.slice(doctorIndex + 1);\n\n // Check if first arg is model selection\n let model: \"sonnet\" | \"opus\" = \"sonnet\"; // default to cheaper\n let questionArgs = afterDoctor;\n\n if (afterDoctor[0] === \"opus\") {\n model = \"opus\";\n questionArgs = afterDoctor.slice(1);\n } else if (afterDoctor[0] === \"sonnet\") {\n model = \"sonnet\";\n questionArgs = afterDoctor.slice(1);\n }\n\n const userQuestion = questionArgs.join(\" \").trim() || undefined;\n await runDoctor(userQuestion, model);\n process.exit(0);\n }\n\n if (args.partners) {\n if (PARTNER_SERVICES.length === 0) {\n console.log(\"No partner APIs available.\");\n process.exit(0);\n }\n\n console.log(`\\nClawRouter Partner APIs (v${VERSION})\\n`);\n\n for (const svc of PARTNER_SERVICES) {\n console.log(` ${svc.name} (${svc.partner})`);\n console.log(` ${svc.description}`);\n console.log(` Tool: blockrun_${svc.id}`);\n console.log(` Method: ${svc.method} /v1${svc.proxyPath}`);\n console.log(\n ` Pricing: ${svc.pricing.perUnit} per ${svc.pricing.unit} (min ${svc.pricing.minimum}, max ${svc.pricing.maximum})`,\n );\n console.log();\n }\n\n if (args.partnersTest) {\n console.log(\"Testing partner endpoints...\\n\");\n const apiBase = \"https://blockrun.ai/api\";\n for (const svc of PARTNER_SERVICES) {\n const url = `${apiBase}/v1${svc.proxyPath}`;\n try {\n const response = await fetch(url, { method: \"GET\" });\n const status = response.status;\n const ok = status === 402 ? \"alive (402 = payment required)\" : `status ${status}`;\n console.log(` ${svc.id}: ${ok}`);\n } catch (err) {\n console.log(` ${svc.id}: error - ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n console.log();\n }\n\n process.exit(0);\n }\n\n if (args.walletRecover) {\n await recoverWalletFromMnemonic();\n process.exit(0);\n }\n\n if (args.chain) {\n await savePaymentChain(args.chain);\n console.log(`[ClawRouter] Payment chain set to: ${args.chain}`);\n console.log(`[ClawRouter] This persists across restarts.`);\n console.log(`[ClawRouter] Run: npx @blockrun/clawrouter`);\n process.exit(0);\n }\n\n if (args.report) {\n const report = await generateReport(args.reportPeriod, args.reportJson);\n console.log(report);\n process.exit(0);\n }\n\n // Resolve wallet key\n const wallet = await resolveOrGenerateWalletKey();\n\n if (wallet.source === \"generated\") {\n console.log(`[ClawRouter] Generated new wallet: ${wallet.address}`);\n } else if (wallet.source === \"saved\") {\n console.log(`[ClawRouter] Using saved wallet: ${wallet.address}`);\n } else {\n console.log(`[ClawRouter] Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);\n }\n\n // Show Solana address if available\n if (wallet.solanaPrivateKeyBytes) {\n try {\n const solAddr = await getSolanaAddress(wallet.solanaPrivateKeyBytes);\n console.log(`[ClawRouter] Solana address: ${solAddr}`);\n } catch {\n // Non-fatal\n }\n }\n\n // Start the proxy\n const proxy = await startProxy({\n wallet,\n port: args.port,\n onReady: (port) => {\n console.log(`[ClawRouter] v${VERSION} | Proxy listening on http://127.0.0.1:${port}`);\n console.log(`[ClawRouter] Health check: http://127.0.0.1:${port}/health`);\n },\n onError: (error) => {\n console.error(`[ClawRouter] Error: ${error.message}`);\n },\n onRouted: (decision) => {\n const cost = decision.costEstimate.toFixed(4);\n const saved = (decision.savings * 100).toFixed(0);\n console.log(`[ClawRouter] [${decision.tier}] ${decision.model} $${cost} (saved ${saved}%)`);\n },\n onLowBalance: (info) => {\n console.warn(`[ClawRouter] Low balance: ${info.balanceUSD}. Fund: ${info.walletAddress}`);\n },\n onInsufficientFunds: (info) => {\n console.error(\n `[ClawRouter] Insufficient funds. Balance: ${info.balanceUSD}, Need: ${info.requiredUSD}`,\n );\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n },\n });\n\n // Check balance on the active payment chain\n const paymentChain = await resolvePaymentChain();\n const displayAddress =\n paymentChain === \"solana\" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address;\n try {\n const balance = await proxy.balanceMonitor.checkBalance();\n if (balance.isEmpty) {\n console.log(`[ClawRouter] Wallet balance: $0.00 (using FREE model)`);\n console.log(`[ClawRouter] Fund wallet for premium models: ${displayAddress}`);\n } else if (balance.isLow) {\n console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD} (low)`);\n } else {\n console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD}`);\n }\n // Invalidate after display so the first real request always gets a fresh check.\n // Prevents a flaky RPC at startup from caching a false $0.00 and triggering\n // free-model fallback on the first request.\n proxy.balanceMonitor.invalidate();\n } catch {\n console.log(`[ClawRouter] Wallet: ${displayAddress} (balance check pending)`);\n }\n\n console.log(`[ClawRouter] Ready - Ctrl+C to stop`);\n\n // Handle graceful shutdown\n const shutdown = async (signal: string) => {\n console.log(`\\n[ClawRouter] Received ${signal}, shutting down...`);\n try {\n await proxy.close();\n console.log(`[ClawRouter] Proxy closed`);\n process.exit(0);\n } catch (err) {\n console.error(`[ClawRouter] Error during shutdown: ${err}`);\n process.exit(1);\n }\n };\n\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n\n // Keep process alive\n await new Promise(() => {});\n}\n\nmain().catch((err) => {\n console.error(`[ClawRouter] Fatal error: ${err.message}`);\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa;AAAb;;;AAAO,IAAM,UAAU;;;;;ACCvB,IASa;AATb;;;;AASM,IAAO,YAAP,MAAO,mBAAkB,MAAK;MAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,cAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,cAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,cAAM,UAAU;UACd,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,IAAI,8BAA8B,YAAY;EACxE;AACA,SAAO;AACT;AApGA,IAAAC,sBAAA;;;;AAIA;AAIA;AAYA;AACA;;;;;ACrBA,IAAa,SACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WAEA,SACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WAEA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA;AAjGb;;;AAAO,IAAM,UAAU,OAAO,KAAK,MAAM;AAClC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC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IA,8CACA,qDACA,yDACA,qDACA,wCACA,qDACA,2DACA,uDACA,uDACA,8DACA,mDACA,oDAIA,2CACA,wDACA,kDACA,kDACA,6DAIA,6DACA,mDACA,8DACA,4DACA,8DACA,0DACA,4DACA,gEAIA,4DAIA,kDACA,qDACA,mDACA,0DACA,uDAIA,sDACA,kDACA,gDAKA,0CACA,gDACA,mDACA,2DACA,uDACA,yDACA,qDACA,uDACA,6DACA,8DACA,wDACA,yDACA,sDACA,iEACA,iEACA,0DACA,yDACA,0DACA,sDACA,sDACA,0DACA,4DACA,yDACA,wDACA,6DACA,gEACA,yCACA,gDACA,2DACA,4DACA,qEACA,yDACA,6CACA,kDACA,yDACA,2DACA,gDACA,kDACA,gEACA,uDACA,oEACA,6DACA,4DACA,4CACA,sDACA,iDACA,0DACA,wDACA,sDACA,qDACA,gDACA,yEACA,wDACA,wEACA,8EAIA,4DACA,gDACA,+CACA,yDACA,uDACA,mDACA,6DACA,2DACA,2DACA,wEACA,0DACA,sDAIA,yDACA,8EACA,+EACA,wEACA,yDACA,qEACA,8DACA,yDACA,yDACA,2DACA,wEACA,oDACA,2DACA,wEACA,oDACA,4DACA,4DACA,gEAIA,6DACA,kEACA,wDACA,oDACA,wDACA,sFACA,wFACA,sFACA,kEACA,+CACA,4CACA,8CACA,wDACA,2EACA,8FACA,8DACA,gEACA,wDACA,6DACA,6EACA,+CACA,yDACA,oEAKA,0CACA,iDACA,uDACA,oDACA,4DACA,6DACA,0DACA,oDACA,sDAEA,sDACA,4DACA,wDACA,oDACA,gEACA,mDACA,sDACA,6DACA,oEACA,sDACA,2DACA,sEACA,wEACA,yDACA,iEACA,qEACA,oEACA,qEACA,8DACA,mEACA,wEACA,wDACA,8DACA,yEACA,0EACA,wDACA,2EACA,yDAIA,kEACA,kEACA,yDACA,qEACA,gFACA,kFACA,8DACA,8DACA,qEACA,8EAIA,sDACA,2CACA,6CACA,gDACA,mEACA,2DACA,yDACA,+CACA,uDACA,2DACA,4CACA,2CACA,+CAC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AC5E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["docsPath","signature","signature","signature","signature","signature","abi","signature","signature","signature","length","formatAbiItem","init_formatAbiItem","version","init_version","BaseError","init_version","docsPath","version","init_formatAbiItem","BaseError","docsPath","size","signature","formatAbiItem","BaseError","size","size","BaseError","size","size","size","index","BaseError","encoder","l","s","crypto","toBytes","pad","crypto","init_utils","s","init_utils","l","toBytes","signature","BaseError","BaseError","address","size","hash","address","address","cacheKey","concatBytes","bytesRegex","integerRegex","init_regex","size","integerRegex","length","BaseError","index","init_regex","abi","index","abi","docsPath","formatAbiItem","init_formatAbiItem","abi","signature","BaseError","init_cursor","size","data","length","consumed","value","size","init_cursor","abi","signature","formatAbiItem","init_formatAbiItem","value","address","BaseError","BaseError","docsPath","chain","hash","index","init_utils","address","init_formatAbiItem","init_utils","BaseError","docsPath","chain","abi","formatAbiItem","signature","init_utils","BaseError","BaseError","docsPath","isLE","_32n","l","init_utils","toBytes","buffer","finished","init_utils","D","init_utils","hash","toBytes","pad","finished","isBytes","abytes","num","hexToNumber","_0n","bytesToHex","hexes","hexToBytes","e","concatBytes","pad","utf8ToBytes","_1n","gen","init_utils","_0n","modulo","_1n","gcd","_2n","P","num","bitLen","isLE","init_utils","_1n","s","P","_0n","base","wbits","init_utils","num","size","bytesToHex","Fn","toBytes","concatBytes","fromBytes","_3n","_4n","_1n","isBytes","Point","P","endo","_0n","a","modN","s","from","l","hexToBytes","utils","hash","randomBytes","e","sign","signature","isHex","o","_2n","tv5","c1","c2","init_utils","hash","create","init_utils","abytes","concatBytes","utf8ToBytes","hash","e","createHasher","Point","num","P","init_utils","P","_3n","_2n","concatBytes","_1n","_0n","e","signature","s","init_utils","createHasher","BaseError","BaseError","e","formatted","address","init_stateOverride","abi","docsPath","isBytes","abytes","abool","numberToHexUnpadded","num","hexToNumber","_0n","bytesToHex","hasHexBuiltin","hexes","asciiToBase16","asciis","hexToBytes","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","e","concatBytes","pad","inRange","isPosBig","aInRange","bitLen","_1n","createHmacDrbg","u8n","u8fr","gen","validateObject","validatorFns","memoized","bitMask","init_utils","version","init_version","version","init_errors","init_version","walk","BaseError","init_errors","docsPath","version","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","charCodeToBase16","charCodeMap","pad","SizeExceedsPaddingSizeError","trim","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","pad","SizeExceedsPaddingSizeError","trim","stringify","value","size","assertSize","index","charCodeToBase16","BaseError","encoder","padRight","pad","slice","assertStartOffset","assertEndOffset","toBigInt","InvalidBytesBooleanError","toNumber","trim","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","stringify","assert","concat","from","assertSize","hexes","size","IntegerOutOfRangeError","fromString","encoder","pad","slice","assertStartOffset","assertEndOffset","trimLeft","trim","validate","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","BaseError","stringify","toRpc","init_contract","BaseError","chain","abi","docsPath","chain","docsPath","cause","wait","args","split","init_utils","BaseError","abi","signature","formatAbiItem","init_formatAbiItem","abi","docsPath","formatAbiItem","signature","init_formatAbiItem","abi","docsPath","ccipRequest","init_ccip","BaseError","toRpc","base","data","offchainLookup","offchainLookupSignature","wait","args","size","init_contract","init_stateOverride","e","isSolanaError","index","ORDERED_ERROR_NAMES","padBytes","slice","index","encoder","decoder","SolanaError","size","buffer","alphabet","base","charCodeToBase16","TextDecoder","TextEncoder","createEncoder","SolanaError","SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE","hexBytes","createDecoder","combineCodec","buffer","decoder","address","index","SolanaError","SolanaError","isAddress","base58Encoder","mod","pow2","SolanaError","address","e","encode","decode","Endian","combineCodec","createEncoder","createDecoder","size","newOffset","createEncoder","createDecoder","slice","combineCodec","getBase16Decoder","SolanaError","index","getEncodedSize","isFixedSize","getU8Encoder","transformEncoder","getU8Decoder","transformDecoder","l","encoder","decoder","containsBytes","init_index_node","AccountRole","isAddress","SolanaError","combineCodec","assertValidBaseString","alphabet","SolanaError","partitionLeadingZeroes","getBigIntFromBaseX","base","getBaseXFromBigInt","getU8Encoder","getU8Decoder","getStructEncoder","getStructDecoder","getArrayEncoder","getShortU16Encoder","getArrayDecoder","getShortU16Decoder","createEncoder","createDecoder","version","combineCodec","transformEncoder","getBase58Encoder","getAddressEncoder","getAddressDecoder","getBase58Decoder","transformDecoder","address","TYPE","index","AccountRole","getAddressComparator","isWritableRole","isSignerRole","l","getBaseXEncoder","getBaseXDecoder","SolanaError","signature","randomBytes","privateKey","signature","getBytesEncoder","SolanaError","address","index","SYSTEM_PROGRAM_ADDRESS","isAdvanceNonceAccountInstructionData","isAddress","signatureBytes","signTransaction","SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT","index","appendTransactionMessageInstruction","SolanaError","signature","context","traverse","traverseSequential","traverseParallel","traverseSingle","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND","candidate","message","appendTransactionMessageInstructions","getAbortablePromise","getTransactionMessageSize","TRANSACTION_SIZE_LIMIT","isSolanaError","SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND","isAddress","version","SolanaError","transformEncoder","getAddressDecoder","getSignaturesToEncode","signature","getSignaturesEncoder","getU8Encoder","getStructEncoder","getBytesEncoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO","address","transformDecoder","getStructDecoder","getArrayDecoder","getBytesDecoder","getU8Decoder","combineCodec","index","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO","getArrayEncoder","getAddressEncoder","getUtf8Encoder","fixDecoderSize","getTupleDecoder","getUtf8Decoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY","getTupleEncoder","getHiddenPrefixDecoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED","encoder","SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE","signatureBytes","OffchainMessageContentFormat","unwrapBigIntValueObject","wrapBigIntValueObject","traverse","pipe","SolanaError","stringify","e","normalizeHeaders","AbortController","args","setMaxListeners","init_index_node","createExplicitAbortToken","e","EXPLICIT_ABORT_TOKEN","AbortController","EventTarget","args","setMaxListeners","e","SolanaError","AbortController","args","setMaxListeners","getAllowedNumericKeypaths","memoizedKeypaths","concat","buffer","toArrayBuffer","e","num","data","e","concat","toArrayBuffer","Receiver","num","Sender","http","randomBytes","createHash","URL","Receiver","Sender","WebSocket","address","e","key","WebSocket","createWebSocketStream","err","open","protocol","http","createHash","WebSocket","WebSocketServer","index","version","WebSocket","s","EventTarget","index_node_default","args","setMaxListeners","WebSocketImpl","createSolanaJsonRpcIntegerOverflowError","e","index","pipe","transformChannelInboundMessages","transformChannelOutboundMessages","cache","AbortController","args","setMaxListeners","SolanaError","address","isAddress","offchainMessageEnvelope","SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING","signature","transaction","o","TextEncoder","e","base58Decoder","SolanaError","signature","safeRace","getTimeoutPromise","AbortController","args","setMaxListeners","lamports","l","createRecentSignatureConfirmationPromiseFactory","signature","e","commitmentComparator","CACHE_TTL_MS","init_index_node","fixDecoderSize","getBytesDecoder","getStructDecoder","getU64Decoder","getU16Decoder","getOptionDecoder","getAddressDecoder","getU32Decoder","getBooleanDecoder","address","isTransactionSigner","kitIsTransactionSigner","getAddressEncoder","transformEncoder","getStructEncoder","getU8Encoder","getU64Encoder","AccountRole","ASSOCIATED_TOKEN_ERROR__INVALID_OWNER","associatedTokenErrorMessages","AccountState","init_index_node","transformEncoder","getStructEncoder","getU8Encoder","getU32Encoder","appendTransactionMessageInstruction","init_src","init_index_node","x402Version","tx","NETWORKS","init_src","init_index_node","x402Version","tx","NETWORKS","homedir","join","mkdir","writeFile","readFileSync","BaseError","init_formatAbiItem","abi","formatAbiItem","signature","address","abi","abi","address","docsPath","BaseError","err","address","hash","signature","secp256k1","s","yParityOrV","recoveryBit","hash","signature","init_cursor","encode","BaseError","address","hash","signature","BaseError","docsPath","chain","docsPath","cause","init_stateOverride","BaseError","BaseError","formatAuthorizationList","chain","chain","base","address","sha256","sha256","version","sha256","version","BaseError","size","hash","version","init_cursor","size","docsPath","cause","chain","format","base","chain","prepareTransactionRequest","getChainId","chainId","from","gas","nonce","type","e","error","getBlock","block","BaseError","abi","address","init_formatAbiItem","docsPath","abi","signature","formatAbiItem","abi","isEqual","index","value","input","address","event","abi","address","abi","address","abi","address","listeners","cleanup","poll","cacheKey","cache","abi","address","transport","eventName","args","shouldRetry","size","chain","base","key","BaseError","e","hash","hash","chain","address","BaseError","res","chain","address","chain","chain","address","event","address","address","address","BaseError","address","address","version","e","address","hash","version","BaseError","address","signature","blobs","commitments","proofs","v","s","signature","address","signature","promiseCache","uid","BaseError","chain","base","body","response","BaseError","init_regex","integerRegex","base","bytesRegex","struct","assert","from","validate","LruMap","size","LruMap","keccak256","assert","from","validate","fromHex","fromBytes","assert","x","slice","prefix","toHex","assert","concat","BaseError","stringify","size","from","addressRegex","assert","InvalidAddressError","checksum","address","hash","keccak256","from","toHex","validate","address","assert","InvalidAddressError","BaseError","bytesRegex","integerRegex","maxInt8","maxInt16","maxInt24","maxInt32","maxInt40","maxInt48","maxInt56","maxInt64","maxInt72","maxInt80","maxInt88","maxInt96","maxInt104","maxInt112","maxInt120","maxInt128","maxInt136","maxInt144","maxInt152","maxInt160","maxInt168","maxInt176","maxInt184","maxInt192","maxInt200","maxInt208","maxInt216","maxInt224","maxInt232","maxInt240","maxInt248","maxInt256","minInt8","minInt16","minInt24","minInt32","minInt40","minInt48","minInt56","minInt64","minInt72","minInt80","minInt88","minInt96","minInt104","minInt112","minInt120","minInt128","minInt136","minInt144","minInt152","minInt160","minInt168","minInt176","minInt184","minInt192","minInt200","minInt208","minInt216","minInt224","minInt232","minInt240","minInt248","minInt256","maxUint8","maxUint16","maxUint24","maxUint32","maxUint40","maxUint48","maxUint56","maxUint64","maxUint72","maxUint80","maxUint88","maxUint96","maxUint104","maxUint112","maxUint120","maxUint128","maxUint136","maxUint144","maxUint152","maxUint160","maxUint168","maxUint176","maxUint184","maxUint192","maxUint200","maxUint208","maxUint216","maxUint224","maxUint232","maxUint240","maxUint248","maxUint256","decodeParameter","checksumAddress","getArrayComponents","decodeArray","decodeTuple","decodeAddress","decodeBool","decodeBytes","decodeNumber","decodeString","sizeOfLength","sizeOfOffset","checksum","wrap","address","slice","toNumber","length","hasDynamicChild","consumed","value","size","toBigInt","encodeArray","encodeTuple","encodeAddress","integerRegex","encodeNumber","encodeBytes","encodeString","concat","assert","InvalidArrayError","BytesSizeMismatchError","BaseError","IntegerOutOfRangeError","fromString","index","staticCursor","RecursiveReadLimitExceededError","PositionOutOfBoundsError","NegativeOffsetError","size","BaseError","checksumAddress","size","data","decodeParameter","encode","concat","encodePacked","address","assert","fromString","integerRegex","bytesRegex","BytesSizeMismatchError","from","BaseError","size","BytesSizeMismatchError","InvalidArrayError","from","getEncodable","fromHex","from","getEncodable","getEncodableList","getEncodableBytes","getSizeOfLength","encode","BaseError","init_utils","init_utils","_0n","_1n","_2n","_3n","_4n","_5n","_8n","mod","pow2","modulo","_0n","invert","mod","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","tonelliShanks","P","Field","FpLegendre","FpSqrt","_3n","FIELD_FIELDS","validateField","validateObject","FpPow","num","_0n","_1n","FpInvertBatch","FpLegendre","_1n","_2n","nLength","Field","bitLen","isLE","_0n","bitMask","_1n","num","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","num","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","init_utils","_0n","_1n","constTimeNegate","validateW","calcWOpts","bitMask","calcOffsets","validateMSMPoints","validateMSMScalars","s","pointPrecomputes","pointWindowSizes","getW","P","wNAF","base","pippenger","bitLen","wbits","validateBasic","validateField","validateObject","nLength","init_utils","validateSigVerOpts","abool","validatePointOpts","validateBasic","validateObject","DERErr","DER","numberToHexUnpadded","num","_0n","bytesToNumberBE","ensureBytes","numToSizedHex","size","bytesToHex","numberToBytesBE","_1n","_2n","_3n","_4n","weierstrassPoints","Fn","Field","toBytes","concatBytes","fromBytes","inRange","isBytes","mod","aInRange","Point","memoized","FpInvertBatch","P","pippenger","endo","a","wNAF","validateOpts","weierstrass","modN","invert","s","from","l","hexToBytes","utils","getMinHashLength","mapHashToField","bitMask","hash","randomBytes","e","sign","createHmacDrbg","signature","isHex","getHash","hash","createCurve","create","weierstrass","secp256k1P","secp256k1N","_0n","_1n","_2n","divNearest","sqrtMod","P","_3n","pow2","Fpk1","Field","secp256k1","createCurve","mod","assert","signature","maxUint256","fromBytes","fromHex","InvalidSerializedSizeError","slice","s","yParity","extract","from","fromRpc","signature","fromRpc","yParity","signature","s","trimLeft","InvalidSerializedSizeError","BaseError","signature","size","from","stringify","from","fromRpc","address","signature","extract","hash","keccak256","concat","fromHex","toTuple","toTuple","address","signature","extract","recoverAddress","recoverPublicKey","signature","s","secp256k1","from","from","assert","slice","signature","recoverAddress","encode","size","concat","validate","BaseError","address","address","hash","index","hash","hash","contracts","abi","address","result","BaseError","init_stateOverride","block","toRpc","call","abi","result","error","e","normalizeSignature","signature","BaseError","isArgOfType","validate","index","getAmbiguousTypes","from","abi","validate","abiItem","slice","index","isArgOfType","getAmbiguousTypes","signature","normalizeSignature","keccak256","fromString","BaseError","encode","abi","options","fromAbi","concat","from","fromAbi","abi","item","encodeData","abi","args","fromAbi","abiFunction","getSelector","encode","concat","from","fromAbi","abi","getSelector","BaseError","encode","from","encodeData","call","address","InvalidWrappedSignatureError","assert","from","magicBytes","unwrap","validate","wrap","magicBytes","assert","slice","InvalidWrappedSignatureError","from","unwrap","signature","wrap","concat","encode","validate","BaseError","s","signature","address","chain","hash","signature","address","signature","hash","address","signature","hash","transport","hash","from","block","transport","address","transport","event","args","hash","address","address","signature","hash","uid","BaseError","chain","wait","body","serializeTransaction","signature","from","isBytes","anumber","wrap","encode","decode","l","from","from","anumber","padding","num","isBytes","checksum","anumber","isBytes","init_utils","hash","init_utils","wordlist","e","hash","s","signature","address","signature","signature","address","hash","decoder","x402Version","fetch","cache","cacheKey","payload","response","randomBytes","x402Version","signature","version","x402Version","signature","version","getAddress","getAddress","signature","from","encodeFunctionData","x402Version","readContract","signTransaction","getTransactionCount","estimateFeesPerGas","confidence","supportsToolCalling","supportsVision","decision","join","size","join","homedir","join","require","LOG_DIR","join","homedir","e","LOG_DIR","join","DEFAULT_TTL_MS","createHash","canonicalize","TIMESTAMP_PATTERN","RpcError","RpcError","mkdir","join","homedir","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","hasHexBuiltin","hexes","bytesToHex","abytes","asciis","asciiToBase16","hexToBytes","concatBytes","abytes","pad","createHasher","randomBytes","Chi","Maj","HashMD","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","SHA256_IV","SHA256_K","SHA256_W","HashMD","D","rotr","Chi","Maj","clean","SHA256_IV","sha256","createHasher","_0n","_1n","abool","isPosBig","anumber","numberToHexUnpadded","num","hexToNumber","_0n","bytesToNumberBE","bytesToHex","bytesToNumberLE","abytes","numberToBytesBE","anumber","hexToBytes","numberToBytesLE","isPosBig","_0n","inRange","aInRange","bitLen","_1n","bitMask","_1n","createHmacDrbg","anumber","u8n","concatBytes","gen","validateObject","memoized","_0n","_1n","_2n","_3n","_4n","_5n","_7n","_8n","mod","pow2","modulo","_0n","invert","mod","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","P","Field","tonelliShanks","_7n","e2","e3","_3n","FpLegendre","FpSqrt","FIELD_FIELDS","validateField","validateObject","FpPow","num","_0n","_1n","FpInvertBatch","FpLegendre","_1n","_2n","nLength","anumber","_0n","_1n","num","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","abytes","isLE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","Field","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","abytes","num","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","_0n","_1n","FpInvertBatch","validateW","calcWOpts","bitMask","calcOffsets","pointPrecomputes","pointWindowSizes","getW","P","_0n","wNAF","Point","_1n","calcWOpts","base","calcOffsets","validateW","isLE","validateField","Field","_0n","Fn","hash","ahash","abytes","pad","clean","aexists","finished","hmac","divNearest","num","_2n","_0n","bitMask","bitLen","_1n","abool","DERErr","DER","numberToHexUnpadded","bytesToNumberBE","abytes","_3n","_4n","weierstrass","Fn","validateObject","pointToBytes","concatBytes","Point","memoized","P","hexToBytes","endo","bytesToHex","wNAF","Fn","Point","randomBytes","getMinHashLength","num","l","mapHashToField","abytes","isBytes","s","utils","hash","ahash","validateObject","hmac","_2n","_1n","size","r","DER","hexToBytes","concatBytes","bytesToHex","bytesToNumberBE","bitMask","aInRange","_0n","extraEntropy","e","sign","createHmacDrbg","signature","P","recoverPublicKey","_2n","sqrtMod","P","_3n","pow2","Fpk1","Field","weierstrass","secp256k1","sha256","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","concatBytes","abytes","pad","createHasher","oidNist","_HMAC","hash","ahash","abytes","pad","clean","aexists","finished","hmac","Chi","Maj","HashMD","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","SHA256_IV","SHA512_IV","HashMD","clean","createHasher","U32_MASK64","_32n","fromBig","split","l","shrSH","s","shrSL","l","rotrSH","rotrSL","rotrBH","rotrBL","add","l","add3L","add3H","add4L","add4H","add5L","add5H","SHA256_K","SHA256_W","SHA2_32B","HashMD","D","rotr","Chi","Maj","clean","_SHA256","SHA256_IV","K512","split","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","HashMD","rotrSH","shrSH","rotrSL","shrSL","rotrBH","rotrBL","add4L","add4H","add5L","add5H","add","add3L","add3H","clean","SHA512_IV","sha256","createHasher","_SHA256","oidNist","sha512","createHasher","oidNist","isBytes","isArrayOf","afn","astr","anumber","aArr","astrArr","anumArr","chain","wrap","encode","decode","alphabet","l","join","from","convertRadix","from","aArr","anumber","radix","num","anumber","isBytes","convertRadix","anumArr","checksum","anumber","afn","isBytes","chain","radix","alphabet","join","sha256","chain","checksum","Point","secp256k1","sha256","createView","concatBytes","abytes","hmac","sha512","version","index","hash","signature","sha512","sha512","index","createKeyPairSignerFromPrivateKeyBytes","join","homedir","mkdir","chain","mkdir","crypto","hashMessage","hash","l","escapeRegex","originalChars","createHash","hash","join","dirname","homedir","join","homedir","DEFAULT_CONFIG","e","join","homedir","sanitized","size","readFileSync","buffer","account","baseUrl","createKeyPairSignerFromPrivateKeyBytes","balanceMonitor","SolanaBalanceMonitor","registerExactSvmScheme","chain","responseCache","s","mkdir","port","writeFile","normalizedModel","cacheKey","index","address","SolanaBalanceMonitor","chain"]} \ No newline at end of file +{"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/abitype/src/human-readable/parseAbiItem.ts","../node_modules/abitype/src/human-readable/parseAbiParameters.ts","../node_modules/abitype/src/exports/index.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/version.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/errors/data.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/@noble/hashes/src/_u64.ts","../node_modules/@noble/hashes/src/cryptoNode.ts","../node_modules/@noble/hashes/src/utils.ts","../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/toEventSelector.ts","../node_modules/viem/errors/address.ts","../node_modules/viem/utils/lru.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/address/isAddress.ts","../node_modules/viem/utils/data/concat.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/regex.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/utils/hash/toFunctionSelector.ts","../node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/viem/constants/solidity.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/utils/encoding/fromBytes.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/abi/formatAbiItemWithArgs.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/errors/request.ts","../node_modules/viem/errors/rpc.ts","../node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/hashes/src/sha2.ts","../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","../node_modules/viem/errors/node.ts","../node_modules/viem/utils/errors/getNodeError.ts","../node_modules/viem/utils/formatters/extract.ts","../node_modules/viem/utils/formatters/formatter.ts","../node_modules/viem/utils/formatters/transactionRequest.ts","../node_modules/viem/utils/stateOverride.ts","../node_modules/viem/constants/number.ts","../node_modules/viem/utils/transaction/assertRequest.ts","../node_modules/viem/utils/address/isAddressEqual.ts","../node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/ox/core/version.ts","../node_modules/ox/core/internal/errors.ts","../node_modules/ox/core/Errors.ts","../node_modules/ox/core/internal/bytes.ts","../node_modules/ox/core/internal/hex.ts","../node_modules/ox/core/Json.ts","../node_modules/ox/core/Bytes.ts","../node_modules/ox/core/Hex.ts","../node_modules/ox/core/Withdrawal.ts","../node_modules/ox/core/BlockOverrides.ts","../node_modules/viem/constants/abis.ts","../node_modules/viem/constants/contract.ts","../node_modules/viem/constants/contracts.ts","../node_modules/viem/errors/chain.ts","../node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/viem/utils/errors/getCallError.ts","../node_modules/viem/utils/promise/withResolvers.ts","../node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/viem/errors/ccip.ts","../node_modules/viem/utils/abi/decodeFunctionData.ts","../node_modules/viem/utils/abi/encodeErrorResult.ts","../node_modules/viem/utils/abi/encodeFunctionResult.ts","../node_modules/viem/utils/ens/localBatchGatewayRequest.ts","../node_modules/viem/utils/ccip.ts","../node_modules/viem/actions/public/call.ts","../node_modules/@solana/errors/src/codes.ts","../node_modules/@solana/errors/src/context.ts","../node_modules/@solana/errors/src/messages.ts","../node_modules/@solana/errors/src/message-formatter.ts","../node_modules/@solana/errors/src/error.ts","../node_modules/@solana/errors/src/stack-trace.ts","../node_modules/@solana/errors/src/rpc-enum-errors.ts","../node_modules/@solana/errors/src/instruction-error.ts","../node_modules/@solana/errors/src/transaction-error.ts","../node_modules/@solana/errors/src/json-rpc-error.ts","../node_modules/@solana/errors/src/simulation-errors.ts","../node_modules/@solana/codecs-core/src/bytes.ts","../node_modules/@solana/codecs-core/src/codec.ts","../node_modules/@solana/codecs-core/src/combine-codec.ts","../node_modules/@solana/codecs-core/src/add-codec-sentinel.ts","../node_modules/@solana/codecs-core/src/assertions.ts","../node_modules/@solana/codecs-core/src/add-codec-size-prefix.ts","../node_modules/@solana/codecs-core/src/array-buffers.ts","../node_modules/@solana/codecs-core/src/decoder-entire-byte-array.ts","../node_modules/@solana/codecs-core/src/fix-codec-size.ts","../node_modules/@solana/codecs-core/src/offset-codec.ts","../node_modules/@solana/codecs-core/src/resize-codec.ts","../node_modules/@solana/codecs-core/src/pad-codec.ts","../node_modules/@solana/codecs-core/src/reverse-codec.ts","../node_modules/@solana/codecs-core/src/transform-codec.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base10.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/codecs-strings/src/baseX-reslice.ts","../node_modules/@solana/codecs-strings/src/base64.ts","../node_modules/@solana/codecs-strings/src/null-characters.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/codecs-strings/src/utf8.ts","../node_modules/@solana/accounts/src/account.ts","../node_modules/@solana/accounts/src/decode-account.ts","../node_modules/@solana/accounts/src/parse-account.ts","../node_modules/@solana/accounts/src/fetch-account.ts","../node_modules/@solana/accounts/src/maybe-account.ts","../node_modules/@solana/assertions/src/crypto.ts","../node_modules/@solana/assertions/src/subtle-crypto.ts","../node_modules/@solana/addresses/src/address.ts","../node_modules/@solana/addresses/src/vendor/noble/ed25519.ts","../node_modules/@solana/addresses/src/curve-internal.ts","../node_modules/@solana/addresses/src/curve.ts","../node_modules/@solana/addresses/src/program-derived-address.ts","../node_modules/@solana/addresses/src/public-key.ts","../node_modules/@solana/codecs-numbers/src/assertions.ts","../node_modules/@solana/codecs-numbers/src/common.ts","../node_modules/@solana/codecs-numbers/src/utils.ts","../node_modules/@solana/codecs-numbers/src/f32.ts","../node_modules/@solana/codecs-numbers/src/f64.ts","../node_modules/@solana/codecs-numbers/src/i128.ts","../node_modules/@solana/codecs-numbers/src/i16.ts","../node_modules/@solana/codecs-numbers/src/i32.ts","../node_modules/@solana/codecs-numbers/src/i64.ts","../node_modules/@solana/codecs-numbers/src/i8.ts","../node_modules/@solana/codecs-numbers/src/short-u16.ts","../node_modules/@solana/codecs-numbers/src/u128.ts","../node_modules/@solana/codecs-numbers/src/u16.ts","../node_modules/@solana/codecs-numbers/src/u32.ts","../node_modules/@solana/codecs-numbers/src/u64.ts","../node_modules/@solana/codecs-numbers/src/u8.ts","../node_modules/@solana/codecs-data-structures/src/assertions.ts","../node_modules/@solana/codecs-data-structures/src/utils.ts","../node_modules/@solana/codecs-data-structures/src/array.ts","../node_modules/@solana/codecs-data-structures/src/bit-array.ts","../node_modules/@solana/codecs-data-structures/src/boolean.ts","../node_modules/@solana/codecs-data-structures/src/bytes.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-data-structures/src/constant.ts","../node_modules/@solana/codecs-data-structures/src/tuple.ts","../node_modules/@solana/codecs-data-structures/src/union.ts","../node_modules/@solana/codecs-data-structures/src/discriminated-union.ts","../node_modules/@solana/codecs-data-structures/src/enum-helpers.ts","../node_modules/@solana/codecs-data-structures/src/enum.ts","../node_modules/@solana/codecs-data-structures/src/hidden-prefix.ts","../node_modules/@solana/codecs-data-structures/src/hidden-suffix.ts","../node_modules/@solana/codecs-data-structures/src/literal-union.ts","../node_modules/@solana/codecs-data-structures/src/map.ts","../node_modules/@solana/codecs-data-structures/src/unit.ts","../node_modules/@solana/codecs-data-structures/src/nullable.ts","../node_modules/@solana/codecs-data-structures/src/set.ts","../node_modules/@solana/codecs-data-structures/src/struct.ts","../node_modules/@solana/options/src/option.ts","../node_modules/@solana/options/src/unwrap-option.ts","../node_modules/@solana/options/src/option-codec.ts","../node_modules/@solana/options/src/unwrap-option-recursively.ts","../node_modules/@solana/codecs/dist/index.node.mjs","../node_modules/@solana/functional/src/pipe.ts","../node_modules/@solana/instructions/src/instruction.ts","../node_modules/@solana/instructions/src/roles.ts","../node_modules/@solana/rpc-types/src/blockhash.ts","../node_modules/@solana/rpc-types/src/cluster-url.ts","../node_modules/@solana/rpc-types/src/commitment.ts","../node_modules/@solana/rpc-types/src/lamports.ts","../node_modules/@solana/rpc-types/src/stringified-bigint.ts","../node_modules/@solana/rpc-types/src/stringified-number.ts","../node_modules/@solana/rpc-types/src/unix-timestamp.ts","../node_modules/@solana/transaction-messages/src/blockhash.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/transaction-messages/src/codecs/address-table-lookup.ts","../node_modules/@solana/transaction-messages/src/codecs/header.ts","../node_modules/@solana/transaction-messages/src/codecs/instruction.ts","../node_modules/@solana/transaction-messages/src/transaction-message.ts","../node_modules/@solana/transaction-messages/src/codecs/transaction-version.ts","../node_modules/@solana/transaction-messages/src/codecs/message.ts","../node_modules/@solana/transaction-messages/src/compile/accounts.ts","../node_modules/@solana/transaction-messages/src/compile/address-table-lookups.ts","../node_modules/@solana/transaction-messages/src/compile/header.ts","../node_modules/@solana/transaction-messages/src/compile/instructions.ts","../node_modules/@solana/transaction-messages/src/compile/lifetime-token.ts","../node_modules/@solana/transaction-messages/src/compile/static-accounts.ts","../node_modules/@solana/transaction-messages/src/compile/message.ts","../node_modules/@solana/transaction-messages/src/compress-transaction-message.ts","../node_modules/@solana/transaction-messages/src/create-transaction-message.ts","../node_modules/@solana/transaction-messages/src/durable-nonce-instruction.ts","../node_modules/@solana/transaction-messages/src/durable-nonce.ts","../node_modules/@solana/transaction-messages/src/fee-payer.ts","../node_modules/@solana/transaction-messages/src/instructions.ts","../node_modules/@solana/transaction-messages/src/decompile-message.ts","../node_modules/@solana/keys/src/algorithm.ts","../node_modules/@solana/keys/src/private-key.ts","../node_modules/@solana/keys/src/public-key.ts","../node_modules/@solana/keys/src/signatures.ts","../node_modules/@solana/keys/src/key-pair.ts","../node_modules/@solana/transactions/src/codecs/signatures-encoder.ts","../node_modules/@solana/transactions/src/codecs/transaction-codec.ts","../node_modules/@solana/transactions/src/lifetime.ts","../node_modules/@solana/transactions/src/compile-transaction.ts","../node_modules/@solana/transactions/src/signatures.ts","../node_modules/@solana/transactions/src/wire-transaction.ts","../node_modules/@solana/transactions/src/transaction-size.ts","../node_modules/@solana/transactions/src/sendable-transaction.ts","../node_modules/@solana/transactions/src/transaction-message-size.ts","../node_modules/@solana/promises/src/race.ts","../node_modules/@solana/promises/src/abortable.ts","../node_modules/@solana/instruction-plans/src/instruction-plan.ts","../node_modules/@solana/instruction-plans/src/append-instruction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-result.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-executor.ts","../node_modules/@solana/instruction-plans/src/transaction-planner.ts","../node_modules/@solana/offchain-messages/src/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/signing-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-common.ts","../node_modules/@solana/offchain-messages/src/codecs/signatures.ts","../node_modules/@solana/offchain-messages/src/codecs/envelope.ts","../node_modules/@solana/offchain-messages/src/content.ts","../node_modules/@solana/offchain-messages/src/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/content.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message.ts","../node_modules/@solana/offchain-messages/src/envelope-common.ts","../node_modules/@solana/offchain-messages/src/envelope-v0.ts","../node_modules/@solana/offchain-messages/src/envelope-v1.ts","../node_modules/@solana/offchain-messages/src/envelope.ts","../node_modules/@solana/offchain-messages/src/signatures.ts","../node_modules/@solana/plugin-core/src/client.ts","../node_modules/@solana/programs/src/program-error.ts","../node_modules/@solana/rpc-spec-types/src/parse-json-with-bigints.ts","../node_modules/@solana/rpc-spec-types/src/rpc-message.ts","../node_modules/@solana/rpc-spec-types/src/stringify-json-with-bigints.ts","../node_modules/@solana/rpc-spec/src/rpc.ts","../node_modules/@solana/rpc-spec/src/rpc-api.ts","../node_modules/@solana/rpc-spec/src/rpc-transport.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast-internal.ts","../node_modules/@solana/rpc-transformers/src/tree-traversal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-options-object-position-config.ts","../node_modules/@solana/rpc-transformers/src/request-transformer.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast-internal.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-result.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-allowed-numeric-values.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-throw-solana-error.ts","../node_modules/@solana/rpc-transformers/src/response-transformer.ts","../node_modules/@solana/rpc-api/src/index.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-headers.ts","../node_modules/@solana/rpc-transport-http/src/http-transport.ts","../node_modules/@solana/rpc-transport-http/src/is-solana-request.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-for-solana-rpc.ts","../node_modules/@solana/fast-stable-stringify/src/index.ts","../node_modules/@solana/rpc/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc/src/rpc-request-coalescer.ts","../node_modules/@solana/rpc/src/rpc-request-deduplication.ts","../node_modules/@solana/rpc/src/rpc-transport.ts","../node_modules/@solana/rpc/src/rpc.ts","../node_modules/@solana/rpc-parsed-types/dist/index.node.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/subscribable/src/async-iterable.ts","../node_modules/@solana/subscribable/src/data-publisher.ts","../node_modules/@solana/subscribable/src/demultiplex.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-api.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-channel.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-pubsub-plan.ts","../node_modules/@solana/rpc-subscriptions-api/src/index.ts","../node_modules/ws/lib/constants.js","../node_modules/ws/lib/buffer-util.js","../node_modules/ws/lib/limiter.js","../node_modules/ws/lib/permessage-deflate.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/stream.js","../node_modules/ws/lib/subprotocol.js","../node_modules/ws/lib/websocket-server.js","../node_modules/ws/wrapper.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/ws-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-channel-websocket/src/websocket-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-autopinger.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool-internal.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json-bigint.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-coalescer.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-transport.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions.ts","../node_modules/@solana/signers/src/deduplicate-signers.ts","../node_modules/@solana/signers/src/transaction-modifying-signer.ts","../node_modules/@solana/signers/src/transaction-partial-signer.ts","../node_modules/@solana/signers/src/transaction-sending-signer.ts","../node_modules/@solana/signers/src/transaction-signer.ts","../node_modules/@solana/signers/src/account-signer-meta.ts","../node_modules/@solana/signers/src/add-signers.ts","../node_modules/@solana/signers/src/fee-payer-signer.ts","../node_modules/@solana/signers/src/message-partial-signer.ts","../node_modules/@solana/signers/src/keypair-signer.ts","../node_modules/@solana/signers/src/message-modifying-signer.ts","../node_modules/@solana/signers/src/message-signer.ts","../node_modules/@solana/signers/src/noop-signer.ts","../node_modules/@solana/signers/src/offchain-message-signer.ts","../node_modules/@solana/signers/src/sign-offchain-message.ts","../node_modules/@solana/signers/src/transaction-with-single-sending-signer.ts","../node_modules/@solana/signers/src/sign-transaction.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/signers/src/signable-message.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-blockheight.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-nonce.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-recent-signature.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-timeout.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-racer.ts","../node_modules/@solana/transaction-confirmation/src/waiters.ts","../node_modules/@solana/kit/src/airdrop-internal.ts","../node_modules/@solana/kit/src/airdrop.ts","../node_modules/@solana/kit/src/fetch-lookup-tables.ts","../node_modules/@solana/kit/src/decompile-transaction-message-fetching-lookup-tables.ts","../node_modules/@solana/kit/src/get-minimum-balance-for-rent-exemption.ts","../node_modules/@solana/kit/src/send-transaction-internal.ts","../node_modules/@solana/kit/src/send-and-confirm-durable-nonce-transaction.ts","../node_modules/@solana/kit/src/send-and-confirm-transaction.ts","../node_modules/@solana/kit/src/send-transaction-without-confirming.ts","../src/solana-balance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/programs/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/errors/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/instructions/createAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/createMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/mintToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/transferToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/decryptableBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/encryptedBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extension.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extensionType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/tokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/transferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/applyConfidentialPendingBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialDeposit.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransferWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialWithdraw.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/configureConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createNativeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emitTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emptyConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMintCloseAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeNonTransferableMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePausableConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePermanentDelegate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeScaledUiAmountMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroup.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroupMember.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferFeeConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/pause.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/reallocate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/removeTokenMetadataKey.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/resume.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferCheckedWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMultiplierScaledUiMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateRateInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupMaxSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawExcessLamports.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccounts.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccountsForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getInitializeInstructionsForExtensions.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getTokenSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getMintSize.ts","../node_modules/@x402/svm/src/constants.ts","../node_modules/@x402/svm/src/utils.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/programs/computeBudget.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestHeapFrame.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestUnits.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitPrice.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setLoadedAccountsDataSizeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/constants.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/internal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateAndSetComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimitInternal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputePrice.ts","../node_modules/@x402/svm/src/exact/client/scheme.ts","../node_modules/@x402/svm/src/v1/index.ts","../node_modules/@x402/svm/src/exact/v1/client/scheme.ts","../node_modules/@x402/svm/src/exact/client/register.ts","../src/proxy.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/utils/abi/encodeEventTopics.ts","../node_modules/viem/errors/log.ts","../node_modules/viem/actions/public/createContractEventFilter.ts","../node_modules/viem/utils/filters/createFilterRequestScope.ts","../node_modules/viem/actions/public/estimateContractGas.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/viem/utils/authorization/hashAuthorization.ts","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/utils/authorization/recoverAuthorizationAddress.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/getTransactionCount.ts","../node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../node_modules/@noble/hashes/src/sha256.ts","../node_modules/viem/utils/hash/sha256.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/utils/transaction/getTransactionType.ts","../node_modules/viem/actions/public/fillTransaction.ts","../node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/public/getContractEvents.ts","../node_modules/viem/utils/abi/parseEventLogs.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/actions/public/getLogs.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/viem/actions/public/watchContractEvent.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/getFilterChanges.ts","../node_modules/viem/actions/public/uninstallFilter.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/viem/actions/ens/getEnsResolver.ts","../node_modules/viem/clients/decorators/public.ts","../node_modules/viem/actions/public/createAccessList.ts","../node_modules/viem/actions/public/createBlockFilter.ts","../node_modules/viem/actions/public/createEventFilter.ts","../node_modules/viem/actions/public/createPendingTransactionFilter.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/getBlobBaseFee.ts","../node_modules/viem/actions/public/getBlockTransactionCount.ts","../node_modules/viem/actions/public/getCode.ts","../node_modules/viem/actions/public/getDelegation.ts","../node_modules/viem/errors/eip712.ts","../node_modules/viem/actions/public/getEip712Domain.ts","../node_modules/viem/actions/public/getFeeHistory.ts","../node_modules/viem/utils/formatters/feeHistory.ts","../node_modules/viem/actions/public/getFilterLogs.ts","../node_modules/viem/actions/public/getProof.ts","../node_modules/viem/utils/authorization/serializeAuthorizationList.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/authorization/verifyAuthorization.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/utils/promise/withDedupe.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/utils/index.ts","../node_modules/viem/utils/rpc/http.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/utils/rpc/id.ts","../node_modules/viem/utils/signature/hashMessage.ts","../node_modules/viem/constants/strings.ts","../node_modules/viem/utils/signature/toPrefixedMessage.ts","../node_modules/viem/utils/signature/hashTypedData.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/errors/typedData.ts","../node_modules/ox/erc8010/SignatureErc8010.ts","../node_modules/ox/core/AbiParameters.ts","../node_modules/ox/core/Address.ts","../node_modules/ox/core/internal/lru.ts","../node_modules/ox/core/Caches.ts","../node_modules/ox/core/Hash.ts","../node_modules/ox/core/PublicKey.ts","../node_modules/ox/core/internal/abiParameters.ts","../node_modules/ox/core/Solidity.ts","../node_modules/ox/core/internal/cursor.ts","../node_modules/ox/core/Authorization.ts","../node_modules/ox/core/Rlp.ts","../node_modules/ox/node_modules/@noble/curves/src/secp256k1.ts","../node_modules/ox/node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/ox/core/Signature.ts","../node_modules/ox/core/Secp256k1.ts","../node_modules/viem/utils/formatters/proof.ts","../node_modules/viem/actions/public/getStorageAt.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/actions/public/getTransactionConfirmations.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/viem/actions/public/simulateBlocks.ts","../node_modules/ox/core/AbiItem.ts","../node_modules/ox/core/internal/abiItem.ts","../node_modules/ox/core/AbiConstructor.ts","../node_modules/ox/core/AbiFunction.ts","../node_modules/viem/actions/public/simulateCalls.ts","../node_modules/viem/constants/address.ts","../node_modules/ox/erc6492/SignatureErc6492.ts","../node_modules/viem/actions/public/verifyHash.ts","../node_modules/viem/utils/signature/serializeSignature.ts","../node_modules/viem/actions/public/verifyMessage.ts","../node_modules/viem/actions/public/verifyTypedData.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/actions/public/watchBlocks.ts","../node_modules/viem/actions/public/watchEvent.ts","../node_modules/viem/actions/public/watchPendingTransactions.ts","../node_modules/viem/utils/siwe/parseSiweMessage.ts","../node_modules/viem/utils/siwe/validateSiweMessage.ts","../node_modules/viem/actions/siwe/verifySiweMessage.ts","../node_modules/viem/actions/wallet/sendRawTransactionSync.ts","../node_modules/viem/clients/createPublicClient.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/index.ts","../node_modules/viem/op-stack/contracts.ts","../node_modules/viem/op-stack/formatters.ts","../node_modules/viem/op-stack/serializers.ts","../node_modules/viem/op-stack/chainConfig.ts","../node_modules/viem/chains/definitions/base.ts","../node_modules/@scure/base/index.ts","../node_modules/@noble/hashes/src/pbkdf2.ts","../node_modules/@scure/bip39/esm/index.js","../node_modules/viem/accounts/privateKeyToAccount.ts","../node_modules/viem/accounts/toAccount.ts","../node_modules/viem/accounts/utils/sign.ts","../node_modules/viem/accounts/utils/signAuthorization.ts","../node_modules/viem/accounts/utils/signMessage.ts","../node_modules/viem/accounts/utils/signTransaction.ts","../node_modules/viem/accounts/utils/signTypedData.ts","../node_modules/@scure/bip39/esm/wordlists/english.js","../node_modules/@x402/core/src/index.ts","../node_modules/@x402/core/src/utils/index.ts","../node_modules/@x402/core/src/http/x402HTTPResourceServer.ts","../node_modules/@x402/core/src/http/httpFacilitatorClient.ts","../node_modules/@x402/core/src/http/x402HTTPClient.ts","../node_modules/@x402/core/src/http/index.ts","../node_modules/@x402/core/src/client/x402Client.ts","../node_modules/@x402/fetch/src/index.ts","../src/payment-preauth.ts","../node_modules/@x402/evm/src/exact/extensions.ts","../node_modules/@x402/evm/src/exact/v1/client/scheme.ts","../node_modules/@x402/evm/src/constants.ts","../node_modules/@x402/evm/src/utils.ts","../node_modules/@x402/evm/src/exact/v1/facilitator/scheme.ts","../node_modules/@x402/evm/src/exact/facilitator/errors.ts","../node_modules/@x402/evm/src/exact/facilitator/eip3009-utils.ts","../node_modules/@x402/evm/src/multicall.ts","../node_modules/@x402/evm/src/v1/index.ts","../node_modules/@x402/evm/src/exact/client/scheme.ts","../node_modules/@x402/evm/src/exact/client/eip3009.ts","../node_modules/@x402/evm/src/exact/client/permit2.ts","../node_modules/@x402/evm/src/exact/client/eip2612.ts","../node_modules/@x402/evm/src/exact/client/erc20approval.ts","../node_modules/@x402/evm/src/exact/client/rpc.ts","../node_modules/@x402/evm/src/exact/client/register.ts","../node_modules/@x402/evm/src/signer.ts","../src/router/rules.ts","../src/router/selector.ts","../src/router/strategy.ts","../src/router/config.ts","../src/router/index.ts","../src/models.ts","../src/logger.ts","../src/stats.ts","../src/fs-read.ts","../src/version.ts","../src/dedup.ts","../src/response-cache.ts","../src/errors.ts","../src/payment-asset.ts","../src/balance.ts","../src/auth.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@noble/curves/src/utils.ts","../node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/@noble/curves/src/secp256k1.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_md.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/legacy.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@scure/bip32/node_modules/@scure/base/index.ts","../node_modules/@scure/bip32/index.ts","../src/wallet.ts","../node_modules/@noble/hashes/src/sha512.ts","../src/compression/types.ts","../src/compression/layers/deduplication.ts","../src/compression/layers/whitespace.ts","../src/compression/codebook.ts","../src/compression/layers/dictionary.ts","../src/compression/layers/paths.ts","../src/compression/layers/json-compact.ts","../src/compression/layers/observation.ts","../src/compression/layers/dynamic-codebook.ts","../src/compression/index.ts","../src/session.ts","../src/updater.ts","../src/exclude-models.ts","../src/config.ts","../src/journal.ts","../src/report.ts","../src/doctor.ts","../src/partners/registry.ts","../src/cli.ts"],"sourcesContent":["export const version = '1.2.3'\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}\nexport function execFallbackSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(fallbackSignatureRegex, 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} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @param structs Struct definitions to include in cache key\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}${structKey}`\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 execFallbackSignature,\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 return parseFunctionSignature(signature, structs)\n\n if (isEventSignature(signature))\n return parseEventSignature(signature, structs)\n\n if (isErrorSignature(signature))\n return parseErrorSignature(signature, structs)\n\n if (isConstructorSignature(signature))\n return parseConstructorSignature(signature, structs)\n\n if (isFallbackSignature(signature)) return parseFallbackSignature(signature)\n\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nexport function parseFunctionSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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\nexport function parseEventSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'event', inputs: abiParameters }\n}\n\nexport function parseErrorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'error', inputs: abiParameters }\n}\n\nexport function parseConstructorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n}\n\nexport function parseFallbackSignature(signature: string) {\n const match = execFallbackSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'fallback' })\n\n return {\n type: 'fallback',\n stateMutability: match.stateMutability ?? 'nonpayable',\n }\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\\spayable)?)(?(?:\\[\\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 if (match.type === 'address payable') {\n type = 'address'\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 structs\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 { Abi } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiItemError } from './errors/abiItem.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signature, 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 item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * type Result = ParseAbiItem<'function balanceOf(address owner) view returns (uint256)'>\n * // ^? type Result = { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * type Result = ParseAbiItem<\n * // ^? type Result = { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * ['function foo(Baz bar) view returns (string)', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n> =\n | (signature extends string\n ? string extends signature\n ? Abi[number]\n : signature extends Signature // Validate signature\n ? ParseSignature\n : never\n : never)\n | (signature extends readonly string[]\n ? string[] extends signature\n ? Abi[number] // Return generic Abi item since type was no inferrable\n : signature extends Signatures // Validate signature\n ? ParseStructs extends infer structs\n ? {\n [key in keyof signature]: ParseSignature<\n signature[key] extends string ? signature[key] : never,\n structs\n >\n } extends infer mapped extends readonly unknown[]\n ? // Filter out `never` since those are structs\n Filter[0] extends infer result\n ? result extends undefined // convert `undefined` to `never` (e.g. `ParseAbiItem<['struct Foo { string name; }']>`)\n ? never\n : result\n : never\n : never\n : never\n : never\n : never)\n\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint256)')\n * // ^? const abiItem: { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * const abiItem = parseAbiItem([\n * // ^? const abiItem: { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * 'function foo(Baz bar) view returns (string)',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n>(\n signature: Narrow &\n (\n | (signature extends string\n ? string extends signature\n ? unknown\n : Signature\n : never)\n | (signature extends readonly string[]\n ? signature extends readonly [] // empty array\n ? Error<'At least one signature required.'>\n : string[] extends signature\n ? unknown\n : Signatures\n : never)\n ),\n): ParseAbiItem {\n let abiItem: ParseAbiItem | undefined\n if (typeof signature === 'string')\n abiItem = parseSignature(signature) as ParseAbiItem\n else {\n const structs = parseStructs(signature as readonly string[])\n const length = signature.length as number\n for (let i = 0; i < length; i++) {\n const signature_ = (signature as readonly string[])[i]!\n if (isStructSignature(signature_)) continue\n abiItem = parseSignature(signature_, structs) as ParseAbiItem\n break\n }\n }\n\n if (!abiItem) throw new InvalidAbiItemError({ signature })\n return abiItem as ParseAbiItem\n}\n","import type { AbiParameter } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiParametersError } from './errors/abiParameter.js'\nimport { isStructSignature, modifiers } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { splitParameters } from './runtime/utils.js'\nimport { parseAbiParameter as parseAbiParameter_ } from './runtime/utils.js'\nimport type { IsStructSignature, Modifier } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { SplitParameters } from './types/utils.js'\nimport type { ParseAbiParameters as ParseAbiParameters_ } from './types/utils.js'\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * type Result = ParseAbiParameters('address from, address to, uint256 amount')\n * // ^? type Result: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * type Result = ParseAbiParameters<\n * // ^? type Result: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * ['Baz bar', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n> =\n | (params extends string\n ? params extends ''\n ? never\n : string extends params\n ? readonly AbiParameter[]\n : ParseAbiParameters_, { modifier: Modifier }>\n : never)\n | (params extends readonly string[]\n ? string[] extends params\n ? AbiParameter // Return generic AbiParameter item since type was no inferrable\n : ParseStructs extends infer structs\n ? {\n [key in keyof params]: params[key] extends string\n ? IsStructSignature extends true\n ? never\n : ParseAbiParameters_<\n SplitParameters,\n { modifier: Modifier; structs: structs }\n >\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends readonly [...infer content]\n ? content['length'] extends 0\n ? never\n : DeepFlatten\n : never\n : never\n : never\n : never)\n\n/**\n * Flatten all members of {@link T}\n *\n * @param T - List of items to flatten\n * @param Acc - The accumulator used while recursing\n * @returns The flattened array\n *\n * @example\n * type Result = DeepFlatten<[['a', 'b'], [['c']]]>\n * // ^? type Result = ['a', 'b', 'c']\n */\ntype DeepFlatten<\n T extends readonly unknown[],\n Acc extends readonly unknown[] = readonly [],\n> = T extends readonly [infer head, ...infer tail]\n ? tail extends undefined\n ? never\n : head extends readonly unknown[]\n ? DeepFlatten]>\n : DeepFlatten\n : Acc\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * const abiParameters = parseAbiParameters('address from, address to, uint256 amount')\n * // ^? const abiParameters: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * const abiParameters = parseAbiParameters([\n * // ^? const abiParameters: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * 'Baz bar',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n>(\n params: Narrow &\n (\n | (params extends string\n ? params extends ''\n ? Error<'Empty string is not allowed.'>\n : unknown\n : never)\n | (params extends readonly string[]\n ? params extends readonly [] // empty array\n ? Error<'At least one parameter required.'>\n : string[] extends params\n ? unknown\n : unknown // TODO: Validate param string\n : never)\n ),\n): ParseAbiParameters {\n const abiParameters: AbiParameter[] = []\n if (typeof params === 'string') {\n const parameters = splitParameters(params)\n const length = parameters.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(parseAbiParameter_(parameters[i]!, { modifiers }))\n }\n } else {\n const structs = parseStructs(params as readonly string[])\n const length = params.length as number\n for (let i = 0; i < length; i++) {\n const signature = (params as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n const parameters = splitParameters(signature)\n const length = parameters.length\n for (let k = 0; k < length; k++) {\n abiParameters.push(\n parseAbiParameter_(parameters[k]!, { modifiers, structs }),\n )\n }\n }\n }\n\n if (abiParameters.length === 0)\n throw new InvalidAbiParametersError({ params })\n\n return abiParameters as ParseAbiParameters\n}\n","export type {\n Abi,\n AbiConstructor,\n AbiError,\n AbiEvent,\n AbiEventParameter,\n AbiFallback,\n AbiFunction,\n AbiInternalType,\n AbiItemType,\n AbiParameter,\n AbiParameterKind,\n AbiReceive,\n AbiStateMutability,\n AbiType,\n Address,\n SolidityAddress,\n SolidityArray,\n SolidityArrayWithoutTuple,\n SolidityArrayWithTuple,\n SolidityBool,\n SolidityBytes,\n SolidityFixedArrayRange,\n SolidityFixedArraySizeLookup,\n SolidityFunction,\n SolidityInt,\n SolidityString,\n SolidityTuple,\n TypedData,\n TypedDataDomain,\n TypedDataParameter,\n TypedDataType,\n} from '../abi.js'\n\n// biome-ignore lint/performance/noBarrelFile: \nexport { BaseError } from '../errors.js'\n\nexport type { Narrow } from '../narrow.js'\nexport { narrow } from '../narrow.js'\n\nexport type {\n Register,\n DefaultRegister,\n ResolvedRegister,\n} from '../register.js'\n\nexport type {\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n AbiTypeToPrimitiveType,\n ExtractAbiError,\n ExtractAbiErrorNames,\n ExtractAbiErrors,\n ExtractAbiEvent,\n ExtractAbiEventNames,\n ExtractAbiEvents,\n ExtractAbiFunction,\n ExtractAbiFunctionNames,\n ExtractAbiFunctions,\n IsAbi,\n IsTypedData,\n TypedDataToPrimitiveTypes,\n} from '../utils.js'\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Human-Readable\n\nexport {\n formatAbi,\n type FormatAbi,\n} from '../human-readable/formatAbi.js'\n\nexport {\n formatAbiItem,\n type FormatAbiItem,\n} from '../human-readable/formatAbiItem.js'\n\nexport {\n formatAbiParameter,\n type FormatAbiParameter,\n} from '../human-readable/formatAbiParameter.js'\n\nexport {\n formatAbiParameters,\n type FormatAbiParameters,\n} from '../human-readable/formatAbiParameters.js'\n\nexport { parseAbi, type ParseAbi } from '../human-readable/parseAbi.js'\n\nexport {\n parseAbiItem,\n type ParseAbiItem,\n} from '../human-readable/parseAbiItem.js'\n\nexport {\n parseAbiParameter,\n type ParseAbiParameter,\n} from '../human-readable/parseAbiParameter.js'\n\nexport {\n parseAbiParameters,\n type ParseAbiParameters,\n} from '../human-readable/parseAbiParameters.js'\n\nexport {\n UnknownTypeError,\n InvalidAbiItemError,\n UnknownSolidityTypeError,\n} from '../human-readable/errors/abiItem.js'\n\nexport {\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n SolidityProtectedKeywordError,\n InvalidParameterError,\n InvalidAbiParametersError,\n InvalidAbiParameterError,\n} from '../human-readable/errors/abiParameter.js'\n\nexport {\n InvalidStructSignatureError,\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../human-readable/errors/signature.js'\n\nexport { InvalidParenthesisError } from '../human-readable/errors/splitParameters.js'\n\nexport { CircularReferenceError } from '../human-readable/errors/struct.js'\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","export const version = '2.46.3'\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 { 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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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 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 IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\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 =\n | HexToBigIntErrorType\n | IntegerOutOfRangeErrorType\n | 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 const value = hexToBigInt(hex, opts)\n const number = Number(value)\n if (!Number.isSafeInteger(number))\n throw new IntegerOutOfRangeError({\n max: `${Number.MAX_SAFE_INTEGER}`,\n min: `${Number.MIN_SAFE_INTEGER}`,\n signed: opts.signed,\n size: opts.size,\n value: `${value}n`,\n })\n return number\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","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * Internal webcrypto alias.\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 * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\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","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\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';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\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\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\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\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 abstract clone(): T;\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\n/** Hash function */\nexport type CHash = ReturnType;\n/** Hash function with output */\nexport type CHashO = ReturnType;\n/** XOF with output */\nexport type CHashXO = ReturnType;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher>(\n hashCons: () => Hash\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash;\n} {\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 createOptHasher, T extends Object>(\n hashCons: (opts?: T) => Hash\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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 createXOFer, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\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 Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\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 IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\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/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\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 clean(B);\n}\n\n/** Keccak sponge function. */\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\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\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(): void {\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): 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(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\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 createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__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 { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.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 { 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 { 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'\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 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 { 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","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","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 AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\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 boolToHex,\n type NumberToHexErrorType,\n numberToHex,\n type StringToHexErrorType,\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, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\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 { 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 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\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 (\n argType === 'object' &&\n isArgOfType(\n Object.values(arg as unknown[] | Record)[\n index\n ],\n component as AbiParameter,\n )\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","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","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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.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 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 { 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 = NegativeOffsetErrorType | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetErrorType | 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 ?? bytes,\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 assertSize,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\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 {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.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 AbiParameterKind,\n true\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 never\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, 10), 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', 10)\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 { AbiParameter } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\nimport { stringify } from '../stringify.js'\n\nexport type FormatAbiItemWithArgsErrorType = ErrorType\n\nexport function formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName = true,\n includeName = false,\n}: {\n abiItem: AbiItem\n args: readonly unknown[]\n includeFunctionName?: boolean | undefined\n includeName?: boolean | undefined\n}) {\n if (!('name' in abiItem)) return\n if (!('inputs' in abiItem)) return\n if (!abiItem.inputs) return\n return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n .map(\n (input: AbiParameter, i: number) =>\n `${includeName && input.name ? `${input.name}: ` : ''}${\n typeof args[i] === 'object' ? stringify(args[i]) : args[i]\n }`,\n )\n .join(', ')})`\n}\n","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 {\n TransactionReceipt,\n TransactionType,\n} 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 TransactionReceiptRevertedErrorType =\n TransactionReceiptRevertedError & {\n name: 'TransactionReceiptRevertedError'\n }\nexport class TransactionReceiptRevertedError extends BaseError {\n receipt: TransactionReceipt\n\n constructor({ receipt }: { receipt: TransactionReceipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n })\n\n this.receipt = receipt\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 raw?: Hex | 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\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://4byte.sourcify.dev/?q=${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.raw = data\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 { 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 url: string\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 this.url = url\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n url: string\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 this.url = url\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n url: string | undefined\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 this.url = url\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n url: string\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 this.url = url\n }\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n | -1\n | -32700 // Parse error\n | -32600 // Invalid request\n | -32601 // Method not found\n | -32602 // Invalid params\n | -32603 // Internal error\n | -32000 // Invalid input\n | -32001 // Resource not found\n | -32002 // Resource unavailable\n | -32003 // Transaction rejected\n | -32004 // Method not supported\n | -32005 // Limit exceeded\n | -32006 // JSON-RPC version not supported\n | -32042 // Method not found\n\ntype RpcErrorOptions = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : (code ?? unknownErrorCode)\n ) as code_\n }\n}\n\nexport type ProviderRpcErrorCode =\n | 4001 // User Rejected Request\n | 4100 // Unauthorized\n | 4200 // Unsupported Method\n | 4900 // Disconnected\n | 4901 // Chain Disconnected\n | 4902 // Chain Not Recognized\n | 5700 // Unsupported non-optional capability\n | 5710 // Unsupported chain id\n | 5720 // Duplicate ID\n | 5730 // Unknown bundle id\n | 5740 // Bundle too large\n | 5750 // Atomic-ready wallet rejected upgrade\n | 5760 // Atomicity not supported\n | 7000 // WalletConnect Session Settlement Failed\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n T = undefined,\n> extends RpcError {\n data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions & {\n data?: T | undefined\n }\n >,\n ) {\n super(cause, options)\n\n this.data = options.data\n }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n code: -32700\n name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage:\n 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n })\n }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n code: -32600\n name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n code: -32601\n name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n code: -32602\n name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n code: -32603\n name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n code: -32000\n name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n code: -32001\n name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n override name = 'ResourceNotFoundRpcError'\n static code = -32001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n })\n }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n code: -32002\n name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n })\n }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n code: -32003\n name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n code: -32004\n name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not supported.`,\n })\n }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n code: -32005\n name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n })\n }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n JsonRpcVersionUnsupportedError & {\n code: -32006\n name: 'JsonRpcVersionUnsupportedError'\n }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n })\n }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n code: 4001\n name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n code: 4100\n name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage:\n 'The requested method and/or account has not been authorized by the user.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n UnsupportedProviderMethodError & {\n code: 4200\n name: 'UnsupportedProviderMethodError'\n }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n code: 4900\n name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n })\n }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n code: 4901\n name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n code: 4902\n name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported non-optional capability\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedNonOptionalCapabilityErrorType =\n UnsupportedNonOptionalCapabilityError & {\n code: 5700\n name: 'UnsupportedNonOptionalCapabilityError'\n }\nexport class UnsupportedNonOptionalCapabilityError extends ProviderRpcError {\n static code = 5700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedNonOptionalCapabilityError.code,\n name: 'UnsupportedNonOptionalCapabilityError',\n shortMessage:\n 'This Wallet does not support a capability that was not marked as optional.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported chain id\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedChainIdErrorType = UnsupportedChainIdError & {\n code: 5710\n name: 'UnsupportedChainIdError'\n}\nexport class UnsupportedChainIdError extends ProviderRpcError {\n static code = 5710 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedChainIdError.code,\n name: 'UnsupportedChainIdError',\n shortMessage: 'This Wallet does not support the requested chain ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Duplicate ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type DuplicateIdErrorType = DuplicateIdError & {\n code: 5720\n name: 'DuplicateIdError'\n}\nexport class DuplicateIdError extends ProviderRpcError {\n static code = 5720 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: DuplicateIdError.code,\n name: 'DuplicateIdError',\n shortMessage: 'There is already a bundle submitted with this ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unknown bundle ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnknownBundleIdErrorType = UnknownBundleIdError & {\n code: 5730\n name: 'UnknownBundleIdError'\n}\nexport class UnknownBundleIdError extends ProviderRpcError {\n static code = 5730 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnknownBundleIdError.code,\n name: 'UnknownBundleIdError',\n shortMessage: 'This bundle id is unknown / has not been submitted',\n })\n }\n}\n\n/**\n * Subclass for an \"Bundle too large\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type BundleTooLargeErrorType = BundleTooLargeError & {\n code: 5740\n name: 'BundleTooLargeError'\n}\nexport class BundleTooLargeError extends ProviderRpcError {\n static code = 5740 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: BundleTooLargeError.code,\n name: 'BundleTooLargeError',\n shortMessage: 'The call bundle is too large for the Wallet to process.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomic-ready wallet rejected upgrade\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicReadyWalletRejectedUpgradeErrorType =\n AtomicReadyWalletRejectedUpgradeError & {\n code: 5750\n name: 'AtomicReadyWalletRejectedUpgradeError'\n }\nexport class AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {\n static code = 5750 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicReadyWalletRejectedUpgradeError.code,\n name: 'AtomicReadyWalletRejectedUpgradeError',\n shortMessage:\n 'The Wallet can support atomicity after an upgrade, but the user rejected the upgrade.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomicity not supported\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicityNotSupportedErrorType = AtomicityNotSupportedError & {\n code: 5760\n name: 'AtomicityNotSupportedError'\n}\nexport class AtomicityNotSupportedError extends ProviderRpcError {\n static code = 5760 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicityNotSupportedError.code,\n name: 'AtomicityNotSupportedError',\n shortMessage:\n 'The wallet does not support atomic execution but the request requires it.',\n })\n }\n}\n\n/**\n * Subclass for a \"Session Settlement Failed\" WalletConnect error.\n *\n * WalletConnect https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n */\nexport type WalletConnectSessionSettlementErrorType =\n WalletConnectSessionSettlementError & {\n code: 7000\n name: 'WalletConnectSessionSettlementError'\n }\nexport class WalletConnectSessionSettlementError extends ProviderRpcError {\n static code = 7000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: WalletConnectSessionSettlementError.code,\n name: 'WalletConnectSessionSettlementError',\n shortMessage: 'WalletConnect session settlement failed.',\n })\n }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): 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/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\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 protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\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 clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\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(): Uint8Array {\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 clone(): HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC;\n} = (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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * hash-to-curve from RFC 9380.\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\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.ts';\nimport { FpInvertBatch, type IField, mod } from './modular.ts';\nimport type { CHash } from './utils.ts';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.ts';\n\nexport type UnicodeOrBytes = string | Uint8Array;\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 */\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/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\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/**\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 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\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 * [RFC 9380 5.2](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 type XY = (x: T, y: T) => { x: T; y: T };\nexport type XYRatio = [T[], T[], T[], T[]]; // xn/xd, yn/yd\nexport function isogenyMap>(field: F, map: XYRatio): XY {\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 [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\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 };\nexport type HTFMethod = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint;\nexport type MapMethod = (scalars: bigint[]) => H2CPoint;\nexport type Hasher = {\n hashToCurve: HTFMethod;\n encodeToCurve: HTFMethod;\n mapToCurve: MapMethod;\n defaults: Opts & { encodeDST?: UnicodeOrBytes };\n};\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n defaults: Opts & { encodeDST?: UnicodeOrBytes }\n): Hasher {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n function map(num: bigint[]) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial: H2CPoint) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n\n return {\n defaults,\n\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): H2CPoint {\n const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options } as Opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\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): H2CPoint {\n const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options } as Opts);\n return clear(map(u[0]));\n },\n\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]): H2CPoint {\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n };\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\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|gas required exceeds allowance/\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 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 { 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 { Prettify } from '../../types/utils.js'\n\nexport type DefineFormatterErrorType = ErrorType\n\nexport function defineFormatter(\n type: type,\n format: (args: parameters, action?: string | undefined) => returnType,\n) {\n return <\n parametersOverride,\n returnTypeOverride,\n exclude extends (keyof parameters | keyof parametersOverride)[] = [],\n >({\n exclude,\n format: overrides,\n }: {\n exclude?: exclude | undefined\n format: (\n args: parametersOverride,\n action?: string | undefined,\n ) => returnTypeOverride\n }) => {\n return {\n exclude,\n format: (args: parametersOverride, action?: string | undefined) => {\n const formatted = format(args as any, action)\n if (exclude) {\n for (const key of exclude) {\n delete (formatted as any)[key]\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n } as Prettify & {\n [_key in exclude[number]]: never\n }\n },\n type,\n }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { AuthorizationList } from '../../types/authorization.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type {\n RpcAuthorizationList,\n RpcTransactionRequest,\n} 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 & { account?: Account | undefined },\n _?: string | undefined,\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 (request.account) rpcRequest.from = request.account.address\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.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : 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","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 type { FeeConflictErrorType } 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 { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = 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\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 } 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, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/** @internal */\nexport const version = '0.1.1'\n","import { version } from '../version.js'\n\n/** @internal */\nexport function getUrl(url: string) {\n return url\n}\n\n/** @internal */\nexport function getVersion() {\n return version\n}\n\n/** @internal */\nexport function prettyPrint(args: unknown) {\n if (!args) return ''\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","import { getVersion } from './internal/errors.js'\n\nexport type GlobalErrorType = Error & {\n name: name\n}\n\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError<\n cause extends Error | undefined = undefined,\n> extends Error {\n details: string\n docs?: string | undefined\n docsOrigin?: string | undefined\n docsPath?: string | undefined\n shortMessage: string\n showVersion?: boolean | undefined\n version?: string | undefined\n\n override cause: cause\n override name = 'BaseError'\n\n static defaultStaticOptions = {\n docsOrigin: 'https://oxlib.sh',\n showVersion: false,\n version: `ox@${getVersion()}`,\n } satisfies BaseError.GlobalOptions\n\n static setStaticOptions(options: BaseError.GlobalOptions) {\n BaseError.prototype.docsOrigin = options.docsOrigin\n BaseError.prototype.showVersion = options.showVersion\n BaseError.prototype.version = options.version\n }\n\n static {\n BaseError.setStaticOptions(BaseError.defaultStaticOptions)\n }\n\n constructor(shortMessage: string, options: BaseError.Options = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details) return options.cause.details\n if (options.cause.shortMessage) return options.cause.shortMessage\n }\n if (\n options.cause &&\n 'details' in options.cause &&\n typeof options.cause.details === 'string'\n )\n return options.cause.details\n if (options.cause?.message) return options.cause.message\n return options.details!\n })()\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath\n return options.docsPath\n })()\n\n const docsBaseUrl = options.docsOrigin ?? BaseError.prototype.docsOrigin\n const docs = `${docsBaseUrl}${docsPath ?? ''}`\n const showVersion = Boolean(\n options.version ?? BaseError.prototype.showVersion,\n )\n const version = options.version ?? BaseError.prototype.version\n\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath || showVersion\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n showVersion ? `Version: ${version}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n')\n\n super(message, options.cause ? { cause: options.cause } : undefined)\n\n this.cause = options.cause as any\n this.details = details\n this.docs = docs\n this.docsOrigin = docsBaseUrl\n this.docsPath = docsPath\n this.shortMessage = shortMessage\n this.showVersion = showVersion\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\nexport declare namespace BaseError {\n type Options = {\n /** Cause of the error. */\n cause?: cause | undefined\n /** Details of the error. */\n details?: string | undefined\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Path of the docs. */\n docsPath?: string | undefined\n /** Meta messages to add to the error. */\n metaMessages?: (string | undefined)[] | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n\n type GlobalOptions = {\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Whether to show the version of the library in the error message. */\n showVersion?: boolean | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n}\n\n/** @internal */\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import * as Bytes from '../Bytes.js'\nimport type * as Errors from '../Errors.js'\n\n/** @internal */\nexport function assertSize(bytes: Bytes.Bytes, size_: number): void {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Bytes.size.ErrorType\n | Bytes.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n export type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start\n ) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n })\n }\n}\n\n/** @internal */\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\n/** @internal */\nexport function 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\n/** @internal */\nexport function pad(bytes: Bytes.Bytes, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n if (size === 0) return bytes\n if (bytes.length > size)\n throw new Bytes.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\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Bytes.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Bytes.Bytes,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value\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 return data as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\n\n/** @internal */\nexport function assertSize(hex: Hex.Hex, size_: number): void {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Hex.size.ErrorType\n | Hex.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(value: Hex.Hex, start?: number | undefined) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Hex.Hex,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start\n ) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n })\n }\n}\n\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function pad(hex_: Hex.Hex, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n\n if (size === 0) return hex_\n\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}` as Hex.Hex\n}\n\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n type ErrorType = Hex.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Hex.Hex,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value.replace('0x', '')\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 (data === '0') return '0x'\n if (dir === 'right' && data.length % 2 === 1) return `0x${data}0`\n return `0x${data}` as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Hex.Hex\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from './Errors.js'\n\nconst bigIntSuffix = '#__bigint'\n\n/**\n * Serializes a value to a canonical JSON string as defined by\n * [RFC 8785 (JSON Canonicalization Scheme)](https://www.rfc-editor.org/rfc/rfc8785).\n *\n * - Object keys are sorted recursively by UTF-16 code unit comparison.\n * - Primitives are serialized per ECMAScript rules (no trailing zeros on numbers, etc.).\n * - No whitespace is inserted.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ b: 2, a: 1 })\n * // @log: '{\"a\":1,\"b\":2}'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ z: [3, { y: 1, x: 2 }], a: 'hello' })\n * // @log: '{\"a\":\"hello\",\"z\":[3,{\"x\":2,\"y\":1}]}'\n * ```\n *\n * @param value - The value to canonicalize.\n * @returns The canonical JSON string.\n */\nexport function canonicalize(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'string')\n return JSON.stringify(value)\n if (typeof value === 'number') {\n if (!Number.isFinite(value))\n throw new TypeError('Cannot canonicalize non-finite number')\n return Object.is(value, -0) ? '0' : JSON.stringify(value)\n }\n if (typeof value === 'bigint')\n throw new TypeError('Cannot canonicalize bigint')\n if (Array.isArray(value))\n return `[${value.map((item) => canonicalize(item)).join(',')}]`\n if (typeof value === 'object') {\n const entries = Object.keys(value as Record)\n .sort()\n .reduce((acc, key) => {\n const v = (value as Record)[key]\n if (v !== undefined)\n acc.push(`${JSON.stringify(key)}:${canonicalize(v)}`)\n return acc\n }, [])\n return `{${entries.join(',')}}`\n }\n return undefined as never\n}\n\nexport declare namespace canonicalize {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(\n string: string,\n reviver?: ((this: any, key: string, value: any) => any) | undefined,\n) {\n return JSON.parse(string, (key, value_) => {\n const value = value_\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length))\n return typeof reviver === 'function' ? reviver(key, value) : value\n })\n}\n\nexport declare namespace parse {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(\n value: any,\n replacer?: ((this: any, key: string, value: any) => any) | null | undefined,\n space?: string | number | undefined,\n) {\n return JSON.stringify(\n value,\n (key, value) => {\n if (typeof replacer === 'function') return replacer(key, value)\n if (typeof value === 'bigint') return value.toString() + bigIntSuffix\n return value\n },\n space,\n )\n}\n\nexport declare namespace stringify {\n type ErrorType = Errors.GlobalErrorType\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/bytes.js'\nimport * as internal_hex from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst decoder = /*#__PURE__*/ new TextDecoder()\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/** Root type for a Bytes array. */\nexport type Bytes = Uint8Array\n\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value: unknown): asserts value is Bytes {\n if (value instanceof Uint8Array) return\n if (!value) throw new InvalidBytesTypeError(value)\n if (typeof value !== 'object') throw new InvalidBytesTypeError(value)\n if (!('BYTES_PER_ELEMENT' in value)) throw new InvalidBytesTypeError(value)\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value)\n}\n\nexport declare namespace assert {\n type ErrorType = InvalidBytesTypeError | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values: readonly Bytes[]): Bytes {\n let length = 0\n for (const arr of values) {\n length += arr.length\n }\n const result = new Uint8Array(length)\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i]\n result.set(arr!, index)\n index += arr!.length\n }\n return result\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value: Hex.Hex | Bytes | readonly number[]): Bytes {\n if (value instanceof Uint8Array) return value\n if (typeof value === 'string') return fromHex(value)\n return fromArray(value)\n}\n\nexport declare namespace from {\n type ErrorType =\n | fromHex.ErrorType\n | fromArray.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value: readonly number[] | Uint8Array): Bytes {\n return value instanceof Uint8Array ? value : new Uint8Array(value)\n}\n\nexport declare namespace fromArray {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value: boolean, options: fromBoolean.Options = {}) {\n const { size } = options\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padLeft(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {\n const { size } = options\n\n let hex = value\n if (size) {\n internal_hex.assertSize(value, size)\n hex = Hex.padRight(value, 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 = internal.charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`,\n )\n }\n bytes[index] = (nibbleLeft << 4) | nibbleRight\n }\n return bytes\n}\n\nexport declare namespace fromHex {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_hex.assertSize.ErrorType\n | Hex.padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(\n value: bigint | number,\n options?: fromNumber.Options | undefined,\n) {\n const hex = Hex.fromNumber(value, options)\n return fromHex(hex)\n}\n\nexport declare namespace fromNumber {\n export type Options = Hex.fromNumber.Options\n\n export type ErrorType =\n | Hex.fromNumber.ErrorType\n | fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Bytes {\n const { size } = options\n\n const bytes = encoder.encode(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padRight(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromString {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA: Bytes, bytesB: Bytes) {\n return equalBytes(bytesA, bytesB)\n}\n\nexport declare namespace isEqual {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(\n value: Bytes,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(\n value: Bytes,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length: number): Bytes {\n return crypto.getRandomValues(new Uint8Array(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value: Bytes): number {\n return value.length\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(\n value: Bytes,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Bytes {\n const { strict } = options\n internal.assertStartOffset(value, start)\n const value_ = value.slice(start, end)\n if (strict) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n export type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes: Bytes, options: toBigInt.Options = {}): bigint {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toBigInt(hex, options)\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(\n bytes: Bytes,\n options: toBoolean.Options = {},\n): boolean {\n const { size } = options\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimLeft(bytes_)\n }\n if (bytes_.length > 1 || bytes_[0]! > 1)\n throw new InvalidBytesBooleanError(bytes_)\n return Boolean(bytes_[0])\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes, options: toHex.Options = {}): Hex.Hex {\n return Hex.fromBytes(value, options)\n}\n\nexport declare namespace toHex {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes: Bytes, options: toNumber.Options = {}): number {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toNumber(hex, options)\n}\n\nexport declare namespace toNumber {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes: Bytes, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimRight(bytes_)\n }\n return decoder.decode(bytes_)\n}\n\nexport declare namespace toString {\n export type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n export type ErrorType =\n | internal.assertSize.ErrorType\n | trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n export type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value: unknown): value is Bytes {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesBooleanError'\n\n constructor(bytes: Bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n })\n }\n}\n\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`,\n {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Bytes.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as internal_bytes from './internal/bytes.js'\nimport * as internal from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\n/** Root type for a Hex string. */\nexport type Hex = `0x${string}`\n\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(\n value: unknown,\n options: assert.Options = {},\n): asserts value is Hex {\n const { strict = false } = options\n if (!value) throw new InvalidHexTypeError(value)\n if (typeof value !== 'string') throw new InvalidHexTypeError(value)\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value)) throw new InvalidHexValueError(value)\n }\n if (!value.startsWith('0x')) throw new InvalidHexValueError(value)\n}\n\nexport declare namespace assert {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | InvalidHexTypeError\n | InvalidHexValueError\n | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values: readonly Hex[]): Hex {\n return `0x${(values as Hex[]).reduce((acc, x) => acc + x.replace('0x', ''), '')}`\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value: Hex | Bytes.Bytes | readonly number[]): Hex {\n if (value instanceof Uint8Array) return fromBytes(value)\n if (Array.isArray(value)) return fromBytes(new Uint8Array(value))\n return value as never\n}\n\nexport declare namespace from {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(\n value: boolean,\n options: fromBoolean.Options = {},\n): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padLeft(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(\n value: Bytes.Bytes,\n options: fromBytes.Options = {},\n): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) string += hexes[value[i]!]\n const hex = `0x${string}` as const\n\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padRight(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBytes {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(\n value: number | bigint,\n options: fromNumber.Options = {},\n): Hex {\n const { signed, size } = options\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 stringValue = (\n signed && value_ < 0 ? BigInt.asUintN(size * 8, BigInt(value_)) : value_\n ).toString(16)\n\n const hex = `0x${stringValue}` as Hex\n if (size) return padLeft(hex, size) as Hex\n return hex\n}\n\nexport declare namespace fromNumber {\n type Options =\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\n type ErrorType =\n | IntegerOutOfRangeError\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Hex {\n return fromBytes(encoder.encode(value), options)\n}\n\nexport declare namespace fromString {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA: Hex, hexB: Hex) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB))\n}\n\nexport declare namespace isEqual {\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(\n value: Hex,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(\n value: Hex,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length: number): Hex {\n return fromBytes(Bytes.random(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(\n value: Hex,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Hex {\n const { strict } = options\n internal.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) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value: Hex): number {\n return Math.ceil((value.length - 2) / 2)\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value: Hex): trimLeft.ReturnType {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value: Hex): trimRight.ReturnType {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {\n const { signed } = options\n\n if (options.size) internal.assertSize(hex, options.size)\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n\n const max_signed = max_unsigned >> 1n\n\n if (value <= max_signed) return value\n return value - max_unsigned - 1n\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType = internal.assertSize.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex: Hex, options: toBoolean.Options = {}): boolean {\n if (options.size) internal.assertSize(hex, options.size)\n const hex_ = trimLeft(hex)\n if (hex_ === '0x') return false\n if (hex_ === '0x1') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | InvalidHexBooleanError\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex: Hex, options: toBytes.Options = {}): Bytes.Bytes {\n return Bytes.fromHex(hex, options)\n}\n\nexport declare namespace toBytes {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex: Hex, options: toNumber.Options = {}): number {\n const { signed, size } = options\n if (!signed && !size) return Number(hex)\n return Number(toBigInt(hex, options))\n}\n\nexport declare namespace toNumber {\n type Options = toBigInt.Options\n\n type ErrorType = toBigInt.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex: Hex, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes = Bytes.fromHex(hex)\n if (size) {\n internal_bytes.assertSize(bytes, size)\n bytes = Bytes.trimRight(bytes)\n }\n return new TextDecoder().decode(bytes)\n}\n\nexport declare namespace toString {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_bytes.assertSize.ErrorType\n | Bytes.fromHex.ErrorType\n | Bytes.trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(\n value: unknown,\n options: validate.Options = {},\n): value is Hex {\n const { strict = false } = options\n try {\n assert(value, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n override readonly name = 'Hex.IntegerOutOfRangeError'\n\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` : ''\n }${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`,\n )\n }\n}\n\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexBooleanError'\n\n constructor(hex: Hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`,\n {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexValueError'\n\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidLengthError'\n\n constructor(value: Hex) {\n super(\n `Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`,\n {\n metaMessages: ['It must be an even length.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Hex.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Hex.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Hex.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/** A Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Withdrawal = {\n address: Hex.Hex\n amount: bigintType\n index: numberType\n validatorIndex: numberType\n}\n\n/** An RPC Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Rpc = Withdrawal\n\n/**\n * Converts a {@link ox#Withdrawal.Rpc} to an {@link ox#Withdrawal.Withdrawal}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.fromRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: '0x620323',\n * index: '0x0',\n * validatorIndex: '0x1',\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: 6423331n,\n * // @log: index: 0,\n * // @log: validatorIndex: 1\n * // @log: }\n * ```\n *\n * @param withdrawal - The RPC withdrawal to convert.\n * @returns An instantiated {@link ox#Withdrawal.Withdrawal}.\n */\nexport function fromRpc(withdrawal: Rpc): Withdrawal {\n return {\n ...withdrawal,\n amount: BigInt(withdrawal.amount),\n index: Number(withdrawal.index),\n validatorIndex: Number(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace fromRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Withdrawal.Withdrawal} to an {@link ox#Withdrawal.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.toRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: 6423331n,\n * index: 0,\n * validatorIndex: 1,\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: '0x620323',\n * // @log: index: '0x0',\n * // @log: validatorIndex: '0x1',\n * // @log: }\n * ```\n *\n * @param withdrawal - The Withdrawal to convert.\n * @returns An RPC Withdrawal.\n */\nexport function toRpc(withdrawal: Withdrawal): Rpc {\n return {\n address: withdrawal.address,\n amount: Hex.fromNumber(withdrawal.amount),\n index: Hex.fromNumber(withdrawal.index),\n validatorIndex: Hex.fromNumber(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace toRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Address from './Address.js'\nimport * as Hex from './Hex.js'\nimport * as Withdrawal from './Withdrawal.js'\n\n/**\n * Block overrides.\n */\nexport type BlockOverrides = {\n /** Base fee per gas. */\n baseFeePerGas?: bigintType | undefined\n /** Blob base fee. */\n blobBaseFee?: bigintType | undefined\n /** Fee recipient (also known as coinbase). */\n feeRecipient?: Address.Address | undefined\n /** Gas limit. */\n gasLimit?: bigintType | undefined\n /** Block number. */\n number?: bigintType | undefined\n /** The previous value of randomness beacon. */\n prevRandao?: bigintType | undefined\n /** Block timestamp. */\n time?: bigintType | undefined\n /** Withdrawals made by validators. */\n withdrawals?: Withdrawal.Withdrawal[] | undefined\n}\n\n/**\n * RPC block overrides.\n */\nexport type Rpc = BlockOverrides\n\n/**\n * Converts an {@link ox#BlockOverrides.Rpc} to an {@link ox#BlockOverrides.BlockOverrides}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.fromRpc({\n * baseFeePerGas: '0x1',\n * blobBaseFee: '0x2',\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: '0x4',\n * number: '0x5',\n * prevRandao: '0x6',\n * time: '0x1234567890',\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: '0x1',\n * index: '0x0',\n * validatorIndex: '0x1',\n * },\n * ],\n * })\n * ```\n *\n * @param rpcBlockOverrides - The RPC block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.BlockOverrides}.\n */\nexport function fromRpc(rpcBlockOverrides: Rpc): BlockOverrides {\n return {\n ...(rpcBlockOverrides.baseFeePerGas && {\n baseFeePerGas: BigInt(rpcBlockOverrides.baseFeePerGas),\n }),\n ...(rpcBlockOverrides.blobBaseFee && {\n blobBaseFee: BigInt(rpcBlockOverrides.blobBaseFee),\n }),\n ...(rpcBlockOverrides.feeRecipient && {\n feeRecipient: rpcBlockOverrides.feeRecipient,\n }),\n ...(rpcBlockOverrides.gasLimit && {\n gasLimit: BigInt(rpcBlockOverrides.gasLimit),\n }),\n ...(rpcBlockOverrides.number && {\n number: BigInt(rpcBlockOverrides.number),\n }),\n ...(rpcBlockOverrides.prevRandao && {\n prevRandao: BigInt(rpcBlockOverrides.prevRandao),\n }),\n ...(rpcBlockOverrides.time && {\n time: BigInt(rpcBlockOverrides.time),\n }),\n ...(rpcBlockOverrides.withdrawals && {\n withdrawals: rpcBlockOverrides.withdrawals.map(Withdrawal.fromRpc),\n }),\n }\n}\n\n/**\n * Converts an {@link ox#BlockOverrides.BlockOverrides} to an {@link ox#BlockOverrides.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.toRpc({\n * baseFeePerGas: 1n,\n * blobBaseFee: 2n,\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: 4n,\n * number: 5n,\n * prevRandao: 6n,\n * time: 78187493520n,\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: 1n,\n * index: 0,\n * validatorIndex: 1,\n * },\n * ],\n * })\n * ```\n *\n * @param blockOverrides - The block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.Rpc}.\n */\nexport function toRpc(blockOverrides: BlockOverrides): Rpc {\n return {\n ...(typeof blockOverrides.baseFeePerGas === 'bigint' && {\n baseFeePerGas: Hex.fromNumber(blockOverrides.baseFeePerGas),\n }),\n ...(typeof blockOverrides.blobBaseFee === 'bigint' && {\n blobBaseFee: Hex.fromNumber(blockOverrides.blobBaseFee),\n }),\n ...(typeof blockOverrides.feeRecipient === 'string' && {\n feeRecipient: blockOverrides.feeRecipient,\n }),\n ...(typeof blockOverrides.gasLimit === 'bigint' && {\n gasLimit: Hex.fromNumber(blockOverrides.gasLimit),\n }),\n ...(typeof blockOverrides.number === 'bigint' && {\n number: Hex.fromNumber(blockOverrides.number),\n }),\n ...(typeof blockOverrides.prevRandao === 'bigint' && {\n prevRandao: Hex.fromNumber(blockOverrides.prevRandao),\n }),\n ...(typeof blockOverrides.time === 'bigint' && {\n time: Hex.fromNumber(blockOverrides.time),\n }),\n ...(blockOverrides.withdrawals && {\n withdrawals: blockOverrides.withdrawals.map(Withdrawal.toRpc),\n }),\n }\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 {\n inputs: [\n {\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n\nexport const batchGatewayAbi = [\n {\n name: 'query',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n type: 'tuple[]',\n name: 'queries',\n components: [\n {\n type: 'address',\n name: 'sender',\n },\n {\n type: 'string[]',\n name: 'urls',\n },\n {\n type: 'bytes',\n name: 'data',\n },\n ],\n },\n ],\n outputs: [\n {\n type: 'bool[]',\n name: 'failures',\n },\n {\n type: 'bytes[]',\n name: 'responses',\n },\n ],\n },\n {\n name: 'HttpError',\n type: 'error',\n inputs: [\n {\n type: 'uint16',\n name: 'status',\n },\n {\n type: 'string',\n name: 'message',\n },\n ],\n },\n] as const\n\nconst universalResolverErrors = [\n {\n inputs: [\n {\n name: 'dns',\n type: 'bytes',\n },\n ],\n name: 'DNSDecodingFailed',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'ens',\n type: 'string',\n },\n ],\n name: 'DNSEncodingFailed',\n type: 'error',\n },\n {\n inputs: [],\n name: 'EmptyAddress',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'HttpError',\n type: 'error',\n },\n {\n inputs: [],\n name: 'InvalidBatchGatewayResponse',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'errorData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n {\n name: 'resolver',\n type: 'address',\n },\n ],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n ],\n name: 'ResolverNotFound',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'primary',\n type: 'string',\n },\n {\n name: 'primaryAddress',\n type: 'bytes',\n },\n ],\n name: 'ReverseAddressMismatch',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'selector',\n type: 'bytes4',\n },\n ],\n name: 'UnsupportedResolverProfile',\n type: 'error',\n },\n] as const\n\nexport const universalResolverResolveAbi = [\n ...universalResolverErrors,\n {\n name: 'resolveWithGateways',\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: 'reverseWithGateways',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'uint256', name: 'coinType' },\n { type: 'string[]', name: 'gateways' },\n ],\n outputs: [\n { type: 'string', name: 'resolvedName' },\n { type: 'address', name: 'resolver' },\n { type: 'address', name: 'reverseResolver' },\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 erc1271Abi = [\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 erc6492SignatureValidatorAbi = [\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-1155 Multi Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-1155) */\nexport const erc1155Abi = [\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'needed',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InsufficientBalance',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'approver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidApprover',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: 'idsLength',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'valuesLength',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InvalidArrayLength',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidOperator',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidReceiver',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidSender',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'ERC1155MissingApprovalForAll',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n ],\n name: 'TransferBatch',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'TransferSingle',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'string',\n name: 'value',\n type: 'string',\n },\n {\n indexed: true,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'URI',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address[]',\n name: 'accounts',\n type: 'address[]',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n ],\n name: 'balanceOfBatch',\n outputs: [\n {\n internalType: 'uint256[]',\n name: '',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'isApprovedForAll',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'interfaceId',\n type: 'bytes4',\n },\n ],\n name: 'supportsInterface',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'uri',\n outputs: [\n {\n internalType: 'string',\n name: '',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\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: 'tokenId',\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 erc6492SignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\nexport const multicall3Bytecode =\n '0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033'\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 { 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 {\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 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","/** @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 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 { Abi, AbiStateMutability } from 'abitype'\n\nimport { AbiFunctionSignatureNotFoundError } from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type SliceErrorType, 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 DecodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = {\n abi: abi\n data: Hex\n}\n\nexport type DecodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allFunctionNames extends\n ContractFunctionName = ContractFunctionName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [functionName in allFunctionNames]: {\n args: ContractFunctionArgs\n functionName: functionName\n }\n }[allFunctionNames]\n >\n : {\n args: readonly unknown[] | undefined\n functionName: string\n }\n\nexport type DecodeFunctionDataErrorType =\n | AbiFunctionSignatureNotFoundError\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | SliceErrorType\n | ErrorType\n\nexport function decodeFunctionData(\n parameters: DecodeFunctionDataParameters,\n) {\n const { abi, data } = parameters as DecodeFunctionDataParameters\n const signature = slice(data, 0, 4)\n const description = abi.find(\n (x) =>\n x.type === 'function' &&\n signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!description)\n throw new AbiFunctionSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeFunctionData',\n })\n return {\n functionName: (description as { name: string }).name,\n args: ('inputs' in description &&\n description.inputs &&\n description.inputs.length > 0\n ? decodeAbiParameters(description.inputs, slice(data, 4))\n : undefined) as readonly unknown[] | undefined,\n } as DecodeFunctionDataReturnType\n}\n","import type { Abi, ExtractAbiErrors } from 'abitype'\n\nimport {\n AbiErrorInputsNotFoundError,\n AbiErrorNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\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 { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeErrorResult'\n\nexport type EncodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n errorName extends ContractErrorName | undefined = ContractErrorName,\n ///\n hasErrors = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiErrors] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractErrorArgs<\n abi,\n errorName extends ContractErrorName\n ? errorName\n : ContractErrorName\n >,\n allErrorNames = ContractErrorName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { errorName?: errorName | allErrorNames | undefined }\n : { errorName: errorName | allErrorNames }\n : { errorName?: errorName | allErrorNames | undefined }\n> &\n (hasErrors extends true ? unknown : never)\n\nexport type EncodeErrorResultReturnType = Hex\n\nexport type EncodeErrorResultErrorType =\n | GetAbiItemErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | EncodeAbiParametersErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function encodeErrorResult<\n const abi extends Abi | readonly unknown[],\n errorName extends ContractErrorName | undefined = undefined,\n>(\n parameters: EncodeErrorResultParameters,\n): EncodeErrorResultReturnType {\n const { abi, errorName, args } = parameters as EncodeErrorResultParameters\n\n let abiItem = abi[0]\n if (errorName) {\n const item = getAbiItem({ abi, args, name: errorName })\n if (!item) throw new AbiErrorNotFoundError(errorName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'error')\n throw new AbiErrorNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toFunctionSelector(definition)\n\n let data: Hex = '0x'\n if (args && args.length > 0) {\n if (!abiItem.inputs)\n throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath })\n data = encodeAbiParameters(abiItem.inputs, args)\n }\n return concatHex([signature, data])\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n AbiFunctionOutputsNotFoundError,\n InvalidArrayError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionName,\n ContractFunctionReturnType,\n} from '../../types/contract.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 GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionResult'\n\nexport type EncodeFunctionResultParameters<\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 allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n result?:\n | ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n never // allow all args. required for overloads to work.\n >\n | undefined\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 (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionResultReturnType = Hex\n\nexport type EncodeFunctionResultErrorType =\n | AbiFunctionOutputsNotFoundError\n | AbiFunctionNotFoundError\n | EncodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function encodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionResultParameters,\n): EncodeFunctionResultReturnType {\n const { abi, functionName, result } =\n parameters as EncodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, 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\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath })\n\n const values = (() => {\n if (abiItem.outputs.length === 0) return []\n if (abiItem.outputs.length === 1) return [result]\n if (Array.isArray(result)) return result\n throw new InvalidArrayError(result)\n })()\n\n return encodeAbiParameters(abiItem.outputs, values)\n}\n","import { batchGatewayAbi } from '../../constants/abis.js'\nimport { solidityError } from '../../constants/solidity.js'\nimport type { Hex } from '../../types/misc.js'\nimport { decodeFunctionData } from '../abi/decodeFunctionData.js'\nimport { encodeErrorResult } from '../abi/encodeErrorResult.js'\nimport { encodeFunctionResult } from '../abi/encodeFunctionResult.js'\nimport type {\n CcipRequestErrorType,\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../ccip.js'\n\nexport const localBatchGatewayUrl = 'x-batch-gateway:true'\n\nexport async function localBatchGatewayRequest(parameters: {\n data: Hex\n ccipRequest: (\n parameters: CcipRequestParameters,\n ) => Promise\n}): Promise {\n const { data, ccipRequest } = parameters\n\n const {\n args: [queries],\n } = decodeFunctionData({ abi: batchGatewayAbi, data })\n\n const failures: boolean[] = []\n const responses: Hex[] = []\n await Promise.all(\n queries.map(async (query, i) => {\n try {\n responses[i] = query.urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({ data: query.data, ccipRequest })\n : await ccipRequest(query)\n failures[i] = false\n } catch (err) {\n failures[i] = true\n responses[i] = encodeError(err as CcipRequestErrorType)\n }\n }),\n )\n\n return encodeFunctionResult({\n abi: batchGatewayAbi,\n functionName: 'query',\n result: [failures, responses],\n })\n}\n\nfunction encodeError(error: CcipRequestErrorType): Hex {\n if (error.name === 'HttpRequestError' && error.status)\n return encodeErrorResult({\n abi: batchGatewayAbi,\n errorName: 'HttpError',\n args: [error.status, error.shortMessage],\n })\n return encodeErrorResult({\n abi: [solidityError],\n errorName: 'Error',\n args: ['shortMessage' in error ? error.shortMessage : error.message],\n })\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Client } from '../clients/createClient.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 { ErrorType } from '../errors/utils.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.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 {\n localBatchGatewayRequest,\n localBatchGatewayUrl,\n} from './ens/localBatchGatewayRequest.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 = urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({\n data: callData,\n ccipRequest: ccipRequest_,\n })\n : 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.toLowerCase()).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","import { type Address, parseAbi } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\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 multicall3Bytecode,\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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } 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 /** Block overrides for the call. */\n blockOverrides?: BlockOverrides.BlockOverrides | 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 authorizationList,\n batch = Boolean(client.batch?.multicall),\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n accessList,\n blobs,\n blockOverrides,\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 =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcBlockOverrides = blockOverrides\n ? BlockOverrides.toRpc(blockOverrides)\n : undefined\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 {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\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,\n 'call',\n ) as TransactionRequest\n\n if (\n batch &&\n shouldPerformMulticall({ request }) &&\n !rpcStateOverride &&\n !rpcBlockOverrides\n ) {\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 params = (() => {\n const base = [\n request as ExactPartial,\n block,\n ] as const\n if (rpcStateOverride && rpcBlockOverrides)\n return [...base, rpcStateOverride, rpcBlockOverrides] as const\n if (rpcStateOverride) return [...base, rpcStateOverride] as const\n if (rpcBlockOverrides) return [...base, {}, rpcBlockOverrides] as const\n return base\n })()\n\n const response = await client.request({\n method: 'eth_call',\n params,\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 {\n batchSize = 1024,\n deployless = false,\n wait = 0,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n data,\n to,\n } = args\n\n const multicallAddress = (() => {\n if (deployless) return null\n if (args.multicallAddress) return args.multicallAddress\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new ClientChainNotConfiguredError()\n })()\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? 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 ...(multicallAddress === null\n ? {\n data: toDeploylessCallViaBytecodeData({\n code: multicall3Bytecode,\n data: calldata,\n }),\n }\n : { to: multicallAddress, data: calldata }),\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: { code: Hex; data: Hex }) {\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","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @module\n * @privateRemarks\n * WARNING:\n * - Don't remove error codes\n * - Don't change or reorder error codes.\n *\n * Good naming conventions:\n * - Prefixing common errors — e.g. under the same package — can be a good way to namespace them. E.g. All codec-related errors start with `SOLANA_ERROR__CODECS__`.\n * - Use consistent names — e.g. choose `PDA` or `PROGRAM_DERIVED_ADDRESS` and stick with it. Ensure your names are consistent with existing error codes. The decision might have been made for you.\n * - Recommended prefixes and suffixes:\n * - `MALFORMED_`: Some input was not constructed properly. E.g. `MALFORMED_BASE58_ENCODED_ADDRESS`.\n * - `INVALID_`: Some input is invalid (other than because it was MALFORMED). E.g. `INVALID_NUMBER_OF_BYTES`.\n * - `EXPECTED_`: Some input was different than expected, no need to specify the \"GOT\" part unless necessary. E.g. `EXPECTED_DECODED_ACCOUNT`.\n * - `_CANNOT_`: Some operation cannot be performed or some input cannot be used due to some condition. E.g. `CANNOT_DECODE_EMPTY_BYTE_ARRAY` or `PDA_CANNOT_END_WITH_PDA_MARKER`.\n * - `_MUST_BE_`: Some condition must be true. E.g. `NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE`.\n * - `_FAILED_TO_`: Tried to perform some operation and failed. E.g. `FAILED_TO_DECODE_ACCOUNT`.\n * - `_NOT_FOUND`: Some operation lead to not finding something. E.g. `ACCOUNT_NOT_FOUND`.\n * - `_OUT_OF_RANGE`: Some value is out of range. E.g. `ENUM_DISCRIMINATOR_OUT_OF_RANGE`.\n * - `_EXCEEDED`: Some limit was exceeded. E.g. `PDA_MAX_SEED_LENGTH_EXCEEDED`.\n * - `_MISMATCH`: Some elements do not match. E.g. `ENCODER_DECODER_FIXED_SIZE_MISMATCH`.\n * - `_MISSING`: Some required input is missing. E.g. `TRANSACTION_FEE_PAYER_MISSING`.\n * - `_UNIMPLEMENTED`: Some required component is not available in the environment. E.g. `SUBTLE_CRYPTO_VERIFY_FUNCTION_UNIMPLEMENTED`.\n */\nexport const SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nexport const SOLANA_ERROR__INVALID_NONCE = 2;\nexport const SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nexport const SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nexport const SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nexport const SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nexport const SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nexport const SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nexport const SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nexport const SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\n\n// JSON-RPC-related errors.\n// Reserve error codes in the range [-32768, -32000]\n// Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs\nexport const SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nexport const SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nexport const SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nexport const SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\n\n// Addresses-related errors.\n// Reserve error codes in the range [2800000-2800999].\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 2800000;\nexport const SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nexport const SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nexport const SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nexport const SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nexport const SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nexport const SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nexport const SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\n\n// Account-related errors.\n// Reserve error codes in the range [3230000-3230999].\nexport const SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 3230000;\nexport const SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nexport const SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\n\n// Subtle-Crypto-related errors.\n// Reserve error codes in the range [3610000-3610999].\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 3610000;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\n\n// Crypto-related errors.\n// Reserve error codes in the range [3611000-3611050].\nexport const SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611000;\n\n// Key-related errors.\n// Reserve error codes in the range [3704000-3704999].\nexport const SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704000;\nexport const SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nexport const SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nexport const SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nexport const SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\n\n// Instruction-related errors.\n// Reserve error codes in the range [4128000-4128999].\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128000;\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nexport const SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\n\n// Instruction errors.\n// Reserve error codes starting with [4615000-4615999] for the Rust enum `InstructionError`.\n// Error names here are dictated by the RPC (see ./instruction-error.ts).\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615000;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\n\n// Signer-related errors.\n// Reserve error codes in the range [5508000-5508999].\nexport const SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508000;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nexport const SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\n\n// Offchain-message-related errors.\n// Reserve error codes in the range [5607000-5607999].\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED = 5607000;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE = 5607001;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE = 5607002;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH = 5607003;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH = 5607004;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO = 5607005;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED = 5607006;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH = 5607007;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH = 5607008;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY = 5607009;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO = 5607010;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING = 5607011;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH = 5607012;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE = 5607013;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION = 5607014;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED = 5607015;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE = 5607016;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE = 5607017;\n\n// Transaction-related errors.\n// Reserve error codes in the range [5663000-5663999].\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663000;\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nexport const SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nexport const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nexport const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nexport const SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;\nexport const SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;\n\n// Transaction errors.\n// Reserve error codes starting with [7050000-7050999] for the Rust enum `TransactionError`.\n// Error names here are dictated by the RPC (see ./transaction-error.ts).\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 7050000;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\n// `InstructionError` intentionally omitted.\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\n\n// Instruction plan related errors.\n// Reserve error codes in the range [7618000-7618999].\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618000;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED = 7618004;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND = 7618005;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN = 7618006;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN = 7618007;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT = 7618008;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT = 7618009;\n\n// Codec-related errors.\n// Reserve error codes in the range [8078000-8078999].\nexport const SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078000;\nexport const SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nexport const SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nexport const SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nexport const SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nexport const SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nexport const SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nexport const SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nexport const SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nexport const SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nexport const SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nexport const SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nexport const SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nexport const SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nexport const SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nexport const SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nexport const SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nexport const SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nexport const SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nexport const SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nexport const SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;\n\n// RPC-related errors.\n// Reserve error codes in the range [8100000-8100999].\nexport const SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 8100000;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nexport const SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\n\n// RPC-Subscriptions-related errors.\n// Reserve error codes in the range [8190000-8190999].\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 8190000;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\n\n// Invariant violation errors.\n// Reserve error codes in the range [9900000-9900999].\n// These errors should only be thrown when there is a bug with the\n// library itself and should, in theory, never reach the end user.\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 9900000;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;\n\n/**\n * A union of every Solana error code\n *\n * @privateRemarks\n * You might be wondering why this is not a TypeScript enum or const enum.\n *\n * One of the goals of this library is to enable people to use some or none of it without having to\n * bundle all of it.\n *\n * If we made the set of error codes an enum then anyone who imported it (even if to only use a\n * single error code) would be forced to bundle every code and its label.\n *\n * Const enums appear to solve this problem by letting the compiler inline only the codes that are\n * actually used. Unfortunately exporting ambient (const) enums from a library like `@solana/errors`\n * is not safe, for a variety of reasons covered here: https://stackoverflow.com/a/28818850\n */\nexport type SolanaErrorCode =\n | typeof SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND\n | typeof SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE\n | typeof SOLANA_ERROR__ADDRESSES__MALFORMED_PDA\n | typeof SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE\n | typeof SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER\n | typeof SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED\n | typeof SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS\n | typeof SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE\n | typeof SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__INVALID_CONSTANT\n | typeof SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS\n | typeof SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE\n | typeof SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES\n | typeof SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA\n | typeof SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH\n | typeof SOLANA_ERROR__INVALID_NONCE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE\n | typeof SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_PARAMS\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_REQUEST\n | typeof SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND\n | typeof SOLANA_ERROR__JSON_RPC__PARSE_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SCAN_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION\n | typeof SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY\n | typeof SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE\n | typeof SOLANA_ERROR__MALFORMED_BIGINT_STRING\n | typeof SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR\n | typeof SOLANA_ERROR__MALFORMED_NUMBER_STRING\n | typeof SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD\n | typeof SOLANA_ERROR__RPC__INTEGER_OVERFLOW\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID\n | typeof SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING\n | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES\n | typeof SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE\n | typeof SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE\n | typeof SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT;\n\n/**\n * Errors of this type are understood to have an optional {@link SolanaError} nested inside as\n * `cause`.\n */\nexport type SolanaErrorCodeWithCause = typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE;\n\n/**\n * Errors of this type have a deprecated `cause` property. Consumers should use the error's\n * `context` instead to access relevant error information.\n */\nexport type SolanaErrorCodeWithDeprecatedCause =\n typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @privateRemarks\n * WARNING:\n * - Don't change or remove members of an error's context.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SolanaErrorCode,\n} from './codes';\nimport { RpcSimulateTransactionResult } from './json-rpc-error';\n\ntype BasicInstructionErrorContext = { [P in T]: { index: number } };\n\ntype DefaultUnspecifiedErrorContextToUndefined = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype ReadonlyContextValue = {\n [P in keyof T]: Readonly;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit {\n readonly [n: number]: number;\n}\n\n/** A amount of bytes. */\ntype Bytes = number;\n\n/**\n * A map of every {@link SolanaError} code to the type of its `context` property.\n */\nexport type SolanaErrorContext = ReadonlyContextValue<\n DefaultUnspecifiedErrorContextToUndefined<\n BasicInstructionErrorContext<\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n > & {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: {\n putativeAddress: string;\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: {\n actual: number;\n maxSeeds: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: {\n actual: number;\n index: number;\n maxSeedLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: {\n bump: number;\n };\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: {\n currentBlockHeight: bigint;\n lastValidBlockHeight: bigint;\n };\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: {\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: {\n stringValues: readonly string[];\n };\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: {\n encodedBytes: ReadonlyUint8Array;\n hexEncodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: {\n decoderFixedSize: number;\n encoderFixedSize: number;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: {\n decoderMaxSize: number | undefined;\n encoderMaxSize: number | undefined;\n };\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n formattedValidDiscriminators: string;\n validDiscriminators: readonly number[];\n };\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: {\n expectedLength: number;\n numExcessBytes: number;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: {\n codecDescription: string;\n expectedSize: number;\n hexZeroValue: string;\n zeroValue: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n expected: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: {\n constant: ReadonlyUint8Array;\n data: ReadonlyUint8Array;\n hexConstant: string;\n hexData: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: {\n formattedNumericalValues: string;\n numericalValues: readonly number[];\n stringValues: readonly string[];\n variant: number | string | symbol;\n };\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: {\n actual: bigint | number;\n codecDescription: string;\n expected: bigint | number;\n };\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: {\n alphabet: string;\n base: number;\n value: string;\n };\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n maxRange: number;\n minRange: number;\n };\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: {\n codecDescription: string;\n max: bigint | number;\n min: bigint | number;\n value: bigint | number;\n };\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: {\n bytesLength: number;\n codecDescription: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: {\n decodedBytes: ReadonlyUint8Array;\n hexDecodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: {\n maxRange: number;\n minRange: number;\n variant: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: {\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: {\n code: number;\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: {\n errorName: string;\n index: number;\n instructionErrorContext?: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: {\n numBytesRequired: number;\n numFreeBytes: number;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n instructionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n transactionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]: {\n actualKind: string;\n expectedKind: string;\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: {\n data?: ReadonlyUint8Array;\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: {\n accountAddresses?: readonly string[];\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: {\n actualProgramAddress: string;\n expectedProgramAddress: string;\n };\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__INVALID_NONCE]: {\n actualNonceValue: string;\n expectedNonceValue: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: {\n cacheKey: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: {\n channelName: string;\n supportedChannelNames: readonly string[];\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: {\n unexpectedValue: unknown;\n };\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: {\n currentBlockHeight: bigint;\n rewardsCompleteBlockHeight: bigint;\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: {\n contextSlot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: {\n numSlotsBehind?: number;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: Omit<\n RpcSimulateTransactionResult,\n 'err'\n >;\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: {\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: {\n byteLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: {\n error: unknown;\n message: string;\n };\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: {\n nonceAccountAddress: string;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]: {\n missingRequiredSigners: readonly string[];\n unexpectedSigners: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]: {\n actualBytes: number;\n maxBytes: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]: {\n actualMessageFormat: number;\n expectedMessageFormat: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]: {\n actualLength: number;\n specifiedLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signatoryAddresses: readonly string[];\n signaturesLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]: {\n signatoriesWithInvalidSignatures: readonly string[];\n signatoriesWithMissingSignatures: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]: {\n actualVersion: number;\n expectedVersion: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: {\n notificationName: string;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: {\n errorEvent: Event;\n };\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: {\n method: string;\n params: readonly unknown[];\n };\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: {\n argumentLabel: string;\n keyPath: readonly (number | string | symbol)[];\n methodName: string;\n optionalPathLabel: string;\n path?: string;\n value: bigint;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: {\n headers: Headers;\n message: string;\n statusCode: number;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: {\n headers: readonly string[];\n };\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: {\n key: CryptoKey;\n };\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: {\n value: bigint;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: {\n errorName: string;\n transactionErrorContext?: unknown;\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: {\n transactionSize: Bytes;\n transactionSizeLimit: Bytes;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: {\n lookupTableAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: {\n highestKnownIndex: number;\n highestRequestedIndex: number;\n lookupTableAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: {\n unitsConsumed: number;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signaturesLength: number;\n signerAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: {\n nonce: string;\n };\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: {\n actualVersion: number;\n };\n }\n >\n>;\n\nexport function decodeEncodedContext(encodedContext: string): object {\n const decodedUrlString = __NODEJS__ ? Buffer.from(encodedContext, 'base64').toString('utf8') : atob(encodedContext);\n return Object.fromEntries(new URLSearchParams(decodedUrlString).entries());\n}\n\nfunction encodeValue(value: unknown): string {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join('%2C%20' /* \", \" */);\n return '%5B' /* \"[\" */ + commaSeparatedValues + /* \"]\" */ '%5D';\n } else if (typeof value === 'bigint') {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null\n ? // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...(value as object) }\n : value,\n ),\n );\n }\n}\n\nfunction encodeObjectContextEntry([key, value]: [string, unknown]): `${typeof key}=${string}` {\n return `${key}=${encodeValue(value)}`;\n}\n\nexport function encodeContextObject(context: object): string {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join('&');\n return __NODEJS__ ? Buffer.from(searchParamsString, 'utf8').toString('base64') : btoa(searchParamsString);\n}\n","/* eslint-disable sort-keys-fix/sort-keys-fix */\n/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors#adding-a-new-error\n *\n * WARNING:\n * - Don't change the meaning of an error message.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,\n SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,\n SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,\n SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,\n SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,\n SolanaErrorCode,\n} from './codes';\n\n/**\n * A map of every {@link SolanaError} code to the error message shown to developers in development\n * mode.\n */\nexport const SolanaErrorMessages: Readonly<{\n // This type makes this data structure exhaustive with respect to `SolanaErrorCode`.\n // TypeScript will fail to build this project if add an error code without a message.\n [P in SolanaErrorCode]: string;\n}> = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: 'Account not found at address: $address',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:\n 'Not all accounts were decoded. Encoded accounts found at addresses: $addresses.',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: 'Expected decoded account at address: $address',\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: 'Failed to decode account data at address: $address',\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: 'Accounts not found at addresses: $addresses',\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:\n 'Unable to find a viable program address bump seed.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: '$putativeAddress is not a base58-encoded address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:\n 'Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: 'The `CryptoKey` must be an `Ed25519` public key.',\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:\n '$putativeOffCurveAddress is not a base58-encoded off-curve address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: 'Invalid seeds; point must fall off the Ed25519 curve.',\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:\n 'Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].',\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:\n 'A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.',\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:\n 'The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.',\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:\n 'Expected program derived address bump to be in the range [0, 255], got: $bump.',\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: 'Program address cannot end with PDA marker.',\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:\n 'The network has progressed past the last block for which this transaction could have been committed.',\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:\n 'Codec [$codecDescription] cannot decode empty byte arrays.',\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:\n 'Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.',\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:\n 'Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:\n 'Encoder and decoder must either both be fixed-size or variable-size.',\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.',\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: 'Expected a fixed-size codec, got a variable-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected a positive byte length, got $bytesLength.',\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: 'Expected a variable-size codec, got a fixed-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:\n 'Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].',\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected $expected bytes, got $bytesLength.',\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]:\n 'Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].',\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:\n 'Invalid discriminated union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:\n 'Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.',\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:\n 'Invalid literal union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:\n 'Expected [$codecDescription] to have $expected items, got $actual.',\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: 'Invalid value $value for base $base with alphabet $alphabet.',\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.',\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.',\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.',\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:\n 'Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].',\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:\n 'Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.',\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:\n 'This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?',\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: 'No random values implementation could be found.',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: 'instruction requires an uninitialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:\n 'instruction tries to borrow reference for an account which is already borrowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'instruction left account with an outstanding borrowed reference',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:\n \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: 'account data too small for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: 'instruction expected an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:\n 'An account does not have enough lamports to be rent-exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: 'Program arithmetic overflowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: 'Failed to serialize or deserialize account data: $encodedData',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:\n 'Builtin programs must consume compute units',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: 'Cross-program invocation call depth too deep',\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: 'Computational budget exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: 'custom program error: #$code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: 'instruction contains duplicate accounts',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:\n 'instruction modifications of multiply-passed account differ',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: 'executable accounts must be rent exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: 'instruction changed executable accounts data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:\n 'instruction changed the balance of an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: 'instruction changed executable bit of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:\n 'instruction modified data of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:\n 'instruction spent from the balance of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: 'generic instruction error',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: 'Provided owner is not allowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: 'Account is immutable',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: 'Incorrect authority provided',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: 'incorrect program id for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: 'insufficient funds for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: 'invalid account data for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: 'Invalid account owner',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: 'invalid program argument',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: 'program returned invalid error code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: 'invalid instruction data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: 'Failed to reallocate account data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: 'Provided seeds do not result in a valid address',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:\n 'Accounts data allocations exceeded the maximum allowed per transaction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: 'Max accounts exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: 'Max instruction trace length exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:\n 'Length of the seed is too long for address generation',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: 'An account required by the instruction is missing',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: 'missing required signature for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:\n 'instruction illegally modified the program id of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: 'insufficient account keys for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:\n 'Cross-program invocation with unauthorized signer or writable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:\n 'Failed to create program execution environment',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: 'Program failed to compile',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: 'Program failed to complete',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: 'instruction modified data of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:\n 'instruction changed the balance of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:\n 'Cross-program invocation reentrancy not allowed for this instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: 'instruction modified rent epoch of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:\n 'sum of account balances before and after instruction do not match',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: 'instruction requires an initialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: '',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: 'Unsupported program id',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: 'Unsupported sysvar',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: 'Invalid instruction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: 'The provided instruction plan is empty.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]:\n 'No failed transaction plan result was found in the provided transaction plan result.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]:\n 'This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved — e.g. by targetting RPCs that support transaction bundles.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:\n 'The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:\n 'The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: 'Invalid transaction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:\n 'No more instructions to pack; the message packer has completed the instruction plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]:\n 'Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]:\n 'Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]:\n 'Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]:\n 'Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: 'The instruction does not have any accounts.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: 'The instruction does not have any data.',\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:\n 'Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.',\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:\n 'Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__INVALID_NONCE]:\n 'The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`',\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:\n 'Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It ' +\n 'should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:\n 'Invariant violation: This data publisher does not publish to the channel named ' +\n '`$channelName`. Supported channels include $supportedChannelNames.',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:\n 'Invariant violation: WebSocket message iterator state is corrupt; iterated without first ' +\n 'resolving existing message promise. It should be impossible to hit this error; please ' +\n 'file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:\n 'Invariant violation: WebSocket message iterator is missing state storage. It should be ' +\n 'impossible to hit this error; please file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:\n 'Invariant violation: Switch statement non-exhaustive. Received unexpected value ' +\n '`$unexpectedValue`. It should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: 'JSON-RPC error: Internal JSON-RPC error ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: 'JSON-RPC error: Invalid method parameter(s) ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:\n 'JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:\n 'JSON-RPC error: The method does not exist / is not available ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:\n 'JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:\n 'Epoch rewards period still active at slot $slot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:\n 'Failed to query long-term storage; please try again',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: 'Minimum context slot has not been reached',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: 'Node is unhealthy; behind by $numSlotsBehind slots',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: 'No snapshot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: 'Transaction simulation failed',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:\n \"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:\n 'Transaction history is not available from this node',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: 'Transaction signature length mismatch',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:\n 'Transaction signature verification failure',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: '$__serverMessage',\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: 'Key pair bytes must be of length 64, got $byteLength.',\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:\n 'Expected private key bytes with length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:\n 'Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:\n 'The provided private key does not match the provided public key.',\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.',\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: 'Lamports value must be in the range [0, 2e64-1]',\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: '`$value` cannot be parsed as a `BigInt`',\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: '$message',\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: '`$value` cannot be parsed as a `Number`',\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: 'No nonce account could be found at address `$nonceAccountAddress`',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]:\n 'Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]:\n 'Attempted to sign an offchain message with an address that is not a signer for it',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]:\n 'The signer addresses in this offchain message envelope do not match the list of ' +\n 'required signers in the message preamble. These unexpected signers were present in the ' +\n 'envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope ' +\n '`[$missingSigners]`.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]:\n 'The message body provided has a byte-length of $actualBytes. The maximum allowable ' +\n 'byte-length is $maxBytes',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]:\n 'Expected message format $expectedMessageFormat, got $actualMessageFormat',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]:\n 'The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]: 'Offchain message content must be non-empty',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]:\n 'Offchain message must specify the address of at least one required signer',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]:\n 'Offchain message envelope must reserve space for at least one signature',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]:\n 'The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]:\n 'The signatories of this offchain message must be listed in lexicographical order',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]:\n 'An address must be listed no more than once among the signatories of an offchain message',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]:\n 'Offchain message is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]:\n 'Offchain message signature verification failed. Signature mismatch for required ' +\n 'signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories ' +\n '[$signatoriesWithMissingSignatures]',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]:\n 'The message body provided contains characters whose codes fall outside the allowed ' +\n 'range. In order to ensure clear-signing compatiblity with hardware wallets, the message ' +\n 'may only contain line feeds and characters in the range [\\\\x20-\\\\x7e].',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]:\n 'Expected offchain message version $expectedVersion. Got $actualVersion.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding offchain messages with version ' +\n '$unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:\n \"The notification name must end in 'Notifications' and the API must supply a \" +\n \"subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:\n 'WebSocket was closed before payload could be added to the send buffer',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: 'WebSocket connection closed',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: 'WebSocket failed to connect',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:\n 'Failed to obtain a subscription id from the server',\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: 'Could not find an API plan for RPC method: `$method`',\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:\n 'The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was ' +\n '`$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: 'HTTP error ($statusCode): $message',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:\n 'HTTP header(s) forbidden: $headers. Learn more at ' +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.',\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:\n 'Multiple distinct signers were identified for address `$address`. Please ensure that ' +\n 'you are using the same signer instance for each address.',\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:\n 'The provided value does not implement the `KeyPairSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:\n 'The provided value does not implement the `MessageModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:\n 'The provided value does not implement the `MessagePartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:\n 'The provided value does not implement any of the `MessageSigner` interfaces',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:\n 'The provided value does not implement the `TransactionModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:\n 'The provided value does not implement the `TransactionPartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:\n 'The provided value does not implement the `TransactionSendingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:\n 'The provided value does not implement any of the `TransactionSigner` interfaces',\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:\n 'More than one `TransactionSendingSigner` was identified.',\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:\n 'No `TransactionSendingSigner` was identified. Please provide a valid ' +\n '`TransactionWithSingleSendingSigner` transaction.',\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:\n 'Wallet account signers do not support signing multiple messages/transactions in a single operation',\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: 'Cannot export a non-extractable key.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: 'No digest implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall ' +\n '@solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]:\n 'No signature verification implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: 'No key generation implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: 'No signing implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: 'No key export implementation could be found.',\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]:\n 'Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'Transaction processing left an account with an outstanding borrowed reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: 'Account in use',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: 'Account loaded twice',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]:\n 'Attempt to debit an account but found no record of a prior credit.',\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]:\n \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: 'This transaction has already been processed',\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: 'Blockhash not found',\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: 'Loader call chain is too deep',\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]:\n 'Transactions are currently disabled due to cluster maintenance',\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]:\n 'Transaction contains a duplicate instruction ($index) that is not allowed',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: 'Insufficient funds for fee',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]:\n 'Transaction results in an account ($accountIndex) with insufficient funds for rent',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: 'This account may not be used to pay transaction fees',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: 'Transaction contains an invalid account reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]:\n 'Transaction loads an address table account with invalid data',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]:\n 'Transaction address table lookup uses an invalid index',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]:\n 'Transaction loads an address table account with an invalid owner',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]:\n 'LoadedAccountsDataSizeLimit set for transaction must be greater than 0.',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]:\n 'This program may not be used for executing instructions',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]:\n 'Transaction leaves an account with a lower balance than rent-exempt minimum',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]:\n 'Transaction loads a writable account that cannot be written',\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]:\n 'Transaction exceeded max loaded accounts data size cap',\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]:\n 'Transaction requires a fee but has no signature present',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: 'Attempt to load a program that does not exist',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]:\n 'Execution of the program referenced by account at index $accountIndex is temporarily restricted.',\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: 'ResanitizationNeeded',\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: 'Transaction failed to sanitize accounts offsets correctly',\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: 'Transaction did not pass signature verification',\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: 'Transaction locked too many accounts',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]:\n 'Sum of account balances before and after transaction do not match',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: 'The transaction failed with the error `$errorName`',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: 'Transaction version is unsupported',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]:\n 'Transaction would exceed account data limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]:\n 'Transaction would exceed total account data limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]:\n 'Transaction would exceed max account limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]:\n 'Transaction would exceed max Block Cost Limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: 'Transaction would exceed max Vote Cost Limit',\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]:\n 'Attempted to sign a transaction with an address that is not a signer for it',\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: 'Transaction is missing an address at index: $index.',\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]:\n 'Transaction has no expected signers therefore it cannot be encoded',\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]:\n 'Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: 'Transaction does not have a blockhash lifetime',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: 'Transaction is not a durable nonce transaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]:\n 'Contents of these address lookup tables unknown: $lookupTableAddresses',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]:\n 'Lookup of address at index $highestRequestedIndex failed for lookup table ' +\n '`$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table ' +\n 'may have been extended since its contents were retrieved',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: 'No fee payer set in CompiledTransaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]:\n 'Could not find program address at index $index',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Failed to estimate the compute unit consumption for this transaction message. This is ' +\n 'likely because simulating the transaction failed. Inspect the `cause` property of this ' +\n 'error to learn more',\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Transaction failed when it was simulated in order to estimate the compute unit consumption. ' +\n 'The compute unit estimate provided is for a transaction that failed when simulated and may not ' +\n 'be representative of the compute units this transaction would consume if successful. Inspect the ' +\n '`cause` property of this error to learn more',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: 'Transaction is missing a fee payer.',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]:\n \"Could not determine this transaction's signature. Make sure that the transaction has \" +\n 'been signed by its fee payer.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]:\n 'Transaction first instruction is not advance nonce account instruction.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]:\n 'Transaction with no instructions cannot be durable nonce transaction.',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]:\n 'This transaction includes an address (`$programAddress`) which is both ' +\n 'invoked and set as the fee payer. Program addresses may not pay fees',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]:\n 'This transaction includes an address (`$programAddress`) which is both invoked and ' +\n 'marked writable. Program addresses may not be writable',\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]:\n 'The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.',\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: 'Transaction is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]:\n 'Transaction version must be in the range [0, 127]. `$actualVersion` given',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]:\n 'The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction.',\n};\n","import { SolanaErrorCode } from './codes';\nimport { encodeContextObject } from './context';\nimport { SolanaErrorMessages } from './messages';\n\nconst enum StateType {\n EscapeSequence,\n Text,\n Variable,\n}\ntype State = Readonly<{\n [START_INDEX]: number;\n [TYPE]: StateType;\n}>;\nconst START_INDEX = 'i';\nconst TYPE = 't';\n\nexport function getHumanReadableErrorMessage(\n code: TErrorCode,\n context: object = {},\n): string {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return '';\n }\n let state: State;\n function commitStateUpTo(endIndex?: number) {\n if (state[TYPE] === StateType.Variable) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n\n fragments.push(\n variableName in context\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName as keyof typeof context]}`\n : `$${variableName}`,\n );\n } else if (state[TYPE] === StateType.Text) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments: string[] = [];\n messageFormatString.split('').forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]:\n messageFormatString[0] === '\\\\'\n ? StateType.EscapeSequence\n : messageFormatString[0] === '$'\n ? StateType.Variable\n : StateType.Text,\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case StateType.EscapeSequence:\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n break;\n case StateType.Text:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n }\n break;\n case StateType.Variable:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join('');\n}\n\nexport function getErrorMessage(\n code: TErrorCode,\n context: Record = {},\n): string {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n /**\n * DANGER: Be sure that the shell command is escaped in such a way that makes it\n * impossible for someone to craft malicious context values that would result in\n * an exploit against anyone who bindly copy/pastes it into their terminal.\n */\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n","import { SolanaErrorCode, SolanaErrorCodeWithCause, SolanaErrorCodeWithDeprecatedCause } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { getErrorMessage } from './message-formatter';\n\n/**\n * A variant of {@link SolanaError} where the `cause` property is deprecated.\n *\n * This type is returned by {@link isSolanaError} when checking for error codes in\n * {@link SolanaErrorCodeWithDeprecatedCause}. Accessing `cause` on these errors will show\n * a deprecation warning in IDEs that support JSDoc `@deprecated` tags.\n */\nexport interface SolanaErrorWithDeprecatedCause<\n TErrorCode extends SolanaErrorCodeWithDeprecatedCause = SolanaErrorCodeWithDeprecatedCause,\n> extends Omit, 'cause'> {\n /**\n * @deprecated The `cause` property is deprecated for this error code.\n * Use the error's `context` property instead to access relevant error information.\n */\n readonly cause?: unknown;\n}\n\n/**\n * A type guard that returns `true` if the input is a {@link SolanaError}, optionally with a\n * particular error code.\n *\n * When the `code` argument is supplied and the input is a {@link SolanaError}, TypeScript will\n * refine the error's {@link SolanaError#context | `context`} property to the type associated with\n * that error code. You can use that context to render useful error messages, or to make\n * context-aware decisions that help your application to recover from the error.\n *\n * @example\n * ```ts\n * import {\n * SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE,\n * SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n * isSolanaError,\n * } from '@solana/errors';\n * import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions';\n *\n * try {\n * const transactionSignature = getSignatureFromTransaction(tx);\n * assertIsFullySignedTransaction(tx);\n * /* ... *\\/\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * displayError(\n * \"We can't send this transaction without signatures for these addresses:\\n- %s\",\n * // The type of the `context` object is now refined to contain `addresses`.\n * e.context.addresses.join('\\n- '),\n * );\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) {\n * if (!tx.feePayer) {\n * displayError('Choose a fee payer for this transaction before sending it');\n * } else {\n * displayError('The fee payer still needs to sign for this transaction');\n * }\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function isSolanaError(\n e: unknown,\n code: TErrorCode,\n): e is SolanaErrorWithDeprecatedCause;\nexport function isSolanaError(\n e: unknown,\n code?: TErrorCode,\n): e is SolanaError;\nexport function isSolanaError(\n e: unknown,\n /**\n * When supplied, this function will require that the input is a {@link SolanaError} _and_ that\n * its error code is exactly this value.\n */\n code?: TErrorCode,\n): e is SolanaError {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError).context.__code === code;\n }\n return true;\n }\n return false;\n}\n\ntype SolanaErrorCodedContext = {\n [P in SolanaErrorCode]: Readonly<{\n __code: P;\n }> &\n (SolanaErrorContext[P] extends undefined ? object : SolanaErrorContext[P]);\n};\n\n/**\n * Encapsulates an error's stacktrace, a Solana-specific numeric code that indicates what went\n * wrong, and optional context if the type of error indicated by the code supports it.\n */\nexport class SolanaError extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n readonly cause?: TErrorCode extends SolanaErrorCodeWithCause ? SolanaError : unknown = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n readonly context: SolanaErrorCodedContext[TErrorCode];\n constructor(\n ...[code, contextAndErrorOptions]: SolanaErrorContext[TErrorCode] extends undefined\n ? [code: TErrorCode, errorOptions?: ErrorOptions | undefined]\n : [code: TErrorCode, contextAndErrorOptions: SolanaErrorContext[TErrorCode] & (ErrorOptions | undefined)]\n ) {\n let context: SolanaErrorContext[TErrorCode] | undefined;\n let errorOptions: ErrorOptions | undefined;\n if (contextAndErrorOptions) {\n Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {\n // If the `ErrorOptions` type ever changes, update this code.\n if (name === 'cause') {\n errorOptions = { cause: descriptor.value };\n } else {\n if (context === undefined) {\n context = {\n __code: code,\n } as unknown as SolanaErrorContext[TErrorCode];\n }\n Object.defineProperty(context, name, descriptor);\n }\n });\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = Object.freeze(\n context === undefined\n ? {\n __code: code,\n }\n : context,\n ) as SolanaErrorCodedContext[TErrorCode];\n // This is necessary so that `isSolanaError()` can identify a `SolanaError` without having\n // to import the class for use in an `instanceof` check.\n this.name = 'SolanaError';\n }\n}\n","export function safeCaptureStackTrace(...args: Parameters): void {\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(...args);\n }\n}\n","import { SolanaErrorCode } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\n\ntype Config = Readonly<{\n /**\n * Oh, hello. You might wonder what in tarnation is going on here. Allow us to explain.\n *\n * One of the goals of `@solana/errors` is to allow errors that are not interesting to your\n * application to shake out of your app bundle in production. This means that we must never\n * export large hardcoded maps of error codes/messages.\n *\n * Unfortunately, where instruction and transaction errors from the RPC are concerned, we have\n * no choice but to keep a map between the RPC `rpcEnumError` enum name and its corresponding\n * `SolanaError` code. In the interest of implementing that map in as few bytes of source code\n * as possible, we do the following:\n *\n * 1. Reserve a block of sequential error codes for the enum in question\n * 2. Hardcode the list of enum names in that same order\n * 3. Match the enum error name from the RPC with its index in that list, and reconstruct the\n * `SolanaError` code by adding the `errorCodeBaseOffset` to that index\n */\n errorCodeBaseOffset: number;\n getErrorContext: (\n errorCode: SolanaErrorCode,\n rpcErrorName: string,\n rpcErrorContext?: unknown,\n ) => SolanaErrorContext[SolanaErrorCode];\n orderedErrorNames: string[];\n rpcEnumError: string | { [key: string]: unknown };\n}>;\n\nexport function getSolanaErrorFromRpcError(\n { errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }: Config,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructorOpt: Function,\n): SolanaError {\n let rpcErrorName;\n let rpcErrorContext;\n if (typeof rpcEnumError === 'string') {\n rpcErrorName = rpcEnumError;\n } else {\n rpcErrorName = Object.keys(rpcEnumError)[0];\n rpcErrorContext = rpcEnumError[rpcErrorName];\n }\n const codeOffset = orderedErrorNames.indexOf(rpcErrorName);\n const errorCode = (errorCodeBaseOffset + codeOffset) as SolanaErrorCode;\n const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);\n const err = new SolanaError(errorCode, errorContext);\n safeCaptureStackTrace(err, constructorOpt);\n return err;\n}\n","import { SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN } from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/solana-sdk/blob/master/instruction-error/src/lib.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'GenericError',\n 'InvalidArgument',\n 'InvalidInstructionData',\n 'InvalidAccountData',\n 'AccountDataTooSmall',\n 'InsufficientFunds',\n 'IncorrectProgramId',\n 'MissingRequiredSignature',\n 'AccountAlreadyInitialized',\n 'UninitializedAccount',\n 'UnbalancedInstruction',\n 'ModifiedProgramId',\n 'ExternalAccountLamportSpend',\n 'ExternalAccountDataModified',\n 'ReadonlyLamportChange',\n 'ReadonlyDataModified',\n 'DuplicateAccountIndex',\n 'ExecutableModified',\n 'RentEpochModified',\n 'NotEnoughAccountKeys',\n 'AccountDataSizeChanged',\n 'AccountNotExecutable',\n 'AccountBorrowFailed',\n 'AccountBorrowOutstanding',\n 'DuplicateAccountOutOfSync',\n 'Custom',\n 'InvalidError',\n 'ExecutableDataModified',\n 'ExecutableLamportChange',\n 'ExecutableAccountNotRentExempt',\n 'UnsupportedProgramId',\n 'CallDepth',\n 'MissingAccount',\n 'ReentrancyNotAllowed',\n 'MaxSeedLengthExceeded',\n 'InvalidSeeds',\n 'InvalidRealloc',\n 'ComputationalBudgetExceeded',\n 'PrivilegeEscalation',\n 'ProgramEnvironmentSetupFailure',\n 'ProgramFailedToComplete',\n 'ProgramFailedToCompile',\n 'Immutable',\n 'IncorrectAuthority',\n 'BorshIoError',\n 'AccountNotRentExempt',\n 'InvalidAccountOwner',\n 'ArithmeticOverflow',\n 'UnsupportedSysvar',\n 'IllegalOwner',\n 'MaxAccountsDataAllocationsExceeded',\n 'MaxAccountsExceeded',\n 'MaxInstructionTraceLengthExceeded',\n 'BuiltinProgramsMustConsumeComputeUnits',\n];\n\nexport function getSolanaErrorFromInstructionError(\n /**\n * The index of the instruction inside the transaction.\n */\n index: bigint | number,\n instructionError: string | { [key: string]: unknown },\n): SolanaError {\n const numberIndex = Number(index);\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 4615001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n index: numberIndex,\n ...(rpcErrorContext !== undefined ? { instructionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {\n return {\n code: Number(rpcErrorContext as bigint | number),\n index: numberIndex,\n };\n }\n return { index: numberIndex };\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: instructionError,\n },\n getSolanaErrorFromInstructionError,\n );\n}\n","import {\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n} from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromInstructionError } from './instruction-error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\n/**\n * How to add an error when an entry is added to the RPC `TransactionError` enum:\n *\n * 1. Follow the instructions in `./codes.ts` to add a corresponding Solana error code\n * 2. Add the `TransactionError` enum name in the same order as it appears in `./codes.ts`\n * 3. Add the new error name/code mapping to `./__tests__/transaction-error-test.ts`\n */\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'AccountInUse',\n 'AccountLoadedTwice',\n 'AccountNotFound',\n 'ProgramAccountNotFound',\n 'InsufficientFundsForFee',\n 'InvalidAccountForFee',\n 'AlreadyProcessed',\n 'BlockhashNotFound',\n // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`\n 'CallChainTooDeep',\n 'MissingSignatureForFee',\n 'InvalidAccountIndex',\n 'SignatureFailure',\n 'InvalidProgramForExecution',\n 'SanitizeFailure',\n 'ClusterMaintenance',\n 'AccountBorrowOutstanding',\n 'WouldExceedMaxBlockCostLimit',\n 'UnsupportedVersion',\n 'InvalidWritableAccount',\n 'WouldExceedMaxAccountCostLimit',\n 'WouldExceedAccountDataBlockLimit',\n 'TooManyAccountLocks',\n 'AddressLookupTableNotFound',\n 'InvalidAddressLookupTableOwner',\n 'InvalidAddressLookupTableData',\n 'InvalidAddressLookupTableIndex',\n 'InvalidRentPayingAccount',\n 'WouldExceedMaxVoteCostLimit',\n 'WouldExceedAccountDataTotalLimit',\n 'DuplicateInstruction',\n 'InsufficientFundsForRent',\n 'MaxLoadedAccountsDataSizeExceeded',\n 'InvalidLoadedAccountsDataSizeLimit',\n 'ResanitizationNeeded',\n 'ProgramExecutionTemporarilyRestricted',\n 'UnbalancedTransaction',\n];\n\nexport function getSolanaErrorFromTransactionError(transactionError: string | { [key: string]: unknown }): SolanaError {\n if (typeof transactionError === 'object' && 'InstructionError' in transactionError) {\n return getSolanaErrorFromInstructionError(\n ...(transactionError.InstructionError as Parameters),\n );\n }\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 7050001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n ...(rpcErrorContext !== undefined ? { transactionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {\n return {\n index: Number(rpcErrorContext as bigint | number),\n };\n } else if (\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT ||\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n ) {\n return {\n accountIndex: Number((rpcErrorContext as { account_index: bigint | number }).account_index),\n };\n }\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: transactionError,\n },\n getSolanaErrorFromTransactionError,\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SolanaErrorCode,\n} from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\nimport { getSolanaErrorFromTransactionError } from './transaction-error';\n\ninterface RpcErrorResponse {\n code: bigint | number;\n data?: unknown;\n message: string;\n}\n\ntype TransactionError = string | { [key: string]: unknown };\n\n/**\n * Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-types/src/response.rs\n * @hidden\n */\nexport interface RpcSimulateTransactionResult {\n accounts:\n | ({\n data:\n | string // LegacyBinary\n | {\n // Json\n parsed: unknown;\n program: string;\n space: bigint;\n }\n // Binary\n | [encodedBytes: string, encoding: 'base58' | 'base64' | 'base64+zstd' | 'binary' | 'jsonParsed'];\n executable: boolean;\n lamports: bigint;\n owner: string;\n rentEpoch: bigint;\n space?: bigint;\n } | null)[]\n | null;\n err: TransactionError | null;\n // Enabled by `enable_cpi_recording`\n innerInstructions?:\n | {\n index: number;\n instructions: (\n | {\n // Compiled\n accounts: number[];\n data: string;\n programIdIndex: number;\n stackHeight?: number;\n }\n | {\n // Parsed\n parsed: unknown;\n program: string;\n programId: string;\n stackHeight?: number;\n }\n | {\n // PartiallyDecoded\n accounts: string[];\n data: string;\n programId: string;\n stackHeight?: number;\n }\n )[];\n }[]\n | null;\n loadedAccountsDataSize: number | null;\n logs: string[] | null;\n replacementBlockhash: string | null;\n returnData: {\n data: [string, 'base64'];\n programId: string;\n } | null;\n unitsConsumed: bigint | null;\n}\n\nexport function getSolanaErrorFromJsonRpcError(putativeErrorResponse: unknown): SolanaError {\n let out: SolanaError;\n if (isRpcErrorResponse(putativeErrorResponse)) {\n const { code: rawCode, data, message } = putativeErrorResponse;\n const code = Number(rawCode);\n if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {\n const { err, ...preflightErrorContext } = data as RpcSimulateTransactionResult;\n const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;\n out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {\n ...preflightErrorContext,\n ...causeObject,\n });\n } else {\n let errorContext;\n switch (code) {\n case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:\n case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:\n case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:\n case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:\n case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:\n case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:\n // The server supplies no structured data, but rather a pre-formatted message. Put\n // the server message in `context` so as not to completely lose the data. The long\n // term fix for this is to add data to the server responses and modify the\n // messages in `@solana/errors` to be actual format strings.\n errorContext = { __serverMessage: message };\n break;\n default:\n if (typeof data === 'object' && !Array.isArray(data)) {\n errorContext = data;\n }\n }\n out = new SolanaError(code as SolanaErrorCode, errorContext as SolanaErrorContext[SolanaErrorCode]);\n }\n } else {\n const message =\n typeof putativeErrorResponse === 'object' &&\n putativeErrorResponse !== null &&\n 'message' in putativeErrorResponse &&\n typeof putativeErrorResponse.message === 'string'\n ? putativeErrorResponse.message\n : 'Malformed JSON-RPC error with no message attribute';\n out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });\n }\n safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);\n return out;\n}\n\nfunction isRpcErrorResponse(value: unknown): value is RpcErrorResponse {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'code' in value &&\n 'message' in value &&\n (typeof value.code === 'number' || typeof value.code === 'bigint') &&\n typeof value.message === 'string'\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaErrorCode,\n} from './codes';\nimport { isSolanaError } from './error';\n\n/**\n * Extracts the underlying cause from a simulation-related error.\n *\n * When a transaction simulation fails, the error is often wrapped in a\n * simulation-specific {@link SolanaError}. This function unwraps such errors\n * by returning the `cause` property, giving you access to the actual error\n * that triggered the simulation failure.\n *\n * If the provided error is not a simulation-related error, it is returned unchanged.\n *\n * The following error codes are considered simulation errors:\n * - {@link SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE}\n * - {@link SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT}\n *\n * @param error - The error to unwrap.\n * @return The underlying cause if the error is a simulation error, otherwise the original error.\n *\n * @example\n * Unwrapping a preflight failure to access the root cause.\n * ```ts\n * import { unwrapSimulationError } from '@solana/errors';\n *\n * try {\n * await sendTransaction(signedTransaction);\n * } catch (e) {\n * const cause = unwrapSimulationError(e);\n * console.log('Send transaction failed due to:', cause);\n * }\n * ```\n */\nexport function unwrapSimulationError(error: unknown): unknown {\n const simulationCodes: SolanaErrorCode[] = [\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n ];\n if (isSolanaError(error) && !!error.cause && simulationCodes.includes(error.context.__code)) {\n return error.cause;\n }\n return error;\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n *\n * @param byteArrays - The array of byte arrays to concatenate.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02]);\n * const bytes2 = new Uint8Array([]);\n * const bytes3 = new Uint8Array([0x03, 0x04]);\n * const bytes = mergeBytes([bytes1, bytes2, bytes3]);\n * // ^ [0x01, 0x02, 0x03, 0x04]\n * ```\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n *\n * @param bytes - The byte array to pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 2);\n * // bytes === paddedBytes\n * ```\n */\nexport function padBytes(bytes: Uint8Array, length: number): Uint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n}\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n *\n * @param bytes - The byte array to truncate or pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Truncates the byte array to the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // ^ [0x01, 0x02]\n * ```\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // bytes === fixedBytes\n * ```\n */\nexport const fixBytes = (bytes: ReadonlyUint8Array | Uint8Array, length: number): ReadonlyUint8Array | Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n\n/**\n * Returns true if and only if the provided `data` byte array contains\n * the provided `bytes` byte array at the specified `offset`.\n *\n * @param data - The byte sequence to search for.\n * @param bytes - The byte array in which to search for `data`.\n * @param offset - The position in `bytes` where the search begins.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const data = new Uint8Array([0x02, 0x03]);\n * containsBytes(bytes, data, 1); // true\n * containsBytes(bytes, data, 2); // false\n * ```\n */\nexport function containsBytes(\n data: ReadonlyUint8Array | Uint8Array,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset: number,\n): boolean {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n return bytesEqual(slice, bytes);\n}\n\n/**\n * Returns true if and only if the provided `bytes1` and `bytes2` byte arrays are equal.\n *\n * @param bytes1 - The first byte array to compare.\n * @param bytes2 - The second byte array to compare.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const bytes2 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * bytesEqual(bytes1, bytes2); // true\n * ```\n */\nexport function bytesEqual(bytes1: ReadonlyUint8Array | Uint8Array, bytes2: ReadonlyUint8Array | Uint8Array): boolean {\n return bytes1.length === bytes2.length && bytes1.every((value, index) => value === bytes2[index]);\n}\n","import {\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * This is a common interface for {@link FixedSizeEncoder} and {@link VariableSizeEncoder}.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n */\ntype BaseEncoder = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a fixed-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const encoder: FixedSizeEncoder;\n * const bytes = encoder.encode(42);\n * const size = encoder.fixedSize; // 4\n * ```\n *\n * @see {@link Encoder}\n * @see {@link VariableSizeEncoder}\n */\nexport type FixedSizeEncoder = BaseEncoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a variable-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * ```ts\n * const encoder: VariableSizeEncoder;\n * const bytes = encoder.encode('hello');\n * const size = encoder.getSizeFromValue('hello');\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n */\nexport type VariableSizeEncoder = BaseEncoder & {\n /** Returns the size of the encoded value in bytes for a given input. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * An `Encoder` can be either:\n * - A {@link FixedSizeEncoder}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeEncoder}, where encoded values can vary in size.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * Encoding a value into a new byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = encoder.encode('hello');\n * ```\n *\n * @example\n * Writing the encoded value into an existing byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = new Uint8Array(100);\n * const nextOffset = encoder.write('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Encoders` manually using the {@link createEncoder} function but it is more common\n * to compose multiple `Encoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Encoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonEncoder = (): Encoder =>\n * getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * ```\n *\n * Note that composed `Encoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Encoder()` is\n * a fixed-size encoder, while `addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())`\n * is a variable-size encoder. This makes the final `Person` encoder a variable-size encoder.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link createEncoder}\n */\nexport type Encoder = FixedSizeEncoder | VariableSizeEncoder;\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * This is a common interface for {@link FixedSizeDecoder} and {@link VariableSizeDecoder}.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n */\ntype BaseDecoder = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: ReadonlyUint8Array | Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: ReadonlyUint8Array | Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\n/**\n * An object that can decode a fixed-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const decoder: FixedSizeDecoder;\n * const value = decoder.decode(bytes);\n * const size = decoder.fixedSize; // 4\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type FixedSizeDecoder = BaseDecoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can decode a variable-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const decoder: VariableSizeDecoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder = BaseDecoder & {\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * An `Decoder` can be either:\n * - A {@link FixedSizeDecoder}, where all byte arrays have the same fixed size.\n * - A {@link VariableSizeDecoder}, where byte arrays can vary in size.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * Getting the decoded value from a byte array.\n * ```ts\n * const decoder: Decoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @example\n * Reading the decoded value from a byte array at a specific offset\n * and getting the offset of the next byte to read.\n * ```ts\n * const decoder: Decoder;\n * const [value, nextOffset] = decoder.read('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Decoders` manually using the {@link createDecoder} function but it is more common\n * to compose multiple `Decoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Decoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonDecoder = (): Decoder =>\n * getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * ```\n *\n * Note that composed `Decoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Decoder()` is\n * a fixed-size decoder, while `addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())`\n * is a variable-size decoder. This makes the final `Person` decoder a variable-size decoder.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link createDecoder}\n */\nexport type Decoder = FixedSizeDecoder | VariableSizeDecoder;\n\n/**\n * An object that can encode and decode a value to and from a fixed-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const codec: FixedSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.fixedSize; // 8\n * ```\n *\n * @see {@link Codec}\n * @see {@link VariableSizeCodec}\n */\nexport type FixedSizeCodec = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a variable-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec: VariableSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.getSizeFromValue(42);\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n */\nexport type VariableSizeCodec = VariableSizeDecoder & VariableSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a byte array.\n *\n * A `Codec` can be either:\n * - A {@link FixedSizeCodec}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeCodec}, where encoded values can vary in size.\n *\n * @example\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode('hello');\n * const value = codec.decode(bytes); // 'hello'\n * ```\n *\n * @remarks\n * For convenience, codecs can encode looser types than they decode.\n * That is, type {@link TFrom} can be a superset of type {@link TTo}.\n * For instance, a `Codec` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * It is worth noting that codecs are the union of encoders and decoders.\n * This means that a `Codec` can be combined from an `Encoder`\n * and a `Decoder` using the {@link combineCodec} function. This is particularly\n * useful for library authors who want to expose all three types of objects to their users.\n *\n * ```ts\n * const encoder: Encoder;\n * const decoder: Decoder;\n * const codec: Codec = combineCodec(encoder, decoder);\n * ```\n *\n * Aside from combining encoders and decoders, codecs can also be created from scratch using\n * the {@link createCodec} function but it is more common to compose multiple codecs together\n * using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create a `Codec` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonCodec = (): Codec =>\n * getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * ```\n *\n * Note that composed `Codec` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Codec()` is\n * a fixed-size codec, while `addCodecSizePrefix(getUtf8Codec(), getU32Codec())`\n * is a variable-size codec. This makes the final `Person` codec a variable-size codec.\n *\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link combineCodec}\n * @see {@link createCodec}\n */\nexport type Codec = FixedSizeCodec | VariableSizeCodec;\n\n/**\n * Gets the encoded size of a given value in bytes using the provided encoder.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @param value - The value to be encoded.\n * @param encoder - The encoder used to determine the encoded size.\n * @returns The size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const fixedSizeEncoder = { fixedSize: 4 };\n * getEncodedSize(123, fixedSizeEncoder); // Returns 4.\n *\n * const variableSizeEncoder = { getSizeFromValue: (value: string) => value.length };\n * getEncodedSize(\"hello\", variableSizeEncoder); // Returns 5.\n * ```\n *\n * @see {@link Encoder}\n */\nexport function getEncodedSize(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/**\n * Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and\n * either the `fixedSize` property (for {@link FixedSizeEncoder | FixedSizeEncoders}) or\n * the `getSizeFromValue` function (for {@link VariableSizeEncoder | VariableSizeEncoders}).\n *\n * Instead of manually implementing `encode`, this utility leverages the existing `write` function\n * and the size helpers to generate a complete encoder. The provided `encode` method will allocate\n * a new `Uint8Array` of the correct size and use `write` to populate it.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size encoders).\n *\n * @param encoder - An encoder object that implements `write`, but not `encode`.\n * - If the encoder has a `fixedSize` property, it is treated as a {@link FixedSizeEncoder}.\n * - Otherwise, it is treated as a {@link VariableSizeEncoder}.\n *\n * @returns A fully functional `Encoder` with both `write` and `encode` methods.\n *\n * @example\n * Creating a custom fixed-size encoder.\n * ```ts\n * const encoder = createEncoder({\n * fixedSize: 4,\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n * ```\n *\n * @example\n * Creating a custom variable-size encoder:\n * ```ts\n * const encoder = createEncoder({\n * getSizeFromValue: (value: string) => value.length,\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = encoder.encode(\"hello\");\n * // 0x68656c6c6f\n * ```\n *\n * @remarks\n * Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose\n * encoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createEncoder`.\n *\n * ```ts\n * // Fixed-size encoder for unsigned 32-bit integers.\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n *\n * // Variable-size encoder for 32-bytes prefixed UTF-8 strings.\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const bytes = encoder.encode(\"hello\");\n * // 0x0500000068656c6c6f\n *\n * // Variable-size encoder for custom objects.\n * type Person = { name: string; age: number };\n * const encoder: Encoder = getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * const bytes = encoder.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link getStructEncoder}\n * @see {@link getU32Encoder}\n * @see {@link getUtf8Encoder}\n * @see {@link addEncoderSizePrefix}\n */\nexport function createEncoder(\n encoder: Omit, 'encode'>,\n): FixedSizeEncoder;\nexport function createEncoder(encoder: Omit, 'encode'>): VariableSizeEncoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function.\n *\n * Instead of manually implementing `decode`, this utility leverages the existing `read` function\n * and the size properties to generate a complete decoder. The provided `decode` method will read\n * from a `Uint8Array` at the given offset and return the decoded value.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeDecoder} will be created, otherwise\n * a {@link VariableSizeDecoder} will be created.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size decoders).\n *\n * @param decoder - A decoder object that implements `read`, but not `decode`.\n * - If the decoder has a `fixedSize` property, it is treated as a {@link FixedSizeDecoder}.\n * - Otherwise, it is treated as a {@link VariableSizeDecoder}.\n *\n * @returns A fully functional `Decoder` with both `read` and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size decoder.\n * ```ts\n * const decoder = createDecoder({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size decoder:\n * ```ts\n * const decoder = createDecoder({\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111]));\n * // \"hello\"\n * ```\n *\n * @remarks\n * Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose\n * decoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createDecoder`.\n *\n * ```ts\n * // Fixed-size decoder for unsigned 32-bit integers.\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n *\n * // Variable-size decoder for 32-bytes prefixed UTF-8 strings.\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111]));\n * // \"hello\"\n *\n * // Variable-size decoder for custom objects.\n * type Person = { name: string; age: number };\n * const decoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0]));\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Decoder}\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link getStructDecoder}\n * @see {@link getU32Decoder}\n * @see {@link getUtf8Decoder}\n * @see {@link addDecoderSizePrefix}\n */\nexport function createDecoder(\n decoder: Omit, 'decode'>,\n): FixedSizeDecoder;\nexport function createDecoder(decoder: Omit, 'decode'>): VariableSizeDecoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/**\n * Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions.\n *\n * This utility combines the behavior of {@link createEncoder} and {@link createDecoder} to produce a fully functional `Codec`.\n * The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeCodec} will be created, otherwise\n * a {@link VariableSizeCodec} will be created.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param codec - A codec object that implements `write` and `read`, but not `encode` or `decode`.\n * - If the codec has a `fixedSize` property, it is treated as a {@link FixedSizeCodec}.\n * - Otherwise, it is treated as a {@link VariableSizeCodec}.\n *\n * @returns A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size codec.\n * ```ts\n * const codec = createCodec({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size codec:\n * ```ts\n * const codec = createCodec({\n * getSizeFromValue: (value: string) => value.length,\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = codec.encode(\"hello\");\n * // 0x68656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n * ```\n *\n * @remarks\n * This function effectively combines the behavior of {@link createEncoder} and {@link createDecoder}.\n * If you only need to encode or decode (but not both), consider using those functions instead.\n *\n * Here are some alternative examples using codec primitives instead of `createCodec`.\n *\n * ```ts\n * // Fixed-size codec for unsigned 32-bit integers.\n * const codec = getU32Codec();\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n *\n * // Variable-size codec for 32-bytes prefixed UTF-8 strings.\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const bytes = codec.encode(\"hello\");\n * // 0x0500000068656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n *\n * // Variable-size codec for custom objects.\n * type Person = { name: string; age: number };\n * const codec: Codec = getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * const bytes = codec.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * const value = codec.decode(bytes);\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link createEncoder}\n * @see {@link createDecoder}\n * @see {@link getStructCodec}\n * @see {@link getU32Codec}\n * @see {@link getUtf8Codec}\n * @see {@link addCodecSizePrefix}\n */\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): FixedSizeCodec;\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): VariableSizeCodec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is fixed-size.\n *\n * A fixed-size object is identified by the presence of a `fixedSize` property.\n * If this property exists, the object is considered a {@link FixedSizeCodec},\n * {@link FixedSizeEncoder}, or {@link FixedSizeDecoder}.\n * Otherwise, it is assumed to be a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is fixed-size, `false` otherwise.\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isFixedSize(encoder); // true\n * ```\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isFixedSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is commonly used to distinguish between fixed-size and variable-size objects at runtime.\n * If you need to enforce this distinction with type assertions, consider using {@link assertIsFixedSize}.\n *\n * @see {@link assertIsFixedSize}\n */\nexport function isFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): encoder is FixedSizeEncoder;\nexport function isFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): decoder is FixedSizeDecoder;\nexport function isFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): codec is FixedSizeCodec;\nexport function isFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is fixed-size.\n *\n * If the object is not fixed-size (i.e., it lacks a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not fixed-size.\n *\n * @example\n * Asserting a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsFixedSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsFixedSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isFixedSize}.\n * If you only need to check whether an object is fixed-size without throwing an error, use {@link isFixedSize} instead.\n *\n * @see {@link isFixedSize}\n */\nexport function assertIsFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): asserts encoder is FixedSizeEncoder;\nexport function assertIsFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): asserts decoder is FixedSizeDecoder;\nexport function assertIsFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): asserts codec is FixedSizeCodec;\nexport function assertIsFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is variable-size.\n *\n * A variable-size object is identified by the absence of a `fixedSize` property.\n * If this property is missing, the object is considered a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is variable-size, `false` otherwise.\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isVariableSize(encoder); // true\n * ```\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isVariableSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is the inverse of {@link isFixedSize}.\n *\n * @see {@link isFixedSize}\n * @see {@link assertIsVariableSize}\n */\nexport function isVariableSize(encoder: Encoder): encoder is VariableSizeEncoder;\nexport function isVariableSize(decoder: Decoder): decoder is VariableSizeDecoder;\nexport function isVariableSize(\n codec: Codec,\n): codec is VariableSizeCodec;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is variable-size.\n *\n * If the object is not variable-size (i.e., it has a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not variable-size.\n *\n * @example\n * Asserting a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsVariableSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsVariableSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isVariableSize}.\n * If you only need to check whether an object is variable-size without throwing an error, use {@link isVariableSize} instead.\n *\n * Also note that this function is the inverse of {@link assertIsFixedSize}.\n *\n * @see {@link isVariableSize}\n * @see {@link assertIsFixedSize}\n */\nexport function assertIsVariableSize(encoder: Encoder): asserts encoder is VariableSizeEncoder;\nexport function assertIsVariableSize(decoder: Decoder): asserts decoder is VariableSizeDecoder;\nexport function assertIsVariableSize(\n codec: Codec,\n): asserts codec is VariableSizeCodec;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an `Encoder` and a `Decoder` into a `Codec`.\n *\n * That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`.\n *\n * This allows for modular composition by keeping encoding and decoding logic separate\n * while still offering a convenient way to bundle them into a single `Codec`.\n * This is particularly useful for library maintainers who want to expose `Encoders`,\n * `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic.\n *\n * The provided `Encoder` and `Decoder` must be compatible in terms of:\n * - **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value.\n * - **Variable Size:** If either has a `maxSize` attribute, it must match the other.\n *\n * If these conditions are not met, a {@link SolanaError} will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param encoder - The `Encoder` to combine.\n * @param decoder - The `Decoder` to combine.\n * @returns A `Codec` that provides both `encode` and `decode` methods.\n *\n * @throws {SolanaError}\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH`\n * Thrown if the encoder and decoder have mismatched size types (fixed vs. variable).\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH`\n * Thrown if both are fixed-size but have different `fixedSize` values.\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH`\n * Thrown if the `maxSize` attributes do not match.\n *\n * @example\n * Creating a fixed-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = getU32Encoder();\n * const decoder = getU32Decoder();\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(42); // 0x2a000000\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Creating a variable-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(\"hello\"); // 0x0500000068656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec.\n * This allows users to import only what they need, improving tree-shaking efficiency.\n *\n * ```ts\n * type MyType = \\/* ... *\\/;\n * const getMyTypeEncoder = (): Encoder => { \\/* ... *\\/ };\n * const getMyTypeDecoder = (): Decoder => { \\/* ... *\\/ };\n * const getMyTypeCodec = (): Codec =>\n * combineCodec(getMyTypeEncoder(), getMyTypeDecoder());\n * ```\n *\n * @see {@link Codec}\n * @see {@link Encoder}\n * @see {@link Decoder}\n */\nexport function combineCodec(\n encoder: FixedSizeEncoder,\n decoder: FixedSizeDecoder,\n): FixedSizeCodec;\nexport function combineCodec(\n encoder: VariableSizeEncoder,\n decoder: VariableSizeDecoder,\n): VariableSizeCodec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {\n decoderFixedSize: decoder.fixedSize,\n encoderFixedSize: encoder.fixedSize,\n });\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {\n decoderMaxSize: decoder.maxSize,\n encoderMaxSize: encoder.maxSize,\n });\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SolanaError,\n} from '@solana/errors';\n\nimport { containsBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Creates an encoder that writes a `Uint8Array` sentinel after the encoded value.\n * This is useful to delimit the encoded value when being read by a decoder.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addEncoderSentinel(\n encoder: FixedSizeEncoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeEncoder;\nexport function addEncoderSentinel(\n encoder: Encoder,\n sentinel: ReadonlyUint8Array,\n): VariableSizeEncoder;\nexport function addEncoderSentinel(encoder: Encoder, sentinel: ReadonlyUint8Array): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds\n // and to avoid writing the sentinel as part of the encoded value.\n const encoderBytes = encoder.encode(value);\n if (findSentinelIndex(encoderBytes, sentinel) >= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {\n encodedBytes: encoderBytes,\n hexEncodedBytes: hexBytes(encoderBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n bytes.set(encoderBytes, offset);\n offset += encoderBytes.length;\n bytes.set(sentinel, offset);\n offset += sentinel.length;\n return offset;\n }) as Encoder['write'];\n\n if (isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });\n }\n\n return createEncoder({\n ...encoder,\n ...(encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {}),\n getSizeFromValue: value => encoder.getSizeFromValue(value) + sentinel.length,\n write,\n });\n}\n\n/**\n * Creates a decoder that continues reading until\n * a given `Uint8Array` sentinel is found.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addDecoderSentinel(\n decoder: FixedSizeDecoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): VariableSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): Decoder {\n const read = ((bytes, offset) => {\n const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);\n const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);\n if (sentinelIndex === -1) {\n throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {\n decodedBytes: candidateBytes,\n hexDecodedBytes: hexBytes(candidateBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds\n // and ensure that the sentinel is not part of the decoded value.\n return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];\n }) as Decoder['read'];\n\n if (isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });\n }\n\n return createDecoder({\n ...decoder,\n ...(decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {}),\n read,\n });\n}\n\n/**\n * Creates a Codec that writes a given `Uint8Array` sentinel after the encoded\n * value and, when decoding, continues reading until the sentinel is found.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255]));\n * codec.encode('hello');\n * // 0x68656c6c6fffff\n * // | └-- Our sentinel.\n * // └-- Our encoded string.\n * ```\n *\n * @remarks\n * Note that the sentinel _must not_ be present in the encoded data and\n * _must_ be present in the decoded data for this to work.\n * If this is not the case, dedicated errors will be thrown.\n *\n * ```ts\n * const sentinel = new Uint8Array([108, 108]); // 'll'\n * const codec = addCodecSentinel(getUtf8Codec(), sentinel);\n *\n * codec.encode('hello'); // Throws: sentinel is in encoded data.\n * codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data.\n * ```\n *\n * Separate {@link addEncoderSentinel} and {@link addDecoderSentinel} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello');\n * const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSentinel}\n * @see {@link addDecoderSentinel}\n */\nexport function addCodecSentinel(\n codec: FixedSizeCodec,\n sentinel: ReadonlyUint8Array,\n): FixedSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): VariableSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): Codec {\n return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));\n}\n\nfunction findSentinelIndex(bytes: ReadonlyUint8Array, sentinel: ReadonlyUint8Array) {\n return bytes.findIndex((byte, index, arr) => {\n if (sentinel.length === 1) return byte === sentinel[0];\n return containsBytes(arr, sentinel, index);\n });\n}\n\nfunction hexBytes(bytes: ReadonlyUint8Array): string {\n return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n","import {\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Asserts that a given byte array is not empty (after the optional provided offset).\n *\n * Returns void if the byte array is not empty but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n * If provided, the byte array is considered empty if it has no bytes after the offset.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws\n * ```\n */\nexport function assertByteArrayIsNotEmptyForCodec(\n codecDescription: string,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription,\n });\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode\n * (after the optional provided offset).\n *\n * Returns void if the byte array has at least the expected number\n * of bytes but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param expected - The minimum number of bytes expected in the byte array.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws\n * ```\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected,\n });\n }\n}\n\n/**\n * Asserts that a given offset is within the byte array bounds.\n * This range is between 0 and the byte array length and is inclusive.\n * An offset equals to the byte array length is considered a valid offset\n * as it allows the post-offset of codecs to signal the end of the byte array.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param offset - The offset to check.\n * @param bytesLength - The length of the byte array from which the offset should be within bounds.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws\n * ```\n */\nexport function assertByteArrayOffsetIsNotOutOfRange(codecDescription: string, offset: number, bytesLength: number) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset,\n });\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\ntype NumberEncoder = Encoder | Encoder;\ntype FixedSizeNumberEncoder =\n | FixedSizeEncoder\n | FixedSizeEncoder;\ntype NumberDecoder = Decoder | Decoder;\ntype FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\ntype NumberCodec = Codec | Codec;\ntype FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addEncoderSizePrefix(\n encoder: FixedSizeEncoder,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): VariableSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds.\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n }) as Encoder['write'];\n\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : (encoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n\n return createEncoder({\n ...encoder,\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: value => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write,\n });\n}\n\n/**\n * Bounds the size of the nested `decoder` by reading its encoded `prefix`.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addDecoderSizePrefix(\n decoder: FixedSizeDecoder,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): VariableSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): Decoder {\n const read = ((bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n // Slice the byte array to the contained size if necessary.\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec('addDecoderSizePrefix', size, bytes);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds.\n return [decoder.decode(bytes), offset + size];\n }) as Decoder['read'];\n\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : (decoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...(maxSize !== null ? { maxSize } : {}), read });\n}\n\n/**\n * Stores the byte size of any given codec as an encoded number prefix.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n * When encoding, the size of the encoded data is stored before the encoded data itself.\n * When decoding, the size is read first to know how many bytes to read next.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * For example, say we want to bound a variable-size base-58 string using a `u32` size prefix.\n * Here’s how you can use the `addCodecSizePrefix` function to achieve that.\n *\n * ```ts\n * const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());\n *\n * getU32Base58Codec().encode('hello world');\n * // 0x0b00000068656c6c6f20776f726c64\n * // | └-- Our encoded base-58 string.\n * // └-- Our encoded u32 size prefix.\n * ```\n *\n * @remarks\n * Separate {@link addEncoderSizePrefix} and {@link addDecoderSizePrefix} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');\n * const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSizePrefix}\n * @see {@link addDecoderSizePrefix}\n */\nexport function addCodecSizePrefix(\n codec: FixedSizeCodec,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): VariableSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): Codec {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Converts a `Uint8Array` to an `ArrayBuffer`. If the underlying buffer is a `SharedArrayBuffer`,\n * it will be copied to a non-shared buffer, for safety.\n *\n * @remarks\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nexport function toArrayBuffer(bytes: ReadonlyUint8Array | Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n let buffer: ArrayBuffer;\n if (typeof SharedArrayBuffer === 'undefined') {\n buffer = bytes.buffer as ArrayBuffer;\n } else if (bytes.buffer instanceof SharedArrayBuffer) {\n buffer = new ArrayBuffer(bytes.length);\n new Uint8Array(buffer).set(new Uint8Array(bytes));\n } else {\n buffer = bytes.buffer;\n }\n return (bytesOffset === 0 || bytesOffset === -bytes.byteLength) && bytesLength === bytes.byteLength\n ? buffer\n : buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, SolanaError } from '@solana/errors';\n\nimport { createDecoder, Decoder } from './codec';\n\n/**\n * Create a {@link Decoder} that asserts that the bytes provided to `decode` or `read` are fully consumed by the inner decoder\n * @param decoder A decoder to wrap\n * @returns A new decoder that will throw if provided with a byte array that it does not fully consume\n *\n * @typeParam T - The type of the decoder\n *\n * @remarks\n * Note that this compares the offset after encoding to the length of the input byte array\n *\n * The `offset` parameter to `decode` and `read` is still considered, and will affect the new offset that is compared to the byte array length\n *\n * The error that is thrown by the returned decoder is a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY`\n *\n * @example\n * Create a decoder that decodes a `u32` (4 bytes) and ensures the entire byte array is consumed\n * ```ts\n * const decoder = createDecoderThatUsesExactByteArray(getU32Decoder());\n * decoder.decode(new Uint8Array([0, 0, 0, 0])); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0])); // throws\n *\n * // with an offset\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0]), 1); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0, 0]), 1); // throws\n * ```\n */\nexport function createDecoderThatConsumesEntireByteArray(decoder: Decoder): Decoder {\n return createDecoder({\n ...decoder,\n read(bytes, offset) {\n const [value, newOffset] = decoder.read(bytes, offset);\n if (bytes.length > newOffset) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, {\n expectedLength: newOffset,\n numExcessBytes: bytes.length - newOffset,\n });\n }\n return [value, newOffset];\n },\n });\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * The resulting encoder ensures that encoded values always have the specified number of bytes.\n * If the original encoded value is larger than `fixedBytes`, it is truncated.\n * If it is smaller, it is padded with trailing zeroes.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @returns A `FixedSizeEncoder` that ensures a consistent output size.\n *\n * @example\n * ```ts\n * const encoder = fixEncoderSize(getUtf8Encoder(), 4);\n * encoder.encode(\"Hello\"); // 0x48656c6c (truncated)\n * encoder.encode(\"Hi\"); // 0x48690000 (padded)\n * encoder.encode(\"Hiya\"); // 0x48697961 (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixEncoderSize(\n encoder: Encoder,\n fixedBytes: TSize,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * The resulting decoder always reads exactly `fixedBytes` bytes from the input.\n * If the nested decoder is also fixed-size, the bytes are truncated or padded as needed.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @returns A `FixedSizeDecoder` that ensures a consistent input size.\n *\n * @example\n * ```ts\n * const decoder = fixDecoderSize(getUtf8Decoder(), 4);\n * decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // \"Hell\" (truncated)\n * decoder.decode(new Uint8Array([72, 105, 0, 0])); // \"Hi\" (zeroes ignored)\n * decoder.decode(new Uint8Array([72, 105, 121, 97])); // \"Hiya\" (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixEncoderSize}\n */\nexport function fixDecoderSize(\n decoder: Decoder,\n fixedBytes: TSize,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodecSize', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes.\n * When encoding:\n * - If the encoded value is larger than `fixedBytes`, it is truncated.\n * - If it is smaller, it is padded with trailing zeroes.\n * - If it is exactly `fixedBytes`, it remains unchanged.\n *\n * When decoding:\n * - Exactly `fixedBytes` bytes are read from the input.\n * - If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @returns A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size.\n *\n * @example\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 4);\n *\n * const bytes1 = codec.encode(\"Hello\"); // 0x48656c6c (truncated)\n * const value1 = codec.decode(bytes1); // \"Hell\"\n *\n * const bytes2 = codec.encode(\"Hi\"); // 0x48690000 (padded)\n * const value2 = codec.decode(bytes2); // \"Hi\"\n *\n * const bytes3 = codec.encode(\"Hiya\"); // 0x48697961 (same length)\n * const value3 = codec.decode(bytes3); // \"Hiya\"\n * ```\n *\n * @remarks\n * If you only need to enforce a fixed size for encoding, use {@link fixEncoderSize}.\n * If you only need to enforce a fixed size for decoding, use {@link fixDecoderSize}.\n *\n * ```ts\n * const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode(\"Hiya\");\n * const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);\n * ```\n *\n * @see {@link fixEncoderSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixCodecSize(\n codec: Codec,\n fixedBytes: TSize,\n): FixedSizeCodec {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));\n}\n","import { assertByteArrayOffsetIsNotOutOfRange } from './assertions';\nimport { Codec, createDecoder, createEncoder, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Configuration object for modifying the offset of an encoder, decoder, or codec.\n *\n * This type defines optional functions for adjusting the **pre-offset** (before encoding/decoding)\n * and the **post-offset** (after encoding/decoding). These functions allow precise control\n * over where data is written or read within a byte array.\n *\n * @property preOffset - A function that modifies the offset before encoding or decoding.\n * @property postOffset - A function that modifies the offset after encoding or decoding.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * };\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * };\n * ```\n *\n * @example\n * Using both pre-offset and post-offset together.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * postOffset: ({ postOffset }) => postOffset + 4,\n * };\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n * @see {@link offsetCodec}\n */\ntype OffsetConfig = {\n postOffset?: PostOffsetFunction;\n preOffset?: PreOffsetFunction;\n};\n\n/**\n * Scope provided to the `preOffset` and `postOffset` functions,\n * containing contextual information about the current encoding or decoding process.\n *\n * The pre-offset function modifies where encoding or decoding begins,\n * while the post-offset function modifies where the next operation continues.\n *\n * @property bytes - The entire byte array being encoded or decoded.\n * @property preOffset - The original offset before encoding or decoding starts.\n * @property wrapBytes - A helper function that wraps offsets around the byte array length.\n *\n * @example\n * Using `wrapBytes` to wrap a negative offset to the end of the byte array.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves to last 4 bytes\n * };\n * ```\n *\n * @example\n * Adjusting the offset dynamically based on the byte array size.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ bytes }) => bytes.length > 10 ? 4 : 2,\n * };\n * ```\n *\n * @see {@link PreOffsetFunction}\n * @see {@link PostOffsetFunction}\n */\ntype PreOffsetFunctionScope = {\n /** The entire byte array. */\n bytes: ReadonlyUint8Array | Uint8Array;\n /** The original offset prior to encode or decode. */\n preOffset: Offset;\n /** Wraps the offset to the byte array length. */\n wrapBytes: (offset: Offset) => Offset;\n};\n\n/**\n * A function that modifies the pre-offset before encoding or decoding.\n *\n * This function is used to adjust the starting position before writing\n * or reading data in a byte array.\n *\n * @param scope - The current encoding or decoding context.\n * @returns The new offset at which encoding or decoding should start.\n *\n * @example\n * Skipping the first 2 bytes before writing or reading.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ preOffset }) => preOffset + 2;\n * ```\n *\n * @example\n * Wrapping the offset to ensure it stays within bounds.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ wrapBytes, preOffset }) => wrapBytes(preOffset + 10);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PreOffsetFunction = (scope: PreOffsetFunctionScope) => Offset;\n\n/**\n * A function that modifies the post-offset after encoding or decoding.\n *\n * This function adjusts where the next encoder or decoder should start\n * after the current operation has completed.\n *\n * @param scope - The current encoding or decoding context, including the modified pre-offset\n * and the original post-offset.\n * @returns The new offset at which the next operation should begin.\n *\n * @example\n * Moving the post-offset forward by 4 bytes.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset }) => postOffset + 4;\n * ```\n *\n * @example\n * Wrapping the post-offset within the byte array length.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ wrapBytes, postOffset }) => wrapBytes(postOffset);\n * ```\n *\n * @example\n * Ensuring a minimum spacing of 8 bytes between values.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset, newPreOffset }) =>\n * Math.max(postOffset, newPreOffset + 8);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PostOffsetFunction = (\n scope: PreOffsetFunctionScope & {\n /** The modified offset used to encode or decode. */\n newPreOffset: Offset;\n /** The original offset returned by the encoder or decoder. */\n postOffset: Offset;\n },\n) => Offset;\n\n/**\n * Moves the offset of a given encoder before and/or after encoding.\n *\n * This function allows an encoder to write its encoded value at a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before encoding) and post-offset adjustments (after encoding).\n *\n * The pre-offset function determines where encoding should start, while the\n * post-offset function adjusts where the next encoder should continue writing.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new encoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Actually written at offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * const nextOffset = encoder.write(42, bytes, 0); // Next encoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to ensure an offset wraps around the byte array length.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Writes at bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetDecoder}\n */\nexport function offsetEncoder(encoder: TEncoder, config: OffsetConfig): TEncoder {\n return createEncoder({\n ...encoder,\n write: (value, bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPreOffset, bytes.length);\n const postOffset = encoder.write(value, bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPostOffset, bytes.length);\n return newPostOffset;\n },\n }) as TEncoder;\n}\n\n/**\n * Moves the offset of a given decoder before and/or after decoding.\n *\n * This function allows a decoder to read its input from a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before decoding) and post-offset adjustments (after decoding).\n *\n * The pre-offset function determines where decoding should start, while the\n * post-offset function adjusts where the next decoder should continue reading.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new decoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array([0, 0, 42, 0]); // Value starts at offset 2\n * decoder.read(bytes, 0); // Actually reads from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array([42, 0, 0, 0]);\n * const [value, nextOffset] = decoder.read(bytes, 0); // Next decoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to read from the last 4 bytes of an array.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 42]); // Value stored at the last 4 bytes\n * decoder.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetEncoder}\n */\nexport function offsetDecoder(decoder: TDecoder, config: OffsetConfig): TDecoder {\n return createDecoder({\n ...decoder,\n read: (bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPreOffset, bytes.length);\n const [value, postOffset] = decoder.read(bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPostOffset, bytes.length);\n return [value, newPostOffset];\n },\n }) as TDecoder;\n}\n\n/**\n * Moves the offset of a given codec before and/or after encoding and decoding.\n *\n * This function allows a codec to encode and decode values at custom offsets\n * within a byte array. It modifies both the **pre-offset** (where encoding/decoding starts)\n * and the **post-offset** (where the next operation should continue).\n *\n * This is particularly useful when working with structured binary formats\n * that require skipping reserved bytes, inserting padding, or aligning fields at\n * specific locations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new codec with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Actually written at offset 2\n * codec.read(bytes, 0); // Actually read from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0);\n * // Next encoding starts at offset 6 instead of 4\n * codec.read(bytes, 0);\n * // Next decoding starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to loop around negative offsets.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Writes at bytes.length - 4\n * codec.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you only need to adjust offsets for encoding, use {@link offsetEncoder}.\n * If you only need to adjust offsets for decoding, use {@link offsetDecoder}.\n *\n * ```ts\n * const bytes = new Uint8Array(10);\n * offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).write(42, bytes, 0);\n * const [value] = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).read(bytes, 0);\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n */\nexport function offsetCodec(codec: TCodec, config: OffsetConfig): TCodec {\n return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config)) as TCodec;\n}\n\n/** A modulo function that handles negative dividends and zero divisors. */\nfunction modulo(dividend: number, divisor: number) {\n if (divisor === 0) return 0;\n return ((dividend % divisor) + divisor) % divisor;\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Updates the size of a given encoder.\n *\n * This function modifies the size of an encoder using a provided transformation function.\n * For fixed-size encoders, it updates the `fixedSize` property, and for variable-size\n * encoders, it adjusts the size calculation based on the encoded value.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The original fixed size of the encoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param encoder - The encoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new encoder with the updated size.\n *\n * @example\n * Increasing the size of a `u16` encoder by 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU16Encoder(), size => size + 2);\n * encoder.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * ```\n *\n * @example\n * Shrinking a `u32` encoder to only use 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU32Encoder(), () => 2);\n * encoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeDecoder}\n */\nexport function resizeEncoder(\n encoder: FixedSizeEncoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder {\n if (isFixedSize(encoder)) {\n const fixedSize = resize(encoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return createEncoder({ ...encoder, fixedSize }) as TEncoder;\n }\n return createEncoder({\n ...encoder,\n getSizeFromValue: value => {\n const newSize = resize(encoder.getSizeFromValue(value));\n if (newSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: newSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return newSize;\n },\n }) as TEncoder;\n}\n\n/**\n * Updates the size of a given decoder.\n *\n * This function modifies the size of a decoder using a provided transformation function.\n * For fixed-size decoders, it updates the `fixedSize` property to reflect the new size.\n * Variable-size decoders remain unchanged, as their size is determined dynamically.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the decoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param decoder - The decoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new decoder with the updated size.\n *\n * @example\n * Expanding a `u16` decoder to read 4 bytes instead of 2.\n * ```ts\n * const decoder = resizeDecoder(getU16Decoder(), size => size + 2);\n * decoder.fixedSize; // 4\n * ```\n *\n * @example\n * Shrinking a `u32` decoder to only read 2 bytes.\n * ```ts\n * const decoder = resizeDecoder(getU32Decoder(), () => 2);\n * decoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeEncoder}\n */\nexport function resizeDecoder(\n decoder: FixedSizeDecoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder {\n if (isFixedSize(decoder)) {\n const fixedSize = resize(decoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeDecoder',\n });\n }\n return createDecoder({ ...decoder, fixedSize }) as TDecoder;\n }\n return decoder;\n}\n\n/**\n * Updates the size of a given codec.\n *\n * This function modifies the size of both the codec using a provided\n * transformation function. It is useful for adjusting the allocated byte size for\n * encoding and decoding without altering the underlying data structure.\n *\n * If the new size is negative, an error will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the encoded/decoded value (for fixed-size codecs).\n * @typeParam TNewSize - The new fixed size after resizing (for fixed-size codecs).\n *\n * @param codec - The codec whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new codec with the updated size.\n *\n * @example\n * Expanding a `u16` codec from 2 to 4 bytes.\n * ```ts\n * const codec = resizeCodec(getU16Codec(), size => size + 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (reads original two bytes)\n * ```\n *\n * @example\n * Shrinking a `u32` codec to only use 2 bytes.\n * ```ts\n * const codec = resizeCodec(getU32Codec(), () => 2);\n * codec.fixedSize; // 2\n * ```\n *\n * @remarks\n * If you only need to resize an encoder, use {@link resizeEncoder}.\n * If you only need to resize a decoder, use {@link resizeDecoder}.\n *\n * ```ts\n * const bytes = resizeEncoder(getU32Encoder(), (size) => size + 2).encode(0xffff);\n * const value = resizeDecoder(getU32Decoder(), (size) => size + 2).decode(bytes);\n * ```\n *\n * @see {@link resizeEncoder}\n * @see {@link resizeDecoder}\n */\nexport function resizeCodec(\n codec: FixedSizeCodec,\n resize: (size: TSize) => TNewSize,\n): FixedSizeCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec {\n return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize)) as TCodec;\n}\n","import { Codec, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { offsetDecoder, offsetEncoder } from './offset-codec';\nimport { resizeDecoder, resizeEncoder } from './resize-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Adds left padding to the given encoder, shifting the encoded value forward\n * by `offset` bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add before encoding.\n * @returns A new encoder with left padding applied.\n *\n * @example\n * ```ts\n * const encoder = padLeftEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given encoder, extending the encoded value by `offset`\n * bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add after encoding.\n * @returns A new encoder with right padding applied.\n *\n * @example\n * ```ts\n * const encoder = padRightEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0xffff0000 (two extra bytes added at the end)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightDecoder}\n */\nexport function padRightEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given decoder, shifting the decoding position forward\n * by `offset` bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip before decoding.\n * @returns A new decoder with left padding applied.\n *\n * @example\n * ```ts\n * const decoder = padLeftDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0, 0, 0x12, 0x34])); // 0xffff (reads from offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftEncoder}\n */\nexport function padLeftDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given decoder, extending the post-offset by `offset`\n * bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip after decoding.\n * @returns A new decoder with right padding applied.\n *\n * @example\n * ```ts\n * const decoder = padRightDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0x12, 0x34, 0, 0])); // 0xffff (ignores trailing bytes)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightEncoder}\n */\nexport function padRightDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given codec, shifting the encoding and decoding positions\n * forward by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * This ensures that values are read and written at a later position in the byte array,\n * while the padding bytes remain unused.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add before encoding and decoding.\n * @returns A new codec with left padding applied.\n *\n * @example\n * ```ts\n * const codec = padLeftCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * const value = codec.decode(bytes); // 0xffff (reads from offset 2)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padLeftEncoder}.\n * If you only need to apply padding for decoding, use {@link padLeftDecoder}.\n *\n * ```ts\n * const bytes = padLeftEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padLeftDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padLeftEncoder}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset)) as TCodec;\n}\n\n/**\n * Adds right padding to the given codec, extending the encoded and decoded value\n * by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * The extra bytes remain unused, ensuring that the next operation starts further\n * along the byte array.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add after encoding and decoding.\n * @returns A new codec with right padding applied.\n *\n * @example\n * ```ts\n * const codec = padRightCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (ignores padding bytes)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padRightEncoder}.\n * If you only need to apply padding for decoding, use {@link padRightDecoder}.\n *\n * ```ts\n * const bytes = padRightEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padRightDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padRightEncoder}\n * @see {@link padRightDecoder}\n */\nexport function padRightCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset)) as TCodec;\n}\n","import {\n assertIsFixedSize,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\nfunction copySourceToTargetInReverse(\n source: ReadonlyUint8Array,\n target_WILL_MUTATE: Uint8Array,\n sourceOffset: number,\n sourceLength: number,\n targetOffset: number = 0,\n) {\n while (sourceOffset < --sourceLength) {\n const leftValue = source[sourceOffset];\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];\n target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;\n sourceOffset++;\n }\n if (sourceOffset === sourceLength) {\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];\n }\n}\n\n/**\n * Reverses the bytes of a fixed-size encoder.\n *\n * Given a `FixedSizeEncoder`, this function returns a new `FixedSizeEncoder` that\n * reverses the bytes within the fixed-size byte array when encoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The fixed-size encoder to reverse.\n * @returns A new encoder that writes bytes in reverse order.\n *\n * @example\n * Encoding a `u16` value in reverse order.\n * ```ts\n * const encoder = reverseEncoder(getU16Encoder({ endian: Endian.Big }));\n * const bytes = encoder.encode(0x1234); // 0x3412 (bytes are flipped)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseDecoder}\n */\nexport function reverseEncoder(\n encoder: FixedSizeEncoder,\n): FixedSizeEncoder {\n assertIsFixedSize(encoder);\n return createEncoder({\n ...encoder,\n write: (value: TFrom, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n copySourceToTargetInReverse(\n bytes /* source */,\n bytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + encoder.fixedSize /* sourceLength */,\n );\n return newOffset;\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size decoder.\n *\n * Given a `FixedSizeDecoder`, this function returns a new `FixedSizeDecoder` that\n * reverses the bytes within the fixed-size byte array before decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the decoded value in bytes.\n *\n * @param decoder - The fixed-size decoder to reverse.\n * @returns A new decoder that reads bytes in reverse order.\n *\n * @example\n * Decoding a reversed `u16` value.\n * ```ts\n * const decoder = reverseDecoder(getU16Decoder({ endian: Endian.Big }));\n * const value = decoder.decode(new Uint8Array([0x34, 0x12])); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseEncoder}\n */\nexport function reverseDecoder(\n decoder: FixedSizeDecoder,\n): FixedSizeDecoder {\n assertIsFixedSize(decoder);\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reversedBytes = bytes.slice();\n copySourceToTargetInReverse(\n bytes /* source */,\n reversedBytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + decoder.fixedSize /* sourceLength */,\n );\n return decoder.read(reversedBytes, offset);\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size codec.\n *\n * Given a `FixedSizeCodec`, this function returns a new `FixedSizeCodec` that\n * reverses the bytes within the fixed-size byte array during encoding and decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded/decoded value in bytes.\n *\n * @param codec - The fixed-size codec to reverse.\n * @returns A new codec that encodes and decodes bytes in reverse order.\n *\n * @example\n * Reversing a `u16` codec.\n * ```ts\n * const codec = reverseCodec(getU16Codec({ endian: Endian.Big }));\n * const bytes = codec.encode(0x1234); // 0x3412 (bytes are flipped)\n * const value = codec.decode(bytes); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @remarks\n * If you only need to reverse an encoder, use {@link reverseEncoder}.\n * If you only need to reverse a decoder, use {@link reverseDecoder}.\n *\n * ```ts\n * const bytes = reverseEncoder(getU16Encoder()).encode(0x1234);\n * const value = reverseDecoder(getU16Decoder()).decode(bytes);\n * ```\n *\n * @see {@link reverseEncoder}\n * @see {@link reverseDecoder}\n */\nexport function reverseCodec(\n codec: FixedSizeCodec,\n): FixedSizeCodec {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Transforms an encoder by mapping its input values.\n *\n * This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B`\n * to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function.\n *\n * This is useful for handling type conversions, applying default values, or structuring data before encoding.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldFrom - The original type expected by the encoder.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n *\n * @param encoder - The encoder to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @returns A new encoder that accepts `TNewFrom` values and transforms them before encoding.\n *\n * @example\n * Encoding a string by counting its characters and storing the length as a `u32`.\n * ```ts\n * const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length);\n * encoder.encode(\"hello\"); // 0x05000000 (stores length 5)\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformDecoder}\n */\nexport function transformEncoder(\n encoder: FixedSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder;\nexport function transformEncoder(\n encoder: VariableSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Transforms a decoder by mapping its output values.\n *\n * This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A`\n * to be converted into values of type `B` after decoding. The transformation is applied via the `map` function.\n *\n * This is useful for post-processing, type conversions, or enriching decoded data.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldTo - The original type returned by the decoder.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param decoder - The decoder to transform.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding.\n * @returns A new decoder that decodes into `TNewTo`.\n *\n * @example\n * Decoding a stored `u32` length into a string of `'x'` characters.\n * ```ts\n * const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length));\n * decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // \"xxxxx\"\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformEncoder}\n */\nexport function transformDecoder(\n decoder: FixedSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder;\nexport function transformDecoder(\n decoder: VariableSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder {\n return createDecoder({\n ...decoder,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Transforms a codec by mapping its input and output values.\n *\n * This function takes an existing `Codec` and returns a `Codec`, allowing:\n * - Values of type `C` to be transformed into `A` before encoding.\n * - Values of type `B` to be transformed into `D` after decoding.\n *\n * This is useful for adapting codecs to work with different representations, handling default values, or\n * converting between primitive and structured types.\n *\n * @typeParam TOldFrom - The original type expected by the codec.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n * @typeParam TOldTo - The original type returned by the codec.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param codec - The codec to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding (optional).\n * @returns A new codec that encodes `TNewFrom` and decodes into `TNewTo`.\n *\n * @example\n * Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters.\n * ```ts\n * const codec = transformCodec(\n * getU32Codec(),\n * (value: string) => value.length, // Encode string length\n * (length) => 'x'.repeat(length) // Decode length into a string of 'x's\n * );\n *\n * const bytes = codec.encode(\"hello\"); // 0x05000000 (stores length 5)\n * const value = codec.decode(bytes); // \"xxxxx\"\n * ```\n *\n * @remarks\n * If only input transformation is needed, use {@link transformEncoder}.\n * If only output transformation is needed, use {@link transformDecoder}.\n *\n * ```ts\n * const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode(\"hello\");\n * const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes);\n * ```\n *\n * @see {@link transformEncoder}\n * @see {@link transformDecoder}\n */\nexport function transformCodec(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder['read']),\n });\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '0123456789';\n\n/**\n * Returns an encoder for base-10 strings.\n *\n * This encoder serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-10 strings.\n *\n * @example\n * Encoding a base-10 string.\n * ```ts\n * const encoder = getBase10Encoder();\n * const bytes = encoder.encode('1024'); // 0x0400\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-10 strings.\n *\n * This decoder deserializes base-10 encoded strings from a byte array.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-10 strings.\n *\n * @example\n * Decoding a base-10 string.\n * ```ts\n * const decoder = getBase10Decoder();\n * const value = decoder.decode(new Uint8Array([0x04, 0x00])); // \"1024\"\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-10 strings.\n *\n * This codec serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-10 strings.\n *\n * @example\n * Encoding and decoding a base-10 string.\n * ```ts\n * const codec = getBase10Codec();\n * const bytes = codec.encode('1024'); // 0x0400\n * const value = codec.decode(bytes); // \"1024\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-10 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase10Codec(), 5);\n * ```\n *\n * If you need a size-prefixed base-10 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase10Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase10Encoder} and {@link getBase10Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase10Encoder().encode('1024');\n * const value = getBase10Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase10Encoder}\n * @see {@link getBase10Decoder}\n */\nexport const getBase10Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings using bit re-slicing.\n *\n * This encoder serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to an alphabet, and encoding the result into a byte array.\n * This approach is commonly used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeEncoder` for encoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding a base-X string using bit re-slicing.\n * ```ts\n * const encoder = getBaseXResliceEncoder('elho', 2);\n * const bytes = encoder.encode('hellolol'); // 0x4aee\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.floor((value.length * bits) / 8),\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-X encoded strings using bit re-slicing.\n *\n * This decoder deserializes base-X encoded strings by re-slicing the bits of a byte array into\n * custom-sized chunks and mapping them to a specified alphabet.\n * This is typically used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeDecoder` for decoding base-X strings using bit re-slicing.\n *\n * @example\n * Decoding a base-X string using bit re-slicing.\n * ```ts\n * const decoder = getBaseXResliceDecoder('elho', 2);\n * const value = decoder.decode(new Uint8Array([0x4a, 0xee])); // \"hellolol\"\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): VariableSizeDecoder =>\n createDecoder({\n read(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-X strings using bit re-slicing.\n *\n * This codec serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to a given alphabet, and encoding the result into bytes.\n * It is particularly suited for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding and decoding a base-X string using bit re-slicing.\n * ```ts\n * const codec = getBaseXResliceCodec('elho', 2);\n * const bytes = codec.encode('hellolol'); // 0x4aee\n * const value = codec.decode(bytes); // \"hellolol\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXResliceCodec('elho', 2), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXResliceCodec('elho', 2), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXResliceEncoder} and {@link getBaseXResliceDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXResliceEncoder('elho', 2).encode('hellolol');\n * const value = getBaseXResliceDecoder('elho', 2).decode(bytes);\n * ```\n *\n * @see {@link getBaseXResliceEncoder}\n * @see {@link getBaseXResliceDecoder}\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): VariableSizeCodec =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n toArrayBuffer,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Returns an encoder for base-64 strings.\n *\n * This encoder serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-64 strings.\n *\n * @example\n * Encoding a base-64 string.\n * ```ts\n * const encoder = getBase64Encoder();\n * const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Encoder = (): VariableSizeEncoder => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return transformEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/**\n * Returns a decoder for base-64 strings.\n *\n * This decoder deserializes base-64 encoded strings from a byte array.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-64 strings.\n *\n * @example\n * Decoding a base-64 string.\n * ```ts\n * const decoder = getBase64Decoder();\n * const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // \"hello+world\"\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Decoder = (): VariableSizeDecoder => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(toArrayBuffer(bytes), offset).toString('base64'), bytes.length],\n });\n }\n\n return transformDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/**\n * Returns a codec for encoding and decoding base-64 strings.\n *\n * This codec serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-64 strings.\n *\n * @example\n * Encoding and decoding a base-64 string.\n * ```ts\n * const codec = getBase64Codec();\n * const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57\n * const value = codec.decode(bytes); // \"hello+world\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-64 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase64Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-64 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase64Encoder} and {@link getBase64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase64Encoder().encode('hello+world');\n * const value = getBase64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase64Encoder}\n * @see {@link getBase64Decoder}\n */\nexport const getBase64Codec = (): VariableSizeCodec => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**\n * Removes all null characters (`\\u0000`) from a string.\n *\n * This function cleans a string by stripping out any null characters,\n * which are often used as padding in fixed-size string encodings.\n *\n * @param value - The string to process.\n * @returns The input string with all null characters removed.\n *\n * @example\n * Removing null characters from a string.\n * ```ts\n * removeNullCharacters('hello\\u0000\\u0000'); // \"hello\"\n * ```\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters (`\\u0000`) at the end to reach a fixed length.\n *\n * If the input string is shorter than the specified length, it is padded with null characters\n * until it reaches the desired size. If it is already long enough, it remains unchanged.\n *\n * @param value - The string to pad.\n * @param chars - The total length of the resulting string, including padding.\n * @returns The input string padded with null characters up to the specified length.\n *\n * @example\n * Padding a string with null characters.\n * ```ts\n * padNullCharacters('hello', 8); // \"hello\\u0000\\u0000\\u0000\"\n * ```\n */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from '@solana/text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/**\n * Returns an encoder for UTF-8 strings.\n *\n * This encoder serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding UTF-8 strings.\n *\n * @example\n * Encoding a UTF-8 string.\n * ```ts\n * const encoder = getUtf8Encoder();\n * const bytes = encoder.encode('hello'); // 0x68656c6c6f\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Encoder = (): VariableSizeEncoder => {\n let textEncoder: TextEncoder;\n return createEncoder({\n getSizeFromValue: value => (textEncoder ||= new TextEncoder()).encode(value).length,\n write: (value: string, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new TextEncoder()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for UTF-8 strings.\n *\n * This decoder deserializes UTF-8 encoded strings from a byte array.\n * It reads all available bytes starting from the given offset.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding UTF-8 strings.\n *\n * @example\n * Decoding a UTF-8 string.\n * ```ts\n * const decoder = getUtf8Decoder();\n * const value = decoder.decode(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // \"hello\"\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Decoder = (): VariableSizeDecoder => {\n let textDecoder: TextDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding UTF-8 strings.\n *\n * This codec serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding UTF-8 strings.\n *\n * @example\n * Encoding and decoding a UTF-8 string.\n * ```ts\n * const codec = getUtf8Codec();\n * const bytes = codec.encode('hello'); // 0x68656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size UTF-8 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 5);\n * ```\n *\n * If you need a size-prefixed UTF-8 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getUtf8Encoder} and {@link getUtf8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getUtf8Encoder().encode('hello');\n * const value = getUtf8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getUtf8Encoder}\n * @see {@link getUtf8Decoder}\n */\nexport const getUtf8Codec = (): VariableSizeCodec => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","import type { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport type { Lamports } from '@solana/rpc-types';\n\n/**\n * The number of bytes required to store the {@link BaseAccount} information without its data.\n *\n * @example\n * ```ts\n * const myTotalAccountSize = myAccountDataSize + BASE_ACCOUNT_SIZE;\n * ```\n */\nexport const BASE_ACCOUNT_SIZE = 128;\n\n/**\n * Defines the attributes common to all Solana accounts. Namely, it contains everything stored\n * on-chain except the account data itself.\n *\n * @interface\n *\n * @example\n * ```ts\n * const BaseAccount: BaseAccount = {\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type BaseAccount = {\n readonly executable: boolean;\n readonly lamports: Lamports;\n readonly programAddress: Address;\n readonly space: bigint;\n};\n\n/**\n * Contains all the information relevant to a Solana account. It includes the account's address and\n * data, as well as the properties of {@link BaseAccount}.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Encoded\n * const myEncodedAccount: Account = {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n *\n * // Decoded\n * type MyAccountData = { name: string; age: number };\n * const myDecodedAccount: Account = {\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type Account = BaseAccount & {\n readonly address: Address;\n readonly data: TData;\n};\n\n/**\n * Represents an encoded account and is equivalent to an {@link Account} with `Uint8Array` account\n * data.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * } satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport type EncodedAccount = Account;\n","import type { Decoder, ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SolanaError,\n} from '@solana/errors';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/**\n * Transforms an {@link EncodedAccount} into an {@link Account} (or a {@link MaybeEncodedAccount}\n * into a {@link MaybeAccount}) by decoding the account data using the provided {@link Decoder}\n * instance.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: EncodedAccount<'1234..5678'>;\n * const myDecoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n *\n * const myDecodedAccount = decodeAccount(myAccount, myDecoder);\n * myDecodedAccount satisfies Account;\n * ```\n */\nexport function decodeAccount(\n encodedAccount: EncodedAccount,\n decoder: Decoder,\n): Account;\nexport function decodeAccount(\n encodedAccount: MaybeEncodedAccount,\n decoder: Decoder,\n): MaybeAccount;\nexport function decodeAccount(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n decoder: Decoder,\n): Account | MaybeAccount {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, {\n address: encodedAccount.address,\n });\n }\n}\n\nfunction accountExists(account: Account | MaybeAccount): account is Account {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/**\n * Asserts that an account stores decoded data, ie. not a `Uint8Array`.\n *\n * Note that it does not check the shape of the data matches the decoded type, only that it is not a\n * `Uint8Array`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: Account;\n * assertAccountDecoded(myAccount);\n *\n * // now the account data can be used as MyAccountData\n * account.data satisfies MyAccountData;\n * ```\n *\n * This is particularly useful for narrowing the result of fetching a JSON parsed account.\n *\n * ```ts\n * const account: MaybeAccount = await fetchJsonParsedAccount(\n * rpc,\n * '1234..5678' as Address,\n * );\n *\n * assertAccountDecoded(account);\n * // now we have a MaybeAccount\n * account satisfies MaybeAccount;\n * ```\n */\nexport function assertAccountDecoded(\n account: Account,\n): asserts account is Account;\nexport function assertAccountDecoded(\n account: MaybeAccount,\n): asserts account is MaybeAccount;\nexport function assertAccountDecoded(\n account: Account | MaybeAccount,\n): asserts account is Account | MaybeAccount {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, {\n address: account.address,\n });\n }\n}\n\n/**\n * Asserts that all input accounts store decoded data, ie. not a `Uint8Array`.\n *\n * As with {@link assertAccountDecoded} it does not check the shape of the data matches the decoded\n * type, only that it is not a `Uint8Array`.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccounts: Account[];\n * assertAccountsDecoded(myAccounts);\n *\n * // now the account data can be used as MyAccountData\n * for (const a of account) {\n * account.data satisfies MyAccountData;\n * }\n * ```\n */\nexport function assertAccountsDecoded(\n accounts: Account[],\n): asserts accounts is Account[];\nexport function assertAccountsDecoded(\n accounts: MaybeAccount[],\n): asserts accounts is MaybeAccount[];\nexport function assertAccountsDecoded(\n accounts: (Account | MaybeAccount)[],\n): asserts accounts is (Account | MaybeAccount)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, {\n addresses: encodedAddresses,\n });\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n} from '@solana/rpc-types';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type { JsonParsedDataResponse } from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/**\n * Parses a base64-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/**\n * Parses a base58-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse };\ntype ParsedAccountMeta = { program: string; type?: string };\ntype JsonParsedAccountData = TData & { parsedAccountMeta?: ParsedAccountMeta };\n\n/**\n * Parses an arbitrary `jsonParsed` account provided by the RPC client into an {@link Account} type\n * or a {@link MaybeAccount} type if the raw data can be set to `null`.\n *\n * The expected data type should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * const myAccount: Account = parseJsonRpcAccount(myJsonRpcAccount);\n * ```\n */\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount,\n): Account, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account, TAddress> | MaybeAccount, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = (rpcAccount.data.parsed.info || {}) as TData;\n\n if (rpcAccount.data.program || rpcAccount.data.parsed.type) {\n (data as JsonParsedAccountData).parsedAccountMeta = {\n program: rpcAccount.data.program,\n type: rpcAccount.data.parsed.type,\n };\n }\n\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n space: rpcAccount.space,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Rpc } from '@solana/rpc-spec';\nimport type { Commitment, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/**\n * Optional configuration for fetching a singular account.\n *\n * @interface\n */\nexport type FetchAccountConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the account as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches a {@link MaybeEncodedAccount} from the provided RPC client and address.\n *\n * It uses the {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} RPC method under the hood\n * with base64 encoding and an additional configuration object can be provided to customize the\n * behavior of the RPC call.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress);\n *\n * // With custom configuration.\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/**\n * Fetches a {@link MaybeAccount} from the provided RPC client and address by using\n * {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} under the hood with the `jsonParsed`\n * encoding.\n *\n * It may also return a {@link MaybeEncodedAccount} if the RPC client does not know how to parse the\n * account at the requested address. In any case, the expected data type should be explicitly\n * provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress);\n * myAccount satisfies MaybeAccount | MaybeEncodedAccount;\n *\n * // With custom configuration.\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchJsonParsedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise<\n | MaybeAccount\n | MaybeEncodedAccount\n> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(address, account as Parameters[1])\n : parseBase64RpcAccount(address, account as Parameters[1]);\n}\n\n/**\n * Optional configuration for fetching multiple accounts.\n *\n * @interface\n */\nexport type FetchAccountsConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the accounts as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches an array of {@link MaybeEncodedAccount | MaybeEncodedAccounts} from the provided RPC\n * client and an array of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with base64 encodings and an additional configuration object can be provided to\n * customize the behavior of the RPC call.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n *\n * @example\n * ```ts\n * const myAddressA = address('1234..5678');\n * const myAddressB = address('8765..4321');\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeEncodedAccount<'1234..5678'>;\n * myAccountB satisfies MaybeEncodedAccount<'8765..4321'>;\n *\n * // With custom configuration.\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount;\n };\n}\n\n/**\n * Fetches an array of {@link MaybeAccount | MaybeAccounts} from a provided RPC client and an array\n * of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with the `jsonParsed` encoding. It may also return a\n * {@link MaybeEncodedAccount} instead of the expected {@link MaybeAccount} if the RPC client does\n * not know how to parse some of the requested accounts. In any case, the array of expected data\n * types should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n * @typeParam TData - The expected types of these accounts' data.\n \n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * type MintData = { supply: bigint };\n * const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeAccount | MaybeEncodedAccount;\n * myAccountB satisfies MaybeAccount | MaybeEncodedAccount;\n * ```\n */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters[1]);\n }) as {\n [P in keyof TAddresses]:\n | MaybeAccount<\n TData[P & keyof TData] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P]\n >\n | MaybeEncodedAccount;\n } & {\n [P in keyof TData]:\n | MaybeAccount<\n TData[P] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P & keyof TAddresses]\n >\n | MaybeEncodedAccount;\n };\n}\n","import { Address } from '@solana/addresses';\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\n\nimport { Account } from './account';\n\n/**\n * Represents an account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type with an additional `exists`\n * attribute set to `true`. When it does not exist, it is represented by an object containing only\n * the address of the account and an `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Account exists\n * const myExistingAccount: MaybeAccount = {\n * exists: true,\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * // ...\n * };\n *\n * // Account does not exist\n * const myMissingAccount: MaybeAccount = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeAccount =\n | { readonly address: Address; readonly exists: false }\n | (Account & { readonly exists: true });\n\n/**\n * Represents an encoded account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type having its `TData` type\n * parameter set to `Uint8Array` with an additional `exists` attribute set to `true`. When it does\n * not exist, it is represented by an object containing only the address of the account and an\n * `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * // Encoded account exists\n * const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = {\n * exists: true,\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * // ...\n * };\n *\n * // Encoded account does not exist\n * const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeEncodedAccount = MaybeAccount;\n\n/**\n * Given a {@link MaybeAccount}, asserts that the account exists and allows it to be used as an\n * {@link Account} type going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccount: MaybeEncodedAccount<'1234..5678'>;\n * assertAccountExists(myAccount);\n *\n * // Now we can use myAccount as an `EncodedAccount`\n * myAccount satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport function assertAccountExists(\n account: MaybeAccount,\n): asserts account is Account & { exists: true } {\n if (!account.exists) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, { address: account.address });\n }\n}\n\n/**\n * Given an array of {@link MaybeAccount | MaybeAccounts}, asserts that all the accounts exist and\n * allows them to be used as an array of {@link Account | Accounts} going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccounts: MaybeEncodedAccount
[];\n * assertAccountsExist(myAccounts);\n *\n * // Now we can use them as an array of `EncodedAccounts`\n * for (const a of myAccounts) {\n * a satisfies EncodedAccount
;\n * }\n * ```\n */\nexport function assertAccountsExist(\n accounts: MaybeAccount[],\n): asserts accounts is (Account & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, { addresses: missingAddresses });\n }\n}\n","import { SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SolanaError } from '@solana/errors';\n\n/**\n * Throws an exception unless {@link Crypto#getRandomValues | `crypto.getRandomValues()`} is\n * available in the current JavaScript environment.\n */\nexport function assertPRNGIsAvailable() {\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.getRandomValues !== 'function') {\n throw new SolanaError(SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SolanaError,\n} from '@solana/errors';\n\nfunction assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT);\n }\n}\n\nlet cachedEd25519Decision: PromiseLike | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .then(() => {\n resolve((cachedEd25519Decision = true));\n })\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#digest | `crypto.subtle.digest()`} is available in\n * the current JavaScript environment.\n */\nexport function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#generateKey | `crypto.subtle.generateKey()`} is\n * available in the current JavaScript environment and has support for the Ed25519 curve.\n */\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED);\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#exportKey | `crypto.subtle.exportKey()`} is\n * available in the current JavaScript environment.\n */\nexport function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#sign | `crypto.subtle.sign()`} is available in the\n * current JavaScript environment.\n */\nexport function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);\n }\n}\n/**\n * Throws an exception unless {@link SubtleCrypto#verify | `crypto.subtle.verify()`} is available in\n * the current JavaScript environment.\n */\nexport function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n combineCodec,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * Represents a string that validates as a Solana address. Functions that require well-formed\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an arbitrary string as a base58-encoded address, use the\n * {@link address}, {@link assertIsAddress}, or {@link isAddress} functions in this package.\n */\nexport type Address = Brand, 'Address'>;\n\nlet memoizedBase58Encoder: Encoder | undefined;\nlet memoizedBase58Decoder: Decoder | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Address} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAddress } from '@solana/addresses';\n *\n * if (isAddress(ownerAddress)) {\n * // At this point, `ownerAddress` has been refined to a\n * // `Address` that can be used with the RPC.\n * const { value: lamports } = await rpc.getBalance(ownerAddress).send();\n * setBalanceLamports(lamports);\n * } else {\n * setError(`${ownerAddress} is not an address`);\n * }\n * ```\n */\nexport function isAddress(putativeAddress: string): putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n try {\n return base58Encoder.encode(putativeAddress).byteLength === 32;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an address or public\n * key, from an untrusted network API or user input. Use this function to assert that such an\n * arbitrary string is a base58-encoded address.\n *\n * @example\n * ```ts\n * import { assertIsAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // At this point, `address` is an `Address` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out not to be a base58-encoded address\n * }\n * }\n * ```\n */\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * Combines _asserting_ that a string is an address with _coercing_ it to the {@link Address} type.\n * It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good address as a string, it's more efficient to typecast it rather\n * than to use the {@link address} helper, because the helper unconditionally performs validation on\n * its input.\n * >\n * > ```ts\n * > import { Address } from '@solana/addresses';\n * >\n * > const MEMO_PROGRAM_ADDRESS =\n * > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;\n * > ```\n */\nexport function address(putativeAddress: TAddress): Address {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded address to a byte array.\n *\n * @example\n * ```ts\n * import { getAddressEncoder } from '@solana/addresses';\n *\n * const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;\n * const addressEncoder = getAddressEncoder();\n * const addressBytes = addressEncoder.encode(address);\n * // Uint8Array(32) [\n * // 150, 183, 190, 48, 171, 8, 39, 156,\n * // 122, 213, 172, 108, 193, 95, 26, 158,\n * // 149, 243, 115, 254, 20, 200, 36, 30,\n * // 248, 179, 178, 232, 220, 89, 53, 127\n * // ]\n * ```\n */\nexport function getAddressEncoder(): FixedSizeEncoder {\n return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), putativeAddress =>\n address(putativeAddress),\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an address to the\n * base58-encoded representation of that address.\n *\n * @example\n * ```ts\n * import { getAddressDecoder } from '@solana/addresses';\n *\n * const addressBytes = new Uint8Array([\n * 150, 183, 190, 48, 171, 8, 39, 156,\n * 122, 213, 172, 108, 193, 95, 26, 158,\n * 149, 243, 115, 254, 20, 200, 36, 30,\n * 248, 179, 178, 232, 220, 89, 53, 127\n * ]);\n * const addressDecoder = getAddressDecoder();\n * const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka\n * ```\n */\nexport function getAddressDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded address.\n *\n * @see {@link getAddressDecoder}\n * @see {@link getAddressEncoder}\n */\nexport function getAddressCodec(): FixedSizeCodec {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\n\nimport { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: ReadonlyUint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport function compressedPointBytesAreOnCurve(bytes: ReadonlyUint8Array): boolean {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SolanaError } from '@solana/errors';\nimport type { AffinePoint } from '@solana/nominal-types';\n\nimport { type Address, getAddressCodec } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * Represents an {@link Address} that validates as being off-curve. Functions that require off-curve\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an address as being off-curve, use the {@link offCurveAddress},\n * {@link assertIsOffCurveAddress}, or {@link isOffCurveAddress} functions in this package.\n */\nexport type OffCurveAddress = AffinePoint, 'invalid'>;\n\n/**\n * A type guard that returns `true` if the input address conforms to the {@link OffCurveAddress}\n * type, and refines its type for use in your application.\n *\n * @example\n * ```ts\n * import { isOffCurveAddress } from '@solana/addresses';\n *\n * if (isOffCurveAddress(accountAddress)) {\n * // At this point, `accountAddress` has been refined to a\n * // `OffCurveAddress` that can be used within your business logic.\n * const { value: account } = await rpc.getAccountInfo(accountAddress).send();\n * } else {\n * setError(`${accountAddress} is not off-curve`);\n * }\n * ```\n */\nexport function isOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): putativeOffCurveAddress is OffCurveAddress {\n const addressBytes = getAddressCodec().encode(putativeOffCurveAddress);\n return compressedPointBytesAreOnCurve(addressBytes) === false;\n}\n\n/**\n * From time to time you might acquire an {@link Address}, that you expect to validate as an\n * off-curve address, from an untrusted source. Use this function to assert that such an address is\n * off-curve.\n *\n * @example\n * ```ts\n * import { assertIsOffCurveAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that the input conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `OffCurveAddress`.\n * assertIsOffCurveAddress(address);\n * // At this point, `address` is an `OffCurveAddress` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out to NOT be a base58-encoded off-curve address\n * }\n * }\n * ```\n */\nexport function assertIsOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): asserts putativeOffCurveAddress is OffCurveAddress {\n if (!isOffCurveAddress(putativeOffCurveAddress)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS);\n }\n}\n\n/**\n * Combines _asserting_ that an {@link Address} is off-curve with _coercing_ it to the\n * {@link OffCurveAddress} type. It's most useful with untrusted input.\n */\nexport function offCurveAddress(\n putativeOffCurveAddress: TAddress,\n): OffCurveAddress {\n assertIsOffCurveAddress(putativeOffCurveAddress);\n return putativeOffCurveAddress;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\nimport { bytesEqual, type ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nimport { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * A tuple representing a program derived address (derived from the address of some program and a\n * set of seeds) and the associated bump seed used to ensure that the address, as derived, does not\n * fall on the Ed25519 curve.\n *\n * Whenever you need to validate an arbitrary tuple as one that represents a program derived\n * address, use the {@link assertIsProgramDerivedAddress} or {@link isProgramDerivedAddress}\n * functions in this package.\n */\nexport type ProgramDerivedAddress = Readonly<\n [Address, ProgramDerivedAddressBump]\n>;\n\n/**\n * Represents an integer in the range [0,255] used in the derivation of a program derived address to\n * ensure that it does not fall on the Ed25519 curve.\n */\nexport type ProgramDerivedAddressBump = Brand;\n\n/**\n * A type guard that returns `true` if the input tuple conforms to the {@link ProgramDerivedAddress}\n * type, and refines its type for use in your program.\n *\n * @see The {@link isAddress} function for an example of how to use a type guard.\n */\nexport function isProgramDerivedAddress(\n value: unknown,\n): value is ProgramDerivedAddress {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * In the event that you receive an address/bump-seed tuple from some untrusted source, use this\n * function to assert that it conforms to the {@link ProgramDerivedAddress} interface.\n *\n * @see The {@link assertIsAddress} function for an example of how to use an assertion function.\n */\nexport function assertIsProgramDerivedAddress(\n value: unknown,\n): asserts value is ProgramDerivedAddress {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {\n bump: value[1],\n });\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = ReadonlyUint8Array | string;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise
{\n assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {\n actual: seeds.length,\n maxSeeds: MAX_SEEDS,\n });\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: bytes.byteLength,\n index: ii,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (compressedPointBytesAreOnCurve(addressBytes)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\n\n/**\n * Given a program's {@link Address} and up to 16 {@link Seed | Seeds}, this method will return the\n * program derived address (PDA) associated with each.\n *\n * @example\n * ```ts\n * import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses';\n *\n * const addressEncoder = getAddressEncoder();\n * const [pda, bumpSeed] = await getProgramDerivedAddress({\n * programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address,\n * seeds: [\n * // Owner\n * addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address),\n * // Token program\n * addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address),\n * // Mint\n * addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address),\n * ],\n * });\n * ```\n */\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);\n}\n\n/**\n * Returns a base58-encoded address derived from some base address, some program address, and a seed\n * string or byte array.\n *\n * @example\n * ```ts\n * import { createAddressWithSeed } from '@solana/addresses';\n *\n * const derivedAddress = await createAddressWithSeed({\n * // The private key associated with this address will be able to sign for `derivedAddress`.\n * baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address,\n * // Only this program will be able to write data to this account.\n * programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address,\n * seed: 'data-account',\n * });\n * ```\n */\nexport async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise
{\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: seedBytes.byteLength,\n index: 0,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES.length), new Uint8Array(PDA_MARKER_BYTES))\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';\n\nimport { Address, getAddressDecoder, getAddressEncoder } from './address';\n\n/**\n * Given a public {@link CryptoKey}, this method will return its associated {@link Address}.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const address = await getAddressFromPublicKey(publicKey);\n * ```\n */\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise
{\n assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\n/**\n * Given an {@link Address}, return a {@link CryptoKey} that can be used to verify signatures.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const publicKey = await getPublicKeyFromAddress(address);\n * ```\n */\nexport async function getPublicKeyFromAddress(address: Address) {\n const addressBytes = getAddressEncoder().encode(address);\n return await crypto.subtle.importKey('raw', addressBytes, { name: 'Ed25519' }, true /* extractable */, ['verify']);\n}\n","import { SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\n/**\n * Ensures that a given number falls within a specified range.\n *\n * If the number is outside the allowed range, an error is thrown.\n * This function is primarily used to validate values before encoding them in a codec.\n *\n * @param codecDescription - A string describing the codec that is performing the validation.\n * @param min - The minimum allowed value (inclusive).\n * @param max - The maximum allowed value (inclusive).\n * @param value - The number to validate.\n *\n * @throws {@link SolanaError} if the value is out of range.\n *\n * @example\n * Validating a number within range.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 42); // Passes\n * ```\n *\n * @example\n * Throwing an error for an out-of-range value.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 300); // Throws\n * ```\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: bigint | number,\n max: bigint | number,\n value: bigint | number,\n) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value,\n });\n }\n}\n","import { Codec, Decoder, Encoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n/**\n * Represents an encoder for numbers and bigints.\n *\n * This type allows encoding values that are either `number` or `bigint`.\n * Depending on the specific implementation, the encoded output may have a fixed or variable size.\n *\n * @see {@link FixedSizeNumberEncoder}\n */\nexport type NumberEncoder = Encoder;\n\n/**\n * Represents a fixed-size encoder for numbers and bigints.\n *\n * This encoder serializes values using an exact number of bytes, defined by `TSize`.\n *\n * @typeParam TSize - The number of bytes used for encoding.\n *\n * @see {@link NumberEncoder}\n */\nexport type FixedSizeNumberEncoder = FixedSizeEncoder;\n\n/**\n * Represents a decoder for numbers and bigints.\n *\n * This type supports decoding values as either `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberDecoder}\n */\nexport type NumberDecoder = Decoder | Decoder;\n\n/**\n * Represents a fixed-size decoder for numbers and bigints.\n *\n * This decoder reads a fixed number of bytes (`TSize`) and converts them into a `number` or `bigint`.\n *\n * @typeParam TSize - The number of bytes expected for decoding.\n *\n * @see {@link NumberDecoder}\n */\nexport type FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\n\n/**\n * Represents a codec for encoding and decoding numbers and bigints.\n *\n * - The encoded value can be either a `number` or a `bigint`.\n * - The decoded value will always be either a `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberCodec}\n */\nexport type NumberCodec = Codec | Codec;\n\n/**\n * Represents a fixed-size codec for encoding and decoding numbers and bigints.\n *\n * This codec uses a specific number of bytes (`TSize`) for serialization.\n * The encoded value can be either a `number` or `bigint`, but the decoded value will always be a `number` or `bigint`,\n * depending on the implementation.\n *\n * @typeParam TSize - The number of bytes used for encoding and decoding.\n *\n * @see {@link NumberCodec}\n */\nexport type FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Configuration options for number codecs that use more than one byte.\n *\n * This configuration applies to all number codecs except `u8` and `i8`,\n * allowing the user to specify the endianness of serialization.\n */\nexport type NumberCodecConfig = {\n /**\n * Specifies whether numbers should be encoded in little-endian or big-endian format.\n *\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the byte order used for number serialization.\n *\n * - `Little`: The least significant byte is stored first.\n * - `Big`: The most significant byte is stored first.\n */\nexport enum Endian {\n Little,\n Big,\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n toArrayBuffer,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n config?: NumberCodecConfig;\n name: string;\n size: TSize;\n};\n\ntype NumberFactoryEncoderInput = NumberFactorySharedInput & {\n range?: [bigint | number, bigint | number];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.Big ? false : true;\n}\n\nexport function numberEncoderFactory(\n input: NumberFactoryEncoderInput,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory(\n input: NumberFactoryDecoderInput,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\n });\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit floating-point numbers (`f32`).\n *\n * This encoder serializes `f32` values using 4 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f32` values.\n *\n * @example\n * Encoding an `f32` value.\n * ```ts\n * const encoder = getF32Encoder();\n * const bytes = encoder.encode(-1.5); // 0x0000c0bf\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit floating-point numbers (`f32`).\n *\n * This decoder deserializes `f32` values from 4 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f32` values.\n *\n * @example\n * Decoding an `f32` value.\n * ```ts\n * const decoder = getF32Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`).\n *\n * This codec serializes `f32` values using 4 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f32` values.\n *\n * @example\n * Encoding and decoding an `f32` value.\n * ```ts\n * const codec = getF32Codec();\n * const bytes = codec.encode(-1.5); // 0x0000c0bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbfc00000\n * ```\n *\n * @remarks\n * `f32` values follow the IEEE 754 single-precision floating-point standard.\n * Precision loss may occur for certain values.\n *\n * - If you need higher precision, consider using {@link getF64Codec}.\n * - If you need integer values, consider using {@link getI32Codec} or {@link getU32Codec}.\n *\n * Separate {@link getF32Encoder} and {@link getF32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF32Encoder().encode(-1.5);\n * const value = getF32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF32Encoder}\n * @see {@link getF32Decoder}\n */\nexport const getF32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit floating-point numbers (`f64`).\n *\n * This encoder serializes `f64` values using 8 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f64` values.\n *\n * @example\n * Encoding an `f64` value.\n * ```ts\n * const encoder = getF64Encoder();\n * const bytes = encoder.encode(-1.5); // 0x000000000000f8bf\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f64',\n set: (view, value, le) => view.setFloat64(0, Number(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit floating-point numbers (`f64`).\n *\n * This decoder deserializes `f64` values from 8 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f64` values.\n *\n * @example\n * Decoding an `f64` value.\n * ```ts\n * const decoder = getF64Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: 'f64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`).\n *\n * This codec serializes `f64` values using 8 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f64` values.\n *\n * @example\n * Encoding and decoding an `f64` value.\n * ```ts\n * const codec = getF64Codec();\n * const bytes = codec.encode(-1.5); // 0x000000000000f8bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbff8000000000000\n * ```\n *\n * @remarks\n * `f64` values follow the IEEE 754 double-precision floating-point standard.\n * Precision loss may still occur but is significantly lower than `f32`.\n *\n * - If you need smaller floating-point values, consider using {@link getF32Codec}.\n * - If you need integer values, consider using {@link getI64Codec} or {@link getU64Codec}.\n *\n * Separate {@link getF64Encoder} and {@link getF64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF64Encoder().encode(-1.5);\n * const value = getF64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF64Encoder}\n * @see {@link getF64Decoder}\n */\nexport const getF64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF64Encoder(config), getF64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit signed integers (`i128`).\n *\n * This encoder serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i128` values.\n *\n * @example\n * Encoding an `i128` value.\n * ```ts\n * const encoder = getI128Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i128',\n range: [-BigInt('0x7fffffffffffffffffffffffffffffff') - 1n, BigInt('0x7fffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit signed integers (`i128`).\n *\n * This decoder deserializes `i128` values from 16 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i128` values.\n *\n * @example\n * Decoding an `i128` value.\n * ```ts\n * const decoder = getI128Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n * 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'i128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit signed integers (`i128`).\n *\n * This codec serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i128` values.\n *\n * @example\n * Encoding and decoding an `i128` value.\n * ```ts\n * const codec = getI128Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^127` and `2^127 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI64Codec} or {@link getI32Codec}.\n * - If you need a larger signed integer, consider using a custom codec.\n * - If you need unsigned integers, consider using {@link getU128Codec}.\n *\n * Separate {@link getI128Encoder} and {@link getI128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI128Encoder().encode(-42);\n * const value = getI128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI128Encoder}\n * @see {@link getI128Decoder}\n */\nexport const getI128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI128Encoder(config), getI128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit signed integers (`i16`).\n *\n * This encoder serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i16` values.\n *\n * @example\n * Encoding an `i16` value.\n * ```ts\n * const encoder = getI16Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ff\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i16',\n range: [-Number('0x7fff') - 1, Number('0x7fff')],\n set: (view, value, le) => view.setInt16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit signed integers (`i16`).\n *\n * This decoder deserializes `i16` values from 2 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i16` values.\n *\n * @example\n * Decoding an `i16` value.\n * ```ts\n * const decoder = getI16Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff])); // -42\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: 'i16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit signed integers (`i16`).\n *\n * This codec serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i16` values.\n *\n * @example\n * Encoding and decoding an `i16` value.\n * ```ts\n * const codec = getI16Codec();\n * const bytes = codec.encode(-42); // 0xd6ff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^15` (`-32,768`) and `2^15 - 1` (`32,767`).\n *\n * - If you need a smaller signed integer, consider using {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI32Codec}.\n * - If you need unsigned integers, consider using {@link getU16Codec}.\n *\n * Separate {@link getI16Encoder} and {@link getI16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI16Encoder().encode(-42);\n * const value = getI16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI16Encoder}\n * @see {@link getI16Decoder}\n */\nexport const getI16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI16Encoder(config), getI16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit signed integers (`i32`).\n *\n * This encoder serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i32` values.\n *\n * @example\n * Encoding an `i32` value.\n * ```ts\n * const encoder = getI32Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ffffff\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i32',\n range: [-Number('0x7fffffff') - 1, Number('0x7fffffff')],\n set: (view, value, le) => view.setInt32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit signed integers (`i32`).\n *\n * This decoder deserializes `i32` values from 4 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i32` values.\n *\n * @example\n * Decoding an `i32` value.\n * ```ts\n * const decoder = getI32Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff, 0xff, 0xff])); // -42\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: 'i32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit signed integers (`i32`).\n *\n * This codec serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i32` values.\n *\n * @example\n * Encoding and decoding an `i32` value.\n * ```ts\n * const codec = getI32Codec();\n * const bytes = codec.encode(-42); // 0xd6ffffff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^31` (`-2,147,483,648`) and `2^31 - 1` (`2,147,483,647`).\n *\n * - If you need a smaller signed integer, consider using {@link getI16Codec} or {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI64Codec}.\n * - If you need unsigned integers, consider using {@link getU32Codec}.\n *\n * Separate {@link getI32Encoder} and {@link getI32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI32Encoder().encode(-42);\n * const value = getI32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI32Encoder}\n * @see {@link getI32Decoder}\n */\nexport const getI32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI32Encoder(config), getI32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit signed integers (`i64`).\n *\n * This encoder serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i64` values.\n *\n * @example\n * Encoding an `i64` value.\n * ```ts\n * const encoder = getI64Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffff\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit signed integers (`i64`).\n *\n * This decoder deserializes `i64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i64` values.\n *\n * @example\n * Decoding an `i64` value.\n * ```ts\n * const decoder = getI64Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit signed integers (`i64`).\n *\n * This codec serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i64` values.\n *\n * @example\n * Encoding and decoding an `i64` value.\n * ```ts\n * const codec = getI64Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^63` and `2^63 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI32Codec} or {@link getI16Codec}.\n * - If you need a larger signed integer, consider using {@link getI128Codec}.\n * - If you need unsigned integers, consider using {@link getU64Codec}.\n *\n * Separate {@link getI64Encoder} and {@link getI64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI64Encoder().encode(-42);\n * const value = getI64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI64Encoder}\n * @see {@link getI64Decoder}\n */\nexport const getI64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit signed integers (`i8`).\n *\n * This encoder serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `i8` values.\n *\n * @example\n * Encoding an `i8` value.\n * ```ts\n * const encoder = getI8Encoder();\n * const bytes = encoder.encode(-42); // 0xd6\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit signed integers (`i8`).\n *\n * This decoder deserializes `i8` values from 1 byte.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `i8` values.\n *\n * @example\n * Decoding an `i8` value.\n * ```ts\n * const decoder = getI8Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6])); // -42\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit signed integers (`i8`).\n *\n * This codec serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `i8` values.\n *\n * @example\n * Encoding and decoding an `i8` value.\n * ```ts\n * const codec = getI8Codec();\n * const bytes = codec.encode(-42); // 0xd6\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @remarks\n * This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`).\n *\n * - If you need a larger signed integer, consider using {@link getI16Codec}.\n * - If you need an unsigned integer, consider using {@link getU8Codec}.\n *\n * Separate {@link getI8Encoder} and {@link getI8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI8Encoder().encode(-42);\n * const value = getI8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI8Encoder}\n * @see {@link getI8Decoder}\n */\nexport const getI8Codec = (): FixedSizeCodec =>\n combineCodec(getI8Encoder(), getI8Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n Offset,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Returns an encoder for `shortU16` values.\n *\n * This encoder serializes `shortU16` values using **1 to 3 bytes**.\n * Smaller values use fewer bytes, while larger values take up more space.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding `shortU16` values.\n *\n * @example\n * Encoding a `shortU16` value.\n * ```ts\n * const encoder = getShortU16Encoder();\n * encoder.encode(42); // 0x2a\n * encoder.encode(128); // 0x8001\n * encoder.encode(16384); // 0x808001\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: bigint | number): number => {\n if (value <= 0b01111111) return 1;\n if (value <= 0b0011111111111111) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value: bigint | number, bytes: Uint8Array, offset: Offset): Offset => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = Number(value) >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n shortU16Bytes[ii - 1] |= 0b10000000;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n },\n });\n\n/**\n * Returns a decoder for `shortU16` values.\n *\n * This decoder deserializes `shortU16` values from **1 to 3 bytes**.\n * The number of bytes used depends on the encoded value.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding `shortU16` values.\n *\n * @example\n * Decoding a `shortU16` value.\n * ```ts\n * const decoder = getShortU16Decoder();\n * decoder.decode(new Uint8Array([0x2a])); // 42\n * decoder.decode(new Uint8Array([0x80, 0x01])); // 128\n * decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n maxSize: 3,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset): [number, Offset] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding `shortU16` values.\n *\n * It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.\n * The larger the value, the more bytes it uses.\n *\n * - If the value is `<= 0x7f` (127), it is stored in a **single byte**\n * and the first bit is set to `0` to indicate the end of the value.\n * - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.\n * - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.\n *\n * In other words, the encoding scheme follows this structure:\n *\n * ```txt\n * 0XXXXXXX <- Values 0 to 127 (1 byte)\n * 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)\n * 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)\n * ```\n *\n * @returns A `VariableSizeCodec` for encoding and decoding `shortU16` values.\n *\n * @example\n * Encoding and decoding `shortU16` values.\n * ```ts\n * const codec = getShortU16Codec();\n * const bytes1 = codec.encode(42); // 0x2a\n * const bytes2 = codec.encode(128); // 0x8001\n * const bytes3 = codec.encode(16384); // 0x808001\n *\n * codec.decode(bytes1); // 42\n * codec.decode(bytes2); // 128\n * codec.decode(bytes3); // 16384\n * ```\n *\n * @remarks\n * This codec efficiently stores small numbers, making it useful for transactions and compact representations.\n *\n * If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.\n *\n * Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getShortU16Encoder().encode(42);\n * const value = getShortU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getShortU16Encoder}\n * @see {@link getShortU16Decoder}\n */\nexport const getShortU16Codec = (): VariableSizeCodec =>\n combineCodec(getShortU16Encoder(), getShortU16Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit unsigned integers (`u128`).\n *\n * This encoder serializes `u128` values using sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u128` values.\n *\n * @example\n * Encoding a `u128` value.\n * ```ts\n * const encoder = getU128Encoder();\n * const bytes = encoder.encode(42n); // 0x2a000000000000000000000000000000\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0n, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit unsigned integers (`u128`).\n *\n * This decoder deserializes `u128` values from sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u128` values.\n *\n * @example\n * Decoding a `u128` value.\n * ```ts\n * const decoder = getU128Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit unsigned integers (`u128`).\n *\n * This codec serializes `u128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u128` values.\n *\n * @example\n * Encoding and decoding a `u128` value.\n * ```ts\n * const codec = getU128Codec();\n * const bytes = codec.encode(42); // 0x2a000000000000000000000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000000000000000000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^128 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU64Codec} or {@link getU32Codec}.\n * - If you need signed integers, consider using {@link getI128Codec}.\n *\n * Separate {@link getU128Encoder} and {@link getU128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU128Encoder().encode(42);\n * const value = getU128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU128Encoder}\n * @see {@link getU128Decoder}\n */\nexport const getU128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit unsigned integers (`u16`).\n *\n * This encoder serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u16` values.\n *\n * @example\n * Encoding a `u16` value.\n * ```ts\n * const encoder = getU16Encoder();\n * const bytes = encoder.encode(42); // 0x2a00\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit unsigned integers (`u16`).\n *\n * This decoder deserializes `u16` values from two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u16` values.\n *\n * @example\n * Decoding a `u16` value.\n * ```ts\n * const decoder = getU16Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`).\n *\n * This codec serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u16` values.\n *\n * @example\n * Encoding and decoding a `u16` value.\n * ```ts\n * const codec = getU16Codec();\n * const bytes = codec.encode(42); // 0x2a00 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^16 - 1`.\n * If you need a larger range, consider using {@link getU32Codec} or {@link getU64Codec}.\n * For signed integers, use {@link getI16Codec}.\n *\n * Separate {@link getU16Encoder} and {@link getU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU16Encoder().encode(42);\n * const value = getU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU16Encoder}\n * @see {@link getU16Decoder}\n */\nexport const getU16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit unsigned integers (`u32`).\n *\n * This encoder serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u32` values.\n *\n * @example\n * Encoding a `u32` value.\n * ```ts\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42); // 0x2a000000\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u32',\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit unsigned integers (`u32`).\n *\n * This decoder deserializes `u32` values from four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u32` values.\n *\n * @example\n * Decoding a `u32` value.\n * ```ts\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`).\n *\n * This codec serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u32` values.\n *\n * @example\n * Encoding and decoding a `u32` value.\n * ```ts\n * const codec = getU32Codec();\n * const bytes = codec.encode(42); // 0x2a000000 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000002a\n * ```\n *\n * @remarks\n * This codec only supports values between `0` and `2^32 - 1`.\n * If you need a larger range, consider using {@link getU64Codec} or {@link getU128Codec}.\n * For signed integers, use {@link getI32Codec}.\n *\n * Separate {@link getU32Encoder} and {@link getU32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU32Encoder().encode(42);\n * const value = getU32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU32Encoder}\n * @see {@link getU32Decoder}\n */\nexport const getU32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU32Encoder(config), getU32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit unsigned integers (`u64`).\n *\n * This encoder serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `u64` values.\n *\n * @example\n * Encoding a `u64` value.\n * ```ts\n * const encoder = getU64Encoder();\n * const bytes = encoder.encode(42); // 0x2a00000000000000\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u64',\n range: [0n, BigInt('0xffffffffffffffff')],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit unsigned integers (`u64`).\n *\n * This decoder deserializes `u64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `u64` values.\n *\n * @example\n * Decoding a `u64` value.\n * ```ts\n * const decoder = getU64Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: 'u64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`).\n *\n * This codec serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u64` values.\n *\n * @example\n * Encoding and decoding a `u64` value.\n * ```ts\n * const codec = getU64Codec();\n * const bytes = codec.encode(42); // 0x2a00000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^64 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU32Codec} or {@link getU16Codec}.\n * - If you need a larger unsigned integer, consider using {@link getU128Codec}.\n * - If you need signed integers, consider using {@link getI64Codec}.\n *\n * Separate {@link getU64Encoder} and {@link getU64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU64Encoder().encode(42);\n * const value = getU64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU64Encoder}\n * @see {@link getU64Decoder}\n */\nexport const getU64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU64Encoder(config), getU64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit unsigned integers (`u8`).\n *\n * This encoder serializes `u8` values using a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `u8` values.\n *\n * @example\n * Encoding a `u8` value.\n * ```ts\n * const encoder = getU8Encoder();\n * const bytes = encoder.encode(42); // 0x2a\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'u8',\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit unsigned integers (`u8`).\n *\n * This decoder deserializes `u8` values from a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `u8` values.\n *\n * @example\n * Decoding a `u8` value.\n * ```ts\n * const decoder = getU8Decoder();\n * const value = decoder.decode(new Uint8Array([0xff])); // 255\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getUint8(0),\n name: 'u8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`).\n *\n * This codec serializes `u8` values using a single byte.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `u8` values.\n *\n * @example\n * Encoding and decoding a `u8` value.\n * ```ts\n * const codec = getU8Codec();\n * const bytes = codec.encode(255); // 0xff\n * const value = codec.decode(bytes); // 255\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^8 - 1` (0 to 255).\n * If you need larger integers, consider using {@link getU16Codec}, {@link getU32Codec}, or {@link getU64Codec}.\n * For signed integers, use {@link getI8Codec}.\n *\n * Separate {@link getU8Encoder} and {@link getU8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU8Encoder().encode(42);\n * const value = getU8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU8Encoder}\n * @see {@link getU8Decoder}\n */\nexport const getU8Codec = (): FixedSizeCodec =>\n combineCodec(getU8Encoder(), getU8Decoder());\n","import { SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SolanaError } from '@solana/errors';\n\n/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: bigint | number,\n actual: bigint | number,\n) {\n if (expected !== actual) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {\n actual,\n codecDescription,\n expected,\n });\n }\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\n/**\n * Functionally, this type helper is equivalent to the identity type — i.e. `type Identity = T`.\n * However, wrapping generic object mappings in this type significantly reduces the number\n * of instantiation expressions processed, which increases TypeScript performance and\n * prevents \"Type instantiation is excessively deep and possibly infinite\" errors.\n *\n * This works because TypeScript doesn't create a new level of nesting when encountering conditional generic types.\n * @see https://github.com/microsoft/TypeScript/issues/34933\n * @see https://github.com/kysely-org/kysely/pull/483\n */\nexport type DrainOuterGeneric = [T] extends [unknown] ? T : never;\n\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null,\n );\n}\n\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : (codec.maxSize ?? null);\n}\n","import {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } from './utils';\n\n/**\n * Defines the possible size strategies for array-like codecs (`array`, `map`, and `set`).\n *\n * The size of the collection can be determined using one of the following approaches:\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} to store a size prefix.\n * - A fixed `number` of items, enforcing an exact length.\n * - The string `\"remainder\"`, which infers the number of items by consuming the rest of the available bytes.\n * This option is only available when encoding fixed-size items.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayLikeCodecSize =\n | TPrefix\n | number\n | 'remainder';\n\n/**\n * Defines the configuration options for array codecs.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayCodecConfig = {\n /**\n * Specifies how the size of the array is determined.\n *\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} stores a size prefix before encoding the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length (only for fixed-size items).\n *\n * @defaultValue A `u32` size prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for arrays of values.\n *\n * This encoder serializes arrays by encoding each element using the provided item encoder.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TFrom - The type of the elements in the array.\n *\n * @param item - The encoder for each item in the array.\n * @param config - Optional configuration for the size encoding strategy.\n * @returns A `VariableSizeEncoder` for encoding arrays.\n *\n * @example\n * Encoding an array of `u8` numbers.\n * ```ts\n * const encoder = getArrayEncoder(getU8Encoder());\n * const bytes = encoder.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: FixedSizeEncoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config?: ArrayCodecConfig,\n): VariableSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig = {},\n): Encoder {\n const size = config.size ?? getU32Encoder();\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\n const prefixSize = typeof size === 'object' ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize,\n }),\n write: (array: TFrom[], bytes, offset) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, array.length);\n }\n if (typeof size === 'object') {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach(value => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for arrays of values.\n *\n * This decoder deserializes arrays by decoding each element using the provided item decoder.\n * By default, a `u32` size prefix is expected to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TTo - The type of the decoded elements in the array.\n *\n * @param item - The decoder for each item in the array.\n * @param config - Optional configuration for the size decoding strategy.\n * @returns A `VariableSizeDecoder` for decoding arrays.\n *\n * @example\n * Decoding an array of `u8` numbers.\n * ```ts\n * const decoder = getArrayDecoder(getU8Decoder());\n * const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // [1, 2, 3]\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayDecoder(\n item: Decoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: FixedSizeDecoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: Decoder,\n config?: ArrayCodecConfig,\n): VariableSizeDecoder;\nexport function getArrayDecoder(item: Decoder, config: ArrayCodecConfig = {}): Decoder {\n const size = config.size ?? getU32Decoder();\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n\n if (size === 'remainder') {\n while (offset < bytes.length) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n }\n\n const [resolvedSize, newOffset] = typeof size === 'number' ? [size, offset] : size.read(bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding arrays of values.\n *\n * This codec serializes arrays by encoding each element using the provided item codec.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * @typeParam TFrom - The type of the elements to encode.\n * @typeParam TTo - The type of the decoded elements.\n *\n * @param item - The codec for each item in the array.\n * @param config - Optional configuration for the size encoding/decoding strategy.\n * @returns A `VariableSizeCodec` for encoding and decoding arrays.\n *\n * @example\n * Encoding and decoding an array of `u8` numbers.\n * ```ts\n * const codec = getArrayCodec(getU8Codec());\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n *\n * const array = codec.decode(bytes);\n * // [1, 2, 3]\n * ```\n *\n * @example\n * Using a `u16` size prefix instead of `u32`.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix telling us to read 3 items.\n * ```\n *\n * @example\n * Using a fixed-size array of 3 items.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 3 });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. There must always be 3 items in the array.\n * ```\n *\n * @example\n * Using the `\"remainder\"` size strategy.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 'remainder' });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.\n * ```\n *\n * @remarks\n * The size of the array can be controlled using the `size` option:\n * - A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length.\n *\n * Separate {@link getArrayEncoder} and {@link getArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);\n * const array = getArrayDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getArrayEncoder}\n * @see {@link getArrayDecoder}\n */\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: FixedSizeCodec,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config?: ArrayCodecConfig,\n): VariableSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig = {},\n): Codec {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction computeArrayLikeCodecSize(size: number | object | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Defines the configuration options for bit array codecs.\n *\n * A bit array codec encodes an array of booleans into bits, packing them into bytes.\n * This configuration allows adjusting the bit ordering.\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n * @see {@link getBitArrayCodec}\n */\nexport type BitArrayCodecConfig = {\n /**\n * Determines whether the bits should be read in reverse order.\n *\n * - `false` (default): The first boolean is stored in the most significant bit (MSB-first).\n * - `true`: The first boolean is stored in the least significant bit (LSB-first).\n *\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Returns an encoder that packs an array of booleans into bits.\n *\n * This encoder converts a list of `boolean` values into a compact bit representation,\n * storing 8 booleans per byte.\n *\n * The `backward` config option determines whether the bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding the bit array.\n * @returns A `FixedSizeEncoder` for encoding bit arrays.\n *\n * @example\n * Encoding a bit array.\n * ```ts\n * const encoder = getBitArrayEncoder(1);\n *\n * encoder.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayEncoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeEncoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Returns a decoder that unpacks bits into an array of booleans.\n *\n * This decoder converts a compact bit representation back into a list of `boolean` values.\n * Each byte is expanded into 8 booleans.\n *\n * The `backward` config option determines whether the bits are read in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for decoding the bit array.\n * @returns A `FixedSizeDecoder` for decoding bit arrays.\n *\n * @example\n * Decoding a bit array.\n * ```ts\n * const decoder = getBitArrayDecoder(1);\n *\n * decoder.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayDecoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeDecoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec('bitArray', size, bytes, offset);\n const booleans: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\n slice.forEach(byte => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes boolean arrays as compact bit representations.\n *\n * This codec efficiently stores boolean arrays as bits, packing 8 values per byte.\n * The `backward` config option determines whether bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding and decoding the bit array.\n * @returns A `FixedSizeCodec` for encoding and decoding bit arrays.\n *\n * @example\n * Encoding and decoding a bit array.\n * ```ts\n * const codec = getBitArrayCodec(1);\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n *\n * codec.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @example\n * Encoding and decoding a bit array backwards.\n * ```ts\n * const codec = getBitArrayCodec(1, { backward: true });\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0x05 (0b00000101)\n *\n * codec.decode(new Uint8Array([0x05]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @remarks\n * Separate {@link getBitArrayEncoder} and {@link getBitArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBitArrayEncoder(1).encode([true, false, true, false]);\n * const value = getBitArrayDecoder(1).decode(bytes);\n * ```\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n */\nexport function getBitArrayCodec(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeCodec {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/**\n * Defines the configuration options for boolean codecs.\n *\n * A boolean codec encodes `true` as `1` and `false` as `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * @typeParam TSize - A number codec, encoder, or decoder used for boolean representation.\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n * @see {@link getBooleanCodec}\n */\nexport type BooleanCodecConfig = {\n /**\n * The number codec used to store boolean values.\n *\n * - By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * - A custom number codec can be provided to change the storage size.\n *\n * @defaultValue `u8`\n */\n size?: TSize;\n};\n\n/**\n * Returns an encoder for boolean values.\n *\n * This encoder converts `true` into `1` and `false` into `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for encoding booleans.\n * @returns A `FixedSizeEncoder` where `N` is the size of the number codec.\n *\n * @example\n * Encoding booleans.\n * ```ts\n * const encoder = getBooleanEncoder();\n *\n * encoder.encode(false); // 0x00\n * encoder.encode(true); // 0x01\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanEncoder(): FixedSizeEncoder;\nexport function getBooleanEncoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig): VariableSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig = {}): Encoder {\n return transformEncoder(config.size ?? getU8Encoder(), (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Returns a decoder for boolean values.\n *\n * This decoder reads a number and interprets `1` as `true` and `0` as `false`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for decoding booleans.\n * @returns A `FixedSizeDecoder` where `N` is the size of the number codec.\n *\n * @example\n * Decoding booleans.\n * ```ts\n * const decoder = getBooleanDecoder();\n *\n * decoder.decode(new Uint8Array([0x00])); // false\n * decoder.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanDecoder(): FixedSizeDecoder;\nexport function getBooleanDecoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig): VariableSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig = {}): Decoder {\n return transformDecoder(config.size ?? getU8Decoder(), (value: bigint | number): boolean => Number(value) === 1);\n}\n\n/**\n * Returns a codec for encoding and decoding boolean values.\n *\n * By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * The `size` option allows customizing the number codec used for storage.\n *\n * @param config - Configuration options for encoding and decoding booleans.\n * @returns A `FixedSizeCodec` where `N` is the size of the number codec.\n *\n * @example\n * Encoding and decoding booleans using a `u8` (default).\n * ```ts\n * const codec = getBooleanCodec();\n *\n * codec.encode(false); // 0x00\n * codec.encode(true); // 0x01\n *\n * codec.decode(new Uint8Array([0x00])); // false\n * codec.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @example\n * Encoding and decoding booleans using a custom number codec.\n * ```ts\n * const codec = getBooleanCodec({ size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * ```\n *\n * @remarks\n * Separate {@link getBooleanEncoder} and {@link getBooleanDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBooleanEncoder().encode(true);\n * const value = getBooleanDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n */\nexport function getBooleanCodec(): FixedSizeCodec;\nexport function getBooleanCodec(\n config: BooleanCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig): VariableSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig = {}): Codec {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for raw byte arrays.\n *\n * This encoder writes byte arrays exactly as provided without modification.\n *\n * The size of the encoded byte array is determined by the length of the input.\n * - To enforce a fixed size, consider using {@link fixEncoderSize}.\n * - To add a size prefix, use {@link addEncoderSizePrefix}.\n * - To add a sentinel value, use {@link addEncoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeEncoder`.\n *\n * @example\n * Encoding a byte array as-is.\n * ```ts\n * const encoder = getBytesEncoder();\n *\n * encoder.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * encoder.encode(new Uint8Array([255, 0, 127])); // 0xff007f\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => value.length,\n write: (value, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n },\n });\n}\n\n/**\n * Returns a decoder for raw byte arrays.\n *\n * This decoder reads byte arrays exactly as provided without modification.\n *\n * The decoded byte array extends from the provided offset to the end of the input.\n * - To enforce a fixed size, consider using {@link fixDecoderSize}.\n * - To add a size prefix, use {@link addDecoderSizePrefix}.\n * - To add a sentinel value, use {@link addDecoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeDecoder`.\n *\n * @example\n * Decoding a byte array as-is.\n * ```ts\n * const decoder = getBytesDecoder();\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Uint8Array([1, 2, 3])\n * decoder.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesDecoder(): VariableSizeDecoder {\n return createDecoder({\n read: (bytes, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding raw byte arrays.\n *\n * This codec serializes and deserializes byte arrays without modification.\n *\n * The size of the encoded and decoded byte array is determined dynamically.\n * This means, when reading, the codec will consume all remaining bytes in the input.\n * - To enforce a fixed size, consider using {@link fixCodecSize}.\n * - To add a size prefix, use {@link addCodecSizePrefix}.\n * - To add a sentinel value, use {@link addCodecSentinel}.\n *\n * @returns A `VariableSizeCodec`.\n *\n * @example\n * Encoding and decoding a byte array.\n * ```ts\n * const codec = getBytesCodec();\n *\n * codec.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * codec.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @remarks\n * Separate {@link getBytesEncoder} and {@link getBytesDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBytesEncoder().encode(new Uint8Array([1, 2, 3]));\n * const value = getBytesDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBytesEncoder}\n * @see {@link getBytesDecoder}\n */\nexport function getBytesCodec(): VariableSizeCodec {\n return combineCodec(getBytesEncoder(), getBytesDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n containsBytes,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getBase16Decoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__CODECS__INVALID_CONSTANT, SolanaError } from '@solana/errors';\n\n/**\n * Returns an encoder that always writes a predefined constant byte sequence.\n *\n * This encoder ensures that encoding always produces the specified byte array,\n * ignoring any input values.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence that will be written during encoding.\n *\n * @param constant - The predefined byte array to encode.\n * @returns A `FixedSizeEncoder` where `N` is the length of the constant.\n *\n * @example\n * Encoding a constant magic number.\n * ```ts\n * const encoder = getConstantEncoder(new Uint8Array([1, 2, 3, 4]));\n *\n * const bytes = encoder.encode();\n * // 0x01020304\n * // └──────┘ The predefined 4-byte constant.\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantEncoder(\n constant: TConstant,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: constant.length,\n write: (_, bytes, offset) => {\n bytes.set(constant, offset);\n return offset + constant.length;\n },\n });\n}\n\n/**\n * Returns a decoder that verifies a predefined constant byte sequence.\n *\n * This decoder reads the next bytes and checks that they match the provided constant.\n * If the bytes differ, it throws an error.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence expected during decoding.\n *\n * @param constant - The predefined byte array to verify.\n * @returns A `FixedSizeDecoder` where `N` is the length of the constant.\n *\n * @example\n * Decoding a constant magic number.\n * ```ts\n * const decoder = getConstantDecoder(new Uint8Array([1, 2, 3]));\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Passes\n * decoder.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantDecoder(\n constant: TConstant,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: constant.length,\n read: (bytes, offset) => {\n const base16 = getBase16Decoder();\n if (!containsBytes(bytes, constant, offset)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {\n constant,\n data: bytes,\n hexConstant: base16.decode(constant),\n hexData: base16.decode(bytes),\n offset,\n });\n }\n return [undefined, offset + constant.length];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes a predefined constant byte sequence.\n *\n * - **Encoding:** Always writes the specified byte array.\n * - **Decoding:** Asserts that the next bytes match the constant, throwing an error if they do not.\n *\n * This is useful for encoding fixed byte patterns required in a binary format or to use in\n * conjunction with other codecs such as {@link getHiddenPrefixCodec} or {@link getHiddenSuffixCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence to encode and verify during decoding.\n *\n * @param constant - The predefined byte array to encode and assert during decoding.\n * @returns A `FixedSizeCodec` where `N` is the length of the constant.\n *\n * @example\n * Encoding and decoding a constant magic number.\n * ```ts\n * const codec = getConstantCodec(new Uint8Array([1, 2, 3]));\n *\n * codec.encode(); // 0x010203\n * codec.decode(new Uint8Array([1, 2, 3])); // Passes\n * codec.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @remarks\n * Separate {@link getConstantEncoder} and {@link getConstantDecoder} functions are available.\n *\n * ```ts\n * const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode();\n * getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes);\n * ```\n *\n * @see {@link getConstantEncoder}\n * @see {@link getConstantDecoder}\n */\nexport function getConstantCodec(\n constant: TConstant,\n): FixedSizeCodec {\n return combineCodec(getConstantEncoder(constant), getConstantDecoder(constant));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for a tuple that can be encoded using a tuple codec.\n *\n * This type maps each provided item encoder to its corresponding value type.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n */\ntype GetEncoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for a tuple that can be decoded using a tuple codec.\n *\n * This type maps each provided item decoder to its corresponding value type.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n */\ntype GetDecoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for tuples.\n *\n * This encoder serializes a fixed-size array (tuple) by encoding its items\n * sequentially using the provided item encoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n *\n * @param items - The encoders for each item in the tuple.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples.\n *\n * @example\n * Encoding a tuple with 2 items.\n * ```ts\n * const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]);\n *\n * const bytes = encoder.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleEncoder[]>(\n items: TItems,\n): FixedSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): VariableSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): Encoder> {\n type TFrom = GetEncoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (value: TFrom, bytes, offset) => {\n assertValidNumberOfItemsForCodec('tuple', items.length, value.length);\n items.forEach((item, index) => {\n offset = item.write(value[index], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for tuples.\n *\n * This decoder deserializes a fixed-size array (tuple) by decoding its items\n * sequentially using the provided item decoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n *\n * @param items - The decoders for each item in the tuple.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples.\n *\n * @example\n * Decoding a tuple with 2 items.\n * ```ts\n * const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]);\n *\n * const tuple = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // ['Alice', 42]\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleDecoder[]>(\n items: TItems,\n): FixedSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): VariableSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): Decoder> {\n type TTo = GetDecoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const values = [] as Array & TTo;\n items.forEach(item => {\n const [newValue, newOffset] = item.read(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding tuples.\n *\n * This codec serializes tuples by encoding and decoding each item sequentially.\n *\n * Unlike the {@link getArrayCodec} codec, each item in the tuple has its own codec\n * and, therefore, can be of a different type.\n *\n * @typeParam TItems - An array of codecs, each corresponding to a tuple element.\n *\n * @param items - The codecs for each item in the tuple.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples.\n *\n * @example\n * Encoding and decoding a tuple with 2 items.\n * ```ts\n * const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]);\n *\n * const bytes = codec.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n *\n * const tuple = codec.decode(bytes);\n * // ['Alice', 42]\n * ```\n *\n * @remarks\n * Separate {@link getTupleEncoder} and {@link getTupleDecoder} functions are available.\n *\n * ```ts\n * const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()])\n * .encode(['Alice', 42]);\n *\n * const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()])\n * .decode(bytes);\n * ```\n *\n * @see {@link getTupleEncoder}\n * @see {@link getTupleDecoder}\n */\nexport function getTupleCodec[]>(\n items: TItems,\n): FixedSizeCodec, GetDecoderTypeFromItems & GetEncoderTypeFromItems>;\nexport function getTupleCodec[]>(\n items: TItems,\n): VariableSizeCodec<\n GetEncoderTypeFromItems,\n GetDecoderTypeFromItems & GetEncoderTypeFromItems\n>;\nexport function getTupleCodec[]>(\n items: TItems,\n): Codec, GetDecoderTypeFromItems & GetEncoderTypeFromItems> {\n return combineCodec(\n getTupleEncoder(items),\n getTupleDecoder(items) as Decoder & GetEncoderTypeFromItems>,\n );\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n Offset,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\nimport { DrainOuterGeneric, getMaxSize, maxCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for values that can be encoded using a union codec.\n *\n * This type maps the provided variant encoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n */\ntype GetEncoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Encoder ? TFrom : never;\n}>[number];\n\n/**\n * Infers the TypeScript type for values that can be decoded using a union codec.\n *\n * This type maps the provided variant decoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n */\ntype GetDecoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Decoder ? TFrom : never;\n}>[number];\n\ntype UnionEncoder[]> = TVariants extends readonly FixedSizeEncoder[]\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder[]> = TVariants extends readonly FixedSizeDecoder[]\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec[]> = TVariants extends readonly FixedSizeCodec[]\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for union types.\n *\n * This encoder serializes values by selecting the correct variant encoder\n * based on the `getIndexFromValue` function.\n *\n * Unlike other codecs, this encoder does not store the variant index.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n *\n * @param variants - The encoders for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @returns An `Encoder` for encoding union values.\n *\n * @example\n * Encoding a union of numbers and booleans.\n * ```ts\n * const encoder = getUnionEncoder(\n * [getU16Encoder(), getBooleanEncoder()],\n * value => (typeof value === 'number' ? 0 : 1)\n * );\n *\n * encoder.encode(42);\n * // 0x2a00\n * // └── Encoded number (42) as `u16`\n *\n * encoder.encode(true);\n * // 0x01\n * // └── Encoded boolean (`true`) as `u8`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionEncoder[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const write: Encoder['write'] = (variant, bytes, offset) => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return variants[index].write(variant, bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createEncoder({ fixedSize, write }) as UnionEncoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createEncoder({\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: variant => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return getEncodedSize(variant, variants[index]);\n },\n write,\n }) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for union types.\n *\n * This decoder deserializes values by selecting the correct variant decoder\n * based on the `getIndexFromBytes` function.\n *\n * Unlike other codecs, this decoder does not assume a stored discriminator.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n *\n * @param variants - The decoders for each variant of the union.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Decoder` for decoding union values.\n *\n * @example\n * Decoding a union of numbers and booleans.\n * ```ts\n * const decoder = getUnionDecoder(\n * [getU16Decoder(), getBooleanDecoder()],\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * decoder.decode(new Uint8Array([0x01])); // true\n * // Type is inferred as `number | boolean`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionDecoder[]>(\n variants: TVariants,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionDecoder {\n type TTo = GetDecoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const read: Decoder['read'] = (bytes, offset) => {\n const index = getIndexFromBytes(bytes, offset);\n assertValidVariantIndex(variants, index);\n return variants[index].read(bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createDecoder({ fixedSize, read }) as UnionDecoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createDecoder({ ...(maxSize !== null ? { maxSize } : {}), read }) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding union types.\n *\n * This codec serializes and deserializes union values by selecting the correct variant\n * based on the provided index functions.\n *\n * Unlike the {@link getDiscriminatedUnionCodec}, this codec does not assume a stored\n * discriminator and must be used with an explicit mechanism for managing discriminators.\n *\n * @typeParam TVariants - An array of codecs, each corresponding to a union variant.\n *\n * @param variants - The codecs for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Codec` for encoding and decoding union values.\n *\n * @example\n * Encoding and decoding a union of numbers and booleans.\n * ```ts\n * const codec = getUnionCodec(\n * [getU16Codec(), getBooleanCodec()],\n * value => (typeof value === 'number' ? 0 : 1),\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * const bytes1 = codec.encode(42); // 0x2a00\n * const value1: number | boolean = codec.decode(bytes1); // 42\n *\n * const bytes2 = codec.encode(true); // 0x01\n * const value2: number | boolean = codec.decode(bytes2); // true\n * ```\n *\n * @remarks\n * If you need a codec that includes a stored discriminator,\n * consider using {@link getDiscriminatedUnionCodec}.\n *\n * Separate {@link getUnionEncoder} and {@link getUnionDecoder} functions are also available.\n *\n * ```ts\n * const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42);\n * const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes);\n * ```\n *\n * @see {@link getUnionEncoder}\n * @see {@link getUnionDecoder}\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getUnionCodec[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionCodec {\n return combineCodec(\n getUnionEncoder(variants, getIndexFromValue),\n getUnionDecoder(variants as readonly Decoder[], getIndexFromBytes) as Decoder<\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction assertValidVariantIndex(variants: readonly unknown[], index: number) {\n if (typeof variants[index] === 'undefined') {\n throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {\n maxRange: variants.length - 1,\n minRange: 0,\n variant: index,\n });\n }\n}\n\nfunction getUnionFixedSize | Encoder)[]>(variants: TVariants) {\n if (variants.length === 0) return 0;\n if (!isFixedSize(variants[0])) return null;\n const variantSize = variants[0].fixedSize;\n const sameSizedVariants = variants.every(variant => isFixedSize(variant) && variant.fixedSize === variantSize);\n return sameSizedVariants ? variantSize : null;\n}\n\nfunction getUnionMaxSize | Encoder)[]>(variants: TVariants) {\n return maxCodecSizes(variants.map(variant => getMaxSize(variant)));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SolanaError } from '@solana/errors';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { DrainOuterGeneric } from './utils';\n\n/**\n * Represents a discriminated union using a specific discriminator property.\n *\n * A discriminated union is a TypeScript-friendly way to represent Rust-like enums.\n * Each variant in the union is distinguished by a shared discriminator property.\n *\n * @typeParam TDiscriminatorProperty - The name of the discriminator property.\n * @typeParam TDiscriminatorValue - The type of the discriminator value.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant\n * | { __kind: 'Write'; fields: [string] } // Tuple variant\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant\n * ```\n */\nexport type DiscriminatedUnion<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorValue extends string = string,\n> = {\n [P in TDiscriminatorProperty]: TDiscriminatorValue;\n};\n\n/**\n * Extracts a variant from a discriminated union based on its discriminator value.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type ClickEvent = GetDiscriminatedUnionVariant;\n * // -> { __kind: 'Move'; x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariant<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Extract>;\n\n/**\n * Extracts a variant from a discriminated union without its discriminator property.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type MoveContent = GetDiscriminatedUnionVariantContent;\n * // -> { x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariantContent<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Omit, TDiscriminatorProperty>;\n\n/**\n * Defines the configuration for discriminated union codecs.\n *\n * This configuration controls how the discriminator is stored and named.\n *\n * @typeParam TDiscriminatorProperty - The property name of the discriminator.\n * @typeParam TDiscriminatorSize - The codec used for the discriminator prefix.\n */\nexport type DiscriminatedUnionCodecConfig<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorSize = NumberCodec | NumberDecoder | NumberEncoder,\n> = {\n /**\n * The property name of the discriminator.\n * @defaultValue `__kind`\n */\n discriminator?: TDiscriminatorProperty;\n /**\n * The codec used to encode/decode the discriminator prefix.\n * @defaultValue `u8` prefix\n */\n size?: TDiscriminatorSize;\n};\n\ntype DiscriminatorValue = bigint | boolean | number | string | null | undefined;\ntype Variants = readonly (readonly [DiscriminatorValue, T])[];\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\ntype GetEncoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Encoder\n ? TFrom extends object\n ? TFrom\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype GetDecoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Decoder\n ? TTo extends object\n ? TTo\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype UnionEncoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for discriminated unions.\n *\n * This encoder serializes objects that follow the discriminated union pattern\n * by prefixing them with a numerical discriminator that represents their variant.\n *\n * Unlike {@link getUnionEncoder}, this encoder automatically extracts and processes\n * the discriminator property (default: `__kind`) from each variant.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant encoders as `[discriminator, encoder]` pairs.\n * @param config - Configuration options for encoding.\n * @returns An `Encoder` for encoding discriminated union objects.\n *\n * @example\n * Encoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageEncoder = getDiscriminatedUnionEncoder([\n * ['Quit', getUnitEncoder()],\n * ['Write', getStructEncoder([['fields', getTupleEncoder([addCodecSizePrefix(getUtf8Encoder(), getU32Encoder())])]])],\n * ['Move', getStructEncoder([['x', getI32Encoder()], ['y', getI32Encoder()]])]\n * ]);\n *\n * messageEncoder.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionEncoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const discriminatorProperty = (config.discriminator ?? '__kind') as TDiscriminatorProperty;\n const prefix = config.size ?? getU8Encoder();\n return getUnionEncoder(\n variants.map(([, variant], index) =>\n transformEncoder(getTupleEncoder([prefix, variant]), (value: TFrom): [number, TFrom] => [index, value]),\n ),\n value => getVariantDiscriminator(variants, value[discriminatorProperty]),\n ) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for discriminated unions.\n *\n * This decoder deserializes objects that follow the discriminated union pattern\n * by **reading a numerical discriminator** and mapping it to the corresponding variant.\n *\n * Unlike {@link getUnionDecoder}, this decoder automatically inserts the discriminator\n * property (default: `__kind`) into the decoded object.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant decoders as `[discriminator, decoder]` pairs.\n * @param config - Configuration options for decoding.\n * @returns A `Decoder` for decoding discriminated union objects.\n *\n * @example\n * Decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageDecoder = getDiscriminatedUnionDecoder([\n * ['Quit', getUnitDecoder()],\n * ['Write', getStructDecoder([['fields', getTupleDecoder([addCodecSizePrefix(getUtf8Decoder(), getU32Decoder())])]])],\n * ['Move', getStructDecoder([['x', getI32Decoder()], ['y', getI32Decoder()]])]\n * ]);\n *\n * messageDecoder.decode(new Uint8Array([0x02,0x05,0x00,0x00,0x00,0x06,0x00,0x00,0x00]));\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionDecoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionDecoder {\n const discriminatorProperty = config.discriminator ?? '__kind';\n const prefix = config.size ?? getU8Decoder();\n return getUnionDecoder(\n variants.map(([discriminator, variant]) =>\n transformDecoder(getTupleDecoder([prefix, variant]), ([, value]) => ({\n [discriminatorProperty]: discriminator,\n ...value,\n })),\n ),\n (bytes, offset) => Number(prefix.read(bytes, offset)[0]),\n ) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding {@link DiscriminatedUnion}.\n *\n * A {@link DiscriminatedUnion} is a TypeScript representation of Rust-like enums, where\n * each variant is distinguished by a discriminator field (default: `__kind`).\n *\n * This codec inserts a numerical prefix to represent the variant index.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant codecs as `[discriminator, codec]` pairs.\n * @param config - Configuration options for encoding/decoding.\n * @returns A `Codec` for encoding and decoding discriminated union objects.\n *\n * @example\n * Encoding and decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Quit', getUnitCodec()],\n * ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],\n * ['Move', getStructCodec([['x', getI32Codec()], ['y', getI32Codec()]])]\n * ]);\n *\n * messageCodec.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n *\n * const value = messageCodec.decode(bytes);\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @example\n * Using a `u32` discriminator instead of `u8`.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { size: getU32Codec() });\n *\n * codec.encode({ __kind: 'Quit' });\n * // 0x00000000\n * // └------┘ 4-byte discriminator (Index 0)\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00]));\n * // { __kind: 'Quit' }\n * ```\n *\n * @example\n * Customizing the discriminator property.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { discriminator: 'message' });\n *\n * codec.encode({ message: 'Quit' }); // 0x00\n * codec.decode(new Uint8Array([0x00])); // { message: 'Quit' }\n * ```\n *\n * @remarks\n * Separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available.\n *\n * ```ts\n * const bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' });\n * const message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes);\n * ```\n *\n * @see {@link getDiscriminatedUnionEncoder}\n * @see {@link getDiscriminatedUnionDecoder}\n */\nexport function getDiscriminatedUnionCodec<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionCodec {\n return combineCodec(\n getDiscriminatedUnionEncoder(variants, config) as Encoder<\n GetEncoderTypeFromVariants\n >,\n getDiscriminatedUnionDecoder(variants, config) as Decoder<\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction getVariantDiscriminator | Encoder>>(\n variants: TVariants,\n discriminatorValue: DiscriminatorValue,\n) {\n const discriminator = variants.findIndex(([key]) => discriminatorValue === key);\n if (discriminator < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, {\n value: discriminatorValue,\n variants: variants.map(([key]) => key),\n });\n }\n return discriminator;\n}\n","/**\n * Defines the \"lookup object\" of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * ```\n */\nexport type EnumLookupObject = { [key: string]: number | string };\n\n/**\n * Returns the allowed input for an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionInput = GetEnumFrom; // \"Left\" | \"Right\" | 0 | 1\n * ```\n */\nexport type GetEnumFrom = TEnum[keyof TEnum] | keyof TEnum;\n\n/**\n * Returns all the available variants of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionOutput = GetEnumTo; // 0 | 1\n * ```\n */\nexport type GetEnumTo = TEnum[keyof TEnum];\n\nexport function getEnumStats(constructor: EnumLookupObject) {\n const numericalValues = [...new Set(Object.values(constructor).filter(v => typeof v === 'number'))].sort();\n const enumRecord = Object.fromEntries(Object.entries(constructor).slice(numericalValues.length)) as Record<\n string,\n number | string\n >;\n const enumKeys = Object.keys(enumRecord);\n const enumValues = Object.values(enumRecord);\n const stringValues: string[] = [\n ...new Set([...enumKeys, ...enumValues.filter((v): v is string => typeof v === 'string')]),\n ];\n\n return { enumKeys, enumRecord, enumValues, numericalValues, stringValues };\n}\n\nexport function getEnumIndexFromVariant({\n enumKeys,\n enumValues,\n variant,\n}: {\n enumKeys: string[];\n enumValues: (number | string)[];\n variant: number | string | symbol;\n}): number {\n const valueIndex = findLastIndex(enumValues, value => value === variant);\n if (valueIndex >= 0) return valueIndex;\n return enumKeys.findIndex(key => key === variant);\n}\n\nexport function getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n}: {\n discriminator: number;\n enumKeys: string[];\n enumValues: (number | string)[];\n useValuesAsDiscriminators: boolean;\n}): number {\n if (!useValuesAsDiscriminators) {\n return discriminator >= 0 && discriminator < enumKeys.length ? discriminator : -1;\n }\n return findLastIndex(enumValues, value => value === discriminator);\n}\n\nfunction findLastIndex(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): number {\n let l = array.length;\n while (l--) {\n if (predicate(array[l], l, array)) return l;\n }\n return -1;\n}\n\nexport function formatNumericalValues(values: number[]): string {\n if (values.length === 0) return '';\n let range: [number, number] = [values[0], values[0]];\n const ranges: string[] = [];\n for (let index = 1; index < values.length; index++) {\n const value = values[index];\n if (range[1] + 1 === value) {\n range[1] = value;\n } else {\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n range = [value, value];\n }\n }\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n return ranges.join(', ');\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n EnumLookupObject,\n formatNumericalValues,\n GetEnumFrom,\n getEnumIndexFromDiscriminator,\n getEnumIndexFromVariant,\n getEnumStats,\n GetEnumTo,\n} from './enum-helpers';\n\n/**\n * Defines the configuration options for enum codecs.\n *\n * The `size` option determines the numerical encoding used for the enum's discriminant.\n * By default, enums are stored as a `u8` (1 byte).\n *\n * The `useValuesAsDiscriminators` option allows mapping the actual enum values\n * as discriminators instead of using their positional index.\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type EnumCodecConfig = {\n /**\n * The codec used to encode/decode the enum discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n\n /**\n * If set to `true`, the enum values themselves will be used as discriminators.\n * This is only valid for numerical enum values.\n *\n * @defaultValue `false`\n */\n useValuesAsDiscriminators?: boolean;\n};\n\n/**\n * Returns an encoder for enums.\n *\n * This encoder serializes enums as a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding the enum.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums.\n *\n * @example\n * Encoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const encoder = getEnumEncoder(Direction);\n *\n * encoder.encode(Direction.Up); // 0x00\n * encoder.encode(Direction.Down); // 0x01\n * encoder.encode(Direction.Left); // 0x02\n * encoder.encode(Direction.Right); // 0x03\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeEncoder, 1>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeEncoder>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Encoder> {\n const prefix = config.size ?? getU8Encoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues, stringValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformEncoder(prefix, (variant: GetEnumFrom): number => {\n const index = getEnumIndexFromVariant({ enumKeys, enumValues, variant });\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, {\n formattedNumericalValues: formatNumericalValues(numericalValues),\n numericalValues,\n stringValues,\n variant,\n });\n }\n return useValuesAsDiscriminators ? (enumValues[index] as number) : index;\n });\n}\n\n/**\n * Returns a decoder for enums.\n *\n * This decoder deserializes enums from a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for decoding the enum.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums.\n *\n * @example\n * Decoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const decoder = getEnumDecoder(Direction);\n *\n * decoder.decode(new Uint8Array([0x00])); // Direction.Up\n * decoder.decode(new Uint8Array([0x01])); // Direction.Down\n * decoder.decode(new Uint8Array([0x02])); // Direction.Left\n * decoder.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeDecoder, 1>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeDecoder>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Decoder> {\n const prefix = config.size ?? getU8Decoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformDecoder(prefix, (value: bigint | number): GetEnumTo => {\n const discriminator = Number(value);\n const index = getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n });\n if (index < 0) {\n const validDiscriminators = useValuesAsDiscriminators\n ? numericalValues\n : [...Array(enumKeys.length).keys()];\n throw new SolanaError(SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator,\n formattedValidDiscriminators: formatNumericalValues(validDiscriminators),\n validDiscriminators,\n });\n }\n return enumValues[index] as GetEnumTo;\n });\n}\n\n/**\n * Returns a codec for encoding and decoding enums.\n *\n * This codec serializes enums as a numerical discriminator, allowing them\n * to be efficiently stored and reconstructed from binary data.\n *\n * By default, the discriminator is derived from the positional index\n * of the enum variant, but it can be configured to use the enum's numeric values instead.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding and decoding the enum.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums.\n *\n * @example\n * Encoding and decoding enums using positional indexes.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const codec = getEnumCodec(Direction);\n *\n * codec.encode(Direction.Up); // 0x00\n * codec.encode(Direction.Down); // 0x01\n * codec.encode(Direction.Left); // 0x02\n * codec.encode(Direction.Right); // 0x03\n *\n * codec.decode(new Uint8Array([0x00])); // Direction.Up\n * codec.decode(new Uint8Array([0x01])); // Direction.Down\n * codec.decode(new Uint8Array([0x02])); // Direction.Left\n * codec.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @example\n * Encoding and decoding enums using their numeric values.\n * ```ts\n * enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 }\n * const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true });\n *\n * codec.encode(GameDifficulty.Easy); // 0x01\n * codec.encode(GameDifficulty.Normal); // 0x04\n * codec.encode(GameDifficulty.Hard); // 0x07\n * codec.encode(GameDifficulty.Expert); // 0x09\n *\n * codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy\n * codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal\n * codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard\n * codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert\n * ```\n *\n * Note that, when using values as discriminators, the enum values must be numerical.\n * Otherwise, an error will be thrown.\n *\n * ```ts\n * enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' }\n * getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error.\n * ```\n *\n * @example\n * Using a custom discriminator size.\n * ```ts\n * enum Status { Pending, Approved, Rejected }\n * const codec = getEnumCodec(Status, { size: getU16Codec() });\n *\n * codec.encode(Status.Pending); // 0x0000\n * codec.encode(Status.Approved); // 0x0100\n * codec.encode(Status.Rejected); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending\n * codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved\n * codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected\n * ```\n *\n * @remarks\n * Separate {@link getEnumEncoder} and {@link getEnumDecoder} functions are available.\n *\n * ```ts\n * const bytes = getEnumEncoder(Direction).encode(Direction.Up);\n * const value = getEnumDecoder(Direction).decode(bytes);\n * ```\n *\n * @see {@link getEnumEncoder}\n * @see {@link getEnumDecoder}\n */\nexport function getEnumCodec(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeCodec, GetEnumTo, 1>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetEnumTo, TSize>;\nexport function getEnumCodec(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeCodec, GetEnumTo>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Codec, GetEnumTo> {\n return combineCodec(getEnumEncoder(constructor, config), getEnumDecoder(constructor, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that prefixes encoded values with hidden data.\n *\n * This encoder applies a list of void encoders before encoding the main value.\n * The prefixed data is encoded before the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param prefixedEncoders - A list of void encoders that produce the hidden prefix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden prefix.\n *\n * @example\n * Prefixing a value with constants.\n * ```ts\n * const encoder = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixEncoder(\n encoder: FixedSizeEncoder,\n prefixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([...prefixedEncoders, encoder]) as Encoder,\n (value: TFrom) => [...prefixedEncoders.map(() => undefined), value] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden prefixed data before decoding the main value.\n *\n * This decoder applies a list of void decoders before decoding the main value.\n * The prefixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param prefixedDecoders - A list of void decoders that produce the hidden prefix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden prefix.\n *\n * @example\n * Decoding a value with prefixed constants.\n * ```ts\n * const decoder = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 0x48, 0x65, 0x6C, 0x6C, 0x6F]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixDecoder(\n decoder: FixedSizeDecoder,\n prefixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([...prefixedDecoders, decoder]) as Decoder,\n tuple => tuple[tuple.length - 1] as TTo,\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden prefix.\n *\n * - **Encoding:** Prefixes the value with hidden data before encoding.\n * - **Decoding:** Skips the hidden prefix before decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param prefixedCodecs - A list of void codecs that produce the hidden prefix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden prefix.\n *\n * @example\n * Encoding and decoding a value with prefixed constants.\n * ```ts\n * const codec = getHiddenPrefixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes before a value, consider using {@link padLeftCodec} instead.\n *\n * Separate {@link getHiddenPrefixEncoder} and {@link getHiddenPrefixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenPrefixEncoder}\n * @see {@link getHiddenPrefixDecoder}\n */\nexport function getHiddenPrefixCodec(\n codec: FixedSizeCodec,\n prefixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenPrefixEncoder(codec, prefixedCodecs), getHiddenPrefixDecoder(codec, prefixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that appends hidden data after the encoded value.\n *\n * This encoder applies a list of void encoders after encoding the main value.\n * The suffixed data is encoded after the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param suffixedEncoders - A list of void encoders that produce the hidden suffix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden suffix.\n *\n * @example\n * Suffixing a value with constants.\n * ```ts\n * const encoder = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixEncoder(\n encoder: FixedSizeEncoder,\n suffixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([encoder, ...suffixedEncoders]) as Encoder,\n (value: TFrom) => [value, ...suffixedEncoders.map(() => undefined)] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden suffixed data after decoding the main value.\n *\n * This decoder applies a list of void decoders after decoding the main value.\n * The suffixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param suffixedDecoders - A list of void decoders that produce the hidden suffix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden suffix.\n *\n * @example\n * Decoding a value with suffixed constants.\n * ```ts\n * const decoder = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F, 1, 2, 3, 4, 5, 6]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixDecoder(\n decoder: FixedSizeDecoder,\n suffixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([decoder, ...suffixedDecoders]) as Decoder,\n tuple => tuple[0],\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden suffix.\n *\n * - **Encoding:** Appends hidden data after encoding the main value.\n * - **Decoding:** Skips the hidden suffix after decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param suffixedCodecs - A list of void codecs that produce the hidden suffix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden suffix.\n *\n * @example\n * Encoding and decoding a value with suffixed constants.\n * ```ts\n * const codec = getHiddenSuffixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes after a value, consider using {@link padRightCodec} instead.\n *\n * Separate {@link getHiddenSuffixEncoder} and {@link getHiddenSuffixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenSuffixEncoder}\n * @see {@link getHiddenSuffixDecoder}\n */\nexport function getHiddenSuffixCodec(\n codec: FixedSizeCodec,\n suffixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenSuffixEncoder(codec, suffixedCodecs), getHiddenSuffixDecoder(codec, suffixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\n/**\n * Defines the configuration options for literal union codecs.\n *\n * A literal union codec encodes values from a predefined set of literals.\n * The `size` option determines the numerical encoding used for the discriminant.\n * By default, literals are stored as a `u8` (1 byte).\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type LiteralUnionCodecConfig = {\n /**\n * The codec used to encode/decode the discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n};\n\ntype Variant = bigint | boolean | number | string | null | undefined;\ntype GetTypeFromVariants = TVariants[number];\n\n/**\n * Returns an encoder for literal unions.\n *\n * This encoder serializes a value from a predefined set of literals\n * as a numerical index representing its position in the `variants` array.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding the literal union.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions.\n *\n * @example\n * Encoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']);\n *\n * sizeEncoder.encode('small'); // 0x00\n * sizeEncoder.encode('medium'); // 0x01\n * sizeEncoder.encode('large'); // 0x02\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n): FixedSizeEncoder, 1>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeEncoder>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Encoder> {\n const discriminator = config.size ?? getU8Encoder();\n return transformEncoder(discriminator, variant => {\n const index = variants.indexOf(variant);\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, {\n value: variant,\n variants,\n });\n }\n return index;\n });\n}\n\n/**\n * Returns a decoder for literal unions.\n *\n * This decoder deserializes a numerical index into a corresponding\n * value from a predefined set of literals.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for decoding the literal union.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions.\n *\n * @example\n * Decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']);\n *\n * sizeDecoder.decode(new Uint8Array([0x00])); // 'small'\n * sizeDecoder.decode(new Uint8Array([0x01])); // 'medium'\n * sizeDecoder.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n): FixedSizeDecoder, 1>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeDecoder>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Decoder> {\n const discriminator = config.size ?? getU8Decoder();\n return transformDecoder(discriminator, (index: bigint | number) => {\n if (index < 0 || index >= variants.length) {\n throw new SolanaError(SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator: index,\n maxRange: variants.length - 1,\n minRange: 0,\n });\n }\n return variants[Number(index)];\n });\n}\n\n/**\n * Returns a codec for encoding and decoding literal unions.\n *\n * A literal union codec serializes and deserializes values\n * from a predefined set of literals, using a numerical index\n * to represent each value in the `variants` array.\n *\n * This allows efficient storage and retrieval of common\n * predefined values such as enum-like structures in TypeScript.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding and decoding the literal union.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions.\n *\n * @example\n * Encoding and decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']);\n *\n * sizeCodec.encode('small'); // 0x00\n * sizeCodec.encode('medium'); // 0x01\n * sizeCodec.encode('large'); // 0x02\n *\n * sizeCodec.decode(new Uint8Array([0x00])); // 'small'\n * sizeCodec.decode(new Uint8Array([0x01])); // 'medium'\n * sizeCodec.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @example\n * Encoding and decoding a union of number literals.\n * ```ts\n * type Level = 10 | 20 | 30;\n * const levelCodec = getLiteralUnionCodec([10, 20, 30]);\n *\n * levelCodec.encode(10); // 0x00\n * levelCodec.encode(20); // 0x01\n * levelCodec.encode(30); // 0x02\n *\n * levelCodec.decode(new Uint8Array([0x00])); // 10\n * levelCodec.decode(new Uint8Array([0x01])); // 20\n * levelCodec.decode(new Uint8Array([0x02])); // 30\n * ```\n *\n * @example\n * Using a custom discriminator size with different variant types.\n * ```ts\n * type MaybeBoolean = false | true | \"either\";\n * const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n * codec.encode('either'); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * codec.decode(new Uint8Array([0x02, 0x00])); // 'either'\n * ```\n *\n * @remarks\n * Separate {@link getLiteralUnionEncoder} and {@link getLiteralUnionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green');\n * const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes);\n * ```\n *\n * @see {@link getLiteralUnionEncoder}\n * @see {@link getLiteralUnionDecoder}\n */\nexport function getLiteralUnionCodec(\n variants: TVariants,\n): FixedSizeCodec, GetTypeFromVariants, 1>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetTypeFromVariants, TSize>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeCodec>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Codec> {\n return combineCodec(getLiteralUnionEncoder(variants, config), getLiteralUnionDecoder(variants, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Defines the configuration options for map codecs.\n *\n * The `size` option determines how the number of entries in the map is stored.\n * It can be:\n * - A {@link NumberCodec} to prefix the map with its size.\n * - A fixed number of entries.\n * - `'remainder'`, which infers the number of entries based on the remaining bytes.\n * This option is only available for fixed-size keys and values.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used for the size prefix.\n */\nexport type MapCodecConfig = {\n /**\n * The size of the map.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for maps.\n *\n * This encoder serializes maps where the keys and values are encoded\n * using the provided key and value encoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n *\n * @param key - The encoder for the map's keys.\n * @param value - The encoder for the map's values.\n * @param config - Configuration options for encoding the map.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps.\n *\n * @example\n * Encoding a map with a `u32` size prefix.\n * ```ts\n * const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder());\n * const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getMapEncoder(\n key: FixedSizeEncoder,\n value: FixedSizeEncoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config?: MapCodecConfig,\n): VariableSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig = {},\n): Encoder> {\n return transformEncoder(\n getArrayEncoder(getTupleEncoder([key, value]), config as object),\n (map: Map): [TFromKey, TFromValue][] => [...map.entries()],\n );\n}\n\n/**\n * Returns a decoder for maps.\n *\n * This decoder deserializes maps where the keys and values are decoded\n * using the provided key and value decoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The decoder for the map's keys.\n * @param value - The decoder for the map's values.\n * @param config - Configuration options for decoding the map.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps.\n *\n * @example\n * Decoding a map with a `u32` size prefix.\n * ```ts\n * const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder());\n * const map = decoder.decode(new Uint8Array([\n * 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05\n * ]));\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getMapDecoder(\n key: FixedSizeDecoder,\n value: FixedSizeDecoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config?: MapCodecConfig,\n): VariableSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig = {},\n): Decoder> {\n return transformDecoder(\n getArrayDecoder(getTupleDecoder([key, value]), config as object) as Decoder<[TToKey, TToValue][]>,\n (entries: [TToKey, TToValue][]): Map => new Map(entries),\n );\n}\n\n/**\n * Returns a codec for encoding and decoding maps.\n *\n * This codec serializes maps where the key/value pairs are encoded\n * and decoded one after another using the provided key and value codecs.\n * The number of entries is determined by the `size` configuration and\n * defaults to a `u32` size prefix.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The codec for the map's keys.\n * @param value - The codec for the map's values.\n * @param config - Configuration options for encoding and decoding the map.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps.\n *\n * @example\n * Encoding and decoding a map with a `u32` size prefix (default).\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec());\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with a `u16` size prefix.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x0200616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 2-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a fixed-size map.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with remainder size.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n * // No size prefix, the size is inferred from the remaining bytes.\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @remarks\n * Separate {@link getMapEncoder} and {@link getMapDecoder} functions are available.\n * ```ts\n * const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]]));\n * const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getMapEncoder}\n * @see {@link getMapDecoder}\n */\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeCodec, Map, 0>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: FixedSizeCodec,\n value: FixedSizeCodec,\n config: MapCodecConfig & { size: number },\n): FixedSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config?: MapCodecConfig,\n): VariableSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig = {},\n): Codec, Map> {\n return combineCodec(getMapEncoder(key, value, config as object), getMapDecoder(key, value, config as object));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for `void` values.\n *\n * This encoder writes nothing to the byte array and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op encoder,\n * such as empty variants in {@link getDiscriminatedUnionEncoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeEncoder`, representing an empty encoder.\n *\n * @example\n * Encoding a `void` value.\n * ```ts\n * getUnitEncoder().encode(undefined); // Produces an empty byte array.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitEncoder(): FixedSizeEncoder {\n return createEncoder({\n fixedSize: 0,\n write: (_value, _bytes, offset) => offset,\n });\n}\n\n/**\n * Returns a decoder for `void` values.\n *\n * This decoder always returns `undefined` and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op decoder,\n * such as empty variants in {@link getDiscriminatedUnionDecoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeDecoder`, representing an empty decoder.\n *\n * @example\n * Decoding a `void` value.\n * ```ts\n * getUnitDecoder().decode(anyBytes); // Returns `undefined`.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitDecoder(): FixedSizeDecoder {\n return createDecoder({\n fixedSize: 0,\n read: (_bytes: ReadonlyUint8Array | Uint8Array, offset) => [undefined, offset],\n });\n}\n\n/**\n * Returns a codec for `void` values.\n *\n * This codec does nothing when encoding or decoding and has a fixed size of 0 bytes.\n * Namely, it always returns `undefined` when decoding and produces an empty byte array when encoding.\n *\n * This can be useful when working with structures that require a no-op codec,\n * such as empty variants in {@link getDiscriminatedUnionCodec}.\n *\n * @returns A `FixedSizeCodec`, representing an empty codec.\n *\n * @example\n * Encoding and decoding a `void` value.\n * ```ts\n * const codec = getUnitCodec();\n *\n * codec.encode(undefined); // Produces an empty byte array.\n * codec.decode(new Uint8Array([])); // Returns `undefined`.\n * ```\n *\n * @example\n * Using unit codecs as empty variants in a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Enter' }\n * | { __kind: 'Leave' }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Enter', getUnitCodec()], // <- No-op codec for empty data\n * ['Leave', getUnitCodec()], // <- No-op codec for empty data\n * ['Move', getStructCodec([...])]\n * ]);\n * ```\n *\n * @remarks\n * Separate {@link getUnitEncoder} and {@link getUnitDecoder} functions are available.\n *\n * ```ts\n * const bytes = getUnitEncoder().encode();\n * const value = getUnitDecoder().decode(bytes);\n * ```\n *\n * @see {@link getUnitEncoder}\n * @see {@link getUnitDecoder}\n */\nexport function getUnitCodec(): FixedSizeCodec {\n return combineCodec(getUnitEncoder(), getUnitDecoder());\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getBooleanDecoder, getBooleanEncoder } from './boolean';\nimport { getConstantDecoder, getConstantEncoder } from './constant';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { getUnitDecoder, getUnitEncoder } from './unit';\n\n/**\n * Defines the configuration options for nullable codecs.\n *\n * This configuration controls how nullable values are encoded and decoded.\n *\n * By default, nullable values are prefixed with a `u8` (0 = `null`, 1 = present).\n * The `noneValue` and `prefix` options allow customizing this behavior.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n * @see {@link getNullableCodec}\n */\nexport type NullableCodecConfig = {\n /**\n * Specifies how `null` values are represented in the encoded data.\n *\n * - By default, `null` values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec.\n * - Custom byte array: `null` values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; `null` values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between `null` and present values.\n *\n * - By default, a `u8` prefix is used (`0 = null`, `1 = present`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines `null`.\n * If no `noneValue` is set, `null` is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values, allowing `null` values to be encoded.\n *\n * This encoder serializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are replaced with the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values.\n *\n * @example\n * Encoding an optional number.\n * ```ts\n * const encoder = getNullableEncoder(getU32Encoder());\n *\n * encoder.encode(null); // 0x00\n * encoder.encode(42); // 0x012a000000\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config: NullableCodecConfig = {},\n): Encoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: TFrom): [boolean, TFrom] => [true, value]),\n ],\n variant => Number(variant !== null),\n );\n}\n\n/**\n * Returns a decoder for optional values, allowing `null` values to be recognized.\n *\n * This decoder deserializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes.\n * - If `noneValue` is a byte array, `null` values match the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values.\n *\n * @example\n * Decoding an optional number.\n * ```ts\n * const decoder = getNullableDecoder(getU32Decoder());\n *\n * decoder.decode(new Uint8Array([0x00])); // null\n * decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config: NullableCodecConfig = {},\n): Decoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => null),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]): TTo => value),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values, allowing `null` values to be handled.\n *\n * This codec serializes and deserializes optional values using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present).\n * This can be customized using a custom number codec or even disabled by setting\n * the `prefix` to `null`.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are represented by the provided constant.\n *\n * For more details on the configuration options, see {@link NullableCodecConfig}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding optional values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values.\n *\n * @example\n * Encoding and decoding an optional number using a `u8` prefix (default).\n * ```ts\n * const codec = getNullableCodec(getU32Codec());\n *\n * codec.encode(null); // 0x00\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' });\n *\n * codec.encode(null); // 0x0000000000\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with zeroes and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), {\n * noneValue: 'zeroes',\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0x00000000\n * codec.encode(42); // 0x2a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0xffff\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([0xff, 0xff])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @example\n * Identifying `null` values by the absence of bytes.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), { prefix: null });\n *\n * codec.encode(null); // Empty bytes\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @remarks\n * Separate {@link getNullableEncoder} and {@link getNullableDecoder} functions are available.\n *\n * ```ts\n * const bytes = getNullableEncoder(getU32Encoder()).encode(42);\n * const value = getNullableDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n */\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config: NullableCodecConfig = {},\n): Codec {\n type ConfigCast = NullableCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getNullableEncoder(item, config as ConfigCast),\n getNullableDecoder(item, config as ConfigCast),\n );\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\n\n/**\n * Defines the configuration options for set codecs.\n *\n * This configuration allows specifying how the size of the set is encoded.\n * The `size` option can be:\n *\n * - A {@link NumberCodec}, {@link NumberEncoder}, or {@link NumberDecoder} to store the size as a prefix.\n * - A fixed number of items, enforcing a strict length.\n * - The string `'remainder'` to infer the set size from the remaining bytes (only for fixed-size items).\n *\n * @typeParam TPrefix - The type used for encoding the size of the set.\n */\nexport type SetCodecConfig = {\n /**\n * The size encoding strategy for the set.\n * @defaultValue Uses a `u32` prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for sets of items.\n *\n * This encoder serializes `Set` values by encoding each item using the provided item encoder.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n *\n * @param item - The encoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns An `Encoder>` for encoding sets of items.\n *\n * @example\n * Encoding a set of `u8` numbers.\n * ```ts\n * const encoder = getSetEncoder(getU8Encoder());\n * const bytes = encoder.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getSetEncoder(\n item: FixedSizeEncoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config?: SetCodecConfig,\n): VariableSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig = {},\n): Encoder> {\n return transformEncoder(getArrayEncoder(item, config as object), (set: Set): TFrom[] => [...set]);\n}\n\n/**\n * Returns a decoder for sets of items.\n *\n * This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder.\n * The number of items is determined by a `u32` size prefix by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The decoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Decoder>` for decoding sets of items.\n *\n * @example\n * Decoding a set of `u8` numbers.\n * ```ts\n * const decoder = getSetDecoder(getU8Decoder());\n * const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // new Set([1, 2, 3])\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetDecoder(\n item: Decoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getSetDecoder(\n item: FixedSizeDecoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getSetDecoder(\n item: Decoder,\n config?: SetCodecConfig,\n): VariableSizeDecoder>;\nexport function getSetDecoder(item: Decoder, config: SetCodecConfig = {}): Decoder> {\n return transformDecoder(getArrayDecoder(item, config as object), (entries: TTo[]): Set => new Set(entries));\n}\n\n/**\n * Returns a codec for encoding and decoding sets of items.\n *\n * This codec serializes `Set` values by encoding each item using the provided item codec.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The codec to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Codec, Set>` for encoding and decoding sets.\n *\n * @example\n * Encoding and decoding a set of `u8` numbers.\n * ```ts\n * const codec = getSetCodec(getU8Codec());\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n *\n * const value = codec.decode(bytes);\n * // new Set([1, 2, 3])\n * ```\n *\n * @example\n * Using a `u16` prefix for size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix indicating 3 items.\n * ```\n *\n * @example\n * Using a fixed-size set.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 3 });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- Exactly 3 items of 1 byte each.\n * ```\n *\n * @example\n * Using remainder to infer set size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remaining bytes.\n * ```\n *\n * @remarks\n * Separate {@link getSetEncoder} and {@link getSetDecoder} functions are available.\n *\n * ```ts\n * const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3]));\n * const value = getSetDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getSetEncoder}\n * @see {@link getSetDecoder}\n */\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeCodec, Set, 0>;\nexport function getSetCodec(\n item: FixedSizeCodec,\n config: SetCodecConfig & { size: number },\n): FixedSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config?: SetCodecConfig,\n): VariableSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig = {},\n): Codec, Set> {\n return combineCodec(getSetEncoder(item, config as object), getSetDecoder(item, config as object));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Represents a collection of named fields used in struct codecs.\n *\n * Each field is defined as a tuple containing:\n * - A string key representing the field name.\n * - A codec used to encode and decode the field's value.\n *\n * @typeParam T - The codec type used for each field.\n */\ntype Fields = readonly (readonly [string, T])[];\n\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\n/**\n * Infers the TypeScript type for an object that can be encoded using a struct codec.\n *\n * This type maps the provided field encoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n */\ntype GetEncoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for an object that can be decoded using a struct codec.\n *\n * This type maps the provided field decoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n */\ntype GetDecoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for custom objects.\n *\n * This encoder serializes an object by encoding its fields sequentially,\n * using the provided field encoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n *\n * @param fields - The name and encoder of each field.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects.\n *\n * @example\n * Encoding a custom struct.\n * ```ts\n * const encoder = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]);\n *\n * const bytes = encoder.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructEncoder>>(\n fields: TFields,\n): FixedSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): VariableSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): Encoder> {\n type TFrom = GetEncoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n fields\n .map(([key, codec]) => getEncodedSize(value[key as keyof TFrom], codec))\n .reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (struct: TFrom, bytes, offset) => {\n fields.forEach(([key, codec]) => {\n offset = codec.write(struct[key as keyof TFrom], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for custom objects.\n *\n * This decoder deserializes an object by decoding its fields sequentially,\n * using the provided field decoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n *\n * @param fields - The name and decoder of each field.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects.\n *\n * @example\n * Decoding a custom struct.\n * ```ts\n * const decoder = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]);\n *\n * const struct = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructDecoder>>(\n fields: TFields,\n): FixedSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): VariableSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): Decoder> {\n type TTo = GetDecoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const struct = {} as TTo;\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.read(bytes, offset);\n offset = newOffset;\n struct[key as keyof TTo] = value;\n });\n return [struct, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding custom objects.\n *\n * This codec serializes objects by encoding and decoding each field sequentially.\n *\n * @typeParam TFields - The fields of the struct, each paired with a codec.\n *\n * @param fields - The name and codec of each field.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects.\n *\n * @example\n * Encoding and decoding a custom struct.\n * ```ts\n * const codec = getStructCodec([\n * ['name', fixCodecSize(getUtf8Codec(), 5)],\n * ['age', getU8Codec()]\n * ]);\n *\n * const bytes = codec.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n *\n * const struct = codec.decode(bytes);\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @remarks\n * Separate {@link getStructEncoder} and {@link getStructDecoder} functions are available.\n *\n * ```ts\n * const bytes = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]).encode({ name: 'Alice', age: 42 });\n *\n * const struct = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getStructEncoder}\n * @see {@link getStructDecoder}\n */\nexport function getStructCodec>>(\n fields: TFields,\n): FixedSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): VariableSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): Codec, GetDecoderTypeFromFields & GetEncoderTypeFromFields> {\n return combineCodec(\n getStructEncoder(fields),\n getStructDecoder(fields) as Decoder & GetEncoderTypeFromFields>,\n );\n}\n","/**\n * An implementation of the Rust `Option` type in JavaScript.\n *\n * In Rust, optional values are represented using `Option`, which can be either:\n * - `Some(T)`, indicating a present value.\n * - `None`, indicating the absence of a value.\n *\n * In JavaScript, this is typically represented as `T | null`. However, this approach fails with nested options.\n * For example, `Option>` in Rust would translate to `T | null | null` in JavaScript, which is equivalent to `T | null`.\n * This means there is no way to differentiate between `Some(None)` and `None`, making nested options impossible.\n *\n * This `Option` type helps solve this by mirroring Rust’s `Option` type.\n *\n * ```ts\n * type Option = Some | None;\n * type Some = { __option: 'Some'; value: T };\n * type None = { __option: 'None' };\n * ```\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Here's how you can create `Option` values.\n *\n * To improve developer experience, helper functions are available.\n * TypeScript can infer the type of `T` or it can be explicitly provided.\n *\n * ```ts\n * // Create an option with a value.\n * some('Hello World');\n * some(123);\n *\n * // Create an empty option.\n * none();\n * none();\n * ```\n *\n * @see {@link Some}\n * @see {@link None}\n * @see {@link some}\n * @see {@link none}\n */\nexport type Option = None | Some;\n\n/**\n * A flexible type that allows working with {@link Option} values or nullable values.\n *\n * It defines a looser type that can be used when encoding {@link Option | Options}.\n * This allows us to pass `null` or the nested value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Accepting both `Option` and `T | null` as input.\n * ```ts\n * function double(value: OptionOrNullable) {\n * const option = isOption(value) ? value : wrapNullable(value);\n * return isSome(option) ? option.value * 2 : 'No value';\n * }\n *\n * double(42); // 84\n * double(some(21)); // 42\n * double(none()); // \"No value\"\n * double(null); // \"No value\"\n * ```\n *\n * @see {@link Option}\n * @see {@link isOption}\n * @see {@link wrapNullable}\n */\nexport type OptionOrNullable = Option | T | null;\n\n/**\n * Represents an {@link Option} that contains a value.\n *\n * This type mirrors Rust’s `Some(T)`, indicating that a value is present.\n *\n * For more details, see {@link Option}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Creating a `Some` value.\n * ```ts\n * const value = some(42);\n * isSome(value); // true\n * isNone(value); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link some}\n * @see {@link isSome}\n */\nexport type Some = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an {@link Option} that contains no value.\n *\n * This type mirrors Rust’s `None`, indicating the absence of a value.\n *\n * For more details, see {@link Option}.\n *\n * @example\n * Creating a `None` value.\n * ```ts\n * const empty = none();\n * isNone(empty); // true\n * isSome(empty); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link none}\n * @see {@link isNone}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} that contains a value.\n *\n * This function explicitly wraps a value in an {@link Option} type.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param value - The value to wrap in an {@link Option}.\n * @returns An {@link Option} containing the provided value.\n *\n * @example\n * Wrapping a value in an `Option`.\n * ```ts\n * const option = some('Hello');\n * option.value; // \"Hello\"\n * isOption(option); // true\n * isSome(option); // true\n * isNone(option); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const some = (value: T): Option => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} that contains no value.\n *\n * This function explicitly represents an absent value.\n *\n * @typeParam T - The type of the expected absent value.\n *\n * @returns An {@link Option} containing no value.\n *\n * @example\n * Creating an empty `Option`.\n * ```ts\n * const empty = none();\n * isOption(empty); // true\n * isSome(empty); // false\n * isNone(empty); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const none = (): Option => ({ __option: 'None' });\n\n/**\n * Checks whether the given value is an {@link Option}.\n *\n * This function determines whether an input follows the `Option` structure.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param input - The value to check.\n * @returns `true` if the value is an {@link Option}, `false` otherwise.\n *\n * @example\n * Checking for `Option` values.\n * ```ts\n * isOption(some(42)); // true\n * isOption(none()); // true\n * isOption(42); // false\n * isOption(null); // false\n * isOption(\"anything else\"); // false\n * ```\n *\n * @see {@link Option}\n */\nexport const isOption = (input: unknown): input is Option =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Checks whether the given {@link Option} contains a value.\n *\n * This function acts as a type guard, ensuring the value is a {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link Some}, `false` otherwise.\n *\n * @example\n * Checking for `Some` values.\n * ```ts\n * isSome(some(42)); // true\n * isSome(none()); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const isSome = (option: Option): option is Some => option.__option === 'Some';\n\n/**\n * Checks whether the given {@link Option} contains no value.\n *\n * This function acts as a type guard, ensuring the value is a {@link None}.\n *\n * @typeParam T - The type of the expected value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link None}, `false` otherwise.\n *\n * @example\n * Checking for `None` values.\n * ```ts\n * isNone(some(42)); // false\n * isNone(none()); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const isNone = (option: Option): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option}, returning its contained value or a fallback.\n *\n * This function extracts the value `T` from an `Option` type.\n * - If the option is {@link Some}, it returns the contained value `T`.\n * - If the option is {@link None}, it returns the fallback value `U`, which defaults to `null`.\n *\n * @typeParam T - The type of the contained value.\n * @typeParam U - The type of the fallback value (defaults to `null`).\n *\n * @param option - The {@link Option} to unwrap.\n * @param fallback - A function that provides a fallback value if the option is {@link None}.\n * @returns The contained value if {@link Some}, otherwise the fallback value.\n *\n * @example\n * Unwrapping an `Option` with no fallback.\n * ```ts\n * unwrapOption(some('Hello World')); // \"Hello World\"\n * unwrapOption(none()); // null\n * ```\n *\n * @example\n * Providing a custom fallback value.\n * ```ts\n * unwrapOption(some('Hello World'), () => 'Default'); // \"Hello World\"\n * unwrapOption(none(), () => 'Default'); // \"Default\"\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport function unwrapOption(option: Option): T | null;\nexport function unwrapOption(option: Option, fallback: () => U): T | U;\nexport function unwrapOption(option: Option, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n *\n * - If the input value is `null`, this function returns {@link None}.\n * - Otherwise, it wraps the value in {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param nullable - The nullable value to wrap.\n * @returns An {@link Option} wrapping the value.\n *\n * @example\n * Wrapping nullable values.\n * ```ts\n * wrapNullable('Hello World'); // Option (Some)\n * wrapNullable(null); // Option (None)\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport const wrapNullable = (nullable: T | null): Option => (nullable !== null ? some(nullable) : none());\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getUnionDecoder,\n getUnionEncoder,\n getUnitDecoder,\n getUnitEncoder,\n} from '@solana/codecs-data-structures';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, None, none, Option, OptionOrNullable, Some, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/**\n * Defines the configuration options for {@link Option} codecs.\n *\n * The `getOptionCodec` function behaves similarly to {@link getNullableCodec}\n * but encodes `Option` types instead of `T | null` types.\n *\n * This configuration controls how {@link None} values are encoded and how presence\n * is determined when decoding.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n * @see {@link getOptionCodec}\n */\nexport type OptionCodecConfig = {\n /**\n * Specifies how {@link None} values are represented in the encoded data.\n *\n * - By default, {@link None} values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec for the item.\n * - Custom byte array: {@link None} values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; {@link None} values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between {@link None} and present values.\n *\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines {@link None}.\n * If no `noneValue` is set, {@link None} is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values using the {@link Option} type.\n *\n * This encoder serializes an {@link OptionOrNullable} value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, {@link None} values are encoded as zeroes.\n * - If `noneValue` is a byte array, {@link None} values are replaced with the provided constant.\n *\n * Unlike {@link getNullableEncoder}, this encoder accepts both {@link Option} and {@link Nullable} values.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values.\n *\n * @example\n * Encoding an optional string.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const encoder = getOptionEncoder(stringCodec);\n *\n * encoder.encode(some('Hi'));\n * encoder.encode('Hi');\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * encoder.encode(none());\n * encoder.encode(null);\n * // 0x00\n * // └-- 1-byte prefix (None).\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder, TSize>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config: OptionCodecConfig = {},\n): Encoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: None | null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: Some | TFrom): [boolean, TFrom] => [\n true,\n isOption(value) && isSome(value) ? value.value : value,\n ]),\n ],\n variant => {\n const option = isOption(variant) ? variant : wrapNullable(variant);\n return Number(isSome(option));\n },\n );\n}\n\n/**\n * Returns a decoder for optional values using the {@link Option} type.\n *\n * This decoder deserializes an `Option` value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes.\n * - If `noneValue` is a byte array, `None` values match the provided constant.\n *\n * Unlike {@link getNullableDecoder}, this decoder always outputs an {@link Option} type.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values.\n *\n * @example\n * Decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const decoder = getOptionDecoder(stringCodec);\n *\n * decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69]));\n * // some('Hi')\n *\n * decoder.decode(new Uint8Array([0x00]));\n * // none()\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder, TSize>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config: OptionCodecConfig = {},\n): Decoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => none()),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value)),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values using the {@link Option} type.\n *\n * This codec serializes and deserializes `Option` values using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `None` values are represented by the provided constant.\n * - If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes.\n *\n * For more details on the configuration options, see {@link OptionCodecConfig}.\n *\n * Note that this behaves similarly to {@link getNullableCodec}, except it\n * encodes {@link OptionOrNullable} values and decodes {@link Option} values.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding option values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values.\n *\n * @example\n * Encoding and decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode(some('Hi'));\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * const noneBytes = codec.encode(none());\n * // 0x00\n * // └-- 1-byte prefix (None).\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding nullable values.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode('Hi'); // 0x01020000004869\n * const noneBytes = codec.encode(null); // 0x00\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding an optional number with a fixed size.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' });\n *\n * const someBytes = codec.encode(some(42)); // 0x012a00\n * const noneBytes = codec.encode(none()); // 0x000000\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding {@link None} values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // 0xffff\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Identifying {@link None} values by the absence of bytes.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { prefix: null });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // new Uint8Array(0)\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @remarks\n * Separate {@link getOptionEncoder} and {@link getOptionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getOptionEncoder(getU32Encoder()).encode(some(42));\n * const value = getOptionDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n */\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec, Option, TSize>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec, Option>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config: OptionCodecConfig = {},\n): Codec, Option> {\n type ConfigCast = OptionCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getOptionEncoder(item, config as ConfigCast),\n getOptionDecoder(item, config as ConfigCast),\n );\n}\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Defines types that should not be recursively unwrapped.\n *\n * These types are preserved as-is when using {@link unwrapOptionRecursively}.\n *\n * @see {@link unwrapOptionRecursively}\n */\ntype UnUnwrappables =\n | Date\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | bigint\n | boolean\n | number\n | string\n | symbol\n | null\n | undefined;\n\n/**\n * A type that recursively unwraps nested {@link Option} types.\n *\n * This type resolves all nested {@link Option} values, ensuring\n * that deeply wrapped values are properly extracted.\n *\n * - If `T` is an {@link Option}, it resolves to the contained value.\n * - If `T` is a known primitive or immutable type, it remains unchanged.\n * - If `T` is an object or array, it recursively unwraps any options found.\n *\n * The fallback type `U` (default: `null`) is used in place of `None` values.\n *\n * @typeParam T - The type to be unwrapped.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @example\n * Resolving nested `Option` types.\n * ```ts\n * UnwrappedOption>>; // string\n * UnwrappedOption; // null\n * ```\n *\n * @example\n * Resolving options inside objects and arrays.\n * ```ts\n * UnwrappedOption<{ a: Some; b: None }>; // { a: number; b: null }\n * UnwrappedOption<[Some, None]>; // [number, null]\n * ```\n *\n * @see {@link unwrapOptionRecursively}\n */\nexport type UnwrappedOption =\n T extends Some\n ? UnwrappedOption\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption }\n : T extends Array\n ? Array>\n : T;\n\n/**\n * Recursively unwraps all nested {@link Option} types within a value.\n *\n * This function traverses a given value and removes all instances\n * of {@link Option}, replacing them with their contained values.\n *\n * - If an {@link Option} is encountered, its value is extracted.\n * - If an array or object is encountered, its elements are traversed recursively.\n * - If `None` is encountered, it is replaced with the fallback value (default: `null`).\n *\n * @typeParam T - The type of the input value.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @param input - The value to unwrap.\n * @param fallback - A function that provides a fallback value for `None` options.\n * @returns The recursively unwrapped value.\n *\n * @example\n * Recursively unwrapping nested options.\n * ```ts\n * unwrapOptionRecursively(some(some('Hello World'))); // \"Hello World\"\n * unwrapOptionRecursively(some(none())); // null\n * ```\n *\n * @example\n * Recursively unwrapping options inside objects and arrays.\n * ```ts\n * unwrapOptionRecursively({\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * });\n * // { a: \"hello\", b: null, c: [{ c1: 42 }, { c2: null }] }\n * ```\n *\n * @example\n * Using a fallback value for `None` options.\n * ```ts\n * unwrapOptionRecursively(\n * {\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * },\n * () => 'Default',\n * );\n * // { a: \"hello\", b: \"Default\", c: [{ c1: 42 }, { c2: \"Default\" }] }\n * ```\n *\n * @remarks\n * This function does not mutate objects or arrays.\n *\n * @see {@link Option}\n * @see {@link UnwrappedOption}\n */\nexport function unwrapOptionRecursively(input: T): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback: () => U): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback?: () => U): UnwrappedOption {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption;\n }\n\n const next = (x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption;\n return (fallback ? fallback() : null) as UnwrappedOption;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption;\n }\n return input as UnwrappedOption;\n}\n","export * from '@solana/codecs-core';\nexport * from '@solana/codecs-data-structures';\nexport * from '@solana/codecs-numbers';\nexport * from '@solana/codecs-strings';\nexport * from '@solana/options';\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","/**\n * A pipeline is a solution that allows you to perform successive transforms of a value using functions. This is useful when building up a transaction message.\n *\n * Until the [pipeline operator](https://github.com/tc39/proposal-pipeline-operator) becomes part of JavaScript you can use this utility to create pipelines.\n *\n * Following common implementations of pipe functions that use TypeScript, this function supports a maximum arity of 10 for type safety.\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```ts\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n *\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * @example Basic\n * ```ts\n * const add = (a, b) => a + b;\n * const add10 = x => add(x, 10);\n * const add100 = x => add(x, 100);\n * const sum = pipe(1, add10, add100);\n * sum === 111; // true\n * ```\n *\n * @example Building a Solana transaction message\n * ```ts\n * const transferTransactionMessage = pipe(\n * // The result of the first expression...\n * createTransactionMessage({ version: 0 }),\n * // ...gets passed as the sole argument to the next function in the pipeline.\n * tx => setTransactionMessageFeePayer(myAddress, tx),\n * // The return value of that function gets passed to the next...\n * tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n * // ...and so on.\n * tx => appendTransactionMessageInstruction(createTransferInstruction(myAddress, toAddress, amountInLamports), tx),\n * );\n * ```\n *\n * @returns The initial value\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n): TInitial;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n): R1;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n): R2;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n): R3;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n): R4;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n): R5;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n): R6;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n): R7;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n): R8;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n): R9;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n /** The function with which to transform the return value of the prior function */\n r9_r10: (r9: R9) => R10,\n): R10;\nexport function pipe(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { AccountLookupMeta, AccountMeta } from './accounts';\n\n/**\n * An instruction destined for a given program.\n *\n * @example\n * ```ts\n * type StakeProgramInstruction = Instruction<'StakeConfig11111111111111111111111111111111'>;\n * ```\n */\nexport interface Instruction<\n TProgramAddress extends string = string,\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n> {\n readonly accounts?: TAccounts;\n readonly data?: ReadonlyUint8Array;\n readonly programAddress: Address;\n}\n\n/**\n * An instruction that loads certain accounts.\n *\n * @example\n * ```ts\n * type InstructionWithTwoAccounts = InstructionWithAccounts<\n * [\n * WritableAccount, // First account\n * RentSysvar, // Second account\n * ]\n * >;\n * ```\n */\nexport interface InstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[],\n> extends Instruction {\n readonly accounts: TAccounts;\n}\n\nexport function isInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): instruction is TInstruction & { programAddress: Address } {\n return instruction.programAddress === programAddress;\n}\n\nexport function assertIsInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): asserts instruction is TInstruction & { programAddress: Address } {\n if (instruction.programAddress !== programAddress) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, {\n actualProgramAddress: instruction.programAddress,\n expectedProgramAddress: programAddress,\n });\n }\n}\n\nexport function isInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithAccounts & TInstruction {\n return instruction.accounts !== undefined;\n}\n\nexport function assertIsInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithAccounts & TInstruction {\n if (instruction.accounts === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, {\n data: instruction.data,\n programAddress: instruction.programAddress,\n });\n }\n}\n\n/**\n * An instruction whose data conforms to a certain type.\n *\n * This is most useful when you have a branded `Uint8Array` that represents a particular\n * instruction's data.\n *\n * @example A type for the \\`AdvanceNonce\\` instruction of the System program\n * ```ts\n * type AdvanceNonceAccountInstruction<\n * TNonceAccountAddress extends string = string,\n * TNonceAuthorityAddress extends string = string,\n * > = Instruction<'11111111111111111111111111111111'> &\n * InstructionWithAccounts<\n * [\n * WritableAccount,\n * ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n * ReadonlySignerAccount,\n * ]\n * > &\n * InstructionWithData;\n * ```\n */\nexport interface InstructionWithData extends Instruction {\n readonly data: TData;\n}\n\nexport function isInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithData & TInstruction {\n return instruction.data !== undefined;\n}\n\nexport function assertIsInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithData & TInstruction {\n if (instruction.data === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, {\n accountAddresses: instruction.accounts?.map(a => a.address),\n programAddress: instruction.programAddress,\n });\n }\n}\n","/**\n * Describes the purpose for which an account participates in a transaction.\n *\n * Every account that participates in a transaction can be read from, but only ones that you mark as\n * writable may be written to, and only ones that you indicate must sign the transaction will gain\n * the privileges associated with signers at runtime.\n *\n * | | `isSigner` | `isWritable` |\n * | ----------------------------- | ---------- | ------------ |\n * | `AccountRole.READONLY` | ❌ | ❌ |\n * | `AccountRole.WRITABLE` | ❌ | ✅ |\n * | `AccountRole.READONLY_SIGNER` | ✅ | ❌ |\n * | `AccountRole.WRITABLE_SIGNER` | ✅ | ✅ |\n */\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\n// Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\n/**\n * @returns An {@link AccountRole} representing the non-signer variant of the supplied role.\n */\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the read-only variant of the supplied role.\n */\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a signer. Also refines the\n * TypeScript type of the supplied role.\n */\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a writable account. Also\n * refines the TypeScript type of the supplied role.\n */\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\n/**\n * Given two {@link AccountRole | AccountRoles}, will return the {@link AccountRole} that grants the\n * highest privileges of both.\n *\n * @example\n * ```ts\n * // Returns `AccountRole.WRITABLE_SIGNER`\n * mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE);\n * ```\n */\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\n/**\n * @returns An {@link AccountRole} representing the signer variant of the supplied role.\n */\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the writable variant of the supplied role.\n */\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { Address, assertIsAddress, getAddressDecoder, getAddressEncoder, isAddress } from '@solana/addresses';\nimport { combineCodec, createEncoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nexport type Blockhash = Brand, 'Blockhash'>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Blockhash} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isBlockhash } from '@solana/rpc-types';\n *\n * if (isBlockhash(blockhash)) {\n * // At this point, `blockhash` has been refined to a\n * // `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsFresh(isValid);\n * } else {\n * setError(`${blockhash} is not a blockhash`);\n * }\n * ```\n */\nexport function isBlockhash(putativeBlockhash: string): putativeBlockhash is Blockhash {\n return isAddress(putativeBlockhash);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as a blockhash, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string is\n * a base58-encoded blockhash.\n *\n * @example\n * ```ts\n * import { assertIsBlockhash } from '@solana/rpc-types';\n *\n * // Imagine a function that determines whether a blockhash is fresh when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const blockhash: string = blockhashInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `blockhash` to `Blockhash`.\n * assertIsBlockhash(blockhash);\n * // At this point, `blockhash` is a `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `blockhash` turned out not to be a base58-encoded blockhash\n * }\n * }\n * ```\n */\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n assertIsAddress(putativeBlockhash);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, error.context);\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, error.context);\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is a blockhash with _coercing_ it to the {@link Blockhash}\n * type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { blockhash } from '@solana/rpc-types';\n *\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash(blockhashFromUserInput)).send();\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good blockhash as a string, it's more efficient to typecast it\n * rather than to use the {@link blockhash} helper, because the helper unconditionally performs\n * validation on its input.\n * >\n * > ```ts\n * > import { Blockhash } from '@solana/rpc-types';\n * >\n * > const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * > ```\n */\nexport function blockhash(putativeBlockhash: string): Blockhash {\n assertIsBlockhash(putativeBlockhash);\n return putativeBlockhash;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded blockhash to a byte array.\n *\n * @example\n * ```ts\n * import { getBlockhashEncoder } from '@solana/rpc-types';\n *\n * const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * const blockhashEncoder = getBlockhashEncoder();\n * const blockhashBytes = blockhashEncoder.encode(blockhash);\n * // Uint8Array(32) [\n * // 136, 123, 44, 249, 43, 19, 60, 14,\n * // 144, 16, 168, 241, 121, 111, 70, 232,\n * // 186, 26, 140, 202, 213, 64, 231, 82,\n * // 179, 66, 103, 237, 52, 117, 217, 93\n * // ]\n * ```\n */\nexport function getBlockhashEncoder(): FixedSizeEncoder {\n const addressEncoder = getAddressEncoder();\n return createEncoder({\n fixedSize: 32,\n write: (value: string, bytes, offset) => {\n assertIsBlockhash(value);\n return addressEncoder.write(value as string as Address, bytes, offset);\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing a blockhash to\n * the base58-encoded representation of that blockhash.\n *\n * @example\n * ```ts\n * import { getBlockhashDecoder } from '@solana/rpc-types';\n *\n * const blockhashBytes = new Uint8Array([\n * 136, 123, 44, 249, 43, 19, 60, 14,\n * 144, 16, 168, 241, 121, 111, 70, 232,\n * 186, 26, 140, 202, 213, 64, 231, 82,\n * 179, 66, 103, 237, 52, 117, 217, 93\n * ]);\n * const blockhashDecoder = getBlockhashDecoder();\n * const blockhash = blockhashDecoder.decode(blockhashBytes); // ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48\n * ```\n */\nexport function getBlockhashDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded blockhash.\n *\n * @see {@link getBlockhashDecoder}\n * @see {@link getBlockhashEncoder}\n */\nexport function getBlockhashCodec(): FixedSizeCodec {\n return combineCodec(getBlockhashEncoder(), getBlockhashDecoder());\n}\n\nexport function getBlockhashComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","export type MainnetUrl = string & { '~cluster': 'mainnet' };\nexport type DevnetUrl = string & { '~cluster': 'devnet' };\nexport type TestnetUrl = string & { '~cluster': 'testnet' };\nexport type ClusterUrl = DevnetUrl | MainnetUrl | TestnetUrl | string;\n\n/** Given a URL casts it to a type that is only accepted where mainnet URLs are expected. */\nexport function mainnet(putativeString: string): MainnetUrl {\n return putativeString as MainnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where devnet URLs are expected. */\nexport function devnet(putativeString: string): DevnetUrl {\n return putativeString as DevnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where testnet URLs are expected. */\nexport function testnet(putativeString: string): TestnetUrl {\n return putativeString as TestnetUrl;\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\n\n/**\n * A union of all possible commitment statuses -- each a measure of the network confirmation and\n * stake levels on a particular block.\n *\n * Read more about the statuses themselves, [here](https://docs.solana.com/cluster/commitments).\n */\nexport type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: commitment satisfies never,\n });\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n} from '@solana/codecs-core';\nimport { getU64Decoder, getU64Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * Represents an integer value denominated in Lamports (ie. $1 \\times 10^{-9}$ ◎).\n *\n * It is represented as a `bigint` in client code and an `u64` in server code.\n */\nexport type Lamports = Brand;\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nlet memoizedU64Encoder: FixedSizeEncoder | undefined;\nlet memoizedU64Decoder: FixedSizeDecoder | undefined;\n\nfunction getMemoizedU64Encoder(): FixedSizeEncoder {\n if (!memoizedU64Encoder) memoizedU64Encoder = getU64Encoder();\n return memoizedU64Encoder;\n}\n\nfunction getMemoizedU64Decoder(): FixedSizeDecoder {\n if (!memoizedU64Decoder) memoizedU64Decoder = getU64Decoder();\n return memoizedU64Decoder;\n}\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link Lamports} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isLamports } from '@solana/rpc-types';\n *\n * if (isLamports(lamports)) {\n * // At this point, `lamports` has been refined to a\n * // `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } else {\n * setError(`${lamports} is not a quantity of Lamports`);\n * }\n * ```\n */\nexport function isLamports(putativeLamports: bigint): putativeLamports is Lamports {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\n/**\n * Lamport values returned from the RPC API conform to the type {@link Lamports}. You can use a\n * value of that type wherever a quantity of Lamports is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a quantity of Lamports, from\n * an untrusted network API or user input. To assert that such an arbitrary number is usable as a\n * quantity of Lamports, use this function.\n *\n * ```ts\n * import { assertIsLamports } from '@solana/rpc-types';\n *\n * // Imagine a function that creates a transfer instruction when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `number` type.\n * const lamports: number = parseInt(quantityInput.value, 10);\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `lamports` to `Lamports`.\n * assertIsLamports(lamports);\n * // At this point, `lamports` is a `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } catch (e) {\n * // `lamports` turned out not to validate as a quantity of Lamports.\n * }\n * }\n * ```\n */\nexport function assertIsLamports(putativeLamports: bigint): asserts putativeLamports is Lamports {\n if (putativeLamports < 0 || putativeLamports > maxU64Value) {\n throw new SolanaError(SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE);\n }\n}\n\n/**\n * This helper combines _asserting_ that a number is a possible number of {@link Lamports} with\n * _coercing_ it to the {@link Lamports} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { lamports } from '@solana/rpc-types';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n */\nexport function lamports(putativeLamports: bigint): Lamports {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n\ntype ExtractAdditionalProps = Omit;\n\n/**\n * Returns an encoder that you can use to encode a 64-bit {@link Lamports} value to 8 bytes in\n * little endian order.\n */\nexport function getDefaultLamportsEncoder(): FixedSizeEncoder {\n return getLamportsEncoder(getMemoizedU64Encoder());\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link Lamports} value to a byte array.\n *\n * You must supply a number decoder that will determine how encode the numeric value.\n *\n * @example\n * ```ts\n * import { getLamportsEncoder } from '@solana/rpc-types';\n * import { getU16Encoder } from '@solana/codecs-numbers';\n *\n * const lamports = lamports(256n);\n * const lamportsEncoder = getLamportsEncoder(getU16Encoder());\n * const lamportsBytes = lamportsEncoder.encode(lamports);\n * // Uint8Array(2) [ 0, 1 ]\n * ```\n */\nexport function getLamportsEncoder(\n innerEncoder: TEncoder,\n): Encoder & ExtractAdditionalProps {\n return innerEncoder;\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a 64-bit little endian\n * number to a {@link Lamports} value.\n */\nexport function getDefaultLamportsDecoder(): FixedSizeDecoder {\n return getLamportsDecoder(getMemoizedU64Decoder());\n}\n\n/**\n * Returns a decoder that you can use to convert an array of bytes representing a number to a\n * {@link Lamports} value.\n *\n * You must supply a number decoder that will determine how many bits to use to decode the numeric\n * value.\n *\n * @example\n * ```ts\n * import { getLamportsDecoder } from '@solana/rpc-types';\n * import { getU16Decoder } from '@solana/codecs-numbers';\n *\n * const lamportsBytes = new Uint8Array([ 0, 1 ]);\n * const lamportsDecoder = getLamportsDecoder(getU16Decoder());\n * const lamports = lamportsDecoder.decode(lamportsBytes); // lamports(256n)\n * ```\n */\nexport function getLamportsDecoder(\n innerDecoder: TDecoder,\n): Decoder & ExtractAdditionalProps {\n return transformDecoder(innerDecoder, value =>\n lamports(typeof value === 'bigint' ? value : BigInt(value)),\n ) as Decoder & ExtractAdditionalProps;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a 64-bit {@link Lamports} value.\n *\n * @see {@link getDefaultLamportsDecoder}\n * @see {@link getDefaultLamportsEncoder}\n */\nexport function getDefaultLamportsCodec(): FixedSizeCodec {\n return combineCodec(getDefaultLamportsEncoder(), getDefaultLamportsDecoder());\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link Lamports} value.\n *\n * @see {@link getLamportsDecoder}\n * @see {@link getLamportsEncoder}\n */\nexport function getLamportsCodec(\n innerCodec: TCodec,\n): Codec & ExtractAdditionalProps {\n return combineCodec(getLamportsEncoder(innerCodec), getLamportsDecoder(innerCodec)) as Codec &\n ExtractAdditionalProps;\n}\n","import { SOLANA_ERROR__MALFORMED_BIGINT_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a `bigint` which has been encoded as a string for transit over a transport\n * that does not support `bigint` values natively. The JSON-RPC is such a transport.\n */\nexport type StringifiedBigInt = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `BigInt`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedBigInt } from '@solana/rpc-types';\n *\n * if (isStringifiedBigInt(bigintString)) {\n * // At this point, `bigintString` has been refined to a `StringifiedBigInt`\n * bigintString satisfies StringifiedBigInt; // OK\n * } else {\n * setError(`${bigintString} does not represent a BigInt`);\n * }\n * ```\n */\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `BigInt`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `BigInt`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedBigInt } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents the supply of some token.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `supplyString` to `StringifiedBigInt`.\n * assertIsStringifiedBigInt(supplyString);\n * // At this point, `supplyString` is a `StringifiedBigInt`.\n * supplyString satisfies StringifiedBigInt;\n * } catch (e) {\n * // `supplyString` turned out not to parse as a `BigInt`\n * }\n * ```\n */\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_BIGINT_STRING, {\n value: putativeBigInt,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `BigInt` with _coercing_ it to the\n * {@link StringifiedBigInt} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedBigInt } from '@solana/rpc-types';\n *\n * const supplyString = stringifiedBigInt('1000000000');\n * ```\n */\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","import { SOLANA_ERROR__MALFORMED_NUMBER_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a number which has been encoded as a string for transit over a transport\n * where loss of precision when using the native number type is a concern. The JSON-RPC is such a\n * transport.\n */\nexport type StringifiedNumber = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `Number`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedNumber } from '@solana/rpc-types';\n *\n * if (isStringifiedNumber(numericString)) {\n * // At this point, `numericString` has been refined to a `StringifiedNumber`\n * numericString satisfies StringifiedNumber; // OK\n * } else {\n * setError(`${numericString} does not represent a number`);\n * }\n * ```\n */\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `Number`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `Number`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedNumber } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents some decimal number.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `decimalNumberString` to `StringifiedNumber`.\n * assertIsStringifiedNumber(decimalNumberString);\n * // At this point, `decimalNumberString` is a `StringifiedNumber`.\n * decimalNumberString satisfies StringifiedNumber;\n * } catch (e) {\n * // `decimalNumberString` turned out not to parse as a number.\n * }\n * ```\n */\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_NUMBER_STRING, {\n value: putativeNumber,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `Number` with _coercing_ it to the\n * {@link StringifiedNumber} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedNumber } from '@solana/rpc-types';\n *\n * const decimalNumberString = stringifiedNumber('-42.1');\n * ```\n */\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","import { SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a Unix timestamp in _seconds_.\n *\n * It is represented as a `bigint` in client code and an `i64` in server code.\n */\nexport type UnixTimestamp = Brand;\n\n// Largest possible value to be represented by an i64\nconst maxI64Value = 9223372036854775807n; // 2n ** 63n - 1n\nconst minI64Value = -9223372036854775808n; // -(2n ** 63n)\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link UnixTimestamp} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isUnixTimestamp } from '@solana/rpc-types';\n *\n * if (isUnixTimestamp(timestamp)) {\n * // At this point, `timestamp` has been refined to a\n * // `UnixTimestamp` that can be used anywhere timestamps are expected.\n * timestamp satisfies UnixTimestamp;\n * } else {\n * setError(`${timestamp} is not a Unix timestamp`);\n * }\n * ```\n */\n\nexport function isUnixTimestamp(putativeTimestamp: bigint): putativeTimestamp is UnixTimestamp {\n return putativeTimestamp >= minI64Value && putativeTimestamp <= maxI64Value;\n}\n\n/**\n * Timestamp values returned from the RPC API conform to the type {@link UnixTimestamp}. You can use\n * a value of that type wherever a timestamp is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a timestamp, from an untrusted\n * network API or user input. To assert that such an arbitrary number is usable as a Unix timestamp,\n * use this function.\n *\n * ```ts\n * import { assertIsUnixTimestamp } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents a timestamp.\n * // At this point we know only that it conforms to the `bigint` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `timestamp` to `UnixTimestamp`.\n * assertIsUnixTimestamp(timestamp);\n * // At this point, `timestamp` is a `UnixTimestamp`.\n * timestamp satisfies UnixTimestamp;\n * } catch (e) {\n * // `timestamp` turned out not to be a valid Unix timestamp\n * }\n * ```\n */\nexport function assertIsUnixTimestamp(putativeTimestamp: bigint): asserts putativeTimestamp is UnixTimestamp {\n if (putativeTimestamp < minI64Value || putativeTimestamp > maxI64Value) {\n throw new SolanaError(SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, {\n value: putativeTimestamp,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a `bigint` represents a Unix timestamp with _coercing_ it\n * to the {@link UnixTimestamp} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { unixTimestamp } from '@solana/rpc-types';\n *\n * const timestamp = unixTimestamp(-42n); // Wednesday, December 31, 1969 3:59:18 PM GMT-08:00\n * ```\n */\nexport function unixTimestamp(putativeTimestamp: bigint): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SolanaError } from '@solana/errors';\nimport { type Blockhash, isBlockhash } from '@solana/rpc-types';\n\nimport { ExcludeTransactionMessageLifetime, TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network. The transaction message will continue to be eligible to land\n * until the network considers the `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type BlockhashLifetimeConstraint = Readonly<{\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction message will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction message eligible to land.\n */\n lastValidBlockHeight: bigint;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the age of the blockhash it\n * includes.\n *\n * Such a transaction can only be landed on the network if the current block height of the network\n * is less than or equal to the value of\n * `TransactionMessageWithBlockhashLifetime['lifetimeConstraint']['lastValidBlockHeight']`.\n */\nexport interface TransactionMessageWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * if (isTransactionMessageWithBlockhashLifetime(message)) {\n * // At this point, `message` has been refined to a `TransactionMessageWithBlockhashLifetime`.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.blockhash === 'string' &&\n typeof transactionMessage.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transactionMessage.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * blockhash-based lifetime, from an untrusted network API or user input. Use this function to\n * assert that such a transaction message actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithBlockhashLifetime`.\n * assertIsTransactionMessageWithBlockhashLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `message` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n if (!isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * Given a blockhash and the last block height at which that blockhash is considered usable to land\n * transactions, this method will return a new transaction message having the same type as the one\n * supplied plus the `TransactionMessageWithBlockhashLifetime` type.\n *\n * @example\n * ```ts\n * import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages';\n *\n * const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n * const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, txMessage);\n * ```\n */\nexport function setTransactionMessageLifetimeUsingBlockhash<\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime {\n type ReturnType = ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime;\n\n if (\n 'lifetimeConstraint' in transactionMessage &&\n transactionMessage.lifetimeConstraint &&\n 'blockhash' in transactionMessage.lifetimeConstraint &&\n transactionMessage.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transactionMessage.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transactionMessage as ReturnType;\n }\n\n return Object.freeze({\n ...transactionMessage,\n lifetimeConstraint: Object.freeze(blockhashLifetimeConstraint),\n }) as ReturnType;\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n type Encoder,\n type VariableSizeCodec,\n type VariableSizeDecoder,\n type VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\n\ntype AddressTableLookup = ReturnType[number];\n\nlet memoizedAddressTableLookupEncoder: VariableSizeEncoder | undefined;\nexport function getAddressTableLookupEncoder(): VariableSizeEncoder {\n if (!memoizedAddressTableLookupEncoder) {\n const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<\n readonly number[]\n >;\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder {\n if (!memoizedAddressTableLookupDecoder) {\n const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): VariableSizeCodec {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile/header';\n\ntype MessageHeader = ReturnType;\n\nlet memoizedU8Encoder: FixedSizeEncoder | undefined;\nfunction getMemoizedU8Encoder(): FixedSizeEncoder {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nlet memoizedU8Decoder: FixedSizeDecoder | undefined;\nfunction getMemoizedU8Decoder(): FixedSizeDecoder {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nlet memoizedU8Codec: FixedSizeCodec | undefined;\nfunction getMemoizedU8Codec(): FixedSizeCodec {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nexport function getMessageHeaderEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['numSignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Encoder()],\n ]) as FixedSizeEncoder;\n}\n\nexport function getMessageHeaderDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['numSignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Decoder()],\n ]) as FixedSizeDecoder;\n}\n\nexport function getMessageHeaderCodec(): FixedSizeCodec {\n return getStructCodec([\n ['numSignerAccounts', getMemoizedU8Codec()],\n ['numReadonlySignerAccounts', getMemoizedU8Codec()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Codec()],\n ]) as FixedSizeCodec;\n}\n","import {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile/instructions';\n\ntype Instruction = ReturnType[number];\n\nlet memoizedGetInstructionEncoder: VariableSizeEncoder | undefined;\nexport function getInstructionEncoder(): VariableSizeEncoder {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = transformEncoder, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', addEncoderSizePrefix(getBytesEncoder(), getShortU16Encoder())],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required;\n },\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: VariableSizeDecoder | undefined;\nexport function getInstructionDecoder(): VariableSizeDecoder {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = transformDecoder, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\n 'data',\n addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder()) as VariableSizeDecoder,\n ],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n },\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): VariableSizeCodec {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { AccountMeta, Instruction } from '@solana/instructions';\n\n/**\n * @deprecated Use `TransactionMessage` instead.\n */\n// TODO(#1147) Stop exporting this in a future major version.\nexport type BaseTransactionMessage<\n TVersion extends TransactionVersion = TransactionVersion,\n TInstruction extends Instruction = Instruction,\n> = Readonly<{\n instructions: readonly TInstruction[];\n version: TVersion;\n}>;\n\nexport const MAX_SUPPORTED_TRANSACTION_VERSION = 0;\n\ntype LegacyInstruction = Instruction;\ntype LegacyTransactionMessage = BaseTransactionMessage<'legacy', LegacyInstruction>;\ntype V0TransactionMessage = BaseTransactionMessage<0, Instruction>;\n\nexport type TransactionMessage = LegacyTransactionMessage | V0TransactionMessage;\nexport type TransactionVersion = 'legacy' | 0;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { MAX_SUPPORTED_TRANSACTION_VERSION, TransactionVersion } from '../transaction-message';\n\nconst VERSION_FLAG_MASK = 0x80;\n\n/**\n * Returns an encoder that you can use to encode a {@link TransactionVersion} to a byte array.\n *\n * Legacy messages will produce an empty array and will not advance the offset. Versioned messages\n * will produce an array with a single byte.\n */\nexport function getTransactionVersionEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => (value === 'legacy' ? 0 : 1),\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === 'legacy') {\n return offset;\n }\n if (value < 0 || value > 127) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {\n actualVersion: value,\n });\n }\n\n if (value > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: value,\n });\n }\n bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link TransactionVersion}.\n *\n * When the byte at the current offset is determined to represent a legacy transaction, this decoder\n * will return `'legacy'` and will not advance the offset.\n */\nexport function getTransactionVersionDecoder(): VariableSizeDecoder {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n if (version > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n return [version as TransactionVersion, offset + 1];\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link TransactionVersion}\n *\n * @see {@link getTransactionVersionDecoder}\n * @see {@link getTransactionVersionEncoder}\n */\nexport function getTransactionVersionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n createEncoder,\n Decoder,\n fixDecoderSize,\n fixEncoderSize,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getConstantEncoder,\n getStructDecoder,\n getStructEncoder,\n getUnionEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from '../compile/message';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nfunction getCompiledMessageLegacyEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return getStructEncoder(getPreludeStructEncoderTuple()) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >;\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return transformEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ]) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >,\n value => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n };\n },\n );\n}\n\nfunction getPreludeStructEncoderTuple() {\n const lifetimeTokenEncoder = getUnionEncoder(\n [\n // Use a 32-byte constant encoder for a missing lifetime token (index 0).\n getConstantEncoder(new Uint8Array(32)),\n // Use a 32-byte base58 encoder for a valid lifetime token (index 1).\n fixEncoderSize(getBase58Encoder(), 32),\n ],\n value => (value === undefined ? 0 : 1),\n );\n\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', lifetimeTokenEncoder],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\n ] as const;\n}\n\nfunction getPreludeStructDecoderTuple() {\n return [\n ['version', getTransactionVersionDecoder() as Decoder],\n ['header', getMessageHeaderDecoder()],\n ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', fixDecoderSize(getBase58Decoder(), 32)],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ] as const;\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link CompiledTransactionMessage} to a byte\n * array.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. The byte array produced by this encoder is the message part.\n */\nexport function getCompiledTransactionMessageEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return createEncoder({\n getSizeFromValue: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link CompiledTransactionMessage}.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. You can use this decoder to decode the message part.\n */\nexport function getCompiledTransactionMessageDecoder(): VariableSizeDecoder<\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return transformDecoder(\n getStructDecoder(getPreludeStructDecoderTuple()) as VariableSizeDecoder<\n CompiledTransactionMessage &\n CompiledTransactionMessageWithLifetime & {\n addressTableLookups?: ReturnType;\n }\n >,\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups };\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link CompiledTransactionMessage}\n *\n * @see {@link getCompiledTransactionMessageDecoder}\n * @see {@link getCompiledTransactionMessageEncoder}\n */\nexport function getCompiledTransactionMessageCodec(): VariableSizeCodec<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime),\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return combineCodec(getCompiledTransactionMessageEncoder(), getCompiledTransactionMessageDecoder());\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SolanaError,\n} from '@solana/errors';\nimport {\n AccountLookupMeta,\n AccountMeta,\n AccountRole,\n Instruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = Brand<(AccountLookupMeta | AccountMeta)[], 'OrderedAccounts'>;\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | Record | StaticAccountEntry,\n ) => AddressMap[Address],\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(feePayer: Address, instructions: readonly Instruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set
();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {\n programAddress: instruction.programAddress,\n });\n default:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {\n programAddress: instruction.programAddress,\n });\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress,\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n {\n programAddress: account.address,\n },\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType;\n const orderedAccounts: (AccountLookupMeta | AccountMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Address,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype AddressTableLookup = Readonly<{\n /** The address of the address lookup table account. */\n lookupTableAddress: Address;\n /** Indexes of accounts in a lookup table to load as read-only. */\n readonlyIndexes: readonly number[];\n /** Indexes of accounts in a lookup table to load as writable. */\n writableIndexes: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Address,\n Readonly<{\n [K in keyof Omit]: number[];\n }>\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readonlyIndexes: [],\n writableIndexes: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndexes.push(account.addressIndex);\n } else {\n entry.readonlyIndexes.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype MessageHeader = Readonly<{\n /**\n * The number of accounts in the static accounts list that are neither writable nor\n * signers.\n *\n * Adding this number to `numSignerAccounts` yields the index of the first read-only non-signer\n * account in the static accounts list.\n */\n numReadonlyNonSignerAccounts: number;\n /**\n * The number of read-only accounts in the static accounts list that must sign this\n * transaction.\n *\n * Subtracting this number from `numSignerAccounts` yields the index of the first read-only\n * signer account in the static accounts list.\n */\n numReadonlySignerAccounts: number;\n /**\n * The number of accounts in the static accounts list that must sign this transaction.\n *\n * Subtracting `numReadonlySignerAccounts` from this number yields the number of\n * writable signer accounts in the static accounts list. Writable signer accounts always\n * begin at index zero in the static accounts list.\n *\n * This number itself is the index of the first non-signer account in the static\n * accounts list.\n */\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { Instruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n /**\n * An ordered list of indices that indicate which accounts in the transaction message's\n * accounts list are loaded by this instruction.\n */\n accountIndices?: number[];\n /** The input to the invoked program */\n data?: ReadonlyUint8Array;\n /**\n * The index of the address in the transaction message's accounts list associated with the\n * program to invoke.\n */\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly Instruction[],\n orderedAccounts: OrderedAccounts,\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { TransactionMessageWithBlockhashLifetime, TransactionMessageWithDurableNonceLifetime } from '../index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (\n | TransactionMessageWithBlockhashLifetime\n | TransactionMessageWithDurableNonceLifetime\n )['lifetimeConstraint'],\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { TransactionMessageWithFeePayer } from '../fee-payer';\nimport { TransactionMessageWithLifetime } from '../lifetime';\nimport { BaseTransactionMessage } from '../transaction-message';\nimport { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { getCompiledAddressTableLookups } from './address-table-lookups';\nimport { getCompiledMessageHeader } from './header';\nimport { getCompiledInstructions } from './instructions';\nimport { getCompiledLifetimeToken } from './lifetime-token';\nimport { getCompiledStaticAccounts } from './static-accounts';\n\ntype BaseCompiledTransactionMessage = Readonly<{\n /**\n * Information about the version of the transaction message and the role of the accounts it\n * loads.\n */\n header: ReturnType;\n instructions: ReturnType;\n /** A list of addresses indicating which accounts to load */\n staticAccounts: ReturnType;\n}>;\n\n/**\n * A transaction message in a form suitable for encoding for execution on the network.\n *\n * You can not fully reconstruct a source message from a compiled message without extra information.\n * In particular, supporting details about the lifetime constraint and the concrete addresses of\n * accounts sourced from account lookup tables are lost to compilation.\n */\nexport type CompiledTransactionMessage = LegacyCompiledTransactionMessage | VersionedCompiledTransactionMessage;\n\nexport type CompiledTransactionMessageWithLifetime = Readonly<{\n /**\n * 32 bytes of data observed by the transaction proposed that makes a transaction eligible to\n * land on the network.\n *\n * In the case of a transaction message with a nonce lifetime constraint, this will be the value\n * of the nonce itself. In all other cases this will be a recent blockhash.\n */\n lifetimeToken: ReturnType;\n}>;\n\ntype LegacyCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n /** A list of address tables and the accounts that this transaction loads from them */\n addressTableLookups?: ReturnType;\n version: 0;\n }>;\n\n/**\n * Converts the type of transaction message data structure that you create in your application to\n * the type of transaction message data structure that can be encoded for execution on the network.\n *\n * This is a lossy process; you can not fully reconstruct a source message from a compiled message\n * without extra information. In particular, supporting details about the lifetime constraint and\n * the concrete addresses of accounts sourced from account lookup tables will be lost to\n * compilation.\n *\n * @see {@link decompileTransactionMessage}\n */\nexport function compileTransactionMessage<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): CompiledTransactionMessageFromTransactionMessage {\n type ReturnType = CompiledTransactionMessageFromTransactionMessage;\n\n const addressMap = getAddressMapFromInstructions(\n transactionMessage.feePayer.address,\n transactionMessage.instructions,\n );\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n const lifetimeConstraint = (transactionMessage as Partial).lifetimeConstraint;\n\n return {\n ...(transactionMessage.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n ...(lifetimeConstraint ? { lifetimeToken: getCompiledLifetimeToken(lifetimeConstraint) } : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transactionMessage.instructions, orderedAccounts),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transactionMessage.version,\n } as ReturnType;\n}\n\ntype CompiledTransactionMessageFromTransactionMessage =\n ForwardTransactionMessageLifetime, TTransactionMessage>;\n\ntype ForwardTransactionMessageVersion =\n TTransactionMessage extends Readonly<{ version: 'legacy' }>\n ? LegacyCompiledTransactionMessage\n : VersionedCompiledTransactionMessage;\n\ntype ForwardTransactionMessageLifetime<\n TCompiledTransactionMessage extends CompiledTransactionMessage,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithLifetime\n ? CompiledTransactionMessageWithLifetime & TCompiledTransactionMessage\n : TCompiledTransactionMessage;\n","import { Address } from '@solana/addresses';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction, isSignerRole } from '@solana/instructions';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BaseTransactionMessage, TransactionMessage } from './transaction-message';\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n// Look up the address in lookup tables, return a lookup meta if it is found in any of them\nfunction findAddressInLookupTables(\n address: Address,\n role: AccountRole.READONLY | AccountRole.WRITABLE,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta | undefined {\n for (const [lookupTableAddress, addresses] of Object.entries(addressesByLookupTableAddress)) {\n for (let i = 0; i < addresses.length; i++) {\n if (address === addresses[i]) {\n return {\n address,\n addressIndex: i,\n lookupTableAddress: lookupTableAddress as Address,\n role,\n };\n }\n }\n }\n}\n\ntype TransactionMessageNotLegacy = Exclude;\n\n// Each account can be AccountLookupMeta | AccountMeta\ntype WidenInstructionAccounts =\n TInstruction extends Instruction\n ? Instruction<\n TProgramAddress,\n {\n [K in keyof TAccounts]: TAccounts[K] extends AccountMeta\n ? AccountLookupMeta | AccountMeta\n : TAccounts[K];\n }\n >\n : TInstruction;\n\ntype ExtractAdditionalProps = Omit;\n\ntype WidenTransactionMessageInstructions =\n TTransactionMessage extends BaseTransactionMessage\n ? BaseTransactionMessage> &\n ExtractAdditionalProps<\n TTransactionMessage,\n BaseTransactionMessage>\n >\n : TTransactionMessage;\n\n/**\n * Given a transaction message and a mapping of lookup tables to the addresses stored in them, this\n * function will return a new transaction message with the same instructions but with all non-signer\n * accounts that are found in the given lookup tables represented by an {@link AccountLookupMeta}\n * instead of an {@link AccountMeta}.\n *\n * This means that these accounts will take up less space in the compiled transaction message. This\n * size reduction is most significant when the transaction includes many accounts from the same\n * lookup table.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import {\n * AddressesByLookupTableAddress,\n * compressTransactionMessageUsingAddressLookupTables,\n * } from '@solana/transaction-messages';\n * import { fetchAddressLookupTable } from '@solana-program/address-lookup-table';\n *\n * const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW');\n * const {\n * data: { addresses },\n * } = await fetchAddressLookupTable(rpc, lookupTableAddress);\n * const addressesByAddressLookupTable: AddressesByLookupTableAddress = {\n * [lookupTableAddress]: addresses,\n * };\n *\n * const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables(\n * transactionMessage,\n * addressesByAddressLookupTable,\n * );\n * ```\n */\nexport function compressTransactionMessageUsingAddressLookupTables<\n TTransactionMessage extends TransactionMessageNotLegacy = TransactionMessageNotLegacy,\n>(\n transactionMessage: TTransactionMessage,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): TTransactionMessage | WidenTransactionMessageInstructions {\n const programAddresses = new Set(transactionMessage.instructions.map(ix => ix.programAddress));\n const eligibleLookupAddresses = new Set(\n Object.values(addressesByLookupTableAddress)\n .flatMap(a => a)\n .filter(address => !programAddresses.has(address)),\n );\n const newInstructions: Instruction[] = [];\n let updatedAnyInstructions = false;\n for (const instruction of transactionMessage.instructions) {\n if (!instruction.accounts) {\n newInstructions.push(instruction);\n continue;\n }\n\n const newAccounts: Mutable> = [];\n let updatedAnyAccounts = false;\n for (const account of instruction.accounts) {\n // If the address is already a lookup, is not in any lookup tables, or is a signer role, return as-is\n if (\n 'lookupTableAddress' in account ||\n !eligibleLookupAddresses.has(account.address) ||\n isSignerRole(account.role)\n ) {\n newAccounts.push(account);\n continue;\n }\n\n // We already checked it's in one of the lookup tables\n const lookupMetaAccount = findAddressInLookupTables(\n account.address,\n account.role,\n addressesByLookupTableAddress,\n )!;\n newAccounts.push(Object.freeze(lookupMetaAccount));\n updatedAnyAccounts = true;\n updatedAnyInstructions = true;\n }\n\n newInstructions.push(\n Object.freeze(updatedAnyAccounts ? { ...instruction, accounts: newAccounts } : instruction),\n );\n }\n\n return Object.freeze(\n updatedAnyInstructions ? { ...transactionMessage, instructions: newInstructions } : transactionMessage,\n );\n}\n","import { TransactionMessage, TransactionVersion } from './transaction-message';\nimport { TransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype TransactionConfig = Readonly<{\n version: TVersion;\n}>;\n\ntype EmptyTransactionMessage = Omit<\n Extract,\n 'instructions'\n> &\n TransactionMessageWithinSizeLimit & { instructions: readonly [] };\n\n/**\n * Given a {@link TransactionVersion} this method will return an empty transaction having the\n * capabilities of that version.\n *\n * @example\n * ```ts\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const message = createTransactionMessage({ version: 0 });\n * ```\n */\nexport function createTransactionMessage(\n config: TransactionConfig,\n): EmptyTransactionMessage {\n return Object.freeze({\n instructions: Object.freeze([]),\n version: config.version,\n }) as EmptyTransactionMessage;\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n AccountRole,\n Instruction,\n InstructionWithAccounts,\n InstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport type AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n> = Instruction<'11111111111111111111111111111111'> &\n InstructionWithAccounts<\n readonly [\n WritableAccount,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount | WritableSignerAccount,\n ]\n > &\n InstructionWithData;\n\ntype AdvanceNonceAccountInstructionData = Brand;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\n/**\n * Creates an instruction for the System program to advance a nonce.\n *\n * This instruction is a prerequisite for a transaction with a nonce-based lifetime to be landed on\n * the network. In order to be considered valid, the transaction must meet all of these criteria.\n *\n * 1. Its lifetime constraint must be a {@link NonceLifetimeConstraint}.\n * 2. The value contained in the on-chain account at the address `nonceAccountAddress` must be equal\n * to {@link NonceLifetimeConstraint.nonce} at the time the transaction is landed.\n * 3. The first instruction in that transaction message must be the one returned by this function.\n *\n * You could also use the `getAdvanceNonceAccountInstruction` method of `@solana-program/system`.\n */\nexport function createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n>(\n nonceAccountAddress: Address,\n nonceAuthorityAddress: Address,\n): AdvanceNonceAccountInstruction {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\n/**\n * A type guard that returns `true` if the instruction conforms to the\n * {@link AdvanceNonceAccountInstruction} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAdvanceNonceAccountInstruction } from '@solana/transaction-messages';\n *\n * if (isAdvanceNonceAccountInstruction(message.instructions[0])) {\n * // At this point, the first instruction in the message has been refined to a\n * // `AdvanceNonceAccountInstruction`.\n * setNonceAccountAddress(message.instructions[0].accounts[0].address);\n * } else {\n * setError('The first instruction is not an `AdvanceNonce` instruction');\n * }\n * ```\n */\nexport function isAdvanceNonceAccountInstruction(\n instruction: Instruction,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SolanaError } from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nimport {\n AdvanceNonceAccountInstruction,\n createAdvanceNonceAccountInstruction,\n isAdvanceNonceAccountInstruction,\n} from './durable-nonce-instruction';\nimport { ExcludeTransactionMessageLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = Readonly<{\n readonly nonce: Nonce;\n readonly nonceAccountAddress: Address;\n readonly nonceAuthorityAddress: Address;\n}>;\n\n/** Represents a string that is particularly known to be the base58-encoded value of a nonce. */\nexport type Nonce = Brand;\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network.\n *\n * The transaction message will continue to be eligible to land until the network considers the\n * `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is\n * destroyed, or the nonce value within changes.\n */\nexport type NonceLifetimeConstraint = Readonly<{\n /**\n * A value contained in the related nonce account at the time the transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the value of a nonce it includes.\n *\n * Such a transaction can only be landed on the network if the nonce is known to the network and has\n * not already been used to land a different transaction.\n */\nexport interface TransactionMessageWithDurableNonceLifetime<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n}\n\n/**\n * A helper type to exclude the durable nonce lifetime constraint from a transaction message.\n */\nexport type ExcludeTransactionMessageDurableNonceLifetime =\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? ExcludeTransactionMessageLifetime\n : TTransactionMessage;\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionMessageWithDurableNonceLifetime(message)) {\n * // At this point, `message` has been refined to a\n * // `TransactionMessageWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.nonce === 'string' &&\n transactionMessage.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transactionMessage.instructions[0])\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * nonce-based lifetime, from an untrusted network API or user input. Use this function to assert\n * that such a transaction message actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithDurableNonceLifetime`.\n * assertIsTransactionMessageWithDurableNonceLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `message` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n if (!isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address,\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\n/**\n * Given a nonce, the account where the value of the nonce is stored, and the address of the account\n * authorized to consume that nonce, this method will return a new transaction having the same type\n * as the one supplied plus the {@link TransactionMessageWithDurableNonceLifetime} type.\n *\n * In particular, this method _prepends_ an instruction to the transaction message designed to\n * consume (or 'advance') the nonce in the same transaction whose lifetime is defined by it.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/transaction-messages';\n * import { fetchNonce } from '@solana-program/system';\n *\n * const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ');\n * const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT');\n *\n * const {\n * data: { blockhash },\n * } = await fetchNonce(rpc, nonceAccountAddress);\n * const nonce = blockhash as string as Nonce;\n *\n * const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce(\n * { nonce, nonceAccountAddress, nonceAuthorityAddress },\n * tx,\n * );\n * ```\n */\nexport function setTransactionMessageLifetimeUsingDurableNonce<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig,\n transactionMessage: TTransactionMessage,\n): SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n> {\n type ReturnType = SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n >;\n\n let newInstructions: [\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n\n const firstInstruction = transactionMessage.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (\n isTransactionMessageWithDurableNonceLifetime(transactionMessage) &&\n transactionMessage.lifetimeConstraint.nonce === nonce\n ) {\n return transactionMessage as unknown as ReturnType;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transactionMessage.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions,\n ];\n }\n\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze(newInstructions),\n lifetimeConstraint: Object.freeze({ nonce }),\n }) as unknown as ReturnType;\n}\n\n/**\n * Helper type that transforms a given transaction message type into a new one that has the\n * `AdvanceNonceAccount` instruction as the first instruction and a lifetime constraint\n * representing the nonce value.\n */\ntype SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = TTransactionMessage extends unknown\n ? Omit<\n // 1. The transaction message only grows in size if it currently has a different (or no) lifetime.\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? TTransactionMessage\n : ExcludeTransactionMessageWithinSizeLimit,\n // 2. Remove the instructions array as we are going to replace it with a new one.\n 'instructions'\n > & {\n // 3. Replace or prepend the first instruction with the advance nonce account instruction.\n readonly instructions: TTransactionMessage['instructions'] extends readonly [\n AdvanceNonceAccountInstruction,\n ...infer TTail extends readonly Instruction[],\n ]\n ? readonly [AdvanceNonceAccountInstruction, ...TTail]\n : readonly [\n AdvanceNonceAccountInstruction,\n ...TTransactionMessage['instructions'],\n ];\n // 4. Set the lifetime constraint to the nonce value.\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n }\n : never;\n","import { Address } from '@solana/addresses';\n\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * Represents a transaction message for which a fee payer has been declared. A transaction must\n * conform to this type to be compiled and landed on the network.\n */\nexport interface TransactionMessageWithFeePayer {\n readonly feePayer: Readonly<{ address: Address }>;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Given a base58-encoded address of a system account, this method will return a new transaction\n * message having the same type as the one supplied plus the {@link TransactionMessageWithFeePayer}\n * type.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const myAddress = address('mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu');\n * const txPaidByMe = setTransactionMessageFeePayer(myAddress, tx);\n * ```\n */\nexport function setTransactionMessageFeePayer<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n feePayer: Address,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayer {\n if (\n 'feePayer' in transactionMessage &&\n feePayer === transactionMessage.feePayer?.address &&\n isAddressOnlyFeePayer(transactionMessage.feePayer)\n ) {\n return transactionMessage as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n }\n const out = {\n ...transactionMessage,\n feePayer: Object.freeze({ address: feePayer }),\n };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n}\n\nfunction isAddressOnlyFeePayer(\n feePayer: Partial['feePayer'],\n): feePayer is { address: Address } {\n return (\n !!feePayer &&\n 'address' in feePayer &&\n typeof feePayer.address === 'string' &&\n Object.keys(feePayer).length === 1\n );\n}\n","import { Instruction } from '@solana/instructions';\n\nimport { ExcludeTransactionMessageDurableNonceLifetime } from './durable-nonce';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype AppendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit, 'instructions'> & {\n readonly instructions: readonly [...TTransactionMessage['instructions'], ...TInstructions];\n }\n : never;\n\n/**\n * A helper type to prepend instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype PrependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit<\n ExcludeTransactionMessageWithinSizeLimit>,\n 'instructions'\n > & {\n readonly instructions: readonly [...TInstructions, ...TTransactionMessage['instructions']];\n }\n : never;\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstructions} if you need to append multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { appendTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransactionMessage = appendTransactionMessageInstruction(\n * {\n * data: getUtf8Encoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * transactionMessage,\n * );\n * ```\n */\nexport function appendTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return appendTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstruction} if you only need to append one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { appendTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = appendTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function appendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze([\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ...instructions,\n ] as readonly [...TTransactionMessage['instructions'], ...TInstructions]),\n }) as AppendTransactionMessageInstructions;\n}\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstructions} if you need to prepend multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstruction(\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return prependTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstruction} if you only need to prepend one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return Object.freeze({\n ...(transactionMessage as ExcludeTransactionMessageDurableNonceLifetime),\n instructions: Object.freeze([\n ...instructions,\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ] as readonly [...TInstructions, ...TTransactionMessage['instructions']]),\n }) as unknown as PrependTransactionMessageInstructions;\n}\n","import { Address, assertIsAddress } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\nimport { pipe } from '@solana/functional';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport type { Blockhash } from '@solana/rpc-types';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BlockhashLifetimeConstraint, setTransactionMessageLifetimeUsingBlockhash } from './blockhash';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from './compile';\nimport type { getCompiledAddressTableLookups } from './compile/address-table-lookups';\nimport { createTransactionMessage } from './create-transaction-message';\nimport { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from './durable-nonce';\nimport { isAdvanceNonceAccountInstruction } from './durable-nonce-instruction';\nimport { setTransactionMessageFeePayer, TransactionMessageWithFeePayer } from './fee-payer';\nimport { appendTransactionMessageInstruction } from './instructions';\nimport { TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage, TransactionVersion } from './transaction-message';\n\nfunction getAccountMetas(message: CompiledTransactionMessage): AccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: AccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction getAddressLookupMetas(\n compiledAddressTableLookups: ReturnType,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta[] {\n // check that all message lookups are known\n const compiledAddressTableLookupAddresses = compiledAddressTableLookups.map(l => l.lookupTableAddress);\n const missing = compiledAddressTableLookupAddresses.filter(a => addressesByLookupTableAddress[a] === undefined);\n if (missing.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, {\n lookupTableAddresses: missing,\n });\n }\n\n const readOnlyMetas: AccountLookupMeta[] = [];\n const writableMetas: AccountLookupMeta[] = [];\n\n // we know that for each lookup, knownLookups[lookup.lookupTableAddress] is defined\n for (const lookup of compiledAddressTableLookups) {\n const addresses = addressesByLookupTableAddress[lookup.lookupTableAddress];\n const readonlyIndexes = lookup.readonlyIndexes;\n const writableIndexes = lookup.writableIndexes;\n\n const highestIndex = Math.max(...readonlyIndexes, ...writableIndexes);\n if (highestIndex >= addresses.length) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n {\n highestKnownIndex: addresses.length - 1,\n highestRequestedIndex: highestIndex,\n lookupTableAddress: lookup.lookupTableAddress,\n },\n );\n }\n\n const readOnlyForLookup: AccountLookupMeta[] = readonlyIndexes.map(r => ({\n address: addresses[r],\n addressIndex: r,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.READONLY,\n }));\n readOnlyMetas.push(...readOnlyForLookup);\n\n const writableForLookup: AccountLookupMeta[] = writableIndexes.map(w => ({\n address: addresses[w],\n addressIndex: w,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.WRITABLE,\n }));\n writableMetas.push(...writableForLookup);\n }\n\n return [...writableMetas, ...readOnlyMetas];\n}\n\nfunction convertInstruction(\n instruction: CompiledTransactionMessage['instructions'][0],\n accountMetas: AccountMeta[],\n): Instruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, {\n index: instruction.programAddressIndex,\n });\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return Object.freeze({\n programAddress,\n ...(accounts && accounts.length ? { accounts: Object.freeze(accounts) } : {}),\n ...(data && data.length ? { data } : {}),\n });\n}\n\ntype LifetimeConstraint =\n | BlockhashLifetimeConstraint\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: Instruction,\n lastValidBlockHeight?: bigint,\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts[0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts[2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nexport type DecompileTransactionMessageConfig = {\n /**\n * If the compiled message loads addresses from one or more address lookup tables, you will have\n * to supply a map of those tables to an array of the addresses they contained at the time that\n * the transaction message was constructed.\n *\n * @see {@link decompileTransactionMessageFetchingLookupTables} if you do not already have this.\n */\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n /**\n * If the compiled message has a blockhash-based lifetime constraint, you will have to supply\n * the block height after which that blockhash is no longer valid for use as a lifetime\n * constraint.\n */\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Converts the type of transaction message data structure appropriate for execution on the network\n * to the type of transaction message data structure designed for use in your application.\n *\n * Because compilation is a lossy process, you can not fully reconstruct a source message from a\n * compiled message without extra information. In order to faithfully reconstruct the original\n * source message you will need to supply supporting details about the lifetime constraint and the\n * concrete addresses of any accounts sourced from account lookup tables.\n *\n * @see {@link compileTransactionMessage}\n */\nexport function decompileTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n config?: DecompileTransactionMessageConfig,\n): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime {\n const feePayer = compiledTransactionMessage.staticAccounts[0];\n if (!feePayer) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING);\n }\n\n const accountMetas = getAccountMetas(compiledTransactionMessage);\n const accountLookupMetas =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? getAddressLookupMetas(\n compiledTransactionMessage.addressTableLookups,\n config?.addressesByLookupTableAddress ?? {},\n )\n : [];\n const transactionMetas = [...accountMetas, ...accountLookupMetas];\n\n const instructions: Instruction[] = compiledTransactionMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, transactionMetas),\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledTransactionMessage.lifetimeToken,\n firstInstruction,\n config?.lastValidBlockHeight,\n );\n\n return pipe(\n createTransactionMessage({ version: compiledTransactionMessage.version as TransactionVersion }),\n m => setTransactionMessageFeePayer(feePayer, m),\n m =>\n instructions.reduce(\n (acc, instruction) => appendTransactionMessageInstruction(instruction, acc),\n m as TransactionMessage,\n ),\n m =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionMessageLifetimeUsingBlockhash(lifetimeConstraint, m)\n : setTransactionMessageLifetimeUsingDurableNonce(lifetimeConstraint, m),\n ) as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime;\n}\n","export const ED25519_ALGORITHM_IDENTIFIER =\n // Resist the temptation to convert this to a simple string; As of version 133.0.3, Firefox\n // requires the object form of `AlgorithmIdentifier` and will throw a `DOMException` otherwise.\n Object.freeze({ name: 'Ed25519' });\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\nfunction addPkcs8Header(bytes: ReadonlyUint8Array): ReadonlyUint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 private key for use\n * with other methods in this package that accept\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]));\n * const extractablePrivateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n * ```\n */\nexport async function createPrivateKeyFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const actualLength = bytes.byteLength;\n if (actualLength !== 32) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, {\n actualLength,\n });\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, ED25519_ALGORITHM_IDENTIFIER, extractable, [\n 'sign',\n ]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SolanaError } from '@solana/errors';\n\n/**\n * Given an extractable [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * private key, gets the corresponding public key as a\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey).\n *\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the public\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes, getPublicKeyFromPrivateKey } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n *\n * const publicKey = await getPublicKeyFromPrivateKey(privateKey);\n * const extractablePublicKey = await getPublicKeyFromPrivateKey(privateKey, true);\n * ```\n */\nexport async function getPublicKeyFromPrivateKey(\n privateKey: CryptoKey,\n extractable: boolean = false,\n): Promise {\n assertKeyExporterIsAvailable();\n\n if (privateKey.extractable === false) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, { key: privateKey });\n }\n\n // Export private key.\n const jwk = await crypto.subtle.exportKey('jwk', privateKey);\n\n // Import public key.\n return await crypto.subtle.importKey(\n 'jwk',\n {\n crv /* curve */: 'Ed25519',\n ext /* extractable */: extractable,\n key_ops /* key operations */: ['verify'],\n kty /* key type */: 'OKP' /* octet key pair */,\n x /* public key x-coordinate */: jwk.x,\n },\n 'Ed25519',\n extractable,\n ['verify'],\n );\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder, ReadonlyUint8Array, toArrayBuffer } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\n/**\n * A 64-byte Ed25519 signature as a base58-encoded string.\n */\nexport type Signature = Brand, 'Signature'>;\n/**\n * A 64-byte Ed25519 signature.\n *\n * Whenever you need to verify that a particular signature is, in fact, the one that would have been\n * produced by signing some known bytes using the private key associated with some known public key,\n * use the {@link verifySignature} function in this package.\n */\nexport type SignatureBytes = Brand;\n\nlet base58Encoder: Encoder | undefined;\n\n/**\n * Asserts that an arbitrary string is a base58-encoded Ed25519 signature.\n *\n * Useful when you receive a string from user input or an untrusted network API that you expect to\n * represent an Ed25519 signature (eg. of a transaction).\n *\n * @example\n * ```ts\n * import { assertIsSignature } from '@solana/keys';\n *\n * // Imagine a function that asserts whether a user-supplied signature is valid or not.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const signature: string = signatureInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signature` to `Signature`.\n * assertIsSignature(signature);\n * // At this point, `signature` is a `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * } catch (e) {\n * // `signature` turned out not to be a base58-encoded signature\n * }\n * }\n * ```\n */\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeSignature.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n assertIsSignatureBytes(bytes);\n}\n\n/**\n * Asserts that an arbitrary `ReadonlyUint8Array` is an Ed25519 signature.\n *\n * Useful when you receive a `ReadonlyUint8Array` from an external interface (like the browser wallets' `signMessage` API) that you expect to\n * represent an Ed25519 signature.\n *\n * @example\n * ```ts\n * import { assertIsSignatureBytes } from '@solana/keys';\n *\n * // Imagine a function that verifies a signature.\n * function verifySignature() {\n * // We know only that the input conforms to the `ReadonlyUint8Array` type.\n * const signatureBytes: ReadonlyUint8Array = signatureBytesInput;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signatureBytes` to `SignatureBytes`.\n * assertIsSignatureBytes(signatureBytes);\n * // At this point, `signatureBytes` is a `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } catch (e) {\n * // `signatureBytes` turned out not to be a 64-byte Ed25519 signature\n * }\n * }\n * ```\n */\nexport function assertIsSignatureBytes(\n putativeSignatureBytes: ReadonlyUint8Array,\n): asserts putativeSignatureBytes is SignatureBytes {\n const numBytes = putativeSignatureBytes.byteLength;\n if (numBytes !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * A type guard that accepts a string as input. It will both return `true` if the string conforms to\n * the {@link Signature} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignature } from '@solana/keys';\n *\n * if (isSignature(signature)) {\n * // At this point, `signature` has been refined to a\n * // `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * setSignatureStatus(status);\n * } else {\n * setError(`${signature} is not a transaction signature`);\n * }\n * ```\n */\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n return isSignatureBytes(bytes);\n}\n\n/**\n * A type guard that accepts a `ReadonlyUint8Array` as input. It will both return `true` if the `ReadonlyUint8Array` conforms to\n * the {@link SignatureBytes} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignatureBytes } from '@solana/keys';\n *\n * if (isSignatureBytes(signatureBytes)) {\n * // At this point, `signatureBytes` has been refined to a\n * // `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } else {\n * setError(`${signatureBytes} is not a 64-byte Ed25519 signature`);\n * }\n * ```\n */\nexport function isSignatureBytes(putativeSignatureBytes: ReadonlyUint8Array): putativeSignatureBytes is SignatureBytes {\n return putativeSignatureBytes.byteLength === 64;\n}\n\n/**\n * Given a private [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and a\n * `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a\n * `Uint8Array`.\n *\n * @example\n * ```ts\n * import { signBytes } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * const signature = await signBytes(privateKey, data);\n * ```\n */\nexport async function signBytes(key: CryptoKey, data: ReadonlyUint8Array): Promise {\n assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(data));\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\n/**\n * This helper combines _asserting_ that a string is an Ed25519 signature with _coercing_ it to the\n * {@link Signature} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signature } from '@solana/keys';\n *\n * const signature = signature(userSuppliedSignature);\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * ```\n */\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\n/**\n * This helper combines _asserting_ that a `ReadonlyUint8Array` is an Ed25519 signature with _coercing_ it to the\n * {@link SignatureBytes} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signatureBytes } from '@solana/keys';\n *\n * const signature = signatureBytes(userSuppliedSignatureBytes);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport function signatureBytes(putativeSignatureBytes: ReadonlyUint8Array): SignatureBytes {\n assertIsSignatureBytes(putativeSignatureBytes);\n return putativeSignatureBytes;\n}\n\n/**\n * Given a public [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), some\n * {@link SignatureBytes}, and a `Uint8Array` of data, this method will return `true` if the\n * signature was produced by signing the data using the private key associated with the public key,\n * and `false` otherwise.\n *\n * @example\n * ```ts\n * import { verifySignature } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport async function verifySignature(\n key: CryptoKey,\n signature: SignatureBytes,\n data: ReadonlyUint8Array,\n): Promise {\n assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(signature), toArrayBuffer(data));\n}\n","import { assertKeyGenerationIsAvailable, assertPRNGIsAvailable } from '@solana/assertions';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SolanaError,\n} from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\nimport { createPrivateKeyFromBytes } from './private-key';\nimport { getPublicKeyFromPrivateKey } from './public-key';\nimport { signBytes, verifySignature } from './signatures';\n\n/**\n * Generates an Ed25519 public/private key pair for use with other methods in this package that\n * accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await generateKeyPair();\n * ```\n */\nexport async function generateKeyPair(): Promise {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ ED25519_ALGORITHM_IDENTIFIER, // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify'],\n );\n return keyPair;\n}\n\n/**\n * Given a 64-byte `Uint8Array` secret key, creates an Ed25519 public/private key pair for use with\n * other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 64 bytes, the first 32 of which represent the private key and the last 32 of which\n * represent its associated public key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairFromBytes } from '@solana/keys';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a CryptoKeyPair from the bytes.\n * const { privateKey, publicKey } = await createKeyPairFromBytes(keypairBytes);\n * ```\n */\nexport async function createKeyPairFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n assertPRNGIsAvailable();\n\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), ED25519_ALGORITHM_IDENTIFIER, /* extractable */ true, [\n 'verify',\n ]),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n\n // Verify the key pair\n const randomBytes = new Uint8Array(32);\n crypto.getRandomValues(randomBytes);\n const signedData = await signBytes(privateKey, randomBytes);\n const isValid = await verifySignature(publicKey, signedData, randomBytes);\n if (!isValid) {\n throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);\n }\n\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 public/private key\n * pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await createKeyPairFromPrivateKeyBytes(new Uint8Array([...]));\n * ```\n *\n * This can be useful when you have a private key but not the corresponding public key or when you\n * need to derive key pairs from seeds. For instance, the following code snippet derives a key pair\n * from the hash of a message.\n *\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedKeypair = await createKeyPairFromPrivateKeyBytes(seed);\n * ```\n */\nexport async function createKeyPairFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const privateKeyPromise = createPrivateKeyFromBytes(bytes, extractable);\n\n // Here we need the private key to be extractable in order to export\n // it as a public key. Therefore, if the `extractable` parameter\n // is `false`, we need to create two private keys such that:\n // - The extractable one is used to create the public key and\n // - The non-extractable one is the one we will return.\n const [publicKey, privateKey] = await Promise.all([\n // This nested promise makes things efficient by\n // creating the public key in parallel with the\n // second private key creation, if it is needed.\n (extractable ? privateKeyPromise : createPrivateKeyFromBytes(bytes, true /* extractable */)).then(\n async privateKey => await getPublicKeyFromPrivateKey(privateKey, true /* extractable */),\n ),\n privateKeyPromise,\n ]);\n\n return { privateKey, publicKey };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { SignaturesMap } from '../transaction';\n\nfunction getSignaturesToEncode(signaturesMap: SignaturesMap): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { getAddressDecoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n padRightDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { getTransactionVersionDecoder } from '@solana/transaction-messages';\n\nimport { SignaturesMap, Transaction, TransactionMessageBytes } from '../transaction';\nimport { getSignaturesEncoder } from './signatures-encoder';\n\n/**\n * Returns an encoder that you can use to encode a {@link Transaction} to a byte array in a wire\n * format appropriate for sending to the Solana network for execution.\n */\nexport function getTransactionEncoder(): VariableSizeEncoder {\n return getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['messageBytes', getBytesEncoder()],\n ]);\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana transaction wire format\n * to a {@link Transaction} object.\n *\n * @example\n * ```ts\n * import { getTransactionDecoder } from '@solana/transactions';\n *\n * const transactionDecoder = getTransactionDecoder();\n * const transaction = transactionDecoder.decode(wireTransactionBytes);\n * for (const [address, signature] in Object.entries(transaction.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\n\nexport function getTransactionDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getShortU16Decoder() })],\n ['messageBytes', getBytesDecoder()],\n ]),\n decodePartiallyDecodedTransaction,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a {@link Transaction}\n *\n * @see {@link getTransactionDecoder}\n * @see {@link getTransactionEncoder}\n */\nexport function getTransactionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder());\n}\n\ntype PartiallyDecodedTransaction = {\n messageBytes: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedTransaction(transaction: PartiallyDecodedTransaction): Transaction {\n const { messageBytes, signatures } = transaction;\n\n /*\n Relevant message structure is at the start:\n - transaction version (0 bytes for legacy transactions, 1 byte for versioned transactions)\n - `numRequiredSignatures` (1 byte, we verify this matches the length of signatures)\n - `numReadOnlySignedAccounts` (1 byte, not used here)\n - `numReadOnlyUnsignedAccounts` (1 byte, not used here)\n - static addresses, with signers first. This is an array of addresses, prefixed with a short-u16 length\n */\n\n const signerAddressesDecoder = getTupleDecoder([\n // read transaction version\n getTransactionVersionDecoder(),\n // read first byte of header, `numSignerAccounts`\n // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need\n padRightDecoder(getU8Decoder(), 2),\n // read static addresses\n getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() }),\n ]);\n const [_txVersion, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);\n\n const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);\n\n // signer addresses and signatures must be the same length\n // we encode an all-zero signature when the signature is missing\n if (signerAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, {\n numRequiredSignatures,\n signaturesLength: signatures.length,\n signerAddresses,\n });\n }\n\n // combine the signer addresses + signatures into the signatures map\n const signaturesMap: SignaturesMap = {};\n signerAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return {\n messageBytes: messageBytes as TransactionMessageBytes,\n signatures: Object.freeze(signaturesMap),\n };\n}\n","import { type Address, isAddress } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SolanaError,\n} from '@solana/errors';\nimport { type Blockhash, isBlockhash, type Slot } from '@solana/rpc-types';\nimport type {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n Nonce,\n TransactionMessage,\n TransactionMessageWithBlockhashLifetime,\n TransactionMessageWithDurableNonceLifetime,\n} from '@solana/transaction-messages';\n\nimport type { Transaction } from './transaction';\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network. The transaction will continue to be eligible to land until the network considers the\n * `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type TransactionBlockhashLifetime = {\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction eligible to land.\n */\n lastValidBlockHeight: Slot;\n};\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionDurableNonceLifetime = {\n /**\n * A value contained in the account with address `nonceAccountAddress` at the time the\n * transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n /** The account that contains the `nonce` value */\n nonceAccountAddress: Address;\n};\n\n/**\n * A transaction whose ability to land on the network is determined by some evanescent criteria.\n *\n * This describes a window of time after which a transaction is constructed and before which it will\n * no longer be accepted by the network.\n *\n * No transaction can land on Solana without having a `lifetimeConstraint` set.\n */\nexport type TransactionWithLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime | TransactionDurableNonceLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by the age of a blockhash observed on the network.\n *\n * The transaction will continue to be eligible to land until the network considers the `blockhash`\n * to be expired.\n */\nexport type TransactionWithBlockhashLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by a nonce.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionWithDurableNonceLifetime = {\n readonly lifetimeConstraint: TransactionDurableNonceLifetime;\n};\n\n/**\n * Helper type that sets the lifetime constraint of a transaction to be the same as the\n * lifetime constraint of the provided transaction message.\n *\n * If the transaction message has no explicit lifetime constraint, neither will the transaction.\n */\nexport type SetTransactionLifetimeFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends TransactionMessage,\n> = TTransactionMessage extends { lifetimeConstraint: unknown }\n ? TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithBlockhashLifetime['lifetimeConstraint']\n ? TransactionWithBlockhashLifetime & TTransaction\n : TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithDurableNonceLifetime['lifetimeConstraint']\n ? TransactionWithDurableNonceLifetime & TTransaction\n : TransactionWithLifetime & TTransaction\n : TTransaction;\n\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address;\n\nfunction compiledInstructionIsAdvanceNonceInstruction(\n instruction: CompiledTransactionMessage['instructions'][number],\n staticAddresses: Address[],\n): instruction is typeof instruction & { accountIndices: [number, number, number] } {\n return (\n staticAddresses[instruction.programAddressIndex] === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accountIndices?.length === 3\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): boolean {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\n/**\n * Get the lifetime constraint for a transaction from a compiled transaction message that includes a lifetime token.\n * @param compiledTransactionMessage A compiled transaction message that includes a lifetime token\n * @returns A lifetime constraint for the transaction\n * Note that this is less precise than checking a decompiled instruction, as we can't inspect\n * the address or role of input accounts (which may be in lookup tables). However, this is\n * sufficient for all valid advance durable nonce instructions.\n * Note that the program address must not be in a lookup table, see [this answer on StackExchange](https://solana.stackexchange.com/a/16224/289)\n * @see {@link isAdvanceNonceAccountInstruction}\n * Note that this function is async to allow for future implementations that may fetch `lastValidBlockHeight` using an RPC\n */\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function getTransactionLifetimeConstraintFromCompiledTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n): Promise {\n const firstInstruction = compiledTransactionMessage.instructions[0];\n const { staticAccounts } = compiledTransactionMessage;\n\n // We need to check if the first instruction is an AdvanceNonceAccount instruction\n if (firstInstruction && compiledInstructionIsAdvanceNonceInstruction(firstInstruction, staticAccounts)) {\n const nonceAccountAddress = staticAccounts[firstInstruction.accountIndices[0]];\n if (!nonceAccountAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, {\n nonce: compiledTransactionMessage.lifetimeToken,\n });\n }\n return {\n nonce: compiledTransactionMessage.lifetimeToken as Nonce,\n nonceAccountAddress,\n };\n } else {\n return {\n blockhash: compiledTransactionMessage.lifetimeToken as Blockhash,\n // This is not known from the compiled message, so we set it to the maximum possible value\n lastValidBlockHeight: 0xffffffffffffffffn,\n };\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * if (isTransactionWithBlockhashLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a `TransactionWithBlockhashLifetime`.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'blockhash' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.blockhash === 'string' &&\n typeof transaction.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transaction.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * blockhash-based lifetime, from for example a wallet. Use this function to\n * assert that such a transaction actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithBlockhashLifetime`.\n * assertIsTransactionWithBlockhashLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `transaction` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithBlockhashLifetime {\n if (!isTransactionWithBlockhashLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithDurableNonceLifetime } from '@solana/transactions';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionWithDurableNonceLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a\n * // `TransactionWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'nonce' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n typeof transaction.lifetimeConstraint.nonceAccountAddress === 'string' &&\n isAddress(transaction.lifetimeConstraint.nonceAccountAddress)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * nonce-based lifetime, from for example a wallet. Use this function to assert\n * that such a transaction actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithDurableNonceLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithDurableNonceLifetime`.\n * assertIsTransactionWithDurableNonceLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `transaction` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithDurableNonceLifetime {\n if (!isTransactionWithDurableNonceLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n","import {\n compileTransactionMessage,\n getCompiledTransactionMessageEncoder,\n isTransactionMessageWithBlockhashLifetime,\n isTransactionMessageWithDurableNonceLifetime,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport type { TransactionWithLifetime } from './lifetime';\nimport type { SignaturesMap, TransactionFromTransactionMessage, TransactionMessageBytes } from './transaction';\n\n/**\n * Returns a {@link Transaction} object for a given {@link TransactionMessage}.\n *\n * This includes the compiled bytes of the transaction message, and a map of signatures. This map\n * will have a key for each address that is required to sign the transaction. The transaction will\n * not yet have signatures for any of these addresses.\n *\n * Whether a transaction message is ready to be compiled or not is enforced for you at the type\n * level. In order to be signable, a transaction message must:\n *\n * - have a version and a list of zero or more instructions (ie. conform to\n * {@link TransactionMessage})\n * - have a fee payer set (ie. conform to {@link TransactionMessageWithFeePayer})\n * - have a lifetime specified (ie. conform to {@link TransactionMessageWithBlockhashLifetime} or\n * {@link TransactionMessageWithDurableNonceLifetime})\n */\nexport function compileTransaction(\n transactionMessage: TTransactionMessage,\n): Readonly> {\n type ReturnType = Readonly>;\n\n const compiledMessage = compileTransactionMessage(transactionMessage);\n const messageBytes = getCompiledTransactionMessageEncoder().encode(compiledMessage) as TransactionMessageBytes;\n\n const transactionSigners = compiledMessage.staticAccounts.slice(0, compiledMessage.header.numSignerAccounts);\n const signatures: SignaturesMap = {};\n for (const signerAddress of transactionSigners) {\n signatures[signerAddress] = null;\n }\n\n let lifetimeConstraint: TransactionWithLifetime['lifetimeConstraint'] | undefined;\n if (isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n lifetimeConstraint = {\n blockhash: transactionMessage.lifetimeConstraint.blockhash,\n lastValidBlockHeight: transactionMessage.lifetimeConstraint.lastValidBlockHeight,\n };\n } else if (isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n lifetimeConstraint = {\n nonce: transactionMessage.lifetimeConstraint.nonce,\n nonceAccountAddress: transactionMessage.instructions[0].accounts[0].address,\n };\n }\n\n return Object.freeze({\n ...(lifetimeConstraint ? { lifetimeConstraint } : undefined),\n messageBytes: messageBytes,\n signatures: Object.freeze(signatures),\n }) as ReturnType;\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { bytesEqual, Decoder } from '@solana/codecs-core';\nimport { getBase58Decoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Signature, SignatureBytes, signBytes } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { Transaction } from './transaction';\n\n/**\n * Represents a transaction that is signed by all of its required signers. Being fully signed is a\n * prerequisite of functions designed to land transactions on the network.\n */\nexport type FullySignedTransaction = NominalType<'transactionSignedness', 'fullySigned'>;\n\nlet base58Decoder: Decoder | undefined;\n\n/**\n * Given a transaction signed by its fee payer, this method will return the {@link Signature} that\n * uniquely identifies it. This string can be used to look up transactions at a later date, for\n * example on a Solana block explorer.\n *\n * @example\n * ```ts\n * import { getSignatureFromTransaction } from '@solana/transactions';\n *\n * const signature = getSignatureFromTransaction(tx);\n * console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`);\n * ```\n */\nexport function getSignatureFromTransaction(transaction: Transaction): Signature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n // We have ordered signatures from the compiled message accounts\n // first signature is the fee payer\n const signatureBytes = Object.values(transaction.signatures)[0];\n if (!signatureBytes) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);\n }\n const transactionSignature = base58Decoder.decode(signatureBytes);\n return transactionSignature as Signature;\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link Transaction}.\n *\n * Though the resulting transaction might have every signature it needs to land on the network, this\n * function will not assert that it does. A partially signed transaction cannot be landed on the\n * network, but can be serialized and deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignTransaction } from '@solana/transactions';\n *\n * const partiallySignedTransaction = await partiallySignTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link signTransaction} if you want to assert that the transaction has all of its required\n * signatures after signing.\n */\nexport async function partiallySignTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const existingSignature = transaction.signatures[address];\n\n // Check if the address is expected to sign the transaction\n if (existingSignature === undefined) {\n // address is not an expected signer for this transaction\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);\n\n if (existingSignature !== null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n const expectedSigners = Object.keys(transaction.signatures);\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {\n expectedAddresses: expectedSigners,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return transaction;\n }\n\n return Object.freeze({\n ...transaction,\n signatures: Object.freeze({\n ...transaction.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link FullySignedTransaction}.\n *\n * This function will throw unless the resulting transaction is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signTransaction } from '@solana/transactions';\n *\n * const signedTransaction = await signTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link partiallySignTransaction} if you want to sign the transaction without asserting that\n * the resulting transaction is fully signed.\n */\nexport async function signTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertIsFullySignedTransaction(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * Checks whether a given {@link Transaction} is fully signed.\n *\n * @example\n * ```ts\n * import { isFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isFullySignedTransaction(transaction)) {\n * // At this point we know that the transaction is signed and can be sent to the network.\n * }\n * ```\n */\nexport function isFullySignedTransaction(\n transaction: TTransaction,\n): transaction is FullySignedTransaction & TTransaction {\n return Object.entries(transaction.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link Transaction}, that you expect to be fully signed,\n * from an untrusted network API or user input. Use this function to assert that such a transaction\n * is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `FullySignedTransaction`.\n * assertIsFullySignedTransaction(transaction);\n * // At this point we know that the transaction is signed and can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsFullySignedTransaction(\n transaction: TTransaction,\n): asserts transaction is FullySignedTransaction & TTransaction {\n const missingSigs: Address[] = [];\n Object.entries(transaction.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n","import { getBase64Decoder } from '@solana/codecs-strings';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/** Represents the wire format of a transaction as a base64-encoded string. */\nexport type Base64EncodedWireTransaction = Brand, 'Base64EncodedWireTransaction'>;\n\n/**\n * Given a signed transaction, this method returns the transaction as a string that conforms to the\n * {@link Base64EncodedWireTransaction} type.\n *\n * @example\n * ```ts\n * import { getBase64EncodedWireTransaction, signTransaction } from '@solana/transactions';\n *\n * const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send();\n * ```\n */\nexport function getBase64EncodedWireTransaction(transaction: Transaction): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes) as Base64EncodedWireTransaction;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type { NominalType } from '@solana/nominal-types';\nimport type { BaseTransactionMessage, TransactionMessageWithinSizeLimit } from '@solana/transaction-messages';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/**\n * The maximum size of a transaction packet in bytes.\n */\nexport const TRANSACTION_PACKET_SIZE = 1280;\n\n/**\n * The size of the transaction packet header in bytes.\n * This includes the IPv6 header and the fragment header.\n */\nexport const TRANSACTION_PACKET_HEADER =\n 40 /* 40 bytes is the size of the IPv6 header. */ + 8; /* 8 bytes is the size of the fragment header. */\n\n/**\n * The maximum size of a transaction in bytes.\n *\n * Note that this excludes the transaction packet header.\n * In other words, this is how much content we can fit in a transaction packet.\n */\nexport const TRANSACTION_SIZE_LIMIT = TRANSACTION_PACKET_SIZE - TRANSACTION_PACKET_HEADER;\n\n/**\n * Gets the size of a given transaction in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionSize(transaction);\n * ```\n */\nexport function getTransactionSize(transaction: Transaction): number {\n return getTransactionEncoder().getSizeFromValue(transaction);\n}\n\n/**\n * A type guard that checks if a transaction is within the size limit.\n */\nexport type TransactionWithinSizeLimit = NominalType<'transactionSize', 'withinLimit'>;\n\n/**\n * Helper type that adds the `TransactionWithinSizeLimit` flag to\n * a transaction if and only if the provided transaction message\n * is also within the size limit.\n */\nexport type SetTransactionWithinSizeLimitFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithinSizeLimit\n ? TransactionWithinSizeLimit & TTransaction\n : TTransaction;\n\n/**\n * Checks if a transaction is within the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * if (isTransactionWithinSizeLimit(transaction)) {\n * transaction satisfies TransactionWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionWithinSizeLimit(\n transaction: TTransaction,\n): transaction is TransactionWithinSizeLimit & TTransaction {\n return getTransactionSize(transaction) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction is within the size limit.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction exceeds the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * assertIsTransactionWithinSizeLimit(transaction);\n * transaction satisfies TransactionWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionWithinSizeLimit(\n transaction: TTransaction,\n): asserts transaction is TransactionWithinSizeLimit & TTransaction {\n const transactionSize = getTransactionSize(transaction);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","import { assertIsFullySignedTransaction, FullySignedTransaction, isFullySignedTransaction } from './signatures';\nimport { Transaction } from './transaction';\nimport {\n assertIsTransactionWithinSizeLimit,\n isTransactionWithinSizeLimit,\n TransactionWithinSizeLimit,\n} from './transaction-size';\n\n/**\n * Helper type that includes all transaction types required\n * for the transaction to be sent to the network.\n *\n * @see {@link isSendableTransaction}\n * @see {@link assertIsSendableTransaction}\n */\nexport type SendableTransaction = FullySignedTransaction & TransactionWithinSizeLimit;\n\n/**\n * Checks if a transaction has all the required\n * conditions to be sent to the network.\n *\n * @example\n * ```ts\n * import { isSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isSendableTransaction(transaction)) {\n * // At this point we know that the transaction can be sent to the network.\n * }\n * ```\n *\n * @see {@link assertIsSendableTransaction}\n */\nexport function isSendableTransaction(\n transaction: TTransaction,\n): transaction is SendableTransaction & TTransaction {\n return isFullySignedTransaction(transaction) && isTransactionWithinSizeLimit(transaction);\n}\n\n/**\n * Asserts that a given transaction has all the\n * required conditions to be sent to the network.\n *\n * From time to time you might acquire a {@link Transaction}\n * from an untrusted network API or user input and you are not sure\n * that it has all the required conditions to be sent to the network\n * — such as being fully signed and within the size limit.\n * This function can be used to assert that such a transaction\n * is in fact sendable.\n *\n * @example\n * ```ts\n * import { assertIsSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `SendableTransaction`.\n * assertIsSendableTransaction(transaction);\n * // At this point we know that the transaction can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT)) {\n * setError(`Transaction exceeds size limit of ${e.context.transactionSizeLimit} bytes`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsSendableTransaction(\n transaction: TTransaction,\n): asserts transaction is SendableTransaction & TTransaction {\n assertIsFullySignedTransaction(transaction);\n assertIsTransactionWithinSizeLimit(transaction);\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithinSizeLimit,\n} from '@solana/transaction-messages';\n\nimport { compileTransaction } from './compile-transaction';\nimport { getTransactionSize, TRANSACTION_SIZE_LIMIT } from './transaction-size';\n\n/**\n * Gets the compiled transaction size of a given transaction message in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionMessageSize(transactionMessage);\n * ```\n */\nexport function getTransactionMessageSize(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n): number {\n return getTransactionSize(compileTransaction(transactionMessage));\n}\n\n/**\n * Checks if a transaction message is within the size limit\n * when compiled into a transaction.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * if (isTransactionMessageWithinSizeLimit(transactionMessage)) {\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n return getTransactionMessageSize(transactionMessage) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction message is within the size limit\n * when compiled into a transaction.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction message exceeds the size limit.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * assertIsTransactionMessageWithinSizeLimit(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): asserts transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n const transactionSize = getTransactionMessageSize(transactionMessage);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","/**\n * Forked from https://github.com/digitalloggers/race-as-promised/tree/master\n *\n * Authored by Brian Kim:\n * https://github.com/nodejs/node/issues/17469#issuecomment-685216777\n *\n * Adapted to module structure.\n *\n * This is free and unencumbered software released into the public domain.\n *\n * Anyone is free to copy, modify, publish, use, compile, sell, or\n * distribute this software, either in source code form or as a compiled\n * binary, for any purpose, commercial or non-commercial, and by any\n * means.\n *\n * In jurisdictions that recognize copyright laws, the author or authors\n * of this software dedicate any and all copyright interest in the\n * software to the public domain. We make this dedication for the benefit\n * of the public at large and to the detriment of our heirs and\n * successors. We intend this dedication to be an overt act of\n * relinquishment in perpetuity of all present and future rights to this\n * software under copyright law.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * For more information, please refer to \n */\n\ntype Deferred = Readonly<{\n reject: (reason?: unknown) => void;\n resolve: (value: unknown) => void;\n}>;\n\nfunction isObject(value: unknown): value is object {\n return value !== null && (typeof value === 'object' || typeof value === 'function');\n}\n\nfunction addRaceContender(contender: object) {\n const deferreds = new Set();\n const record = { deferreds, settled: false };\n\n // This call to `then` happens once for the lifetime of the value.\n Promise.resolve(contender).then(\n value => {\n for (const { resolve } of deferreds) {\n resolve(value);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n err => {\n for (const { reject } of deferreds) {\n reject(err);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n );\n return record;\n}\n\n// Keys are the values passed to race, values are a record of data containing a\n// set of deferreds and whether the value has settled.\nconst wm = new WeakMap; settled: boolean }>();\n/**\n * An implementation of [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)\n * that causes all of the losing promises to settle. This allows them to be released and garbage\n * collected, preventing memory leaks.\n *\n * Read more here: https://github.com/nodejs/node/issues/17469\n */\nexport async function safeRace(contenders: T): Promise> {\n let deferred: Deferred;\n const result = new Promise((resolve, reject) => {\n deferred = { reject, resolve };\n for (const contender of contenders) {\n if (!isObject(contender)) {\n // If the contender is a primitive, attempting to use it as a key in the\n // weakmap would throw an error. Luckily, it is safe to call\n // `Promise.resolve(contender).then` on a primitive value multiple times\n // because the promise fulfills immediately.\n Promise.resolve(contender).then(resolve, reject);\n continue;\n }\n\n let record = wm.get(contender);\n if (record === undefined) {\n record = addRaceContender(contender);\n record.deferreds.add(deferred);\n wm.set(contender, record);\n } else if (record.settled) {\n // If the value has settled, it is safe to call\n // `Promise.resolve(contender).then` on it.\n Promise.resolve(contender).then(resolve, reject);\n } else {\n record.deferreds.add(deferred);\n }\n }\n });\n\n // The finally callback executes when any value settles, preventing any of\n // the unresolved values from retaining a reference to the resolved value.\n return await (result.finally(() => {\n for (const contender of contenders) {\n if (isObject(contender)) {\n const record = wm.get(contender)!;\n record.deferreds.delete(deferred);\n }\n }\n }) as Promise>);\n}\n","import { safeRace } from './race';\n\n/**\n * Returns a new promise that will reject if the abort signal fires before the original promise\n * settles. Resolves or rejects with the value of the original promise otherwise.\n *\n * @example\n * ```ts\n * const result = await getAbortablePromise(\n * // Resolves or rejects when `fetch` settles.\n * fetch('https://example.com/json').then(r => r.json()),\n * // ...unless it takes longer than 5 seconds, after which the `AbortSignal` is triggered.\n * AbortSignal.timeout(5000),\n * );\n * ```\n */\nexport function getAbortablePromise(promise: Promise, abortSignal?: AbortSignal): Promise {\n if (!abortSignal) {\n return promise;\n } else {\n return safeRace([\n // This promise only ever rejects if the signal is aborted. Otherwise it idles forever.\n // It's important that this come before the input promise; in the event of an abort, we\n // want to throw even if the input promise's result is ready\n new Promise((_, reject) => {\n if (abortSignal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(abortSignal.reason);\n } else {\n abortSignal.addEventListener('abort', function () {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n });\n }\n }),\n promise,\n ]);\n }\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SolanaError,\n} from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\n/**\n * A set of instructions with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans in order to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely the following plans are supported:\n * - {@link SingleInstructionPlan} - A plan that contains a single instruction.\n * This is a simple instruction wrapper and the simplest leaf in this tree.\n * - {@link ParallelInstructionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialInstructionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that instructions inside it can be split into separate transactions.\n * - {@link MessagePackerInstructionPlan} - A plan that can dynamically pack\n * instructions into transaction messages.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myInstructionPlan: InstructionPlan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * instructionC,\n * instructionD,\n * ]);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link ParallelInstructionPlan}\n * @see {@link SequentialInstructionPlan}\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type InstructionPlan =\n | MessagePackerInstructionPlan\n | ParallelInstructionPlan\n | SequentialInstructionPlan\n | SingleInstructionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the instructions inside them can be split into separate transactions.\n * When `divisible` is `false`, the instructions inside the plan should\n * all be executed atomically — either in a single transaction or in a\n * transaction bundle.\n *\n * You may use the {@link sequentialInstructionPlan} and {@link nonDivisibleSequentialInstructionPlan}\n * helpers to create objects of this type.\n *\n * @example Simple sequential plan with two instructions.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan;\n * ```\n *\n * @example Non-divisible sequential plan with two instructions.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @example Sequential plan with nested parallel plans.\n * Here, instructions A and B can be executed in parallel, but they must both be finalized\n * before instructions C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * parallelInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @see {@link sequentialInstructionPlan}\n * @see {@link nonDivisibleSequentialInstructionPlan}\n */\nexport type SequentialInstructionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without consequence.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialInstructionPlan}.\n *\n * You may use the {@link parallelInstructionPlan} helper to create objects of this type.\n *\n * @example Simple parallel plan with two instructions.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @example Parallel plan with nested sequential plans.\n * Here, instructions A and B must be executed sequentially and so must instructions C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @see {@link parallelInstructionPlan}\n */\nexport type ParallelInstructionPlan = Readonly<{\n kind: 'parallel';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan that contains a single instruction.\n *\n * This is a simple instruction wrapper that transforms an instruction into a plan.\n *\n * You may use the {@link singleInstructionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * plan satisfies SingleInstructionPlan;\n * ```\n *\n * @see {@link singleInstructionPlan}\n */\nexport type SingleInstructionPlan = Readonly<{\n instruction: TInstruction;\n kind: 'single';\n}>;\n\n/**\n * A plan that can dynamically pack instructions into transaction messages.\n *\n * This plan provides a {@link MessagePacker} via the `getMessagePacker`\n * method, which enables instructions to be dynamically packed into the\n * provided transaction message until there are no more instructions to pack.\n * The returned {@link MessagePacker} offers a `packMessageToCapacity(message)`\n * method that packs the provided message — when possible — and a `done()` method\n * that checks whether there are more instructions to pack.\n *\n * Several helper functions are provided to create objects of this type such as\n * {@link getLinearMessagePackerInstructionPlan} or {@link getMessagePackerInstructionPlanFromInstructions}.\n *\n * @example An message packer plan for a write instruction that uses as many bytes as possible.\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example A message packer plan for multiple realloc instructions.\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example Using a message packer plan.\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link getLinearMessagePackerInstructionPlan}\n * @see {@link getMessagePackerInstructionPlanFromInstructions}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport type MessagePackerInstructionPlan = Readonly<{\n getMessagePacker: () => MessagePacker;\n kind: 'messagePacker';\n}>;\n\n/**\n * The message packer returned by the {@link MessagePackerInstructionPlan}.\n *\n * It offers a `packMessageToCapacity(transactionMessage)` method that packs as many instructions\n * as possible into the provided transaction message, while still being able to fit into the\n * transaction size limit. It returns the updated transaction message with the packed instructions\n * or throws an error if the current transaction message cannot accommodate this plan.\n *\n * The `done()` method checks whether there are more instructions to pack into\n * transaction messages.\n *\n * @example\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type MessagePacker = Readonly<{\n /** Checks whether the message packer has more instructions to pack into transaction messages. */\n done: () => boolean;\n /**\n * Packs the provided transaction message with instructions or throws if not possible.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN}\n * if the provided transaction message cannot be used to fill the next instructions.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE}\n * if the message packer is already done and no more instructions can be packed.\n */\n packMessageToCapacity: (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer;\n}>;\n\n/**\n * Creates a {@link ParallelInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = parallelInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n */\nexport function parallelInstructionPlan(plans: (Instruction | InstructionPlan)[]): ParallelInstructionPlan {\n return Object.freeze({\n kind: 'parallel',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function sequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: true } {\n return Object.freeze({\n divisible: true,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a non-divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function nonDivisibleSequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: false } {\n return Object.freeze({\n divisible: false,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a {@link SingleInstructionPlan} from an {@link Instruction} object.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n */\nexport function singleInstructionPlan(instruction: Instruction): SingleInstructionPlan {\n return Object.freeze({ instruction, kind: 'single' });\n}\n\nfunction parseSingleInstructionPlans(plans: (Instruction | InstructionPlan)[]): InstructionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleInstructionPlan(plan)));\n}\n\n/**\n * Checks if the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a single instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * if (isSingleInstructionPlan(plan)) {\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * }\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link assertIsSingleInstructionPlan}\n */\nexport function isSingleInstructionPlan(plan: InstructionPlan): plan is SingleInstructionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a single instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * assertIsSingleInstructionPlan(plan);\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link isSingleInstructionPlan}\n */\nexport function assertIsSingleInstructionPlan(plan: InstructionPlan): asserts plan is SingleInstructionPlan {\n if (!isSingleInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a message packer instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * if (isMessagePackerInstructionPlan(plan)) {\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link assertIsMessagePackerInstructionPlan}\n */\nexport function isMessagePackerInstructionPlan(plan: InstructionPlan): plan is MessagePackerInstructionPlan {\n return plan.kind === 'messagePacker';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a message packer instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * assertIsMessagePackerInstructionPlan(plan);\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link isMessagePackerInstructionPlan}\n */\nexport function assertIsMessagePackerInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is MessagePackerInstructionPlan {\n if (!isMessagePackerInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'messagePacker',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isSequentialInstructionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsSequentialInstructionPlan}\n */\nexport function isSequentialInstructionPlan(plan: InstructionPlan): plan is SequentialInstructionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsSequentialInstructionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isSequentialInstructionPlan}\n */\nexport function assertIsSequentialInstructionPlan(plan: InstructionPlan): asserts plan is SequentialInstructionPlan {\n if (!isSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a non-divisible sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isNonDivisibleSequentialInstructionPlan(plan)) {\n * // All instructions must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsNonDivisibleSequentialInstructionPlan}\n */\nexport function isNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): plan is SequentialInstructionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a non-divisible sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsNonDivisibleSequentialInstructionPlan(plan);\n * // All instructions must be executed atomically.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isNonDivisibleSequentialInstructionPlan}\n */\nexport function assertIsNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is SequentialInstructionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a parallel instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * if (isParallelInstructionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * }\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link assertIsParallelInstructionPlan}\n */\nexport function isParallelInstructionPlan(plan: InstructionPlan): plan is ParallelInstructionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a parallel instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * assertIsParallelInstructionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link isParallelInstructionPlan}\n */\nexport function assertIsParallelInstructionPlan(plan: InstructionPlan): asserts plan is ParallelInstructionPlan {\n if (!isParallelInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Finds the first instruction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the instruction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param instructionPlan - The instruction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @returns The first matching instruction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const nonDivisible = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing instructionC and instructionD.\n * ```\n *\n * @example\n * Finding a specific single instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const found = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.instruction === instructionB,\n * );\n * // Returns the SingleInstructionPlan wrapping instructionB.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function findInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): InstructionPlan | undefined {\n if (predicate(instructionPlan)) {\n return instructionPlan;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return undefined;\n }\n for (const subPlan of instructionPlan.plans) {\n const foundPlan = findInstructionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every instruction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the instruction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param instructionPlan - The instruction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const allDivisible = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single instructions use a specific program.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const allUseSameProgram = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.instruction.programAddress === myProgramAddress,\n * );\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function everyInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): boolean {\n if (!predicate(instructionPlan)) {\n return false;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return true;\n }\n return instructionPlan.plans.every(p => everyInstructionPlan(p, predicate));\n}\n\n/**\n * Transforms an instruction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the instruction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param instructionPlan - The instruction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed instruction plan tree.\n *\n * @example\n * Making all sequential plans non-divisible to ensure atomicity.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' && p.divisible) {\n * return nonDivisibleSequentialInstructionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Filtering out debug instructions before production execution.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, debugInstruction, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' || p.kind === 'parallel') {\n * return { ...p, plans: p.plans.filter((p) => !isDebugInstruction(p)) };\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function transformInstructionPlan(\n instructionPlan: InstructionPlan,\n fn: (plan: InstructionPlan) => InstructionPlan,\n): InstructionPlan {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return Object.freeze(fn(instructionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...instructionPlan,\n plans: instructionPlan.plans.map(p => transformInstructionPlan(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleInstructionPlan} and {@link MessagePackerInstructionPlan}\n * instances from an instruction plan tree.\n *\n * This function recursively traverses any nested structure of instruction plans and extracts\n * all the leaf plans they contain. It's useful when you need to access all the individual\n * instructions or message packers that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param instructionPlan - The instruction plan to extract leaf plans from\n * @returns An array of all single and message packer instruction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * instructionE,\n * ]);\n *\n * const leafPlans = flattenInstructionPlan(plan);\n * // Array of `SingleInstructionPlan` containing:\n * // instructionA, instructionB, instructionC, instructionD and instructionE.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n */\nexport function flattenInstructionPlan(\n instructionPlan: InstructionPlan,\n): (MessagePackerInstructionPlan | SingleInstructionPlan)[] {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return [instructionPlan];\n }\n return instructionPlan.plans.flatMap(flattenInstructionPlan);\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs instructions\n * such that each instruction consumes as many bytes as possible from the given\n * `totalLength` while still being able to fit into the given transaction messages.\n *\n * This is particularly useful for instructions that write data to accounts and must\n * span multiple transactions due to their size limit.\n *\n * This message packer will first call `getInstruction` with a length of zero to\n * determine the base size of the instruction before figuring out how many\n * additional bytes can be packed into the transaction message. That remaining space\n * will then be used to call `getInstruction` again with the appropriate length.\n *\n * @param getInstruction - A function that returns an instruction for a given offset and length.\n * @param totalLength - The total length of the data to write, in bytes.\n *\n * @example\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getLinearMessagePackerInstructionPlan({\n getInstruction,\n totalLength: totalBytes,\n}: {\n getInstruction: (offset: number, length: number) => Instruction;\n totalLength: number;\n}): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let offset = 0;\n return Object.freeze({\n done: () => offset >= totalBytes,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (offset >= totalBytes) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const messageSizeWithBaseInstruction = getTransactionMessageSize(\n appendTransactionMessageInstruction(getInstruction(offset, 0), message),\n );\n const freeSpace =\n TRANSACTION_SIZE_LIMIT -\n messageSizeWithBaseInstruction /* Includes the base instruction (length: 0). */ -\n 1; /* Leeway for shortU16 numbers in transaction headers. */\n\n if (freeSpace <= 0) {\n const messageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n // (+1) We need to pack at least one byte of data otherwise\n // there is no point packing the base instruction alone.\n numBytesRequired: messageSizeWithBaseInstruction - messageSize + 1,\n // (-1) Leeway for shortU16 numbers in transaction headers.\n numFreeBytes: TRANSACTION_SIZE_LIMIT - messageSize - 1,\n });\n }\n\n const length = Math.min(totalBytes - offset, freeSpace);\n const instruction = getInstruction(offset, length);\n offset += length;\n return appendTransactionMessageInstruction(instruction, message);\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} from a list of instructions.\n *\n * This can be useful to prepare a set of instructions that can be iterated over\n * — e.g. to pack a list of instructions that gradually reallocate the size of an account\n * one `REALLOC_LIMIT` (10'240 bytes) at a time.\n *\n * @example\n * ```ts\n * const plan = getMessagePackerInstructionPlanFromInstructions([\n * instructionA,\n * instructionB,\n * instructionC,\n * ]);\n *\n * const messagePacker = plan.getMessagePacker();\n * firstTransactionMessage = messagePacker.packMessageToCapacity(firstTransactionMessage);\n * // Contains instruction A and instruction B.\n * secondTransactionMessage = messagePacker.packMessageToCapacity(secondTransactionMessage);\n * // Contains instruction C.\n * messagePacker.done(); // true\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport function getMessagePackerInstructionPlanFromInstructions(\n instructions: TInstruction[],\n): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let instructionIndex = 0;\n return Object.freeze({\n done: () => instructionIndex >= instructions.length,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (instructionIndex >= instructions.length) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const originalMessageSize = getTransactionMessageSize(message);\n\n for (let index = instructionIndex; index < instructions.length; index++) {\n message = appendTransactionMessageInstruction(instructions[index], message);\n const messageSize = getTransactionMessageSize(message);\n\n if (messageSize > TRANSACTION_SIZE_LIMIT) {\n if (index === instructionIndex) {\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n {\n numBytesRequired: messageSize - originalMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - originalMessageSize,\n },\n );\n }\n instructionIndex = index;\n return message;\n }\n }\n\n instructionIndex = instructions.length;\n return message;\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\nconst REALLOC_LIMIT = 10_240;\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs a list of realloc instructions.\n *\n * That is, it splits instruction by chunks of `REALLOC_LIMIT` (10'240) bytes until\n * the given total size is reached.\n *\n * @example\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getReallocMessagePackerInstructionPlan({\n getInstruction,\n totalSize,\n}: {\n getInstruction: (size: number) => Instruction;\n totalSize: number;\n}): MessagePackerInstructionPlan {\n const numberOfInstructions = Math.ceil(totalSize / REALLOC_LIMIT);\n const lastInstructionSize = totalSize % REALLOC_LIMIT;\n const instructions = new Array(numberOfInstructions)\n .fill(0)\n .map((_, i) => getInstruction(i === numberOfInstructions - 1 ? lastInstructionSize : REALLOC_LIMIT));\n\n return getMessagePackerInstructionPlanFromInstructions(instructions);\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, SolanaError } from '@solana/errors';\nimport { type Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport { flattenInstructionPlan, InstructionPlan } from './instruction-plan';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\n\ntype AppendTransactionMessageInstructions = ReturnType<\n typeof appendTransactionMessageInstructions\n>;\n\n/**\n * Appends all instructions from an instruction plan to a transaction message.\n *\n * This function flattens the instruction plan into its leaf plans and sequentially\n * appends each instruction to the provided transaction message. It handles both\n * single instructions and message packer plans.\n *\n * Note that any {@link MessagePackerInstructionPlan} is assumed to only append\n * instructions. If it modifies other properties of the transaction message, the\n * type of the returned transaction message may not accurately reflect those changes.\n *\n * @typeParam TTransactionMessage - The type of transaction message being modified.\n *\n * @param transactionMessage - The transaction message to append instructions to.\n * @param instructionPlan - The instruction plan containing the instructions to append.\n * @returns The transaction message with all instructions from the plan appended.\n *\n * @example\n * Appending a simple instruction plan to a transaction message.\n * ```ts\n * import { appendTransactionMessageInstructionPlan } from '@solana/instruction-plans';\n * import { createTransactionMessage, setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const message = setTransactionMessageFeePayer(feePayer, createTransactionMessage({ version: 0 }));\n * const plan = singleInstructionPlan(myInstruction);\n *\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @example\n * Appending a sequential instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function appendTransactionMessageInstructionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer,\n>(\n instructionPlan: InstructionPlan,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n type Out = AppendTransactionMessageInstructions;\n\n const leafInstructionPlans = flattenInstructionPlan(instructionPlan);\n\n return leafInstructionPlans.reduce(\n (messageSoFar, plan) => {\n const kind = plan.kind;\n if (kind === 'single') {\n return appendTransactionMessageInstruction(plan.instruction, messageSoFar) as unknown as Out;\n }\n if (kind === 'messagePacker') {\n const messagerPacker = plan.getMessagePacker();\n let nextMessage: Out = messageSoFar;\n while (!messagerPacker.done()) {\n nextMessage = messagerPacker.packMessageToCapacity(nextMessage) as Out;\n }\n return nextMessage;\n }\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, {\n kind,\n });\n },\n transactionMessage as unknown as Out,\n );\n}\n","import { SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, SolanaError } from '@solana/errors';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\n/**\n * A set of transaction messages with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely, the following plans are supported:\n * - {@link SingleTransactionPlan} - A plan that contains a single transaction message.\n * This is the simplest leaf in this tree.\n * - {@link ParallelTransactionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialTransactionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that transaction messages inside it can be split into separate batches.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myTransactionPlan: TransactionPlan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * messageC,\n * ]);\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link ParallelTransactionPlan}\n * @see {@link SequentialTransactionPlan}\n */\nexport type TransactionPlan = ParallelTransactionPlan | SequentialTransactionPlan | SingleTransactionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the transaction messages inside them can be split into separate batches.\n * When `divisible` is `false`, the transaction messages inside the plan should\n * all be executed atomically — usually in a transaction bundle.\n *\n * You may use the {@link sequentialTransactionPlan} and {@link nonDivisibleSequentialTransactionPlan}\n * helpers to create objects of this type.\n *\n * @example\n * Simple sequential plan with two transaction messages.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan;\n * ```\n *\n * @example\n * Non-divisible sequential plan with two transaction messages.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan & { divisible: false };\n * ```\n *\n * @example\n * Sequential plan with nested parallel plans.\n * Here, messages A and B can be executed in parallel, but they must both be finalized\n * before messages C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * parallelTransactionPlan([messageC, messageD]),\n * ]);\n * ```\n *\n * @see {@link sequentialTransactionPlan}\n * @see {@link nonDivisibleSequentialTransactionPlan}\n */\nexport type SequentialTransactionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without causing any side effects.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialTransactionPlan}.\n *\n * You may use the {@link parallelTransactionPlan} helper to create objects of this type.\n *\n * @example\n * Simple parallel plan with two transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @example\n * Parallel plan with nested sequential plans.\n * Here, messages A and B must be executed sequentially and so must messages C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @see {@link parallelTransactionPlan}\n */\nexport type ParallelTransactionPlan = Readonly<{\n kind: 'parallel';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan that contains a single transaction message.\n *\n * This is a simple transaction message wrapper that transforms a message into a plan.\n *\n * You may use the {@link singleTransactionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link singleTransactionPlan}\n */\nexport type SingleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n}>;\n\n/**\n * Creates a {@link ParallelTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = parallelTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n */\nexport function parallelTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): ParallelTransactionPlan {\n return Object.freeze({ kind: 'parallel', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function sequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function nonDivisibleSequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a {@link SingleTransactionPlan} from a {@link TransactionMessage} object.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link SingleTransactionPlan}\n */\nexport function singleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlan {\n return Object.freeze({ kind: 'single', message: transactionMessage });\n}\n\nfunction parseSingleTransactionPlans(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): TransactionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleTransactionPlan(plan)));\n}\n\n/**\n * Checks if the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a single transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * if (isSingleTransactionPlan(plan)) {\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link assertIsSingleTransactionPlan}\n */\nexport function isSingleTransactionPlan(plan: TransactionPlan): plan is SingleTransactionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a single transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * assertIsSingleTransactionPlan(plan);\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link isSingleTransactionPlan}\n */\nexport function assertIsSingleTransactionPlan(plan: TransactionPlan): asserts plan is SingleTransactionPlan {\n if (!isSingleTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * if (isSequentialTransactionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsSequentialTransactionPlan}\n */\nexport function isSequentialTransactionPlan(plan: TransactionPlan): plan is SequentialTransactionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsSequentialTransactionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isSequentialTransactionPlan}\n */\nexport function assertIsSequentialTransactionPlan(plan: TransactionPlan): asserts plan is SequentialTransactionPlan {\n if (!isSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a non-divisible sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * if (isNonDivisibleSequentialTransactionPlan(plan)) {\n * // All transaction messages must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlan}\n */\nexport function isNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): plan is SequentialTransactionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a non-divisible sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlan(plan);\n * // All transaction messages must be executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isNonDivisibleSequentialTransactionPlan}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): asserts plan is SequentialTransactionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a parallel transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * if (isParallelTransactionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link assertIsParallelTransactionPlan}\n */\nexport function isParallelTransactionPlan(plan: TransactionPlan): plan is ParallelTransactionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a parallel transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * assertIsParallelTransactionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link isParallelTransactionPlan}\n */\nexport function assertIsParallelTransactionPlan(plan: TransactionPlan): asserts plan is ParallelTransactionPlan {\n if (!isParallelTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * @deprecated Use {@link flattenTransactionPlan} instead.\n */\nexport const getAllSingleTransactionPlans = flattenTransactionPlan;\n\n/**\n * Retrieves all individual {@link SingleTransactionPlan} instances from a transaction plan tree.\n *\n * This function recursively traverses any nested structure of transaction plans and extracts\n * all the single transaction plans they contain. It's useful when you need to access all\n * the actual transaction messages that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param transactionPlan - The transaction plan to extract single plans from\n * @returns An array of all single transaction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * messageE,\n * ]);\n *\n * const singlePlans = flattenTransactionPlan(plan);\n * // Array of `SingleTransactionPlan` containing:\n * // messageA, messageB, messageC and messageD.\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * ```\n */\nexport function flattenTransactionPlan(transactionPlan: TransactionPlan): SingleTransactionPlan[] {\n if (transactionPlan.kind === 'single') {\n return [transactionPlan];\n }\n return transactionPlan.plans.flatMap(flattenTransactionPlan);\n}\n\n/**\n * Finds the first transaction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param transactionPlan - The transaction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @return The first matching transaction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const nonDivisible = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing messageC and messageD.\n * ```\n *\n * @example\n * Finding a specific single transaction plan.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB, messageC]);\n *\n * const found = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.message === messageB,\n * );\n * // Returns the SingleTransactionPlan wrapping messageB.\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function findTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): TransactionPlan | undefined {\n if (predicate(transactionPlan)) {\n return transactionPlan;\n }\n if (transactionPlan.kind === 'single') {\n return undefined;\n }\n for (const subPlan of transactionPlan.plans) {\n const foundPlan = findTransactionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every transaction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param transactionPlan - The transaction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const allDivisible = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single plans have a specific fee payer.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const allUseSameFeePayer = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.message.feePayer.address === myFeePayer,\n * );\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function everyTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): boolean {\n if (!predicate(transactionPlan)) {\n return false;\n }\n if (transactionPlan.kind === 'single') {\n return true;\n }\n return transactionPlan.plans.every(p => everyTransactionPlan(p, predicate));\n}\n\n/**\n * Transforms a transaction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlan - The transaction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed transaction plan tree.\n *\n * @example\n * Removing parallelism by converting parallel plans to sequential.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'parallel') {\n * return sequentialTransactionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Updating the fee payer on all transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'single') {\n * return singleTransactionPlan({ ...p.message, feePayer: newFeePayer });\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function transformTransactionPlan(\n transactionPlan: TransactionPlan,\n fn: (plan: TransactionPlan) => TransactionPlan,\n): TransactionPlan {\n if (transactionPlan.kind === 'single') {\n return Object.freeze(fn(transactionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlan,\n plans: transactionPlan.plans.map(p => transformTransactionPlan(p, fn)),\n }),\n ),\n );\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { getSignatureFromTransaction, Transaction } from '@solana/transactions';\n\n/**\n * The result of executing a transaction plan.\n *\n * This is structured as a recursive tree of results that mirrors the structure\n * of the original transaction plan, capturing the execution status at each level.\n *\n * Namely, the following result types are supported:\n * - {@link SingleTransactionPlanResult} - A result for a single transaction message\n * containing its execution status.\n * - {@link ParallelTransactionPlanResult} - A result containing other results that\n * were executed in parallel.\n * - {@link SequentialTransactionPlanResult} - A result containing other results that\n * were executed sequentially. It also retains the divisibility property from the\n * original plan.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link TransactionPlanResultStatus}\n */\nexport type TransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = ParallelTransactionPlanResult | SequentialTransactionPlanResult | TSingle;\n\n/**\n * A {@link TransactionPlanResult} where all single transaction results are successful.\n *\n * This type represents a transaction plan result tree where every\n * {@link SingleTransactionPlanResult} has a 'successful' status. It can be used\n * to ensure that an entire execution completed without any failures or cancellations.\n *\n * Note: This is different from {@link SuccessfulSingleTransactionPlanResult} which\n * represents a single successful transaction, whereas this type represents an entire\n * plan result tree (which may contain parallel/sequential structures) where all\n * leaf nodes are successful.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n *\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link SuccessfulSingleTransactionPlanResult}\n */\nexport type SuccessfulTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = TransactionPlanResult>;\n\n/** A context object that may be passed along with successful results. */\nexport type TransactionPlanResultContext = Record;\n\n/**\n * A result for a sequential transaction plan.\n *\n * This represents the execution result of a {@link SequentialTransactionPlan} and\n * contains child results that were executed sequentially. It also retains the\n * divisibility property from the original plan.\n *\n * You may use the {@link sequentialTransactionPlanResult} and\n * {@link nonDivisibleSequentialTransactionPlanResult} helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult;\n * ```\n *\n * @example\n * Non-divisible sequential result.\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link sequentialTransactionPlanResult}\n * @see {@link nonDivisibleSequentialTransactionPlanResult}\n */\nexport type SequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a parallel transaction plan.\n *\n * This represents the execution result of a {@link ParallelTransactionPlan} and\n * contains child results that were executed in parallel.\n *\n * You may use the {@link parallelTransactionPlanResult} helper to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link parallelTransactionPlanResult}\n */\nexport type ParallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n kind: 'parallel';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a single transaction plan.\n *\n * This represents the execution result of a {@link SingleTransactionPlan} and\n * contains the original transaction message along with its execution status.\n *\n * You may use the {@link successfulSingleTransactionPlanResult},\n * {@link failedSingleTransactionPlanResult}, or {@link canceledSingleTransactionPlanResult}\n * helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TTransactionMessage - The type of the transaction message\n *\n * @example\n * Successful result with a transaction and context.\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Failed result with an error.\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError(SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Canceled result.\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link successfulSingleTransactionPlanResult}\n * @see {@link failedSingleTransactionPlanResult}\n * @see {@link canceledSingleTransactionPlanResult}\n */\nexport type SingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n status: TransactionPlanResultStatus;\n}>;\n\n/**\n * The status of a single transaction plan execution.\n *\n * This represents the outcome of executing a single transaction message and can be one of:\n * - `successful` - The transaction was successfully executed. Contains the transaction\n * and an optional context object.\n * - `failed` - The transaction execution failed. Contains the error that caused the failure.\n * - `canceled` - The transaction execution was canceled.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n */\nexport type TransactionPlanResultStatus =\n | Readonly<{ context: TContext; kind: 'successful'; signature: Signature; transaction?: Transaction }>\n | Readonly<{ error: Error; kind: 'failed' }>\n | Readonly<{ kind: 'canceled' }>;\n\n/**\n * Creates a divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `true`,\n * indicating that the nested plans were executed sequentially but could have been\n * split into separate transactions or batches.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: true };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function sequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `false`,\n * indicating that the nested plans were executed sequentially and could not have been\n * split into separate transactions or batches (e.g., they were executed as a transaction bundle).\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function nonDivisibleSequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans });\n}\n\n/**\n * Creates a {@link ParallelTransactionPlanResult} from an array of nested results.\n *\n * This function creates a parallel result indicating that the nested plans\n * were executed in parallel.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed in parallel\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n */\nexport function parallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): ParallelTransactionPlanResult {\n return Object.freeze({ kind: 'parallel', plans });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and transaction.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param transaction - The successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n transaction: Transaction,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({\n context: context ?? ({} as TContext),\n kind: 'successful',\n signature: getSignatureFromTransaction(transaction),\n transaction,\n }),\n });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and signature.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the signature of the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param signature - The signature of the successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * signature\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResultFromSignature<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n signature: Signature,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ context: context ?? ({} as TContext), kind: 'successful', signature }),\n });\n}\n\n/**\n * Creates a failed {@link SingleTransactionPlanResult} from a transaction message and error.\n *\n * This function creates a single result with a 'failed' status, indicating that\n * the transaction execution failed. It includes the original transaction message\n * and the error that caused the failure.\n *\n * @template TContext - The type of the context object (not used in failed results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param error - The error that caused the transaction to fail\n *\n * @example\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError({\n * code: 123,\n * message: 'Transaction simulation failed',\n * }),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function failedSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage, error: Error): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ error, kind: 'failed' }),\n });\n}\n\n/**\n * Creates a canceled {@link SingleTransactionPlanResult} from a transaction message.\n *\n * This function creates a single result with a 'canceled' status, indicating that\n * the transaction execution was canceled. It includes the original transaction message.\n *\n * @template TContext - The type of the context object (not used in canceled results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n *\n * @example\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function canceledSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ kind: 'canceled' }),\n });\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSingleTransactionPlanResult(result)) {\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link assertIsSingleTransactionPlanResult}\n */\nexport function isSingleTransactionPlanResult(plan: TransactionPlanResult): plan is SingleTransactionPlanResult {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSingleTransactionPlanResult(result);\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link isSingleTransactionPlanResult}\n */\nexport function assertIsSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SingleTransactionPlanResult {\n if (!isSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a successful single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSuccessfulSingleTransactionPlanResult(result)) {\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * }\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'successful';\n}\n\n/**\n * Asserts that the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a successful single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSuccessfulSingleTransactionPlanResult(result);\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulSingleTransactionPlanResult {\n if (!isSuccessfulSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'successful single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a failed single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * if (isFailedSingleTransactionPlanResult(result)) {\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * }\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link assertIsFailedSingleTransactionPlanResult}\n */\nexport function isFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is FailedSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'failed';\n}\n\n/**\n * Asserts that the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a failed single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * assertIsFailedSingleTransactionPlanResult(result);\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link isFailedSingleTransactionPlanResult}\n */\nexport function assertIsFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is FailedSingleTransactionPlanResult {\n if (!isFailedSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'failed single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a canceled single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * if (isCanceledSingleTransactionPlanResult(result)) {\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * }\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link assertIsCanceledSingleTransactionPlanResult}\n */\nexport function isCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is CanceledSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'canceled';\n}\n\n/**\n * Asserts that the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a canceled single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * assertIsCanceledSingleTransactionPlanResult(result);\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link isCanceledSingleTransactionPlanResult}\n */\nexport function assertIsCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is CanceledSingleTransactionPlanResult {\n if (!isCanceledSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'canceled single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isSequentialTransactionPlanResult(result)) {\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsSequentialTransactionPlanResult}\n */\nexport function isSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsSequentialTransactionPlanResult(result);\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isSequentialTransactionPlanResult}\n */\nexport function assertIsSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult {\n if (!isSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a non-divisible sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isNonDivisibleSequentialTransactionPlanResult(result)) {\n * // Transactions were executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlanResult}\n */\nexport function isNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a non-divisible sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlanResult(result);\n * // Transactions were executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isNonDivisibleSequentialTransactionPlanResult}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a parallel transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * if (isParallelTransactionPlanResult(result)) {\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link assertIsParallelTransactionPlanResult}\n */\nexport function isParallelTransactionPlanResult(plan: TransactionPlanResult): plan is ParallelTransactionPlanResult {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a parallel transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * assertIsParallelTransactionPlanResult(result);\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link isParallelTransactionPlanResult}\n */\nexport function assertIsParallelTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is ParallelTransactionPlanResult {\n if (!isParallelTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It recursively checks all nested results\n * to ensure every {@link SingleTransactionPlanResult} has a 'successful' status.\n *\n * Note: This is different from {@link isSuccessfulSingleTransactionPlanResult} which\n * checks if a single result is successful. This function checks that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if all single transaction results in the tree are successful, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * if (isSuccessfulTransactionPlanResult(result)) {\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * }\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulTransactionPlanResult {\n return everyTransactionPlanResult(\n plan,\n r => !isSingleTransactionPlanResult(r) || isSuccessfulSingleTransactionPlanResult(r),\n );\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It throws if any {@link SingleTransactionPlanResult}\n * in the tree has a 'failed' or 'canceled' status.\n *\n * Note: This is different from {@link assertIsSuccessfulSingleTransactionPlanResult} which\n * asserts that a single result is successful. This function asserts that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT` if\n * any single transaction result in the tree is not successful.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * assertIsSuccessfulTransactionPlanResult(result);\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulTransactionPlanResult {\n if (!isSuccessfulTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT, {\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Finds the first transaction plan result in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan result tree,\n * returning the first result that satisfies the predicate. It checks the root result\n * first, then recursively searches through nested results.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @param predicate - A function that returns `true` for the result to find.\n * @returns The first matching transaction plan result, or `undefined` if no match is found.\n *\n * @example\n * Finding a failed transaction result.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * ]);\n *\n * const failed = findTransactionPlanResult(\n * result,\n * (r) => r.kind === 'single' && r.status.kind === 'failed',\n * );\n * // Returns the failed single transaction plan result for messageB.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function findTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (result: TransactionPlanResult) => boolean,\n): TransactionPlanResult | undefined {\n if (predicate(transactionPlanResult)) {\n return transactionPlanResult;\n }\n if (transactionPlanResult.kind === 'single') {\n return undefined;\n }\n for (const subResult of transactionPlanResult.plans) {\n const foundResult = findTransactionPlanResult(subResult, predicate);\n if (foundResult) {\n return foundResult;\n }\n }\n return undefined;\n}\n\n/**\n * Retrieves the first failed transaction plan result from a transaction plan result tree.\n *\n * This function searches the transaction plan result tree using a depth-first traversal\n * and returns the first single transaction result with a 'failed' status. If no failed\n * result is found, it throws a {@link SolanaError}.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @return The first failed single transaction plan result.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND` if no\n * failed transaction plan result is found. The error context contains a non-enumerable\n * `transactionPlanResult` property for recovery purposes.\n *\n * @example\n * Retrieving the first failed result from a parallel execution.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * failedSingleTransactionPlanResult(messageC, anotherError),\n * ]);\n *\n * const firstFailed = getFirstFailedSingleTransactionPlanResult(result);\n * // Returns the failed result for messageB.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n */\nexport function getFirstFailedSingleTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n): FailedSingleTransactionPlanResult {\n const result = findTransactionPlanResult(\n transactionPlanResult,\n r => r.kind === 'single' && r.status.kind === 'failed',\n );\n\n if (!result) {\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can recover but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n const context = {};\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n context,\n );\n }\n\n return result as FailedSingleTransactionPlanResult;\n}\n\n/**\n * Checks if every transaction plan result in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan result tree,\n * returning `true` only if the predicate returns `true` for every result in the tree\n * (including the root result and all nested results).\n *\n * @param transactionPlanResult - The transaction plan result tree to check.\n * @param predicate - A function that returns `true` if the result satisfies the condition.\n * @return `true` if every result in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all transactions were successful.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * const allSuccessful = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind === 'successful',\n * );\n * // Returns true because all single results are successful.\n * ```\n *\n * @example\n * Checking if no transactions were canceled.\n * ```ts\n * const result = sequentialTransactionPlanResult([resultA, resultB, resultC]);\n *\n * const noCanceled = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind !== 'canceled',\n * );\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function everyTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (plan: TransactionPlanResult) => boolean,\n): boolean {\n if (!predicate(transactionPlanResult)) {\n return false;\n }\n if (transactionPlanResult.kind === 'single') {\n return true;\n }\n return transactionPlanResult.plans.every(p => everyTransactionPlanResult(p, predicate));\n}\n\n/**\n * Transforms a transaction plan result tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan result tree, applying the\n * transformation function to each result. The transformation is applied bottom-up,\n * meaning nested results are transformed first, then the parent results receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed results are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlanResult - The transaction plan result tree to transform.\n * @param fn - A function that transforms each result and returns a new result.\n * @return A new transformed transaction plan result tree.\n *\n * @example\n * Converting all canceled results to failed results.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * canceledSingleTransactionPlanResult(messageB),\n * ]);\n *\n * const transformed = transformTransactionPlanResult(result, (r) => {\n * if (r.kind === 'single' && r.status.kind === 'canceled') {\n * return failedSingleTransactionPlanResult(r.message, new Error('Execution canceled'));\n * }\n * return r;\n * });\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function transformTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n fn: (plan: TransactionPlanResult) => TransactionPlanResult,\n): TransactionPlanResult {\n if (transactionPlanResult.kind === 'single') {\n return Object.freeze(fn(transactionPlanResult));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlanResult,\n plans: transactionPlanResult.plans.map(p => transformTransactionPlanResult(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleTransactionPlanResult} instances from a transaction plan result tree.\n *\n * This function recursively traverses any nested structure of transaction plan results and extracts\n * all the single results they contain. It's useful when you need to access all the individual\n * transaction results, regardless of their organization in the result tree (parallel or sequential).\n *\n * @param result - The transaction plan result to extract single results from\n * @returns An array of all single transaction plan results contained in the tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * sequentialTransactionPlanResult([resultA, resultB]),\n * nonDivisibleSequentialTransactionPlanResult([resultC, resultD]),\n * resultE,\n * ]);\n *\n * const singleResults = flattenTransactionPlanResult(result);\n * // Array of `SingleTransactionPlanResult` containing:\n * // resultA, resultB, resultC, resultD and resultE.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n */\nexport function flattenTransactionPlanResult(result: TransactionPlanResult): SingleTransactionPlanResult[] {\n if (result.kind === 'single') {\n return [result];\n }\n return result.plans.flatMap(flattenTransactionPlanResult);\n}\n\n/**\n * A {@link SingleTransactionPlanResult} with 'successful' status.\n */\nexport type SuccessfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = SingleTransactionPlanResult & { status: { kind: 'successful' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'failed' status.\n */\nexport type FailedSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'failed' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'canceled' status.\n */\nexport type CanceledSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'canceled' } };\n\n/**\n * A summary of a {@link TransactionPlanResult}, categorizing transactions by their execution status.\n * - `successful`: Indicates whether all transactions were successful (i.e., no failed or canceled transactions).\n * - `successfulTransactions`: An array of successful transactions, each including its signature.\n * - `failedTransactions`: An array of failed transactions, each including the error that caused the failure.\n * - `canceledTransactions`: An array of canceled transactions.\n */\nexport type TransactionPlanResultSummary = Readonly<{\n canceledTransactions: CanceledSingleTransactionPlanResult[];\n failedTransactions: FailedSingleTransactionPlanResult[];\n successful: boolean;\n successfulTransactions: SuccessfulSingleTransactionPlanResult[];\n}>;\n\n/**\n * Summarize a {@link TransactionPlanResult} into a {@link TransactionPlanResultSummary}.\n * @param result The transaction plan result to summarize\n * @returns A summary of the transaction plan result\n */\nexport function summarizeTransactionPlanResult(result: TransactionPlanResult): TransactionPlanResultSummary {\n const successfulTransactions: TransactionPlanResultSummary['successfulTransactions'] = [];\n const failedTransactions: TransactionPlanResultSummary['failedTransactions'] = [];\n const canceledTransactions: TransactionPlanResultSummary['canceledTransactions'] = [];\n\n const flattenedResults = flattenTransactionPlanResult(result);\n\n for (const singleResult of flattenedResults) {\n switch (singleResult.status.kind) {\n case 'successful': {\n successfulTransactions.push(singleResult as SuccessfulSingleTransactionPlanResult);\n break;\n }\n case 'failed': {\n failedTransactions.push(singleResult as FailedSingleTransactionPlanResult);\n break;\n }\n case 'canceled': {\n canceledTransactions.push(singleResult as CanceledSingleTransactionPlanResult);\n break;\n }\n }\n }\n\n return Object.freeze({\n canceledTransactions,\n failedTransactions,\n successful: failedTransactions.length === 0 && canceledTransactions.length === 0,\n successfulTransactions,\n });\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { getAbortablePromise } from '@solana/promises';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { Transaction } from '@solana/transactions';\n\nimport type {\n ParallelTransactionPlan,\n SequentialTransactionPlan,\n SingleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\nimport {\n canceledSingleTransactionPlanResult,\n failedSingleTransactionPlanResult,\n parallelTransactionPlanResult,\n sequentialTransactionPlanResult,\n SingleTransactionPlanResult,\n successfulSingleTransactionPlanResult,\n successfulSingleTransactionPlanResultFromSignature,\n type TransactionPlanResult,\n type TransactionPlanResultContext,\n} from './transaction-plan-result';\n\n/**\n * Executes a transaction plan and returns the execution results.\n *\n * This function traverses the transaction plan tree, executing each transaction\n * message and collecting results that mirror the structure of the original plan.\n *\n * @typeParam TContext - The type of the context object that may be passed along with successful results.\n * @param transactionPlan - The transaction plan to execute.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel execution.\n * @return A promise that resolves to the execution results.\n *\n * @see {@link TransactionPlan}\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutor = (\n transactionPlan: TransactionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\ntype ExecuteResult = {\n context?: TContext;\n} & ({ signature: Signature } | { transaction: Transaction });\n\ntype ExecuteTransactionMessage = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\n/**\n * Configuration object for creating a new transaction plan executor.\n *\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutorConfig = {\n /** Called whenever a transaction message must be sent to the blockchain. */\n executeTransactionMessage: ExecuteTransactionMessage;\n};\n\n/**\n * Creates a new transaction plan executor based on the provided configuration.\n *\n * The executor will traverse the provided `TransactionPlan` sequentially or in parallel,\n * executing each transaction message using the `executeTransactionMessage` function.\n *\n * - If that function is successful, the executor will return a successful `TransactionPlanResult`\n * for that message including the transaction and any custom context.\n * - If that function throws an error, the executor will stop processing and cancel all\n * remaining transaction messages in the plan.\n * - If the `abortSignal` is triggered, the executor will immediately stop processing the plan and\n * return a `TransactionPlanResult` with the status set to `canceled`.\n *\n * @param config - Configuration object containing the transaction message executor function.\n * @return A {@link TransactionPlanExecutor} function that can execute transaction plans.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * if any transaction in the plan fails to execute. The error context contains a\n * `transactionPlanResult` property with the partial results up to the point of failure.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED}\n * if the transaction plan contains non-divisible sequential plans, which are not\n * supported by this executor.\n *\n * @example\n * ```ts\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * const transactionPlanExecutor = createTransactionPlanExecutor({\n * executeTransactionMessage: async (message) => {\n * const transaction = await signTransactionMessageWithSigners(message);\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * return { transaction };\n * }\n * });\n * ```\n *\n * @see {@link TransactionPlanExecutorConfig}\n */\nexport function createTransactionPlanExecutor(config: TransactionPlanExecutorConfig): TransactionPlanExecutor {\n return async (plan, { abortSignal } = {}): Promise => {\n const context: TraverseContext = {\n ...config,\n abortSignal: abortSignal,\n canceled: abortSignal?.aborted ?? false,\n };\n\n // Fail early if there are non-divisible sequential plans in the\n // transaction plan as they are not supported by this executor.\n assertDivisibleSequentialPlansOnly(plan);\n\n const cancelHandler = () => {\n context.canceled = true;\n };\n abortSignal?.addEventListener('abort', cancelHandler);\n const transactionPlanResult = await traverse(plan, context);\n abortSignal?.removeEventListener('abort', cancelHandler);\n\n if (context.canceled) {\n const abortReason = abortSignal?.aborted ? abortSignal.reason : undefined;\n const context = { cause: findErrorFromTransactionPlanResult(transactionPlanResult) ?? abortReason };\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can create recovery plans but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, context);\n }\n\n return transactionPlanResult;\n };\n}\n\ntype TraverseContext = TransactionPlanExecutorConfig & {\n abortSignal?: AbortSignal;\n canceled: boolean;\n};\n\nasync function traverse(transactionPlan: TransactionPlan, context: TraverseContext): Promise {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(transactionPlan, context);\n case 'parallel':\n return await traverseParallel(transactionPlan, context);\n case 'single':\n return await traverseSingle(transactionPlan, context);\n default:\n transactionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n transactionPlan: SequentialTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n\n const results: TransactionPlanResult[] = [];\n\n for (const subPlan of transactionPlan.plans) {\n const result = await traverse(subPlan, context);\n results.push(result);\n }\n\n return sequentialTransactionPlanResult(results);\n}\n\nasync function traverseParallel(\n transactionPlan: ParallelTransactionPlan,\n context: TraverseContext,\n): Promise {\n const results = await Promise.all(transactionPlan.plans.map(plan => traverse(plan, context)));\n return parallelTransactionPlanResult(results);\n}\n\nasync function traverseSingle(\n transactionPlan: SingleTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (context.canceled) {\n return canceledSingleTransactionPlanResult(transactionPlan.message);\n }\n\n try {\n const result = await getAbortablePromise(\n context.executeTransactionMessage(transactionPlan.message, { abortSignal: context.abortSignal }),\n context.abortSignal,\n );\n if ('transaction' in result) {\n return successfulSingleTransactionPlanResult(transactionPlan.message, result.transaction, result.context);\n } else {\n return successfulSingleTransactionPlanResultFromSignature(\n transactionPlan.message,\n result.signature,\n result.context,\n );\n }\n } catch (error) {\n context.canceled = true;\n return failedSingleTransactionPlanResult(transactionPlan.message, error as Error);\n }\n}\n\nfunction findErrorFromTransactionPlanResult(result: TransactionPlanResult): Error | undefined {\n if (result.kind === 'single') {\n return result.status.kind === 'failed' ? result.status.error : undefined;\n }\n for (const plan of result.plans) {\n const error = findErrorFromTransactionPlanResult(plan);\n if (error) {\n return error;\n }\n }\n}\n\nfunction assertDivisibleSequentialPlansOnly(transactionPlan: TransactionPlan): void {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'parallel':\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'single':\n default:\n return;\n }\n}\n\n/**\n * Wraps a transaction plan execution promise to return a\n * {@link TransactionPlanResult} even on execution failure.\n *\n * When a transaction plan executor throws a\n * {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * error, this helper catches it and returns the `TransactionPlanResult`\n * from the error context instead of throwing.\n *\n * This allows us to handle the result of an execution in a single unified way\n * instead of using try/catch and examine the `TransactionPlanResult` in both\n * success and failure cases.\n *\n * Any other errors are re-thrown as normal.\n *\n * @param promise - A promise returned by a transaction plan executor.\n * @return A promise that resolves to the transaction plan result, even if some transactions failed.\n *\n * @example\n * Handling failures using a single result object:\n * ```ts\n * const result = await passthroughFailedTransactionPlanExecution(\n * transactionPlanExecutor(transactionPlan)\n * );\n *\n * const summary = summarizeTransactionPlanResult(result);\n * if (summary.successful) {\n * console.log('All transactions executed successfully');\n * } else {\n * console.log(`${summary.successfulTransactions.length} succeeded`);\n * console.log(`${summary.failedTransactions.length} failed`);\n * console.log(`${summary.canceledTransactions.length} canceled`);\n * }\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n * @see {@link summarizeTransactionPlanResult}\n */\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise {\n try {\n return await promise;\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN)) {\n return error.context.transactionPlanResult as TransactionPlanResult;\n }\n throw error;\n }\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { getAbortablePromise } from '@solana/promises';\nimport {\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\nimport {\n InstructionPlan,\n MessagePackerInstructionPlan,\n ParallelInstructionPlan,\n SequentialInstructionPlan,\n SingleInstructionPlan,\n} from './instruction-plan';\nimport {\n flattenTransactionPlan,\n nonDivisibleSequentialTransactionPlan,\n parallelTransactionPlan,\n sequentialTransactionPlan,\n SingleTransactionPlan,\n singleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\n\n/**\n * Plans one or more transactions according to the provided instruction plan.\n *\n * @param instructionPlan - The instruction plan to be planned and executed.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel the planning process.\n *\n * @see {@link InstructionPlan}\n * @see {@link TransactionPlan}\n */\nexport type TransactionPlanner = (\n instructionPlan: InstructionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise;\n\ntype Mutable = { -readonly [P in keyof T]: T[P] };\n\ntype CreateTransactionMessage = (config?: {\n abortSignal?: AbortSignal;\n}) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\ntype OnTransactionMessageUpdated = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\n/**\n * Configuration object for creating a new transaction planner.\n *\n * @see {@link createTransactionPlanner}\n */\nexport type TransactionPlannerConfig = {\n /** Called whenever a new transaction message is needed. */\n createTransactionMessage: CreateTransactionMessage;\n /**\n * Called whenever a transaction message is updated — e.g. new instructions were added.\n * This function must return the updated transaction message back — even if no changes were made.\n */\n onTransactionMessageUpdated?: OnTransactionMessageUpdated;\n};\n\n/**\n * Creates a new transaction planner based on the provided configuration.\n *\n * At the very least, the `createTransactionMessage` function must be provided.\n * This function is used to create new transaction messages whenever needed.\n *\n * Additionally, the `onTransactionMessageUpdated` function can be provided\n * to update transaction messages during the planning process. This function will\n * be called whenever a transaction message is updated, e.g. when new instructions\n * are added to a transaction message. It accepts the updated transaction message\n * and must return a transaction message back, even if no changes were made.\n *\n * @example\n * ```ts\n * const transactionPlanner = createTransactionPlanner({\n * createTransactionMessage: () => pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(mySigner, message),\n * )\n * });\n * ```\n *\n * @see {@link TransactionPlannerConfig}\n */\nexport function createTransactionPlanner(config: TransactionPlannerConfig): TransactionPlanner {\n return async (instructionPlan, { abortSignal } = {}): Promise => {\n const plan = await traverse(instructionPlan, {\n abortSignal,\n createTransactionMessage: config.createTransactionMessage,\n onTransactionMessageUpdated: config.onTransactionMessageUpdated ?? (msg => msg),\n parent: null,\n parentCandidates: [],\n });\n\n if (!plan) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN);\n }\n\n return freezeTransactionPlan(plan);\n };\n}\n\ntype MutableTransactionPlan = Mutable;\ntype MutableSingleTransactionPlan = Mutable;\n\ntype TraverseContext = {\n abortSignal?: AbortSignal;\n createTransactionMessage: CreateTransactionMessage;\n onTransactionMessageUpdated: OnTransactionMessageUpdated;\n parent: InstructionPlan | null;\n parentCandidates: MutableSingleTransactionPlan[];\n};\n\nasync function traverse(\n instructionPlan: InstructionPlan,\n context: TraverseContext,\n): Promise {\n context.abortSignal?.throwIfAborted();\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(instructionPlan, context);\n case 'parallel':\n return await traverseParallel(instructionPlan, context);\n case 'single':\n return await traverseSingle(instructionPlan, context);\n case 'messagePacker':\n return await traverseMessagePacker(instructionPlan, context);\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n instructionPlan: SequentialInstructionPlan,\n context: TraverseContext,\n): Promise {\n let candidate: MutableSingleTransactionPlan | null = null;\n\n // Check if the sequential plan must fit entirely in its parent candidates\n // due to constraints like being inside a parallel plan or not being divisible.\n const mustEntirelyFitInParentCandidate =\n context.parent && (context.parent.kind === 'parallel' || !instructionPlan.divisible);\n\n // If so, try to fit the entire plan inside one of the parent candidates.\n if (mustEntirelyFitInParentCandidate) {\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, message =>\n fitEntirePlanInsideMessage(instructionPlan, message),\n );\n // If that's possible, we the candidate is mutated and we can return null.\n // Otherwise, we proceed with the normal traversal and no parent candidate.\n if (candidate) {\n return null;\n }\n } else {\n // Otherwise, we can use the first parent candidate, if any,\n // since we know it must be a divisible sequential plan.\n candidate = context.parentCandidates.length > 0 ? context.parentCandidates[0] : null;\n }\n\n const transactionPlans: TransactionPlan[] = [];\n for (const plan of instructionPlan.plans) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidate ? [candidate] : [],\n });\n if (transactionPlan) {\n candidate = getSequentialCandidate(transactionPlan);\n const newPlans =\n transactionPlan.kind === 'sequential' && (transactionPlan.divisible || !instructionPlan.divisible)\n ? transactionPlan.plans\n : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a sequential plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return {\n divisible: instructionPlan.divisible,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nasync function traverseParallel(\n instructionPlan: ParallelInstructionPlan,\n context: TraverseContext,\n): Promise {\n const candidates: MutableSingleTransactionPlan[] = [...context.parentCandidates];\n const transactionPlans: TransactionPlan[] = [];\n\n // Reorder children so message packer plans are last.\n const sortedChildren = Array.from(instructionPlan.plans).sort(\n (a, b) => Number(a.kind === 'messagePacker') - Number(b.kind === 'messagePacker'),\n );\n\n for (const plan of sortedChildren) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidates,\n });\n if (transactionPlan) {\n candidates.push(...getParallelCandidates(transactionPlan));\n const newPlans = transactionPlan.kind === 'parallel' ? transactionPlan.plans : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a parallel plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return { kind: 'parallel', plans: transactionPlans };\n}\n\nasync function traverseSingle(\n instructionPlan: SingleInstructionPlan,\n context: TraverseContext,\n): Promise {\n const predicate = (message: TransactionMessage & TransactionMessageWithFeePayer) =>\n appendTransactionMessageInstructions([instructionPlan.instruction], message);\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, predicate);\n if (candidate) {\n return null;\n }\n const message = await createNewMessage(context, predicate);\n return { kind: 'single', message };\n}\n\nasync function traverseMessagePacker(\n instructionPlan: MessagePackerInstructionPlan,\n context: TraverseContext,\n): Promise {\n const messagePacker = instructionPlan.getMessagePacker();\n const transactionPlans: SingleTransactionPlan[] = [];\n const candidates = [...context.parentCandidates];\n\n while (!messagePacker.done()) {\n const candidate = await selectAndMutateCandidate(context, candidates, messagePacker.packMessageToCapacity);\n if (!candidate) {\n const message = await createNewMessage(context, messagePacker.packMessageToCapacity);\n const newPlan: MutableSingleTransactionPlan = { kind: 'single', message };\n transactionPlans.push(newPlan);\n }\n }\n\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n if (context.parent?.kind === 'parallel') {\n return { kind: 'parallel', plans: transactionPlans };\n }\n return {\n divisible: context.parent?.kind === 'sequential' ? context.parent.divisible : true,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nfunction getSequentialCandidate(latestPlan: MutableTransactionPlan): MutableSingleTransactionPlan | null {\n if (latestPlan.kind === 'single') {\n return latestPlan;\n }\n if (latestPlan.kind === 'sequential' && latestPlan.plans.length > 0) {\n return getSequentialCandidate(latestPlan.plans[latestPlan.plans.length - 1]);\n }\n return null;\n}\n\nfunction getParallelCandidates(latestPlan: TransactionPlan): MutableSingleTransactionPlan[] {\n return flattenTransactionPlan(latestPlan);\n}\n\nasync function selectAndMutateCandidate(\n context: Pick,\n candidates: MutableSingleTransactionPlan[],\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n for (const candidate of candidates) {\n try {\n const message = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(candidate.message), {\n abortSignal: context.abortSignal,\n }),\n ),\n context.abortSignal,\n );\n if (getTransactionMessageSize(message) <= TRANSACTION_SIZE_LIMIT) {\n candidate.message = message;\n return candidate;\n }\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN)) {\n // Try the next candidate.\n } else {\n throw error;\n }\n }\n }\n return null;\n}\n\nasync function createNewMessage(\n context: Pick,\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n const newMessage = await getAbortablePromise(\n Promise.resolve(context.createTransactionMessage({ abortSignal: context.abortSignal })),\n context.abortSignal,\n );\n const updatedMessage = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(newMessage), { abortSignal: context.abortSignal }),\n ),\n context.abortSignal,\n );\n const updatedMessageSize = getTransactionMessageSize(updatedMessage);\n if (updatedMessageSize > TRANSACTION_SIZE_LIMIT) {\n const newMessageSize = getTransactionMessageSize(newMessage);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: updatedMessageSize - newMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - newMessageSize,\n });\n }\n return updatedMessage;\n}\n\nfunction freezeTransactionPlan(plan: MutableTransactionPlan): TransactionPlan {\n const kind = plan.kind;\n switch (kind) {\n case 'single':\n return singleTransactionPlan(plan.message);\n case 'sequential':\n return plan.divisible\n ? sequentialTransactionPlan(plan.plans.map(freezeTransactionPlan))\n : nonDivisibleSequentialTransactionPlan(plan.plans.map(freezeTransactionPlan));\n case 'parallel':\n return parallelTransactionPlan(plan.plans.map(freezeTransactionPlan));\n default:\n plan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nfunction fitEntirePlanInsideMessage(\n instructionPlan: InstructionPlan,\n message: TransactionMessage & TransactionMessageWithFeePayer,\n): TransactionMessage & TransactionMessageWithFeePayer {\n let newMessage: TransactionMessage & TransactionMessageWithFeePayer = message;\n\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n case 'parallel':\n for (const plan of instructionPlan.plans) {\n newMessage = fitEntirePlanInsideMessage(plan, newMessage);\n }\n return newMessage;\n case 'single':\n newMessage = appendTransactionMessageInstructions([instructionPlan.instruction], message);\n // eslint-disable-next-line no-case-declarations\n const newMessageSize = getTransactionMessageSize(newMessage);\n if (newMessageSize > TRANSACTION_SIZE_LIMIT) {\n const baseMessageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: newMessageSize - baseMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - baseMessageSize,\n });\n }\n return newMessage;\n case 'messagePacker':\n // eslint-disable-next-line no-case-declarations\n const messagePacker = instructionPlan.getMessagePacker();\n while (!messagePacker.done()) {\n newMessage = messagePacker.packMessageToCapacity(newMessage);\n }\n return newMessage;\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n","import { assertIsAddress, isAddress } from '@solana/addresses';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * A 32-byte array identifying the application requesting off-chain message signing.\n *\n * This may be any arbitrary bytes. For instance the on-chain address of a program, DAO instance,\n * Candy Machine, et cetera.\n *\n * This field SHOULD be displayed to users as a base58-encoded ASCII string rather than interpreted\n * otherwise.\n */\nexport type OffchainMessageApplicationDomain = Brand<\n EncodedString,\n 'OffchainMessageApplicationDomain'\n>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the\n * {@link OffchainMessageApplicationDomain} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * if (isOffchainMessageApplicationDomain(applicationDomain)) {\n * // At this point, `applicationDomain` has been refined to an\n * // `OffchainMessageApplcationDomain` that can be used to craft a message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } else {\n * setError(`${applicationDomain} is not a valid application domain for an offchain message`);\n * }\n * ```\n */\nexport function isOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): putativeApplicationDomain is OffchainMessageApplicationDomain {\n return isAddress(putativeApplicationDomain);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an offchain message\n * application domain, from an untrusted network API or user input. Use this function to assert that\n * such an arbitrary string is a base58-encoded application domain.\n *\n * @example\n * ```ts\n * import { assertIsOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * // Imagine a function that determines whether an application domain is valid.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const applicationDomain: string = applicationDomainInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `applicationDomain` to `OffchainMessageApplicationDomain`.\n * assertIsOffchainMessageApplicationDomain(applicationDomain);\n * // At this point, `applicationDomain` is a `OffchainMessageApplicationDomain` that can be\n * // used to craft an offchain message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } catch (e) {\n * // `applicationDomain` turned out not to be a base58-encoded application domain\n * }\n * }\n * ```\n */\nexport function assertIsOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): asserts putativeApplicationDomain is OffchainMessageApplicationDomain {\n try {\n assertIsAddress(putativeApplicationDomain);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n error.context,\n );\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n error.context,\n );\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is an offchain message application domain with _coercing_ it\n * to the {@link OffchainMessageApplicationDomain} type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good application domain as a string, it's more efficient to typecast\n * > it rather than to use the {@link offchainMessageApplicationDomain} helper, because the helper\n * > unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageApplicationDomain } from '@solana/offchain-messages';\n * >\n * > const applicationDomain =\n * > 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * > ```\n */\nexport function offchainMessageApplicationDomain(putativeApplicationDomain: string): OffchainMessageApplicationDomain {\n assertIsOffchainMessageApplicationDomain(putativeApplicationDomain);\n return putativeApplicationDomain;\n}\n","import { Address, getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformEncoder,\n} from '@solana/codecs-core';\n\nimport { OffchainMessageApplicationDomain, offchainMessageApplicationDomain } from '../application-domain';\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded offchain message application\n * domain to a byte array.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainEncoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomain =\n * 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * const offchainMessageApplicationDomainEncoder = getOffchainMessageApplicationDomainEncoder();\n * const offchainMessageApplicationDomainBytes =\n * offchainMessageApplicationDomainEncoder.encode(offchainMessageApplicationDomain);\n * // Uint8Array(32) [\n * // 247, 203, 28, 80, 52, 240, 169, 19,\n * // 21, 103, 107, 119, 91, 235, 13, 48,\n * // 194, 169, 148, 160, 78, 105, 235, 37,\n * // 232, 160, 49, 47, 64, 89, 18, 153,\n * // ]\n * ```\n */\nexport function getOffchainMessageApplicationDomainEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getAddressEncoder(),\n putativeApplicationDomain => offchainMessageApplicationDomain(putativeApplicationDomain) as string as Address,\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an offchain\n * message application domain to the base58-encoded representation of that application domain.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomainBytes = new Uint8Array([\n * 247, 203, 28, 80, 52, 240, 169, 19,\n * 21, 103, 107, 119, 91, 235, 13, 48,\n * 194, 169, 148, 160, 78, 105, 235, 37,\n * 232, 160, 49, 47, 64, 89, 18, 153,\n * ]);\n * const offchainMessageApplicationDomainDecoder = getOffchainMessageApplicationDomainDecoder();\n * const offchainMessageApplicationDomain =\n * offchainMessageApplicationDomainDecoder.decode(offchainMessageApplicationDomainBytes);\n * // HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx\n * ```\n */\nexport function getOffchainMessageApplicationDomainDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder<\n OffchainMessageApplicationDomain,\n 32\n >;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded offchain message\n * application domain.\n *\n * @see {@link getOffchainMessageApplicationDomainDecoder}\n * @see {@link getOffchainMessageApplicationDomainEncoder}\n */\nexport function getOffchainMessageApplicationDomainCodec(): FixedSizeCodec<\n OffchainMessageApplicationDomain,\n OffchainMessageApplicationDomain,\n 32\n> {\n return combineCodec(getOffchainMessageApplicationDomainEncoder(), getOffchainMessageApplicationDomainDecoder());\n}\n","import {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getConstantDecoder, getConstantEncoder } from '@solana/codecs-data-structures';\n\n// The string `'\\xffsolana offchain'`\nconst OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES: ReadonlyUint8Array = new Uint8Array([\n 0xff, 0x73, 0x6f, 0x6c, 0x61, 0x6e, 0x61, 0x20, 0x6f, 0x66, 0x66, 0x63, 0x68, 0x61, 0x69, 0x6e,\n]);\n\nexport function getOffchainMessageSigningDomainDecoder(): FixedSizeDecoder {\n return getConstantDecoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeDecoder;\n}\n\nexport function getOffchainMessageSigningDomainEncoder(): FixedSizeEncoder {\n return getConstantEncoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeEncoder;\n}\n\nexport function getOffchainMessageSigningDomainCodec(): FixedSizeCodec {\n return combineCodec(getOffchainMessageSigningDomainEncoder(), getOffchainMessageSigningDomainDecoder());\n}\n","import { Address, getAddressDecoder } from '@solana/addresses';\nimport {\n FixedSizeDecoder,\n FixedSizeEncoder,\n offsetDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageVersion } from '../version';\nimport { getOffchainMessageSigningDomainDecoder, getOffchainMessageSigningDomainEncoder } from './signing-domain';\n\ntype TDecoderFields = Parameters[0];\ntype TEncoderFields = Parameters[0];\n\nfunction getSigningDomainPrefixedDecoder(...fields: T) {\n return getHiddenPrefixDecoder(getStructDecoder(fields), [getOffchainMessageSigningDomainDecoder()]);\n}\n\nfunction getSigningDomainPrefixedEncoder(...fields: T) {\n return getHiddenPrefixEncoder(getStructEncoder(fields), [getOffchainMessageSigningDomainEncoder()]);\n}\n\nfunction getVersionTransformer(fixedVersion?: OffchainMessageVersion) {\n return (version: number) => {\n if (version > 1) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n if (fixedVersion != null && version !== fixedVersion) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION, {\n actualVersion: version,\n expectedVersion: fixedVersion,\n });\n }\n return version;\n };\n}\n\nexport function createOffchainMessagePreambleDecoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TDecoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer(version)) as FixedSizeDecoder],\n ...fields,\n );\n}\n\nexport function createOffchainMessagePreambleEncoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TEncoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedEncoder(\n ['version', transformEncoder(getU8Encoder(), getVersionTransformer(version)) as FixedSizeEncoder],\n ...fields,\n );\n}\n\nexport function decodeRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const { version, bytesAfterVersion } = getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer())],\n ['bytesAfterVersion', getBytesDecoder()],\n ).decode(bytes);\n return offsetDecoder(\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses;\n }),\n {\n preOffset: ({ preOffset }) =>\n preOffset +\n (version === 0\n ? 32 + 1 // skip the application domain and message format of v0 messages\n : 0),\n },\n ).decode(bytesAfterVersion);\n}\n\nexport function getSignatoriesComparator(): (a: ReadonlyUint8Array, b: ReadonlyUint8Array) => -1 | 0 | 1 {\n return (x, y) => {\n if (x.length !== y.length) {\n return x.length < y.length ? -1 : 1;\n }\n for (let ii = 0; ii < x.length; ii++) {\n if (x[ii] === y[ii]) {\n continue;\n } else {\n return x[ii] < y[ii] ? -1 : 1;\n }\n }\n return 0;\n };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\n\nfunction getSignaturesToEncode(signaturesMap: OffchainMessageEnvelope['signatures']): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getU8Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { Address, address } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\nimport { OffchainMessageBytes } from '../message';\nimport { decodeRequiredSignatoryAddresses } from './preamble-common';\nimport { getSignaturesEncoder } from './signatures';\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageEnvelope} to a byte array\n * appropriate for sharing with a third party for validation.\n */\nexport function getOffchainMessageEnvelopeEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['content', getBytesEncoder()],\n ]),\n envelope => {\n const signaturesMapAddresses = Object.keys(envelope.signatures).map(address);\n if (signaturesMapAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(envelope.content);\n const missingRequiredSigners = [];\n const unexpectedSigners = [];\n for (const address of signatoryAddresses) {\n if (!signaturesMapAddresses.includes(address)) {\n missingRequiredSigners.push(address);\n }\n }\n for (const address of signaturesMapAddresses) {\n if (!signatoryAddresses.includes(address)) {\n unexpectedSigners.push(address);\n }\n }\n if (missingRequiredSigners.length || unexpectedSigners.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH, {\n missingRequiredSigners,\n unexpectedSigners,\n });\n }\n const orderedSignatureMap: OffchainMessageEnvelope['signatures'] = {};\n for (const address of signatoryAddresses) {\n orderedSignatureMap[address] = envelope.signatures[address];\n }\n return {\n ...envelope,\n signatures: orderedSignatureMap,\n };\n },\n );\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana offchain message format\n * to a {@link OffchainMessageEnvelope} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageEnvelopeDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelopeDecoder = getOffchainMessageEnvelopeDecoder();\n * const offchainMessageEnvelope = offchainMessageEnvelopeDecoder.decode(offchainMessageEnvelopeBytes);\n * for (const [address, signature] in Object.entries(offchainMessageEnvelope.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\nexport function getOffchainMessageEnvelopeDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getU8Decoder() })],\n ['content', getBytesDecoder()],\n ]),\n decodePartiallyDecodedOffchainMessageEnvelope,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageEnvelope}\n *\n * @see {@link getOffchainMessageEnvelopeDecoder}\n * @see {@link getOffchainMessageEnvelopeEncoder}\n */\nexport function getOffchainMessageEnvelopeCodec() {\n return combineCodec(getOffchainMessageEnvelopeEncoder(), getOffchainMessageEnvelopeDecoder());\n}\n\ntype PartiallyDecodedOffchainMessageEnvelope = {\n content: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedOffchainMessageEnvelope(\n offchainMessageEnvelope: PartiallyDecodedOffchainMessageEnvelope,\n): OffchainMessageEnvelope {\n const { content, signatures } = offchainMessageEnvelope;\n\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(content);\n\n // Signer addresses and signatures must be the same length\n // We encode an all-zero signature when the signature is missing\n if (signatoryAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH, {\n numRequiredSignatures: signatoryAddresses.length,\n signatoryAddresses,\n signaturesLength: signatures.length,\n });\n }\n\n // Combine the signer addresses + signatures into the signatures map\n const signaturesMap: OffchainMessageEnvelope['signatures'] = {};\n signatoryAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return Object.freeze({\n content: content as OffchainMessageBytes,\n signatures: Object.freeze(signaturesMap),\n });\n}\n\nfunction decodeAndValidateRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const signatoryAddresses = decodeRequiredSignatoryAddresses(bytes);\n\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n\n return signatoryAddresses;\n}\n","import { getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nconst MAX_BODY_BYTES =\n // Largest 16-bit unsigned integer\n 0xffff;\nconst MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE =\n // Space remaining in the mininum IPv6 MTU after network header overhead\n 1232;\n\n/**\n * A restriction on what characters the message text can contain and how long it can be.\n *\n * The aim of this restriction is to make a message more likely to be signable by a hardware wallet\n * that imposes limits on message size. In the case of wanting a message to be clear-signable,\n * restricting the character set to ASCII may ensure that certain models of hardware wallet without\n * extended character sets can display it onscreen.\n *\n * @remarks This only applies to v0 messages.\n */\nexport enum OffchainMessageContentFormat {\n RESTRICTED_ASCII_1232_BYTES_MAX = 0,\n UTF8_1232_BYTES_MAX = 1,\n UTF8_65535_BYTES_MAX = 2,\n}\n\n/**\n * Describes message text that is no more than 1232 bytes long and made up of characters with ASCII\n * character codes in the range [0x20, 0x7e].\n *\n * @remarks This type aims to restrict text to that which can be clear-signed by hardware wallets\n * that can only display ASCII characters onscreen.\n */\nexport type OffchainMessageContentRestrictedAsciiOf1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 1232 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 65535 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of65535BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX;\n text: Brand;\n}>;\n\nexport type OffchainMessageContent =\n | OffchainMessageContentRestrictedAsciiOf1232BytesMax\n | OffchainMessageContentUtf8Of1232BytesMax\n | OffchainMessageContentUtf8Of65535BytesMax;\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (isTextRestrictedAscii(putativeContent.text) === false) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX ||\n putativeContent.text.length === 0 ||\n isTextRestrictedAscii(putativeContent.text) === false\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is restricted ASCII with\n * _coercing_ it to the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type. It's most\n * useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageContentRestrictedAsciiOf1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: offchainMessageContentRestrictedAsciiOf1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentRestrictedAsciiOf1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good ASCII content as a string, it's more efficient to typecast it\n * > rather than to use the {@link offchainMessageContentRestrictedAsciiOf1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n * > text: 'Hello world',\n * > } as OffchainMessageContentRestrictedAsciiOf1232BytesMax<'Hello world'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentRestrictedAsciiOf1232BytesMax(\n text: TText,\n): OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n });\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 1232 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of1232BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 1232 bytes, it's more efficient\n * > to typecast it rather than to use the {@link offchainMessageContentUtf8Of1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of1232BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of1232BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of65535BytesMax}\n * type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of65535BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 65535 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of65535BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of65535BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of65535BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of65535BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 65535 bytes, it's more efficient\n * > to typecast it rather than to use the {@link OffchainMessageContentUtf8Of65535BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of65535BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of65535BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of65535BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent);\n return putativeContent;\n}\n\nfunction isTextRestrictedAscii(putativeRestrictedAsciiString: string): boolean {\n return /^[\\x20-\\x7e]+$/.test(putativeRestrictedAsciiString);\n}\n","import {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageContentUtf8Of1232BytesMax,\n assertIsOffchainMessageContentUtf8Of65535BytesMax,\n OffchainMessageContentFormat,\n OffchainMessageContentRestrictedAsciiOf1232BytesMax,\n OffchainMessageContentUtf8Of1232BytesMax,\n OffchainMessageContentUtf8Of65535BytesMax,\n} from './content';\nimport { OffchainMessagePreambleV0 } from './preamble-v0';\nimport { OffchainMessageWithRequiredSignatories } from './signatures';\n\nexport type BaseOffchainMessageV0 = Omit<\n OffchainMessagePreambleV0,\n 'messageFormat' | 'messageLength' | 'requiredSignatories'\n>;\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax}\n */\nexport interface OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent {\n readonly content: OffchainMessageContentRestrictedAsciiOf1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link offchainMessageContentUtf8Of1232BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of1232BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentUtf8Of65535BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of65535BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of65535BytesMax;\n}\n\n/**\n * A union of the formats a v0 message's contents can take.\n *\n * @remarks From v1 and onward, an offchain message has only one format: UTF-8 text of arbitrary\n * length.\n */\nexport type OffchainMessageWithContent =\n | OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent\n | OffchainMessageWithUtf8Of1232BytesMaxContent\n | OffchainMessageWithUtf8Of65535BytesMaxContent;\n\nexport type OffchainMessageV0 = BaseOffchainMessageV0 &\n OffchainMessageWithContent &\n OffchainMessageWithRequiredSignatories;\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }>,\n): asserts putativeMessage is OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link offchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link offchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentUtf8Of65535BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of65535BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of65535BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeMessage.content);\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getEnumDecoder, getEnumEncoder } from '@solana/codecs-data-structures';\n\nimport { OffchainMessageContentFormat } from '../content';\n\nexport function getOffchainMessageContentFormatDecoder(): FixedSizeDecoder {\n return getEnumDecoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatEncoder(): FixedSizeEncoder {\n return getEnumEncoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatCodec(): FixedSizeCodec<\n OffchainMessageContentFormat,\n OffchainMessageContentFormat,\n 1\n> {\n return combineCodec(getOffchainMessageContentFormatEncoder(), getOffchainMessageContentFormatDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder, getU16Decoder, getU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\n\nimport { OffchainMessagePreambleV0 } from '../preamble-v0';\nimport {\n getOffchainMessageApplicationDomainDecoder,\n getOffchainMessageApplicationDomainEncoder,\n} from './application-domain';\nimport { getOffchainMessageContentFormatDecoder, getOffchainMessageContentFormatEncoder } from './content';\nimport { createOffchainMessagePreambleDecoder, createOffchainMessagePreambleEncoder } from './preamble-common';\n\nexport function getOffchainMessageV0PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainDecoder()],\n ['messageFormat', getOffchainMessageContentFormatDecoder()],\n [\n 'requiredSignatories',\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(address => Object.freeze({ address }));\n }),\n ],\n ['messageLength', getU16Decoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainEncoder()],\n ['messageFormat', getOffchainMessageContentFormatEncoder()],\n [\n 'requiredSignatories',\n transformEncoder(\n getArrayEncoder(getAddressEncoder(), { size: getU8Encoder() }),\n (signatoryAddresses: OffchainMessagePreambleV0['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(({ address }) => address);\n },\n ),\n ],\n ['messageLength', getU16Encoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0PreambleEncoder(), getOffchainMessageV0PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageContentFormat } from '../content';\nimport {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageUtf8Of1232BytesMax,\n assertIsOffchainMessageUtf8Of65535BytesMax,\n OffchainMessageV0,\n} from '../message-v0';\nimport { getOffchainMessageV0PreambleDecoder, getOffchainMessageV0PreambleEncoder } from './preamble-v0';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV0} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV0Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV0Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v0 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 0.\n */\nexport function getOffchainMessageV0Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV0PreambleDecoder(), getUtf8Decoder()]),\n ([{ messageLength, messageFormat, requiredSignatories, ...preambleRest }, text]) => {\n const actualLength = getUtf8Encoder().getSizeFromValue(text);\n if (messageLength !== actualLength) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH, {\n actualLength: actualLength,\n specifiedLength: messageLength,\n });\n }\n const offchainMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }> = Object.freeze({\n ...preambleRest,\n content: Object.freeze({\n format: messageFormat,\n text,\n }),\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n switch (messageFormat) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n return offchainMessage;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: messageFormat satisfies never,\n });\n }\n }\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV0} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV0Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV0PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...preamble } = offchainMessage;\n switch (offchainMessage.content.format) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n break;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: offchainMessage.content satisfies never,\n });\n }\n }\n const messageLength = getUtf8Encoder().getSizeFromValue(content.text);\n const compiledPreamble = {\n ...preamble,\n messageFormat: content.format,\n messageLength,\n };\n return [compiledPreamble, content.text] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV0}\n *\n * @see {@link getOffchainMessageV0Decoder}\n * @see {@link getOffchainMessageV0Encoder}\n */\nexport function getOffchainMessageV0Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0Encoder(), getOffchainMessageV0Decoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getBytesDecoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessagePreambleV1 } from '../preamble-v1';\nimport {\n createOffchainMessagePreambleDecoder,\n createOffchainMessagePreambleEncoder,\n getSignatoriesComparator,\n} from './preamble-common';\n\nexport function getOffchainMessageV1PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(/* version */ 1, [\n 'requiredSignatories',\n transformDecoder(\n getArrayDecoder(fixDecoderSize(getBytesDecoder(), 32), { size: getU8Decoder() }),\n signatoryAddressesBytes => {\n if (signatoryAddressesBytes.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const comparator = getSignatoriesComparator();\n for (let ii = 0; ii < signatoryAddressesBytes.length - 1; ii++) {\n switch (comparator(signatoryAddressesBytes[ii], signatoryAddressesBytes[ii + 1])) {\n case 0:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n case 1:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED);\n }\n }\n const addressDecoder = getAddressDecoder();\n return signatoryAddressesBytes.map(addressBytes =>\n Object.freeze({\n address: addressDecoder.decode(addressBytes),\n }),\n );\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(/* version */ 1, [\n 'requiredSignatories',\n transformEncoder(\n transformEncoder(\n getArrayEncoder(getBytesEncoder(), { size: getU8Encoder() }),\n (signatoryAddressesBytes: readonly ReadonlyUint8Array[]) => {\n return signatoryAddressesBytes.toSorted(getSignatoriesComparator());\n },\n ),\n (signatoryAddresses: OffchainMessagePreambleV1['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const seenSignatories = new Set();\n for (const { address } of signatoryAddresses) {\n if (seenSignatories.has(address)) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n }\n seenSignatories.add(address);\n }\n const addressEncoder = getAddressEncoder();\n return signatoryAddresses.map(({ address }) => addressEncoder.encode(address));\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1PreambleEncoder(), getOffchainMessageV1PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY, SolanaError } from '@solana/errors';\n\nimport { OffchainMessageV1 } from '../message-v1';\nimport { getOffchainMessageV1PreambleDecoder, getOffchainMessageV1PreambleEncoder } from './preamble-v1';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV1} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV1Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV1Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v1 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 1.\n */\nexport function getOffchainMessageV1Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV1PreambleDecoder(), getUtf8Decoder()]),\n ([{ requiredSignatories, ...preambleRest }, text]) => {\n if (text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return Object.freeze({\n ...preambleRest,\n content: text,\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV1} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV1Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV1PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...compiledPreamble } = offchainMessage;\n if (content.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return [compiledPreamble, content] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV1}\n *\n * @see {@link getOffchainMessageV1Decoder}\n * @see {@link getOffchainMessageV1Encoder}\n */\nexport function getOffchainMessageV1Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1Encoder(), getOffchainMessageV1Decoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getHiddenPrefixDecoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, SolanaError } from '@solana/errors';\n\nimport { OffchainMessage } from '../message';\nimport { getOffchainMessageV0Decoder, getOffchainMessageV0Encoder } from './message-v0';\nimport { getOffchainMessageV1Decoder, getOffchainMessageV1Encoder } from './message-v1';\nimport { getOffchainMessageSigningDomainDecoder } from './signing-domain';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessage} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageDecoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded an offchain message (version: ${offchainMessage.version}`);\n * ```\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the decoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageDecoder(): VariableSizeDecoder {\n return createDecoder({\n read(bytes, offset): [OffchainMessage, number] {\n const version = getHiddenPrefixDecoder(getU8Decoder(), [\n // Discard the signing domain\n getOffchainMessageSigningDomainDecoder(),\n ]).decode(bytes, offset);\n switch (version) {\n case 0:\n return getOffchainMessageV0Decoder().read(bytes, offset);\n case 1:\n return getOffchainMessageV1Decoder().read(bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n },\n });\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessage} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the encoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: offchainMessage => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().getSizeFromValue(offchainMessage);\n case 1:\n return getOffchainMessageV1Encoder().getSizeFromValue(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n write: (offchainMessage, bytes, offset) => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().write(offchainMessage, bytes, offset);\n case 1:\n return getOffchainMessageV1Encoder().write(offchainMessage, bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessage}\n *\n * @see {@link getOffchainMessageDecoder}\n * @see {@link getOffchainMessageEncoder}\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the codecs specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageEncoder(), getOffchainMessageDecoder());\n}\n","import { VariableSizeEncoder } from '@solana/codecs-core';\n\nimport { OffchainMessageEnvelope } from './envelope';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\nexport function compileOffchainMessageEnvelopeUsingEncoder(\n offchainMessage: T,\n encoder: VariableSizeEncoder,\n) {\n const offchainMessageBytes = encoder.encode(offchainMessage) as OffchainMessageBytes;\n const signatures: OffchainMessageEnvelope['signatures'] = {};\n for (const { address } of offchainMessage.requiredSignatories) {\n signatures[address] = null;\n }\n return Object.freeze({\n content: offchainMessageBytes,\n signatures: Object.freeze(signatures),\n });\n}\n","import { getOffchainMessageV0Encoder } from './codecs/message-v0';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV0 } from './message-v0';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV0}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV0Envelope(offchainMessage: OffchainMessageV0): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV0Encoder());\n}\n","import { getOffchainMessageV1Encoder } from './codecs/message-v1';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV1 } from './message-v1';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV1}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV1Envelope(offchainMessage: OffchainMessageV1): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV1Encoder());\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { compileOffchainMessageV0Envelope } from './envelope-v0';\nimport { compileOffchainMessageV1Envelope } from './envelope-v1';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\ntype OrderedMap = Record;\ntype OffchainMessageSignaturesMap = OrderedMap;\n\nexport interface OffchainMessageEnvelope {\n /** The bytes of the combined offchain message preamble and content */\n readonly content: OffchainMessageBytes;\n /**\n * A map between the addresses of an offchain message's signers, and the 64-byte Ed25519\n * signature of the combined message preamble and message content by the private key associated\n * with each.\n */\n readonly signatures: OffchainMessageSignaturesMap;\n}\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessage}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the compile functions\n * specific to that version so as not to bundle more code than you need.\n */\nexport function compileOffchainMessageEnvelope(offchainMessage: OffchainMessage): OffchainMessageEnvelope {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return compileOffchainMessageV0Envelope(offchainMessage);\n case 1:\n return compileOffchainMessageV1Envelope(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: version satisfies never,\n });\n }\n}\n","import { Address, getAddressFromPublicKey, getPublicKeyFromAddress } from '@solana/addresses';\nimport { bytesEqual } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes, signBytes, verifySignature } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { decodeRequiredSignatoryAddresses } from './codecs/preamble-common';\nimport { OffchainMessageEnvelope } from './envelope';\n\n/**\n * Represents an offchain message envelope that is signed by all of its required signers.\n */\nexport type FullySignedOffchainMessageEnvelope = NominalType<'offchainMessageEnvelopeSignedness', 'fullySigned'>;\n\n/**\n * Represents an address that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatory = Readonly<{\n address: Address;\n}>;\n\n/**\n * An offchain message having a list of accounts that must sign it in order for it to be valid.\n */\nexport interface OffchainMessageWithRequiredSignatories<\n TSignatory extends OffchainMessageSignatory = OffchainMessageSignatory,\n> {\n requiredSignatories: readonly TSignatory[];\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message, this method will return a new signed offchain message\n * envelope of type {@link OffchainMessageEnvelope}.\n *\n * Though the resulting message might be signed by all required signers, this function will not\n * assert that it is. A partially signed message is not complete, but can be serialized and\n * deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const partiallySignedOffchainMessage = await partiallySignOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link signOffchainMessageEnvelope} if you want to assert that the message is signed by all\n * its required signers after signing.\n */\nexport async function partiallySignOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n const requiredSignatoryAddresses = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n\n // Check if the address is expected to sign the message\n if (!requiredSignatoryAddresses.includes(address)) {\n // address is not an expected signer for this message\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const existingSignature = offchainMessageEnvelope.signatures[address];\n const newSignature = await signBytes(keyPair.privateKey, offchainMessageEnvelope.content);\n\n if (existingSignature != null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE, {\n expectedAddresses: requiredSignatoryAddresses,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return offchainMessageEnvelope;\n }\n\n return Object.freeze({\n ...offchainMessageEnvelope,\n signatures: Object.freeze({\n ...offchainMessageEnvelope.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message envelope, this method will return a new signed envelope of\n * type {@link FullySignedOffchainMessageEnvelope}.\n *\n * This function will throw unless the resulting message is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const signedOffchainMessage = await signOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link partiallySignOffchainMessageEnvelope} if you want to sign the message without\n * asserting that the resulting message envelope is fully signed.\n */\nexport async function signOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n const out = await partiallySignOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope);\n assertIsFullySignedOffchainMessageEnvelope(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * A type guard that returns `true` if the input {@link OffchainMessageEnvelope} is fully signed,\n * and refines its type for use in your program, adding the\n * {@link FullySignedOffchainMessageEnvelope} type.\n *\n * @example\n * ```ts\n * import { isFullySignedOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * if (isFullySignedOffchainMessageEnvelope(offchainMessageEnvelope)) {\n * // At this point we know that the offchain message is fully signed.\n * }\n * ```\n */\nexport function isFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n return Object.entries(offchainMessage.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link OffchainMessageEnvelope}, that you expect to be\n * fully signed, from an untrusted network API or user input. Use this function to assert that such\n * an offchain message is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedOffchainMessage } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast\n * // `offchainMessageEnvelope` to `FullySignedOffchainMessageEnvelope`.\n * assertIsFullySignedOffchainMessageEnvelope(offchainMessage);\n * // At this point we know that the offchain message is signed by all required signers.\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function assertIsFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): asserts offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n const missingSigs: Address[] = [];\n Object.entries(offchainMessage.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n\n/**\n * Asserts that there are signatures present for all of an offchain message's required signatories,\n * and that those signatures are valid given the message.\n *\n * @example\n * ```ts\n * import { isSolanaError, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE } from '@solana/errors';\n * import { verifyOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * try {\n * await verifyOffchainMessageEnvelope(offchainMessageEnvelope);\n * // At this point the message is valid and signed by all of the required signatories.\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) {\n * if (e.context.signatoriesWithMissingSignatures.length) {\n * console.error(\n * 'Missing signatures for the following addresses',\n * e.context.signatoriesWithMissingSignatures,\n * );\n * }\n * if (e.context.signatoriesWithInvalidSignatures.length) {\n * console.error(\n * 'Signatures for the following addresses are invalid',\n * e.context.signatoriesWithInvalidSignatures,\n * );\n * }\n * }\n * throw e;\n * }\n */\nexport async function verifyOffchainMessageEnvelope(offchainMessageEnvelope: OffchainMessageEnvelope): Promise {\n let errorContext;\n const requiredSignatories = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n await Promise.all(\n requiredSignatories.map(async address => {\n const signature = offchainMessageEnvelope.signatures[address];\n if (signature == null) {\n errorContext ||= {};\n errorContext.signatoriesWithMissingSignatures ||= [];\n errorContext.signatoriesWithMissingSignatures.push(address);\n } else {\n const publicKey = await getPublicKeyFromAddress(address);\n if (await verifySignature(publicKey, signature, offchainMessageEnvelope.content)) {\n return true;\n } else {\n errorContext ||= {};\n errorContext.signatoriesWithInvalidSignatures ||= [];\n errorContext.signatoriesWithInvalidSignatures.push(address);\n }\n }\n }),\n );\n if (errorContext) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, errorContext);\n }\n}\n","/**\n * Defines a plugin that transforms or extends a client with additional functionality.\n *\n * For instance, plugins may add RPC capabilities, wallet integration, transaction building,\n * or other features necessary for interacting with the Solana blockchain.\n *\n * Plugins are functions that take a client object as input and return a new client object\n * or a promise that resolves to a new client object. This allows for both synchronous\n * and asynchronous transformations and extensions of the client.\n *\n * Plugins are usually applied using the `use` method on a {@link Client} or {@link AsyncClient}\n * instance, which {@link createEmptyClient} provides as a starting point.\n *\n * @typeParam TInput - The input client object type that this plugin accepts.\n * @typeParam TOutput - The output type. Either a new client object or a promise resolving to one.\n *\n * @example Basic RPC plugin\n * Given an RPC endpoint, this plugin adds an `rpc` property to the client.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc } from '@solana/kit';\n *\n * // Define a simple RPC plugin.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n *\n * // Use the plugin.\n * const client = createEmptyClient().use(rpcPlugin('https://api.mainnet-beta.solana.com'));\n * await client.rpc.getLatestBlockhash().send();\n * ```\n *\n * @example Async plugin that generates a payer wallet\n * The following plugin shows how to create an asynchronous plugin that generates a new keypair signer.\n *\n * ```ts\n * import { createEmptyClient, generateKeypairSigner } from '@solana/kit';\n *\n * // Define a plugin that generates a new keypair signer.\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n *\n * // Use the plugin.\n * const client = await createEmptyClient().use(generatedPayerPlugin());\n * console.log(client.payer.address);\n * ```\n *\n * @example Plugins with input requirements\n * A plugin can specify required properties on the input client. The example below requires the\n * client to already have a `payer` signer attached to the client in order to perform an airdrop.\n *\n * ```ts\n * import { createEmptyClient, TransactionSigner, Lamports, lamports } from '@solana/kit';\n *\n * // Define a plugin that airdrops lamports to the payer set on the client.\n * function airdropPayerPlugin(lamports: Lamports) {\n * return async (client: T) => {\n * await myAirdropFunction(client.payer, lamports);\n * return client;\n * };\n * }\n *\n * // Use the plugins.\n * const client = await createEmptyClient()\n * .use(generatedPayerPlugin()) // This is required before using the airdrop plugin.\n * .use(airdropPayerPlugin(lamports(1_000_000_000n)));\n * ```\n *\n * @example Chaining plugins\n * Multiple plugins — asynchronous or not — can be chained together to build up complex clients.\n * The example below demonstrates how to gradually build a client with multiple plugins.\n * Notice how, despite having multiple asynchronous plugins, we only need to `await` the final result.\n * This is because the `use` method on `AsyncClient` returns another `AsyncClient`, allowing for seamless chaining.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc, createSolanaRpcSubscriptions, generateKeypairSigner } from '@solana/kit';\n *\n * // Define multiple plugins.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n * function rpcSubscriptionsPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpcSubscriptions(endpoint) });\n * }\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n * function generatedAuthorityPlugin() {\n * return async (client: T) => ({...client, authority: await generateKeypairSigner() });\n * }\n *\n * // Chain plugins together.\n * const client = await createEmptyClient()\n * .use(rpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(rpcSubscriptionsPlugin('wss://api.mainnet-beta.solana.com'))\n * .use(generatedPayerPlugin())\n * .use(generatedAuthorityPlugin());\n * ```\n */\nexport type ClientPlugin | object> = (input: TInput) => TOutput;\n\n/**\n * A client that can be extended with plugins.\n *\n * The `Client` type represents a client object that can be built up through\n * the application of one or more plugins. It provides a `use` method to\n * apply plugins, either synchronously (returning a new `Client`) or\n * asynchronously (returning an {@link AsyncClient}).\n *\n * @typeParam TSelf - The current shape of the client object including all applied plugins.\n */\nexport type Client = TSelf & {\n /**\n * Applies a plugin to extend or transform the client.\n *\n * @param plugin The plugin function to apply to this client.\n * @returns Either a new `Client` (for sync plugins) or {@link AsyncClient} (for async plugins).\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => TOutput extends Promise ? AsyncClient : Client;\n};\n\n/**\n * An asynchronous wrapper that represents a promise of a client.\n *\n * The `AsyncClient` type is returned when an async plugin is applied to a client.\n * It behaves like a `Promise>` but with an additional `use` method\n * that allows chaining more plugins before the promise resolves.\n *\n * This enables fluent chaining of both synchronous and asynchronous plugins\n * without having to await intermediate promises.\n *\n * @typeParam TSelf - The shape of the client object that this async client will resolve to.\n */\nexport type AsyncClient = Promise> & {\n /**\n * Applies a plugin to the client once it resolves.\n *\n * @param plugin The plugin function to apply to the resolved client.\n * @returns A new `AsyncClient` representing the result of applying the plugin.\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => AsyncClient ? (U extends object ? U : never) : TOutput>;\n};\n\n// TODO(loris): Add examples in this docblock using real plugins once they have been published.\n\n/**\n * Creates a new empty client that can be extended with plugins.\n *\n * This serves as an entry point for building Solana clients.\n * Start with an empty client and chain the `.use()` method\n * to apply plugins that add various functionalities such as RPC\n * connectivity, wallet integration, transaction building, and more.\n *\n * See {@link ClientPlugin} for detailed examples on creating and using plugins.\n *\n * @returns An empty client object with only the `use` method available.\n *\n * @example Basic client setup\n * ```ts\n * import { createEmptyClient } from '@solana/client';\n *\n * const client = createEmptyClient()\n * .use(myRpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(myWalletPlugin());\n * ```\n */\nexport function createEmptyClient(): Client {\n return addUse({});\n}\n\nfunction addUse(value: TSelf): Client {\n return Object.freeze({\n ...value,\n use | object>(plugin: ClientPlugin) {\n const result = plugin(value);\n return result instanceof Promise ? createAsyncClient(result) : addUse(result);\n },\n } as Client);\n}\n\nfunction createAsyncClient(promise: Promise): AsyncClient {\n return Object.freeze({\n catch(onrejected) {\n return promise.then(v => addUse(v)).catch(onrejected);\n },\n finally(onfinally) {\n return promise.then(v => addUse(v)).finally(onfinally);\n },\n then(onfulfilled, onrejected) {\n return promise.then(v => addUse(v)).then(onfulfilled, onrejected);\n },\n use | object>(plugin: ClientPlugin) {\n return createAsyncClient(promise.then(plugin));\n },\n } as AsyncClient);\n}\n","import type { Address } from '@solana/addresses';\nimport { isSolanaError, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SolanaError } from '@solana/errors';\n\n/**\n * Identifies whether an error -- typically caused by a transaction failure -- is a custom program\n * error from the provided program address.\n *\n * @param transactionMessage The transaction message that failed to execute. Since the RPC response\n * only provides the index of the failed instruction, the transaction message is required to\n * determine its program address\n * @param programAddress The address of the program from which the error is expected to have\n * originated\n * @param code The expected error code of the custom program error. When provided, the function will\n * check that the custom program error code matches the given value.\n *\n * @example\n * ```ts\n * try {\n * // Send and confirm your transaction.\n * } catch (error) {\n * if (isProgramError(error, transactionMessage, myProgramAddress, 42)) {\n * // Handle custom program error 42 from this program.\n * } else if (isProgramError(error, transactionMessage, myProgramAddress)) {\n * // Handle all other custom program errors from this program.\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isProgramError(\n error: unknown,\n transactionMessage: { instructions: Record },\n programAddress: Address,\n code?: TProgramErrorCode,\n): error is Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> &\n SolanaError {\n if (!isSolanaError(error, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM)) {\n return false;\n }\n const instructionProgramAddress = transactionMessage.instructions[error.context.index]?.programAddress;\n if (!instructionProgramAddress || instructionProgramAddress !== programAddress) {\n return false;\n }\n return typeof code === 'undefined' || error.context.code === code;\n}\n","/**\n * This function is a replacement for `JSON.parse` that can handle large\n * unsafe integers by parsing them as BigInts. It transforms every\n * numerical value into a BigInt without loss of precision.\n */\nexport function parseJsonWithBigInts(json: string): unknown {\n return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {\n return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;\n });\n}\n\nfunction wrapIntegersInBigIntValueObject(json: string): string {\n const out = [];\n let inQuote = false;\n for (let ii = 0; ii < json.length; ii++) {\n let isEscaped = false;\n if (json[ii] === '\\\\') {\n out.push(json[ii++]);\n isEscaped = !isEscaped;\n }\n if (json[ii] === '\"') {\n out.push(json[ii]);\n if (!isEscaped) {\n inQuote = !inQuote;\n }\n continue;\n }\n if (!inQuote) {\n const consumedNumber = consumeNumber(json, ii);\n if (consumedNumber?.length) {\n ii += consumedNumber.length - 1;\n // Don't wrap numbers that contain a decimal point or a negative exponent.\n if (consumedNumber.match(/\\.|[eE]-/)) {\n out.push(consumedNumber);\n } else {\n out.push(wrapBigIntValueObject(consumedNumber));\n }\n continue;\n }\n }\n out.push(json[ii]);\n }\n\n return out.join('');\n}\n\nfunction consumeNumber(json: string, ii: number): string | null {\n /** @see https://stackoverflow.com/a/13340826/11440277 */\n const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/;\n\n // Stop early if the first character isn't a digit or a minus sign.\n if (!json[ii]?.match(/[-\\d]/)) {\n return null;\n }\n\n // Otherwise, check if the next characters form a valid JSON number.\n const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);\n return numberMatch ? numberMatch[0] : null;\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: string): string {\n return `{\"$n\":\"${value}\"}`;\n}\n\nfunction unwrapBigIntValueObject({ $n }: BigIntValueObject): bigint {\n if ($n.match(/[eE]/)) {\n const [units, exponent] = $n.split(/[eE]/);\n return BigInt(units) * BigInt(10) ** BigInt(exponent);\n }\n return BigInt($n);\n}\n\nfunction isBigIntValueObject(value: unknown): value is BigIntValueObject {\n return !!value && typeof value === 'object' && '$n' in value && typeof value.$n === 'string';\n}\n","import { RpcRequest } from './rpc-request';\n\nlet _nextMessageId = 0n;\nfunction getNextMessageId(): string {\n const id = _nextMessageId;\n _nextMessageId++;\n return id.toString();\n}\n\n/**\n * Returns a spec-compliant JSON RPC 2.0 message, given a method name and some params.\n *\n * Generates a new `id` on each call by incrementing a `bigint` and casting it to a string.\n */\nexport function createRpcMessage(request: RpcRequest) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method: request.methodName,\n params: request.params,\n };\n}\n","/**\n * Transforms a value into a JSON string, whilst rendering bigints as large unsafe integers.\n */\nexport function stringifyJsonWithBigInts(value: unknown, space?: number | string): string {\n return unwrapBigIntValueObject(\n JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? wrapBigIntValueObject(v) : v), space),\n );\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: bigint): BigIntValueObject {\n return { $n: `${value}` };\n}\n\nfunction unwrapBigIntValueObject(value: string): string {\n return value.replace(/\\{\\s*\"\\$n\"\\s*:\\s*\"(-?\\d+)\"\\s*\\}/g, '$1');\n}\n","import { SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\n\nimport { RpcApi, RpcPlan } from './rpc-api';\nimport { RpcTransport } from './rpc-transport';\n\nexport type RpcConfig = Readonly<{\n api: RpcApi;\n transport: TRpcTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcMethods`.\n *\n * Calling each method returns a {@link PendingRpcRequest | PendingRpcRequest} where\n * `TResponse` is that method's response type.\n */\nexport type Rpc = {\n [TMethodName in keyof TRpcMethods]: PendingRpcRequestBuilder>;\n};\n\n/**\n * Pending requests are the result of calling a supported method on a {@link Rpc} object. They\n * encapsulate all of the information necessary to make the request without actually making it.\n *\n * Calling the {@link PendingRpcRequest.send | `send(options)`} method on a\n * {@link PendingRpcRequest | PendingRpcRequest} will trigger the request and return a\n * promise for `TResponse`.\n */\nexport type PendingRpcRequest = {\n send(options?: RpcSendOptions): Promise;\n};\n\nexport type RpcSendOptions = Readonly<{\n /**\n * An optional signal that you can supply when triggering a {@link PendingRpcRequest} that you\n * might later need to abort.\n */\n abortSignal?: AbortSignal;\n}>;\n\ntype PendingRpcRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TMethodImplementations]: PendingRpcRequestReturnTypeMapper;\n }>\n>;\n\ntype PendingRpcRequestReturnTypeMapper =\n // Check that this property of the TRpcMethods interface is, in fact, a function.\n TMethodImplementation extends Callable\n ? (...args: Parameters) => PendingRpcRequest>\n : never;\n\n/**\n * Creates a {@link Rpc} instance given a {@link RpcApi | RpcApi} and a\n * {@link RpcTransport} capable of fulfilling them.\n */\nexport function createRpc(\n rpcConfig: RpcConfig,\n): Rpc {\n return makeProxy(rpcConfig);\n}\n\nfunction makeProxy(\n rpcConfig: RpcConfig,\n): Rpc {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const getApiPlan = Reflect.get(target, methodName, receiver);\n if (!getApiPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {\n method: methodName,\n params: rawParams,\n });\n }\n const apiPlan = getApiPlan(...rawParams);\n return createPendingRpcRequest(rpcConfig, apiPlan);\n };\n },\n }) as Rpc;\n}\n\nfunction createPendingRpcRequest(\n { transport }: RpcConfig,\n plan: RpcPlan,\n): PendingRpcRequest {\n return {\n async send(options?: RpcSendOptions): Promise {\n return await plan.execute({ signal: options?.abortSignal, transport });\n },\n };\n}\n","import {\n Callable,\n createRpcMessage,\n RpcRequestTransformer,\n RpcResponse,\n RpcResponseTransformer,\n} from '@solana/rpc-spec-types';\n\nimport type { RpcTransport } from './rpc-transport';\n\nexport type RpcApiConfig = Readonly<{\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n /**\n * An optional function that transforms the {@link RpcResponse} before it is returned to the\n * caller.\n *\n * Use cases for this include constructing complex data types from serialized data, and throwing\n * exceptions.\n */\n responseTransformer?: RpcResponseTransformer;\n}>;\n\n/**\n * This type allows an {@link RpcApi} to describe how a particular request should be issued to the\n * JSON RPC server.\n *\n * Given a function that was called on a {@link Rpc}, this object exposes an `execute` function that\n * dictates which request will be sent, how the underlying transport will be used, and how the\n * responses will be transformed.\n *\n * This function accepts a {@link RpcTransport} and an `AbortSignal` and asynchronously returns a\n * {@link RpcResponse}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * transport.\n * - call the underlying transport zero, one or multiple times depending on the use-case (e.g.\n * caching or aggregating multiple responses).\n * - transform the response from the JSON RPC server, in case it does not match the `TResponse`\n * specified by the {@link PendingRpcRequest | PendingRpcRequest} returned from that\n * function.\n */\nexport type RpcPlan = {\n execute: (\n config: Readonly<{\n signal?: AbortSignal;\n transport: RpcTransport;\n }>,\n ) => Promise>;\n};\n\n/**\n * For each of `TRpcMethods`, this object exposes a method with the same name that maps between its\n * input arguments and a {@link RpcPlan | RpcPlan} that implements the execution of a\n * JSON RPC request to fetch `TResponse`.\n */\nexport type RpcApi = {\n [MethodName in keyof TRpcMethods]: RpcReturnTypeMapper;\n};\n\ntype RpcReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcApiMethod = (...args: any) => any;\ninterface RpcApiMethods {\n [methodName: string]: RpcApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a {@link RpcPlan} by\n * creating an `execute` function that:\n *\n * - sets the transport payload to a JSON RPC v2 payload object with the requested `methodName` and\n * `params` properties, optionally transformed by {@link RpcApiConfig.requestTransformer}.\n * - transforms the transport's response using the {@link RpcApiConfig.responseTransformer}\n * function, if provided.\n *\n * @example\n * ```ts\n * // For example, given this `RpcApi`:\n * const rpcApi = createJsonRpcApi({\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * responseTransformer: response => response.result,\n * });\n *\n * // ...the following function call:\n * rpcApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Returns the \"result\" property of the RPC response.\n * ```\n */\nexport function createJsonRpcApi(config?: RpcApiConfig): RpcApi {\n return new Proxy({} as RpcApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcMethods as string;\n return function (\n ...rawParams: Parameters<\n TRpcMethods[TMethodName] extends CallableFunction ? TRpcMethods[TMethodName] : never\n >\n ): RpcPlan> {\n const rawRequest = Object.freeze({ methodName, params: rawParams });\n const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;\n return Object.freeze(>>{\n execute: async ({ signal, transport }) => {\n const payload = createRpcMessage(request);\n const response = await transport({ payload, signal });\n if (!config?.responseTransformer) {\n return response;\n }\n return config.responseTransformer(response, request);\n },\n });\n };\n },\n });\n}\n","import { RpcResponse } from '@solana/rpc-spec-types';\n\ntype Config = Readonly<{\n /** A value of arbitrary type to be sent to a RPC server */\n payload: unknown;\n /**\n * An optional `AbortSignal` on which the `'abort'` event will be fired if the request should be\n * cancelled.\n */\n signal?: AbortSignal;\n}>;\n\n/**\n * A function that can act as a transport for a {@link Rpc}. It need only return a promise for a\n * response given the supplied config.\n */\nexport type RpcTransport = {\n (config: Config): Promise>;\n};\n\n/**\n * Returns `true` if the given payload is a JSON RPC v2 payload.\n *\n * This means, the payload is an object such that:\n *\n * - It has a `jsonrpc` property with a value of `'2.0'`.\n * - It has a `method` property that is a string.\n * - It has a `params` property of any type.\n *\n * @example\n * ```ts\n * import { isJsonRpcPayload } from '@solana/rpc-spec';\n *\n * if (isJsonRpcPayload(payload)) {\n * const payloadMethod: string = payload.method;\n * const payloadParams: unknown = payload.params;\n * }\n * ```\n */\nexport function isJsonRpcPayload(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: string;\n params: unknown;\n}> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n","export function downcastNodeToNumberIfBigint(value: bigint): number;\nexport function downcastNodeToNumberIfBigint(value: T): T;\nexport function downcastNodeToNumberIfBigint(value: unknown): unknown {\n return typeof value === 'bigint'\n ? // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n Number(value)\n : value;\n}\n","import { RpcRequest, RpcRequestTransformer, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nexport type KeyPathWildcard = { readonly ['__keyPathWildcard:@solana/kit']: unique symbol };\nexport type KeyPath = ReadonlyArray;\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n\ntype NodeVisitor = (value: unknown, state: TState) => unknown;\nexport type TraversalState = Readonly<{\n keyPath: KeyPath;\n}>;\n\nfunction getTreeWalker(visitors: NodeVisitor[]) {\n return function traverse(node: unknown, state: TState): unknown {\n if (Array.isArray(node)) {\n return node.map((element, ii) => {\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, ii],\n };\n return traverse(element, nextState);\n });\n } else if (typeof node === 'object' && node !== null) {\n const out: Record = {};\n for (const propName in node) {\n if (!Object.prototype.hasOwnProperty.call(node, propName)) {\n continue;\n }\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, propName],\n };\n out[propName] = traverse(node[propName as keyof typeof node], nextState);\n }\n return out;\n } else {\n return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);\n }\n };\n}\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided visitors at\n * each node. A custom initial state can be provided but must at least provide `{ keyPath: [] }`.\n *\n * @example\n * ```ts\n * import { getTreeWalkerRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getTreeWalkerRequestTransformer(\n * [\n * // Replaces foo.bar with \"baz\".\n * (node, state) => (state.keyPath === ['foo', 'bar'] ? 'baz' : node),\n * // Increments all numbers by 1.\n * node => (typeof node === number ? node + 1 : node),\n * ],\n * { keyPath: [] },\n * );\n * ```\n */\nexport function getTreeWalkerRequestTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const traverse = getTreeWalker(visitors);\n return Object.freeze({\n ...request,\n params: traverse(request.params, initialState),\n });\n };\n}\n\nexport function getTreeWalkerResponseTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcResponseTransformer {\n return json => getTreeWalker(visitors)(json, initialState);\n}\n","import { downcastNodeToNumberIfBigint } from './request-transformer-bigint-downcast-internal';\nimport { getTreeWalkerRequestTransformer } from './tree-traversal';\n\n/**\n * Creates a transformer that downcasts all `BigInt` values to `Number`.\n *\n * @example\n * ```ts\n * import { getBigIntDowncastRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getBigIntDowncastRequestTransformer();\n * ```\n *\n */\nexport function getBigIntDowncastRequestTransformer() {\n return getTreeWalkerRequestTransformer([downcastNodeToNumberIfBigint], { keyPath: [] });\n}\n","import { Commitment } from '@solana/rpc-types';\n\nexport function applyDefaultCommitment({\n commitmentPropertyName,\n params,\n optionsObjectPositionInParams,\n overrideCommitment,\n}: Readonly<{\n commitmentPropertyName: string;\n optionsObjectPositionInParams: number;\n overrideCommitment?: Commitment;\n params: unknown[];\n}>) {\n const paramInTargetPosition = params[optionsObjectPositionInParams];\n if (\n // There's no config.\n paramInTargetPosition === undefined ||\n // There is a config object.\n (paramInTargetPosition && typeof paramInTargetPosition === 'object' && !Array.isArray(paramInTargetPosition))\n ) {\n if (\n // The config object already has a commitment set.\n paramInTargetPosition &&\n commitmentPropertyName in paramInTargetPosition\n ) {\n if (\n !paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] ||\n paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] === 'finalized'\n ) {\n // Delete the commitment property; `finalized` is already the server default.\n const nextParams = [...params];\n const {\n [commitmentPropertyName as keyof typeof paramInTargetPosition]: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...rest\n } = paramInTargetPosition;\n if (Object.keys(rest).length > 0) {\n nextParams[optionsObjectPositionInParams] = rest;\n } else {\n if (optionsObjectPositionInParams === nextParams.length - 1) {\n nextParams.length--;\n } else {\n nextParams[optionsObjectPositionInParams] = undefined;\n }\n }\n return nextParams;\n }\n } else if (overrideCommitment !== 'finalized') {\n // Apply the default commitment.\n const nextParams = [...params];\n nextParams[optionsObjectPositionInParams] = {\n ...paramInTargetPosition,\n [commitmentPropertyName]: overrideCommitment,\n };\n return nextParams;\n }\n }\n return params;\n}\n","import type { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { applyDefaultCommitment } from './request-transformer-default-commitment-internal';\n\n/**\n * Creates a transformer that adds the provided default commitment to the configuration object of the request when applicable.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getDefaultCommitmentRequestTransformer, OPTIONS_OBJECT_POSITION_BY_METHOD } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultCommitmentRequestTransformer({\n * defaultCommitment: 'confirmed',\n * optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n * });\n */\nexport function getDefaultCommitmentRequestTransformer({\n defaultCommitment,\n optionsObjectPositionByMethod,\n}: Readonly<{\n defaultCommitment?: Commitment;\n optionsObjectPositionByMethod: Record;\n}>): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const { params, methodName } = request;\n\n // We only apply default commitment to array parameters.\n if (!Array.isArray(params)) {\n return request;\n }\n\n // Find the position of the options object in the parameters and abort if not found.\n const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];\n if (optionsObjectPositionInParams == null) {\n return request;\n }\n\n return Object.freeze({\n methodName,\n params: applyDefaultCommitment({\n commitmentPropertyName: methodName === 'sendTransaction' ? 'preflightCommitment' : 'commitment',\n optionsObjectPositionInParams,\n overrideCommitment: defaultCommitment,\n params,\n }),\n });\n };\n}\n","import { KeyPath, TraversalState } from './tree-traversal';\n\nexport function getIntegerOverflowNodeVisitor(onIntegerOverflow: (keyPath: KeyPath, value: bigint) => void) {\n return (value: T, { keyPath }: TraversalState): T => {\n if (typeof value === 'bigint') {\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath as (number | string)[], value);\n }\n }\n return value;\n };\n}\n","import { RpcRequest } from '@solana/rpc-spec-types';\n\nimport { getIntegerOverflowNodeVisitor } from './request-transformer-integer-overflow-internal';\nimport { getTreeWalkerRequestTransformer, KeyPath } from './tree-traversal';\n\nexport type IntegerOverflowHandler = (request: RpcRequest, keyPath: KeyPath, value: bigint) => void;\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided handler\n * when an integer overflow is detected.\n *\n * @example\n * ```ts\n * import { getIntegerOverflowRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getIntegerOverflowRequestTransformer((request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * });\n * ```\n */\nexport function getIntegerOverflowRequestTransformer(onIntegerOverflow: IntegerOverflowHandler) {\n return (request: RpcRequest): RpcRequest => {\n const transformer = getTreeWalkerRequestTransformer(\n [getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))],\n { keyPath: [] },\n );\n return transformer(request);\n };\n}\n","export const OPTIONS_OBJECT_POSITION_BY_METHOD: Record = {\n accountNotifications: 1,\n blockNotifications: 1,\n getAccountInfo: 1,\n getBalance: 1,\n getBlock: 1,\n getBlockHeight: 0,\n getBlockProduction: 0,\n getBlocks: 2,\n getBlocksWithLimit: 2,\n getEpochInfo: 0,\n getFeeForMessage: 1,\n getInflationGovernor: 0,\n getInflationReward: 1,\n getLargestAccounts: 0,\n getLatestBlockhash: 0,\n getLeaderSchedule: 1,\n getMinimumBalanceForRentExemption: 1,\n getMultipleAccounts: 1,\n getProgramAccounts: 1,\n getSignaturesForAddress: 1,\n getSlot: 0,\n getSlotLeader: 0,\n getStakeMinimumDelegation: 0,\n getSupply: 0,\n getTokenAccountBalance: 1,\n getTokenAccountsByDelegate: 2,\n getTokenAccountsByOwner: 2,\n getTokenLargestAccounts: 1,\n getTokenSupply: 1,\n getTransaction: 1,\n getTransactionCount: 0,\n getVoteAccounts: 0,\n isBlockhashValid: 1,\n logsNotifications: 1,\n programNotifications: 1,\n requestAirdrop: 2,\n sendTransaction: 1,\n signatureNotifications: 1,\n simulateTransaction: 1,\n};\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { getBigIntDowncastRequestTransformer } from './request-transformer-bigint-downcast';\nimport { getDefaultCommitmentRequestTransformer } from './request-transformer-default-commitment';\nimport { getIntegerOverflowRequestTransformer, IntegerOverflowHandler } from './request-transformer-integer-overflow';\nimport { OPTIONS_OBJECT_POSITION_BY_METHOD } from './request-transformer-options-object-position-config';\n\nexport type RequestTransformerConfig = Readonly<{\n /**\n * An optional {@link Commitment} value to use as the default when none is supplied by the\n * caller.\n */\n defaultCommitment?: Commitment;\n /**\n * An optional function that will be called whenever a `bigint` input exceeds that which can be\n * expressed using JavaScript numbers.\n *\n * This is used in the default {@link SolanaRpcSubscriptionsApi} to throw an exception rather\n * than to allow truncated values to propagate through a program.\n */\n onIntegerOverflow?: IntegerOverflowHandler;\n}>;\n\n/**\n * Returns the default request transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcRequestTransformer | RpcRequestTransformers} together such as the\n * {@link getDefaultCommitmentTransformer}, the {@link getIntegerOverflowRequestTransformer} and the\n * {@link getBigIntDowncastRequestTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultRequestTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultRequestTransformerForSolanaRpc({\n * defaultCommitment: 'confirmed',\n * onIntegerOverflow: (request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * },\n * });\n * ```\n */\nexport function getDefaultRequestTransformerForSolanaRpc(config?: RequestTransformerConfig): RpcRequestTransformer {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n return (request: RpcRequest): RpcRequest => {\n return pipe(\n request,\n handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : r => r,\n getBigIntDowncastRequestTransformer(),\n getDefaultCommitmentRequestTransformer({\n defaultCommitment: config?.defaultCommitment,\n optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n }),\n );\n };\n}\n","import { KeyPath, KEYPATH_WILDCARD, TraversalState } from './tree-traversal';\n\nexport function getBigIntUpcastVisitor(allowedNumericKeyPaths: readonly KeyPath[]) {\n return function upcastNodeToBigIntIfNumber(value: unknown, { keyPath }: TraversalState) {\n const isInteger = (typeof value === 'number' && Number.isInteger(value)) || typeof value === 'bigint';\n if (!isInteger) return value;\n if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {\n return Number(value);\n } else {\n return BigInt(value);\n }\n };\n}\n\nfunction keyPathIsAllowedToBeNumeric(keyPath: KeyPath, allowedNumericKeyPaths: readonly KeyPath[]) {\n return allowedNumericKeyPaths.some(prohibitedKeyPath => {\n if (prohibitedKeyPath.length !== keyPath.length) {\n return false;\n }\n for (let ii = keyPath.length - 1; ii >= 0; ii--) {\n const keyPathPart = keyPath[ii];\n const prohibitedKeyPathPart = prohibitedKeyPath[ii];\n if (\n prohibitedKeyPathPart !== keyPathPart &&\n (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== 'number')\n ) {\n return false;\n }\n }\n return true;\n });\n}\n","import { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath } from './tree-traversal';\n\n/**\n * Returns a transformer that upcasts all `Number` values to `BigInts` unless they match within the\n * provided {@link KeyPath | KeyPaths}. In other words, the provided {@link KeyPath | KeyPaths} will\n * remain as `Number` values, any other numeric value will be upcasted to a `BigInt`.\n *\n * Note that you can use {@link KEYPATH_WILDCARD} to match any key within a {@link KeyPath}.\n *\n * @example\n * ```ts\n * import { getBigIntUpcastResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getBigIntUpcastResponseTransformer([\n * ['index'],\n * ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n * ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n * ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n * ]);\n * ```\n */\nexport function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths: readonly KeyPath[]) {\n return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });\n}\n","import { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\ntype JsonRpcResponse = { result: unknown };\n\n/**\n * Returns a transformer that extracts the `result` field from the body of the RPC response.\n *\n * For instance, we go from `{ jsonrpc: '2.0', result: 'foo', id: 1 }` to `'foo'`.\n *\n * @example\n * ```ts\n * import { getResultResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getResultResponseTransformer();\n * ```\n */\nexport function getResultResponseTransformer(): RpcResponseTransformer {\n return json => (json as JsonRpcResponse).result;\n}\n","import { KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\nexport type AllowedNumericKeypaths = Partial>;\n\n// Numeric values nested in `jsonParsed` accounts\nexport const jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nexport const jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n];\nexport const innerInstructionsConfigs = [\n ['index'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n];\nexport const messageConfig = [\n ['addressTableLookups', KEYPATH_WILDCARD, 'writableIndexes', KEYPATH_WILDCARD],\n ['addressTableLookups', KEYPATH_WILDCARD, 'readonlyIndexes', KEYPATH_WILDCARD],\n ['header', 'numReadonlySignedAccounts'],\n ['header', 'numReadonlyUnsignedAccounts'],\n ['header', 'numRequiredSignatures'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n] as const;\n","import { getSolanaErrorFromJsonRpcError } from '@solana/errors';\nimport { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { innerInstructionsConfigs, jsonParsedAccountsConfigs } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\ntype JsonRpcResponse = { error: Parameters[0] } | { result: unknown };\n\n// Keypaths for simulateTransaction result that should remain as Number (not BigInt)\n// Note: These are relative to the error.data root, not result.value like in success responses\nfunction getSimulateTransactionAllowedNumericKeypaths(): readonly KeyPath[] {\n return [\n ['loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['innerInstructions', KEYPATH_WILDCARD, ...c]),\n ];\n}\n\n/**\n * Returns a transformer that throws a {@link SolanaError} with the appropriate RPC error code if\n * the body of the RPC response contains an error.\n *\n * @example\n * ```ts\n * import { getThrowSolanaErrorResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getThrowSolanaErrorResponseTransformer();\n * ```\n */\nexport function getThrowSolanaErrorResponseTransformer(): RpcResponseTransformer {\n return (json, request) => {\n const jsonRpcResponse = json as JsonRpcResponse;\n if ('error' in jsonRpcResponse) {\n const { error } = jsonRpcResponse;\n\n // Check if this is a sendTransaction preflight failure (error code -32002)\n // These errors contain RpcSimulateTransactionResult in error.data which needs\n // BigInt values downcast to Number for fields that should be numbers\n const isSendTransactionPreflightFailure =\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n (error.code === -32002 || error.code === -32002n);\n\n if (isSendTransactionPreflightFailure && 'data' in error && error.data) {\n // Apply BigInt downcast transformation to error.data\n const treeWalker = getTreeWalkerResponseTransformer(\n [getBigIntUpcastVisitor(getSimulateTransactionAllowedNumericKeypaths())],\n { keyPath: [] },\n );\n const transformedData = treeWalker(error.data, request);\n\n // Reconstruct error with transformed data\n const transformedError = { ...error, data: transformedData };\n throw getSolanaErrorFromJsonRpcError(transformedError);\n }\n\n throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);\n }\n return jsonRpcResponse;\n };\n}\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcResponse, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { AllowedNumericKeypaths } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastResponseTransformer } from './response-transformer-bigint-upcast';\nimport { getResultResponseTransformer } from './response-transformer-result';\nimport { getThrowSolanaErrorResponseTransformer } from './response-transformer-throw-solana-error';\n\nexport type ResponseTransformerConfig = Readonly<{\n /**\n * An optional map from the name of an API method to an array of {@link KeyPath | KeyPaths}\n * pointing to values in the response that should materialize in the application as `Number`\n * instead of `BigInt`.\n */\n allowedNumericKeyPaths?: AllowedNumericKeypaths;\n}>;\n\n/**\n * Returns the default response transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcResponseTransformer | RpcResponseTransformers} together such as the\n * {@link getThrowSolanaErrorResponseTransformer}, the {@link getResultResponseTransformer} and the\n * {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpc({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpc(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(\n response,\n r => getThrowSolanaErrorResponseTransformer()(r, request),\n r => getResultResponseTransformer()(r, request),\n r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request),\n );\n };\n}\n\n/**\n * Returns the default response transformer for the Solana RPC Subscriptions API.\n *\n * Under the hood, this function composes the {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpcSubscriptions } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpcSubscriptions(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(response, r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));\n };\n}\n","/**\n * This package contains types that describe the [methods](https://solana.com/docs/rpc/http) of the\n * Solana JSON RPC API, and utilities for creating a {@link RpcApi} implementation with sensible\n * defaults. It can be used standalone, but it is also exported as part of Kit\n * [`@solana/kit`](https://github.com/anza-xyz/kit/tree/main/packages/kit).\n *\n * @example\n * Each RPC method is described in terms of a TypeScript type of the following form:\n *\n * ```ts\n * type ExampleApi = {\n * getSomething(address: Address): Something;\n * };\n * ```\n *\n * A {@link RpcApi} that implements `ExampleApi` will ultimately expose its defined methods on any\n * {@link Rpc} that uses it.\n *\n * ```ts\n * const rpc: Rpc = createExampleRpc(/* ... *\\/);\n * const something: Something = await rpc.getSomething(address('95DpK3y3GF7U8s1k4EvZ7xqyeCkhsHeZaE97iZpHUGMN')).send();\n * ```\n *\n * @packageDocumentation\n */\nimport { createJsonRpcApi, RpcApi } from '@solana/rpc-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpc,\n innerInstructionsConfigs,\n jsonParsedAccountsConfigs,\n jsonParsedTokenAccountsConfigs,\n KEYPATH_WILDCARD,\n messageConfig,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype SolanaRpcApiForAllClusters = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n SendTransactionApi &\n SimulateTransactionApi;\ntype SolanaRpcApiForTestClusters = RequestAirdropApi & SolanaRpcApiForAllClusters;\n/**\n * Represents the RPC methods available on test clusters.\n *\n * For instance, the test clusters support the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApi = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the devnet cluster.\n *\n * For instance, the devnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiDevnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the testnet cluster.\n *\n * For instance, the testnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiTestnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the mainnet cluster.\n *\n * For instance, the mainnet cluster does not support the {@link RequestAirdropApi} whereas test\n * clusters do.\n */\nexport type SolanaRpcApiMainnet = SolanaRpcApiForAllClusters;\n\nexport type {\n GetAccountInfoApi,\n GetBalanceApi,\n GetBlockApi,\n GetBlockCommitmentApi,\n GetBlockHeightApi,\n GetBlockProductionApi,\n GetBlocksApi,\n GetBlocksWithLimitApi,\n GetBlockTimeApi,\n GetClusterNodesApi,\n GetEpochInfoApi,\n GetEpochScheduleApi,\n GetFeeForMessageApi,\n GetFirstAvailableBlockApi,\n GetGenesisHashApi,\n GetHealthApi,\n GetHighestSnapshotSlotApi,\n GetIdentityApi,\n GetInflationGovernorApi,\n GetInflationRateApi,\n GetInflationRewardApi,\n GetLargestAccountsApi,\n GetLatestBlockhashApi,\n GetLeaderScheduleApi,\n GetMaxRetransmitSlotApi,\n GetMaxShredInsertSlotApi,\n GetMinimumBalanceForRentExemptionApi,\n GetMultipleAccountsApi,\n GetProgramAccountsApi,\n GetRecentPerformanceSamplesApi,\n GetRecentPrioritizationFeesApi,\n GetSignaturesForAddressApi,\n GetSignatureStatusesApi,\n GetSlotApi,\n GetSlotLeaderApi,\n GetSlotLeadersApi,\n GetStakeMinimumDelegationApi,\n GetSupplyApi,\n GetTokenAccountBalanceApi,\n GetTokenAccountsByDelegateApi,\n GetTokenAccountsByOwnerApi,\n GetTokenLargestAccountsApi,\n GetTokenSupplyApi,\n GetTransactionApi,\n GetTransactionCountApi,\n GetVersionApi,\n GetVoteAccountsApi,\n IsBlockhashValidApi,\n MinimumLedgerSlotApi,\n RequestAirdropApi,\n SendTransactionApi,\n SimulateTransactionApi,\n};\n\ntype Config = RequestTransformerConfig;\n\n/**\n * Creates a {@link RpcApi} implementation of the Solana JSON RPC API with some default behaviours.\n *\n * The default behaviours include:\n * - A transform that converts `bigint` inputs to `number` for compatibility with version 1.0 of the\n * Solana JSON RPC.\n * - A transform that calls the config's {@link Config.onIntegerOverflow | onIntegerOverflow}\n * handler whenever a `bigint` input would overflow a JavaScript IEEE 754 number. See\n * [this](https://github.com/solana-labs/solana-web3.js/issues/1116) GitHub issue for more\n * information.\n * - A transform that applies a default commitment wherever not specified\n */\nexport function createSolanaRpcApi<\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n TRpcMethods extends SolanaRpcApi | SolanaRpcApiDevnet | SolanaRpcApiMainnet | SolanaRpcApiTestnet = SolanaRpcApi,\n>(config?: Config): RpcApi {\n return createJsonRpcApi({\n requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),\n responseTransformer: getDefaultResponseTransformerForSolanaRpc({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n }),\n });\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n ...c,\n ]),\n ...messageConfig.map(c => ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', ...c] as const),\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => ['meta', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ...messageConfig.map(c => ['transaction', 'message', ...c] as const),\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: [\n ['value', 'loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['value', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ],\n };\n }\n return memoizedKeypaths;\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SolanaError } from '@solana/errors';\n\nexport type AllowedHttpRequestHeaders = Readonly<\n {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | Capitalize> // `Foo-bar`\n | K // `Foo-Bar`\n | Lowercase // `foo-bar`\n | Uncapitalize // `foo-Bar`\n // `FOO-BAR`\n | Uppercase]?: never;\n } & { [headerName: string]: string }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n // Though technically forbidden in non-Node environments, we don't have a way to target\n // TypeScript types depending on which platform you are authoring for. `Accept-Encoding` is\n // therefore omitted from the forbidden headers type, but is still a runtime error in dev mode\n // when supplied in a non-Node context.\n // | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n // Similar to `Accept-Encoding`, we don't have a way to target TypeScript types depending on\n // which platform you are authoring for. `Origin` is therefore omitted from the forbidden\n // headers type, but is still a runtime error in dev mode when supplied in a browser context.\n // | 'Origin'\n | 'Permissions-Policy'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via'\n | `Proxy-${string}`\n | `Sec-${string}`;\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record = /* @__PURE__ */ Object.assign(\n {\n 'accept-charset': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n 'permissions-policy': true,\n // Prefix matching is implemented in code, below.\n // 'proxy-': true,\n // 'sec-': true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n },\n __NODEJS__ ? undefined : { 'accept-encoding': true },\n __BROWSER__ ? { origin: true } : undefined,\n);\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record,\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, {\n headers: badHeaders,\n });\n }\n}\n\n// Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n// in the `DisallowedHeaders` type.\nexport function normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError } from '@solana/errors';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\nimport type Dispatcher from 'undici-types/dispatcher';\n\nimport { HttpTransportConfig as Config } from './http-transport-config';\nimport { assertIsAllowedHttpRequestHeaders, normalizeHeaders } from './http-transport-headers';\n\nlet didWarnDispatcherWasSuppliedInNonNodeEnvironment = false;\nfunction warnDispatcherWasSuppliedInNonNodeEnvironment() {\n if (didWarnDispatcherWasSuppliedInNonNodeEnvironment) {\n return;\n }\n didWarnDispatcherWasSuppliedInNonNodeEnvironment = true;\n console.warn(\n 'You have supplied a `Dispatcher` to `createHttpTransport()`. It has been ignored ' +\n 'because Undici dispatchers only work in Node environments. To eliminate this ' +\n 'warning, omit the `dispatcher_NODE_ONLY` property from your config when running in ' +\n 'a non-Node environment.',\n );\n}\n\n/**\n * Creates a function you can use to make `POST` requests with headers suitable for sending JSON\n * data to a server.\n *\n * @example\n * ```ts\n * import { createHttpTransport } from '@solana/rpc-transport-http';\n *\n * const transport = createHttpTransport({ url: 'https://api.mainnet-beta.solana.com' });\n * const response = await transport({\n * payload: { id: 1, jsonrpc: '2.0', method: 'getSlot' },\n * });\n * const data = await response.json();\n * ```\n */\nexport function createHttpTransport(config: Config): RpcTransport {\n if (process.env.NODE_ENV !== \"production\" && !__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n warnDispatcherWasSuppliedInNonNodeEnvironment();\n }\n const { fromJson, headers, toJson, url } = config;\n if (process.env.NODE_ENV !== \"production\" && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n let dispatcherConfig: { dispatcher: Dispatcher | undefined } | undefined;\n if (__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n dispatcherConfig = { dispatcher: config.dispatcher_NODE_ONLY };\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest({\n payload,\n signal,\n }: Parameters[0]): Promise> {\n const body = toJson ? toJson(payload) : JSON.stringify(payload);\n const requestInfo = {\n ...dispatcherConfig,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetch(url, requestInfo);\n if (!response.ok) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {\n headers: response.headers,\n message: response.statusText,\n statusCode: response.status,\n });\n }\n if (fromJson) {\n return fromJson(await response.text(), payload) as TResponse;\n }\n return await response.json();\n };\n}\n","import { isJsonRpcPayload } from '@solana/rpc-spec';\n\nconst SOLANA_RPC_METHODS = [\n 'getAccountInfo',\n 'getBalance',\n 'getBlock',\n 'getBlockCommitment',\n 'getBlockHeight',\n 'getBlockProduction',\n 'getBlocks',\n 'getBlocksWithLimit',\n 'getBlockTime',\n 'getClusterNodes',\n 'getEpochInfo',\n 'getEpochSchedule',\n 'getFeeForMessage',\n 'getFirstAvailableBlock',\n 'getGenesisHash',\n 'getHealth',\n 'getHighestSnapshotSlot',\n 'getIdentity',\n 'getInflationGovernor',\n 'getInflationRate',\n 'getInflationReward',\n 'getLargestAccounts',\n 'getLatestBlockhash',\n 'getLeaderSchedule',\n 'getMaxRetransmitSlot',\n 'getMaxShredInsertSlot',\n 'getMinimumBalanceForRentExemption',\n 'getMultipleAccounts',\n 'getProgramAccounts',\n 'getRecentPerformanceSamples',\n 'getRecentPrioritizationFees',\n 'getSignaturesForAddress',\n 'getSignatureStatuses',\n 'getSlot',\n 'getSlotLeader',\n 'getSlotLeaders',\n 'getStakeMinimumDelegation',\n 'getSupply',\n 'getTokenAccountBalance',\n 'getTokenAccountsByDelegate',\n 'getTokenAccountsByOwner',\n 'getTokenLargestAccounts',\n 'getTokenSupply',\n 'getTransaction',\n 'getTransactionCount',\n 'getVersion',\n 'getVoteAccounts',\n 'index',\n 'isBlockhashValid',\n 'minimumLedgerSlot',\n 'requestAirdrop',\n 'sendTransaction',\n 'simulateTransaction',\n] as const;\n\n/**\n * Helper function that checks if a given `RpcRequest` comes from the Solana RPC API.\n */\nexport function isSolanaRequest(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: (typeof SOLANA_RPC_METHODS)[number];\n params: unknown;\n}> {\n return isJsonRpcPayload(payload) && (SOLANA_RPC_METHODS as readonly string[]).includes(payload.method);\n}\n","import { RpcTransport } from '@solana/rpc-spec';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\n\nimport { createHttpTransport } from './http-transport';\nimport { HttpTransportConfig } from './http-transport-config';\nimport { isSolanaRequest } from './is-solana-request';\n\ntype Config = Pick;\n\n/**\n * Creates a {@link RpcTransport} that uses JSON HTTP requests — much like the\n * {@link createHttpTransport} function - except that it also uses custom `toJson` and `fromJson`\n * functions in order to allow `bigint` values to be serialized and deserialized correctly over the\n * wire.\n *\n * Since this is something specific to the Solana RPC API, these custom JSON functions are only\n * triggered when the request is recognized as a Solana RPC request. Normal RPC APIs should aim to\n * wrap their `bigint` values — e.g. `u64` or `i64` — in special value objects that represent the\n * number as a string to avoid numerical values going above `Number.MAX_SAFE_INTEGER`.\n *\n * It has the same configuration options as {@link createHttpTransport}, but without the `fromJson`\n * and `toJson` options.\n */\nexport function createHttpTransportForSolanaRpc(config: Config): RpcTransport {\n return createHttpTransport({\n ...config,\n fromJson: (rawResponse: string, payload: unknown) =>\n isSolanaRequest(payload) ? parseJsonWithBigInts(rawResponse) : JSON.parse(rawResponse),\n toJson: (payload: unknown) =>\n isSolanaRequest(payload) ? stringifyJsonWithBigInts(payload) : JSON.stringify(payload),\n });\n}\n","/**\n * This project is a fork of [nickyout/fast-stable-stringify](https://github.com/nickyout/fast-stable-stringify)\n *\n * The most popular repository providing this feature is [substack's json-stable-stringify](https://www.npmjs.com/package/json-stable-stringify). The intent of this library is to provide a faster alternative for when performance is more important than features. It assumes you provide basic javascript values without circular references, and returns a non-indented string.\n *\n * Just like substack's, it:\n *\n * - handles all variations of all basic javascript values (number, string, boolean, array, object, null, Date, BigInt)\n * - handles undefined _and_ function in the same way as `JSON.stringify`\n * - **does not support ie8 (and below) with complete certainty**.\n *\n * Unlike substack's, it:\n *\n * - does not implement the 'replacer' or 'space' arguments of the JSON.stringify method\n * - does not check for circular references\n *\n * @example\n * ```js\n * import stringify from '@solana/fast-stable-stringify';\n * stringify({ d: 0, c: 1, a: 2, b: 3, e: 4 }); // '{\"a\":2,\"b\":3,\"c\":1,\"d\":0,\"e\":4}'\n * ```\n *\n * @packageDocumentation\n */\nconst objToString = Object.prototype.toString;\nconst objKeys =\n Object.keys ||\n function (obj) {\n const keys = [];\n for (const name in obj) {\n keys.push(name);\n }\n return keys;\n };\n\nfunction stringify(val: unknown, isArrayProp: boolean) {\n let i, max, str, keys, key, propVal, toStr;\n if (val === true) {\n return 'true';\n }\n if (val === false) {\n return 'false';\n }\n switch (typeof val) {\n case 'object':\n if (val === null) {\n return null;\n } else if ('toJSON' in val && typeof val.toJSON === 'function') {\n return stringify(val.toJSON(), isArrayProp);\n } else {\n toStr = objToString.call(val);\n if (toStr === '[object Array]') {\n str = '[';\n max = (val as unknown[]).length - 1;\n for (i = 0; i < max; i++) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true) + ',';\n }\n if (max > -1) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true);\n }\n return str + ']';\n } else if (toStr === '[object Object]') {\n // only object is left\n keys = objKeys(val).sort();\n max = keys.length;\n str = '';\n i = 0;\n while (i < max) {\n key = keys[i];\n propVal = stringify((val as Record)[key], false);\n if (propVal !== undefined) {\n if (str) {\n str += ',';\n }\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += JSON.stringify(key) + ':' + propVal;\n }\n i++;\n }\n return '{' + str + '}';\n } else {\n return JSON.stringify(val);\n }\n }\n case 'function':\n case 'undefined':\n return isArrayProp ? null : undefined;\n case 'bigint':\n return `${val.toString()}n`;\n case 'string':\n return JSON.stringify(val);\n default:\n return isFinite(val as number) ? val : null;\n }\n}\n\nexport default function (\n val:\n | Function // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n | undefined,\n): undefined;\nexport default function (val: unknown): string;\nexport default function (val: unknown): string | undefined {\n const returnVal = stringify(val, false);\n if (returnVal !== undefined) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n return '' + returnVal;\n }\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcApi } from '@solana/rpc-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\n/**\n * When you create {@link Rpc} instances with custom transports but otherwise the default RPC API\n * behaviours, use this.\n *\n * @example\n * ```ts\n * const myCustomRpc = createRpc({\n * api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n * transport: myCustomTransport,\n * });\n * ```\n */\nexport const DEFAULT_RPC_CONFIG: Partial[0]>> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { AbortController } from '@solana/event-target-impl';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\n// This used to be a `Symbol()`, but there's a bug in Node <21 where the `undici` library passes\n// the `reason` property of the `AbortSignal` straight to `Error.captureStackTrace()` without first\n// typechecking it. `Error.captureStackTrace()` fatals when given a `Symbol`.\n// See https://github.com/nodejs/undici/pull/2597\nlet EXPLICIT_ABORT_TOKEN: ReturnType;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return process.env.NODE_ENV !== \"production\"\n ? {\n EXPLICIT_ABORT_TOKEN:\n 'This object is thrown from the request that underlies a series of coalesced ' +\n 'requests when the last request in that series aborts',\n }\n : {};\n}\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: TTransport,\n getDeduplicationKey: GetDeduplicationKeyFn,\n): TTransport {\n let coalescedRequestsByDeduplicationKey: Record | undefined;\n return async function makeCoalescedHttpRequest(\n request: Parameters[0],\n ): Promise> {\n const { payload, signal } = request;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(request);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n queueMicrotask(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n const responsePromise = (async () => {\n try {\n return await transport({\n ...request,\n signal: abortController.signal,\n });\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n // We triggered this error when the last subscriber aborted. Letting this\n // error bubble up from here would cause runtime fatals where there should\n // be none.\n return;\n }\n throw e;\n }\n })();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise,\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise>;\n return await new Promise>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n queueMicrotask(() => {\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n }\n });\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject((e.target as AbortSignal).reason);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise\n .then(resolve)\n .catch(reject)\n .finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as RpcResponse;\n }\n } as TTransport;\n}\n","import fastStableStringify from '@solana/fast-stable-stringify';\nimport { isJsonRpcPayload } from '@solana/rpc-spec';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport, createHttpTransportForSolanaRpc } from '@solana/rpc-transport-http';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { RpcTransportFromClusterUrl } from './rpc-clusters';\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\ntype RpcTransportConfig = Parameters[0];\ninterface DefaultRpcTransportConfig extends RpcTransportConfig {\n url: TClusterUrl;\n}\n\nfunction normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n // Lowercasing header names makes it easier to override user-supplied headers.\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n\n/**\n * Creates a {@link RpcTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - An automatically-set `Solana-Client` request header, containing the version of `@solana/kit`\n * - Logic that coalesces multiple calls in the same runloop, for the same methods with the same\n * arguments, into a single network request.\n * - [node-only] An automatically-set `Accept-Encoding` request header asking the server to compress\n * responses\n *\n * @param config\n */\nexport function createDefaultRpcTransport(\n config: DefaultRpcTransportConfig,\n): RpcTransportFromClusterUrl {\n return pipe(\n createHttpTransportForSolanaRpc({\n ...config,\n headers: {\n ...(__NODEJS__ &&\n ({\n // Keep these headers lowercase so they will be overridden by any user-supplied headers below.\n 'accept-encoding':\n // Natively supported by Node LTS v20.18.0 and above.\n 'br,gzip,deflate', // Brotli, gzip, and Deflate, in that order.\n } as { [overrideHeader: string]: string })),\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': __VERSION__ ? `js/${__VERSION__}` : 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }) as RpcTransportFromClusterUrl,\n transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey),\n );\n}\n","import { createSolanaRpcApi } from '@solana/rpc-api';\nimport { createRpc, RpcTransport } from '@solana/rpc-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport type { RpcFromTransport, SolanaRpcApiFromTransport } from './rpc-clusters';\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { createDefaultRpcTransport } from './rpc-transport';\n\ntype DefaultRpcTransportConfig = Parameters<\n typeof createDefaultRpcTransport\n>[0];\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given a cluster URL and some\n * optional transport config. See {@link createDefaultRpcTransport} for the shape of the transport\n * config.\n */\nexport function createSolanaRpc(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcFromTransport(createDefaultRpcTransport({ url: clusterUrl, ...config }));\n}\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given the supplied\n * {@link RpcTransport}.\n */\nexport function createSolanaRpcFromTransport(transport: TTransport) {\n return createRpc({\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n transport,\n }) as RpcFromTransport, TTransport>;\n}\n","\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable {\n const iteratorState: Map> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher = Record> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter>(\n eventEmitter: TypedEventEmitter | TypedEventTarget,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\nimport { createAsyncIterableFromDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsApi, RpcSubscriptionsPlan } from './rpc-subscriptions-api';\nimport { PendingRpcSubscriptionsRequest, RpcSubscribeOptions } from './rpc-subscriptions-request';\nimport { RpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsConfig = Readonly<{\n api: RpcSubscriptionsApi;\n transport: RpcSubscriptionsTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcSubscriptionsMethods`.\n *\n * Calling each method returns a\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} where\n * `TNotification` is that method's notification type.\n */\nexport type RpcSubscriptions = {\n [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder<\n OverloadImplementations\n >;\n};\n\ntype PendingRpcSubscriptionsRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TSubscriptionMethodImplementations]: PendingRpcSubscriptionsRequestReturnTypeMapper<\n TSubscriptionMethodImplementations[P]\n >;\n }>\n>;\n\ntype PendingRpcSubscriptionsRequestReturnTypeMapper =\n // Check that this property of the TRpcSubscriptionMethods interface is, in fact, a function.\n TSubscriptionMethodImplementation extends Callable\n ? (\n ...args: Parameters\n ) => PendingRpcSubscriptionsRequest>\n : never;\n\n/**\n * Creates a {@link RpcSubscriptions} instance given a\n * {@link RpcSubscriptionsApi | RpcSubscriptionsApi} and a\n * {@link RpcSubscriptionsTransport} capable of fulfilling them.\n */\nexport function createSubscriptionRpc(\n rpcConfig: RpcSubscriptionsConfig,\n): RpcSubscriptions {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const notificationName = p.toString();\n const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);\n if (!createRpcSubscriptionPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {\n notificationName,\n });\n }\n const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);\n return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);\n };\n },\n }) as RpcSubscriptions;\n}\n\nfunction createPendingRpcSubscription(\n transport: RpcSubscriptionsTransport,\n subscriptionsPlan: RpcSubscriptionsPlan,\n): PendingRpcSubscriptionsRequest {\n return {\n async subscribe({ abortSignal }: RpcSubscribeOptions): Promise> {\n const notificationsDataPublisher = await transport({\n signal: abortSignal,\n ...subscriptionsPlan,\n });\n return createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName: 'notification',\n dataPublisher: notificationsDataPublisher,\n errorChannelName: 'error',\n });\n },\n };\n}\n","import { Callable, RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsTransportDataEvents } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsApiConfig = Readonly<{\n planExecutor: RpcSubscriptionsPlanExecutor>;\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n}>;\n\n/**\n * A function that implements a protocol for subscribing and unsubscribing from notifications given\n * a {@link RpcSubscriptionsChannel}, a {@link RpcRequest}, and an `AbortSignal`.\n *\n * @returns A {@link DataPublisher} that emits {@link RpcSubscriptionsTransportDataEvents}\n */\ntype RpcSubscriptionsPlanExecutor = (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n request: RpcRequest;\n signal: AbortSignal;\n }>,\n) => Promise>>;\n\n/**\n * This type allows an {@link RpcSubscriptionsApi} to describe how a particular subscription should\n * be issued to the JSON RPC server.\n *\n * Given a function that was called on a {@link RpcSubscriptions}, this object exposes an `execute`\n * function that dictates which subscription request will be sent, how the underlying transport will\n * be used, and how the notifications will be transformed.\n *\n * This function accepts a {@link RpcSubscriptionsChannel} and an `AbortSignal` and asynchronously\n * returns a {@link DataPublisher}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * channel.\n * - call the underlying channel zero, one or multiple times depending on the use-case (e.g.\n * caching or coalescing multiple subscriptions).\n * - transform the notification from the JSON RPC server, in case it does not match the\n * `TNotification` specified by the\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} emitted\n * from the publisher returned.\n */\nexport type RpcSubscriptionsPlan = Readonly<{\n /**\n * This method may be called with a newly-opened channel or a pre-established channel.\n */\n execute: (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n signal: AbortSignal;\n }>,\n ) => Promise>>;\n /**\n * This request is used to uniquely identify the subscription.\n * It typically comes from the method name and parameters of the subscription call,\n * after potentially being transformed by the RPC Subscriptions API.\n */\n request: RpcRequest;\n}>;\n\n/**\n * For each of `TRpcSubscriptionsMethods`, this object exposes a method with the same name that maps\n * between its input arguments and a\n * {@link RpcSubscriptionsPlan | RpcSubscriptionsPlan} that implements the execution\n * of a JSON RPC subscription for `TNotifications`.\n */\nexport type RpcSubscriptionsApi = {\n [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper<\n TRpcSubscriptionMethods[MethodName]\n >;\n};\n\ntype RpcSubscriptionsReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcSubscriptionsPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcSubscriptionsApiMethod = (...args: any) => any;\nexport interface RpcSubscriptionsApiMethods {\n [methodName: string]: RpcSubscriptionsApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a\n * {@link RpcSubscriptionsPlan} by creating an `execute` function that:\n *\n * - calls the supplied {@link RpcSubscriptionsApiConfig.planExecutor} with a JSON RPC v2 payload\n * object with the requested `methodName` and `params` properties, optionally transformed by\n * {@link RpcSubscriptionsApiConfig.requestTransformer}.\n *\n * @example\n * ```ts\n * // For example, given this `RpcSubscriptionsApi`:\n * const rpcSubscriptionsApi = createJsonRpcSubscriptionsApi({\n * async planExecutor({ channel, request }) {\n * await channel.send(request);\n * return {\n * ...channel,\n * on(type, listener, options) {\n * if (type !== 'message') {\n * return channel.on(type, listener, options);\n * }\n * return channel.on(\n * 'message',\n * function resultGettingListener(message) {\n * listener(message.result);\n * },\n * options,\n * );\n * }\n * }\n * },\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * });\n *\n * // ...the following function call:\n * rpcSubscriptionsApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcSubscriptionsPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Emits the \"result\" property of each RPC Subscriptions message.\n * ```\n */\nexport function createRpcSubscriptionsApi(\n config: RpcSubscriptionsApiConfig,\n): RpcSubscriptionsApi {\n return new Proxy({} as RpcSubscriptionsApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcSubscriptionsApiMethods as string;\n return function (\n ...params: Parameters<\n TRpcSubscriptionsApiMethods[TNotificationName] extends CallableFunction\n ? TRpcSubscriptionsApiMethods[TNotificationName]\n : never\n >\n ): RpcSubscriptionsPlan> {\n const rawRequest = { methodName, params };\n const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;\n return {\n execute(planConfig) {\n return config.planExecutor({ ...planConfig, request });\n },\n request,\n };\n };\n },\n });\n}\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype RpcSubscriptionsChannelSolanaErrorCode =\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT;\n\nexport type RpcSubscriptionChannelEvents = {\n /**\n * Fires when the channel closes unexpectedly.\n * @eventProperty\n */\n error: SolanaError;\n /**\n * Fires on every message received from the remote end.\n * @eventProperty\n */\n message: TInboundMessage;\n};\n\n/**\n * A {@link DataPublisher} on which you can subscribe to events of type\n * {@link RpcSubscriptionChannelEvents | RpcSubscriptionChannelEvents}.\n * Additionally, you can use this object to send messages of type `TOutboundMessage` back to the\n * remote end by calling its {@link RpcSubscriptionsChannel.send | `send(message)`} method.\n */\nexport interface RpcSubscriptionsChannel extends DataPublisher<\n RpcSubscriptionChannelEvents\n> {\n send(message: TOutboundMessage): Promise;\n}\n\n/**\n * A channel creator is a function that accepts an `AbortSignal`, returns a new\n * {@link RpcSubscriptionsChannel}, and tears down the channel when the abort signal fires.\n */\nexport type RpcSubscriptionsChannelCreator = (\n config: Readonly<{\n abortSignal: AbortSignal;\n }>,\n) => Promise>;\n\n/**\n * Given a channel with inbound messages of type `T` and a function of type `T => U`, returns a new\n * channel with inbound messages of type `U`.\n *\n * Note that this only affects messages of type `\"message\"` and thus, does not affect incoming error\n * messages.\n *\n * @example Parsing incoming JSON messages\n * ```ts\n * const transformedChannel = transformChannelInboundMessages(channel, JSON.parse);\n * ```\n */\nexport function transformChannelInboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TInboundMessage) => TNewInboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n on(type, subscriber, options) {\n if (type !== 'message') {\n return channel.on(\n type,\n subscriber as (data: RpcSubscriptionChannelEvents[typeof type]) => void,\n options,\n );\n }\n return channel.on(\n 'message',\n message => (subscriber as (data: TNewInboundMessage) => void)(transform(message)),\n options,\n );\n },\n });\n}\n\n/**\n * Given a channel with outbound messages of type `T` and a function of type `U => T`, returns a new\n * channel with outbound messages of type `U`.\n *\n * @example Stringifying JSON messages before sending them over the wire\n * ```ts\n * const transformedChannel = transformChannelOutboundMessages(channel, JSON.stringify);\n * ```\n */\nexport function transformChannelOutboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TNewOutboundMessage) => TOutboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n send: message => channel.send(transform(message)),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n getSolanaErrorFromJsonRpcError,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport { createRpcMessage, RpcRequest, RpcResponseData, RpcResponseTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\nimport { demultiplexDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionChannelEvents } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\n\ntype Config = Readonly<{\n channel: RpcSubscriptionsChannel | RpcResponseData>;\n responseTransformer?: RpcResponseTransformer;\n signal: AbortSignal;\n subscribeRequest: RpcRequest;\n unsubscribeMethodName: string;\n}>;\n\ntype RpcNotification = Readonly<{\n method: string;\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\n\ntype RpcSubscriptionId = number;\n\ntype RpcSubscriptionNotificationEvents = Omit, 'message'> & {\n notification: TNotification;\n};\n\nconst subscriberCountBySubscriptionIdByChannel = new WeakMap>();\nfunction decrementSubscriberCountAndReturnNewCount(channel: WeakKey, subscriptionId?: number): number | undefined {\n return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);\n}\nfunction incrementSubscriberCount(channel: WeakKey, subscriptionId?: number): void {\n augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);\n}\nfunction getSubscriberCountBySubscriptionIdForChannel(channel: WeakKey): Record {\n let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);\n if (!subscriberCountBySubscriptionId) {\n subscriberCountBySubscriptionIdByChannel.set(channel, (subscriberCountBySubscriptionId = {}));\n }\n return subscriberCountBySubscriptionId;\n}\nfunction augmentSubscriberCountAndReturnNewCount(\n amount: -1 | 1,\n channel: WeakKey,\n subscriptionId?: number,\n): number | undefined {\n if (subscriptionId === undefined) {\n return;\n }\n const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);\n if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) {\n subscriberCountBySubscriptionId[subscriptionId] = 0;\n }\n const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];\n if (newCount <= 0) {\n delete subscriberCountBySubscriptionId[subscriptionId];\n } else {\n subscriberCountBySubscriptionId[subscriptionId] = newCount;\n }\n return newCount;\n}\n\nconst cache = new WeakMap();\nfunction getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel: RpcSubscriptionsChannel>,\n subscribeRequest: RpcRequest,\n responseTransformer?: RpcResponseTransformer,\n): DataPublisher<{\n [channelName: `notification:${number}`]: TNotification;\n}> {\n let publisherByResponseTransformer = cache.get(channel);\n if (!publisherByResponseTransformer) {\n cache.set(channel, (publisherByResponseTransformer = new WeakMap()));\n }\n const responseTransformerKey = responseTransformer ?? channel;\n let publisher = publisherByResponseTransformer.get(responseTransformerKey);\n if (!publisher) {\n publisherByResponseTransformer.set(\n responseTransformerKey,\n (publisher = demultiplexDataPublisher(channel, 'message', rawMessage => {\n const message = rawMessage as RpcNotification | RpcResponseData;\n if (!('method' in message)) {\n return;\n }\n const transformedNotification = responseTransformer\n ? responseTransformer(message.params.result, subscribeRequest)\n : message.params.result;\n return [`notification:${message.params.subscription}`, transformedNotification];\n })),\n );\n }\n return publisher;\n}\n\n/**\n * Given a channel, this function executes the particular subscription plan required by the Solana\n * JSON RPC Subscriptions API.\n *\n * @param config\n *\n * 1. Calls the `subscribeRequest` on the remote RPC\n * 2. Waits for a response containing the subscription id\n * 3. Returns a {@link DataPublisher} that publishes notifications related to that subscriptions id,\n * filtering out all others\n * 4. Calls the `unsubscribeMethodName` on the remote RPC when the abort signal is fired.\n */\nexport async function executeRpcPubSubSubscriptionPlan({\n channel,\n responseTransformer,\n signal,\n subscribeRequest,\n unsubscribeMethodName,\n}: Config): Promise>> {\n let subscriptionId: number | undefined;\n channel.on(\n 'error',\n () => {\n // An error on the channel indicates that the subscriptions are dead.\n // There is no longer any sense hanging on to subscription ids.\n // Erasing it here will prevent the unsubscribe code from running.\n subscriptionId = undefined;\n subscriberCountBySubscriptionIdByChannel.delete(channel);\n },\n { signal },\n );\n /**\n * STEP 1\n * Create a promise that rejects if this subscription is aborted and sends\n * the unsubscribe message if the subscription is active at that time.\n */\n const abortPromise = new Promise((_, reject) => {\n function handleAbort(this: AbortSignal) {\n /**\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they\n * will be assigned the same subscription id, and will occupy one subscription slot. We\n * must be careful not to send the unsubscribe message until the last subscriber aborts.\n */\n if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {\n const unsubscribePayload = createRpcMessage({\n methodName: unsubscribeMethodName,\n params: [subscriptionId],\n });\n subscriptionId = undefined;\n channel.send(unsubscribePayload).catch(() => {});\n }\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n }\n if (signal.aborted) {\n handleAbort.call(signal);\n } else {\n signal.addEventListener('abort', handleAbort);\n }\n });\n /**\n * STEP 2\n * Send the subscription request.\n */\n const subscribePayload = createRpcMessage(subscribeRequest);\n await channel.send(subscribePayload);\n /**\n * STEP 3\n * Wait for the acknowledgement from the server with the subscription id.\n */\n const subscriptionIdPromise = new Promise((resolve, reject) => {\n const abortController = new AbortController();\n signal.addEventListener('abort', abortController.abort.bind(abortController));\n const options = { signal: abortController.signal } as const;\n channel.on(\n 'error',\n err => {\n abortController.abort();\n reject(err);\n },\n options,\n );\n channel.on(\n 'message',\n message => {\n if (message && typeof message === 'object' && 'id' in message && message.id === subscribePayload.id) {\n abortController.abort();\n if ('error' in message) {\n reject(getSolanaErrorFromJsonRpcError(message.error));\n } else {\n resolve(message.result);\n }\n }\n },\n options,\n );\n });\n subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);\n if (subscriptionId == null) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);\n }\n incrementSubscriberCount(channel, subscriptionId);\n /**\n * STEP 4\n * Filter out notifications unrelated to this subscription.\n */\n const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel,\n subscribeRequest,\n responseTransformer,\n );\n const notificationKey = `notification:${subscriptionId}` as const;\n return {\n on(type, listener, options) {\n switch (type) {\n case 'notification':\n return notificationPublisher.on(\n notificationKey,\n listener as (data: RpcSubscriptionNotificationEvents['notification']) => void,\n options,\n );\n case 'error':\n return channel.on(\n 'error',\n listener as (data: RpcSubscriptionNotificationEvents['error']) => void,\n options,\n );\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {\n channelName: type,\n supportedChannelNames: ['notification', 'error'],\n });\n }\n },\n };\n}\n","import {\n createRpcSubscriptionsApi,\n executeRpcPubSubSubscriptionPlan,\n RpcSubscriptionsApi,\n RpcSubscriptionsApiMethods,\n} from '@solana/rpc-subscriptions-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpcSubscriptions,\n jsonParsedAccountsConfigs,\n KEYPATH_WILDCARD,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\nexport type SolanaRpcSubscriptionsApi = AccountNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsApiUnstable = BlockNotificationsApi &\n SlotsUpdatesNotificationsApi &\n VoteNotificationsApi;\n\nexport type {\n AccountNotificationsApi,\n BlockNotificationsApi,\n LogsNotificationsApi,\n ProgramNotificationsApi,\n RootNotificationsApi,\n SignatureNotificationsApi,\n SlotNotificationsApi,\n SlotsUpdatesNotificationsApi,\n VoteNotificationsApi,\n};\n\ntype Config = RequestTransformerConfig;\n\nfunction createSolanaRpcSubscriptionsApi_INTERNAL(\n config?: Config,\n): RpcSubscriptionsApi {\n const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);\n const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n });\n return createRpcSubscriptionsApi({\n planExecutor({ request, ...rest }) {\n return executeRpcPubSubSubscriptionPlan({\n ...rest,\n responseTransformer,\n subscribeRequest: { ...request, methodName: request.methodName.replace(/Notifications$/, 'Subscribe') },\n unsubscribeMethodName: request.methodName.replace(/Notifications$/, 'Unsubscribe'),\n });\n },\n requestTransformer,\n });\n}\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config,\n): RpcSubscriptionsApi {\n return createSolanaRpcSubscriptionsApi_INTERNAL(config);\n}\n\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(config?: Config) {\n return createSolanaRpcSubscriptionsApi_INTERNAL(\n config,\n );\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths<\n RpcSubscriptionsApi\n>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths<\n RpcSubscriptionsApi\n> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\n }\n return memoizedKeypaths;\n}\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 CLOSE_TIMEOUT: 30000,\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","'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\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\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\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\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 | String)[]} 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 CLOSE_TIMEOUT,\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 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._closeTimeout = options.closeTimeout;\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 {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\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 closeTimeout: CLOSE_TIMEOUT,\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 websocket._closeTimeout = opts.closeTimeout;\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 websocket._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 //\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. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\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","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\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 { 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 { CLOSE_TIMEOUT, 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 {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\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 closeTimeout: CLOSE_TIMEOUT,\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 !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\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 * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\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, headers);\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","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","// When building the browser bundle, this import gets replaced by `globalThis.WebSocket`.\nimport WebSocketImpl from 'ws';\n\nexport default globalThis.WebSocket\n ? globalThis.WebSocket // Use native `WebSocket` in runtimes that support it (eg. Deno)\n : WebSocketImpl;\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { EventTarget } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport { getDataPublisherFromEventEmitter } from '@solana/subscribable';\nimport WebSocket from '@solana/ws-impl';\n\nexport type Config = Readonly<{\n /**\n * The number of bytes to admit into the WebSocket's send buffer before queueing messages on the\n * client.\n *\n * When you call {@link RpcSubscriptionsChannel.send | `send()`} on a `WebSocket` the runtime\n * might add the message to a buffer rather than send it right away. In the event that\n * `socket.bufferedAmount` exceeds the value configured here, messages will be added to a queue\n * in your application code instead of being sent to the WebSocket, until such time as the\n * `bufferedAmount` falls back below the high watermark.\n */\n sendBufferHighWatermark: number;\n /**\n * An `AbortSignal` to fire when you want to explicitly close the `WebSocket`.\n *\n * If the channel is open it will be closed with a normal closure code\n * (https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1) If the channel has not been\n * established yet, firing this signal will result in the `AbortError` being thrown to the\n * caller who was trying to open the channel.\n */\n signal: AbortSignal;\n /**\n * A string representing the target endpoint.\n *\n * In Node, it must be an absolute URL using the `ws` or `wss` protocol.\n */\n url: string;\n}>;\n\ntype WebSocketMessage = ArrayBufferLike | ArrayBufferView | Blob | string;\n\nconst NORMAL_CLOSURE_CODE = 1000; // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n\n/**\n * Creates an object that represents an open channel to a `WebSocket` server.\n *\n * You can use it to send messages by calling its\n * {@link RpcSubscriptionsChannel.send | `send()`} function and you can receive them by subscribing\n * to the {@link RpcSubscriptionChannelEvents} it emits.\n */\nexport function createWebSocketChannel({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise> {\n if (signal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(signal.reason);\n }\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise }> | undefined;\n let hasConnected = false;\n const listenerRemovers = new Set<() => void>();\n function cleanupListeners() {\n listenerRemovers.forEach(r => {\n r();\n });\n listenerRemovers.clear();\n }\n function handleAbort() {\n cleanupListeners();\n if (!hasConnected) {\n rejectOpen(signal.reason);\n }\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(NORMAL_CLOSURE_CODE);\n }\n }\n function handleClose(ev: CloseEvent) {\n cleanupListeners();\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('message', handleMessage);\n webSocket.removeEventListener('open', handleOpen);\n if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) {\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, {\n cause: ev,\n }),\n }),\n );\n }\n }\n function handleError(ev: Event) {\n if (signal.aborted) {\n return;\n }\n if (!hasConnected) {\n const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, {\n errorEvent: ev,\n });\n rejectOpen(failedToConnectError);\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: failedToConnectError,\n }),\n );\n }\n }\n function handleMessage(ev: MessageEvent) {\n if (signal.aborted) {\n return;\n }\n eventTarget.dispatchEvent(new CustomEvent('message', { detail: ev.data }));\n }\n const eventTarget = new EventTarget();\n const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n function handleOpen() {\n hasConnected = true;\n resolveOpen({\n ...dataPublisher,\n async send(message) {\n if (webSocket.readyState !== WebSocket.OPEN) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);\n }\n if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {\n let onCancel!: () => void;\n const promise = new Promise((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n new SolanaError(\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n ),\n );\n };\n });\n bufferDrainWatcher = {\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {\n const TypedArrayConstructor = message.constructor as {\n new (...args: [typeof message]): typeof message;\n };\n // Clone the message to prevent mutation while queued.\n message = new TypedArrayConstructor(message);\n }\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n });\n }\n const webSocket = new WebSocket(url);\n signal.addEventListener('abort', handleAbort);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('message', handleMessage);\n webSocket.addEventListener('open', handleOpen);\n let rejectOpen!: (e: SolanaError) => void;\n let resolveOpen!: (value: RpcSubscriptionsChannel) => void;\n return new Promise>((resolve, reject) => {\n rejectOpen = reject;\n resolveOpen = resolve;\n });\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_SUBSCRIPTIONS_CONFIG: Partial<\n NonNullable[0]>\n> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { isSolanaError, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\ntype Config> = Readonly<{\n abortSignal: AbortSignal;\n channel: TChannel;\n intervalMs: number;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that sends a ping message to\n * the inner channel if a message has not been sent or received in the last `intervalMs`. In web\n * browsers, this implementation sends no ping when the network is down, and sends a ping\n * immediately upon the network coming back up.\n */\nexport function getRpcSubscriptionsChannelWithAutoping>({\n abortSignal: callerAbortSignal,\n channel,\n intervalMs,\n}: Config): TChannel {\n let intervalId: ReturnType | undefined;\n function sendPing() {\n channel.send(PING_PAYLOAD).catch((e: unknown) => {\n if (isSolanaError(e, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED)) {\n pingerAbortController.abort();\n }\n });\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, intervalMs);\n }\n const pingerAbortController = new AbortController();\n pingerAbortController.signal.addEventListener('abort', () => {\n clearInterval(intervalId);\n });\n callerAbortSignal.addEventListener('abort', () => {\n pingerAbortController.abort();\n });\n channel.on(\n 'error',\n () => {\n pingerAbortController.abort();\n },\n { signal: pingerAbortController.signal },\n );\n channel.on('message', restartPingTimer, { signal: pingerAbortController.signal });\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n if (__BROWSER__) {\n globalThis.addEventListener(\n 'offline',\n function handleOffline() {\n clearInterval(intervalId);\n },\n { signal: pingerAbortController.signal },\n );\n globalThis.addEventListener(\n 'online',\n function handleOnline() {\n sendPing();\n restartPingTimer();\n },\n { signal: pingerAbortController.signal },\n );\n }\n return {\n ...channel,\n send(...args) {\n if (!pingerAbortController.signal.aborted) {\n restartPingTimer();\n }\n return channel.send(...args);\n },\n };\n}\n","import { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\nexport type ChannelPoolEntry = {\n channel: PromiseLike> | RpcSubscriptionsChannel;\n readonly dispose: () => void;\n subscriptionCount: number;\n};\n\ntype ChannelPool = { readonly entries: ChannelPoolEntry[]; freeChannelIndex: number };\n\nexport function createChannelPool(): ChannelPool {\n return {\n entries: [],\n freeChannelIndex: -1,\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannelCreator } from '@solana/rpc-subscriptions-spec';\n\nimport { ChannelPoolEntry, createChannelPool } from './rpc-subscriptions-channel-pool-internal';\n\ntype Config = Readonly<{\n maxSubscriptionsPerChannel: number;\n minChannels: number;\n}>;\n\n/**\n * Given a channel creator, will return a new channel creator with the following behavior.\n *\n * 1. When called, returns a {@link RpcSubscriptionsChannel}. Adds that channel to a pool.\n * 2. When called again, creates and returns new\n * {@link RpcSubscriptionChannel | RpcSubscriptionChannels} up to the number specified by\n * `minChannels`.\n * 3. When `minChannels` channels have been created, subsequent calls vend whichever existing\n * channel from the pool has the fewest subscribers, or the next one in rotation in the event of\n * a tie.\n * 4. Once all channels carry the number of subscribers specified by the number\n * `maxSubscriptionsPerChannel`, new channels in excess of `minChannel` will be created,\n * returned, and added to the pool.\n * 5. A channel will be destroyed once all of its subscribers' abort signals fire.\n */\nexport function getChannelPoolingChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n>(createChannel: TChannelCreator, { maxSubscriptionsPerChannel, minChannels }: Config): TChannelCreator {\n const pool = createChannelPool();\n /**\n * This function advances the free channel index to the pool entry with the most capacity. It\n * sets the index to `-1` if all channels are full.\n */\n function recomputeFreeChannelIndex() {\n if (pool.entries.length < minChannels) {\n // Don't set the free channel index until the pool fills up; we want to keep creating\n // channels before we start rotating among them.\n pool.freeChannelIndex = -1;\n return;\n }\n let mostFreeChannel: Readonly<{ poolIndex: number; subscriptionCount: number }> | undefined;\n for (let ii = 0; ii < pool.entries.length; ii++) {\n const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;\n const nextPoolEntry =\n // Start from the item two positions after the current item. This way, the\n // search will finish on the item after the current one. This ensures that, if\n // any channels tie for having the most capacity, the one that will be chosen is\n // the one immediately to the current one's right (wrapping around).\n pool.entries[nextPoolIndex];\n if (\n nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel &&\n (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)\n ) {\n mostFreeChannel = {\n poolIndex: nextPoolIndex,\n subscriptionCount: nextPoolEntry.subscriptionCount,\n };\n }\n }\n pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;\n }\n return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {\n let poolEntry: ChannelPoolEntry;\n function destroyPoolEntry() {\n const index = pool.entries.findIndex(entry => entry === poolEntry);\n pool.entries.splice(index, 1);\n poolEntry.dispose();\n recomputeFreeChannelIndex();\n }\n if (pool.freeChannelIndex === -1) {\n const abortController = new AbortController();\n const newChannelPromise = createChannel({ abortSignal: abortController.signal });\n newChannelPromise\n .then(newChannel => {\n newChannel.on('error', destroyPoolEntry, { signal: abortController.signal });\n })\n .catch(destroyPoolEntry);\n poolEntry = {\n channel: newChannelPromise,\n dispose() {\n abortController.abort();\n },\n subscriptionCount: 0,\n };\n pool.entries.push(poolEntry);\n } else {\n poolEntry = pool.entries[pool.freeChannelIndex];\n }\n /**\n * A note about subscription counts.\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they will be\n * assigned the same subscription id, and will occupy one subscription slot. We can't tell,\n * from here, whether a subscription will be treated in this way or not, so we\n * unconditionally increment the subscription count every time a subscription request is\n * made. This may result in subscription channels being treated as out-of-capacity when in\n * fact they are not.\n */\n poolEntry.subscriptionCount++;\n abortSignal.addEventListener('abort', function destroyConsumer() {\n poolEntry.subscriptionCount--;\n if (poolEntry.subscriptionCount === 0) {\n destroyPoolEntry();\n } else if (pool.freeChannelIndex !== -1) {\n // Back the free channel index up one position, and recompute it.\n pool.freeChannelIndex--;\n recomputeFreeChannelIndex();\n }\n });\n recomputeFreeChannelIndex();\n return poolEntry.channel;\n } as TChannelCreator;\n}\n","import { pipe } from '@solana/functional';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that parses data published to\n * the `'message'` channel as JSON, and JSON-stringifies messages sent via the\n * {@link RpcSubscriptionsChannel.send | send(message)} method.\n */\nexport function getRpcSubscriptionsChannelWithJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, JSON.parse),\n c => transformChannelOutboundMessages(c, JSON.stringify),\n );\n}\n","import { pipe } from '@solana/functional';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Similarly, to {@link getRpcSubscriptionsChannelWithJSONSerialization}, this function will\n * stringify and parse JSON message to and from the given `string` channel. However, this function\n * parses any integer value as a `BigInt` in order to safely handle numbers that exceed the\n * JavaScript [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\n * value.\n */\nexport function getRpcSubscriptionsChannelWithBigIntJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, parseJsonWithBigInts),\n c => transformChannelOutboundMessages(c, stringifyJsonWithBigInts),\n );\n}\n","import { createWebSocketChannel } from '@solana/rpc-subscriptions-channel-websocket';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { getRpcSubscriptionsChannelWithAutoping } from './rpc-subscriptions-autopinger';\nimport { getChannelPoolingChannelCreator } from './rpc-subscriptions-channel-pool';\nimport { RpcSubscriptionsChannelCreatorFromClusterUrl } from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsChannelWithJSONSerialization } from './rpc-subscriptions-json';\nimport { getRpcSubscriptionsChannelWithBigIntJSONSerialization } from './rpc-subscriptions-json-bigint';\n\nexport type DefaultRpcSubscriptionsChannelConfig = Readonly<{\n /**\n * The number of milliseconds to wait since the last message sent or received over the channel\n * before sending a ping message to keep the channel open.\n */\n intervalMs?: number;\n /**\n * The number of subscribers that may share a channel before a new channel must be created.\n *\n * It is important that you set this to the maximum number of subscriptions that your RPC\n * provider recommends making over a single connection; the default is set deliberately low, so\n * as to comply with the restrictive limits of the public mainnet RPC node.\n *\n * @defaultValue 100\n */\n maxSubscriptionsPerChannel?: number;\n /** The number of channels to create before reusing a channel for a new subscription. */\n minChannels?: number;\n /**\n * The number of bytes of data to admit into the\n * [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) buffer before\n * buffering data on the client.\n */\n sendBufferHighWatermark?: number;\n /** The URL of the web socket server. Must use the `ws` or `wss` protocols. */\n url: TClusterUrl;\n}>;\n\n/**\n * Similar to {@link createDefaultRpcSubscriptionsChannelCreator} with some Solana-specific\n * defaults.\n *\n * For instance, it safely handles `BigInt` values in JSON messages since Solana RPC servers accept\n * and return integers larger than [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER).\n */\nexport function createDefaultSolanaRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization,\n });\n}\n\n/**\n * Creates a function that returns new subscription channels when called.\n */\nexport function createDefaultRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithJSONSerialization,\n });\n}\n\nfunction createDefaultRpcSubscriptionsChannelCreatorImpl(\n config: DefaultRpcSubscriptionsChannelConfig & {\n jsonSerializer: (channel: RpcSubscriptionsChannel) => RpcSubscriptionsChannel;\n },\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n if (/^wss?:/i.test(config.url) === false) {\n const protocolMatch = config.url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? \"Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or \" +\n `'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`,\n );\n }\n const { intervalMs, ...rest } = config;\n const createDefaultRpcSubscriptionsChannel = (({ abortSignal }) => {\n return createWebSocketChannel({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n signal: abortSignal,\n })\n .then(config.jsonSerializer)\n .then(channel =>\n getRpcSubscriptionsChannelWithAutoping({\n abortSignal,\n channel,\n intervalMs: intervalMs ?? 5_000,\n }),\n );\n }) as RpcSubscriptionsChannelCreatorFromClusterUrl;\n return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {\n maxSubscriptionsPerChannel:\n config.maxSubscriptionsPerChannel ??\n /**\n * A note about this default. The idea here is that, because some RPC providers impose\n * an upper limit on the number of subscriptions you can make per channel, we must\n * choose a number low enough to avoid hitting that limit. Without knowing what provider\n * a given person is using, or what their limit is, we have to choose the lowest of all\n * known limits. As of this writing (October 2024) that is the public mainnet RPC node\n * (api.mainnet-beta.solana.com) at 100 subscriptions.\n */\n 100,\n minChannels: config.minChannels ?? 1,\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport fastStableStringify from '@solana/fast-stable-stringify';\nimport { RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype CacheEntry = {\n readonly abortController: AbortController;\n readonly dataPublisherPromise: Promise;\n numSubscribers: number;\n};\n\n/**\n * Given a {@link RpcSubscriptionsTransport}, will return a new transport that coalesces identical\n * subscriptions into a single subscription request to the server. The determination of whether a\n * subscription is the same as another is based on the `rpcRequest` returned by its\n * {@link RpcSubscriptionsPlan}. The subscription will only be aborted once all subscribers abort,\n * or there is an error.\n */\nexport function getRpcSubscriptionsTransportWithSubscriptionCoalescing(\n transport: TTransport,\n): TTransport {\n const cache = new Map();\n return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {\n const { request, signal } = config;\n const subscriptionConfigurationHash = fastStableStringify([request.methodName, request.params]);\n\n let cachedDataPublisherPromise = cache.get(subscriptionConfigurationHash);\n if (!cachedDataPublisherPromise) {\n const abortController = new AbortController();\n const dataPublisherPromise = transport({\n ...config,\n signal: abortController.signal,\n });\n dataPublisherPromise\n .then(dataPublisher => {\n dataPublisher.on(\n 'error',\n () => {\n cache.delete(subscriptionConfigurationHash);\n abortController.abort();\n },\n { signal: abortController.signal },\n );\n })\n .catch(() => {});\n cache.set(\n subscriptionConfigurationHash,\n (cachedDataPublisherPromise = {\n abortController,\n dataPublisherPromise,\n numSubscribers: 0,\n }),\n );\n }\n cachedDataPublisherPromise.numSubscribers++;\n signal.addEventListener(\n 'abort',\n () => {\n cachedDataPublisherPromise.numSubscribers--;\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n queueMicrotask(() => {\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n cache.delete(subscriptionConfigurationHash);\n cachedDataPublisherPromise.abortController.abort();\n }\n });\n }\n },\n { signal: cachedDataPublisherPromise.abortController.signal },\n );\n return cachedDataPublisherPromise.dataPublisherPromise;\n } as TTransport;\n}\n","import { pipe } from '@solana/functional';\nimport { RpcSubscriptionsChannelCreator, RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport {\n RpcSubscriptionsChannelCreatorDevnet,\n RpcSubscriptionsChannelCreatorFromClusterUrl,\n RpcSubscriptionsChannelCreatorMainnet,\n RpcSubscriptionsChannelCreatorTestnet,\n RpcSubscriptionsTransportDevnet,\n RpcSubscriptionsTransportFromClusterUrl,\n RpcSubscriptionsTransportMainnet,\n RpcSubscriptionsTransportTestnet,\n} from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsTransportWithSubscriptionCoalescing } from './rpc-subscriptions-coalescer';\n\nexport type DefaultRpcSubscriptionsTransportConfig = Readonly<{\n createChannel: RpcSubscriptionsChannelCreatorFromClusterUrl;\n}>;\n\n/**\n * Creates a {@link RpcSubscriptionsTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - Logic that coalesces multiple subscriptions for the same notifications with the same arguments\n * into a single subscription.\n *\n * @param config\n */\nexport function createDefaultRpcSubscriptionsTransport({\n createChannel,\n}: DefaultRpcSubscriptionsTransportConfig) {\n return pipe(\n createRpcSubscriptionsTransportFromChannelCreator(\n createChannel,\n ) as RpcSubscriptionsTransport as RpcSubscriptionsTransportFromClusterUrl,\n transport => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport),\n );\n}\n\nexport function createRpcSubscriptionsTransportFromChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n TInboundMessage,\n TOutboundMessage,\n>(createChannel: TChannelCreator) {\n return (async ({ execute, signal }) => {\n const channel = await createChannel({ abortSignal: signal });\n return await execute({ channel, signal });\n }) as TChannelCreator extends RpcSubscriptionsChannelCreatorDevnet\n ? RpcSubscriptionsTransportDevnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorTestnet\n ? RpcSubscriptionsTransportTestnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorMainnet\n ? RpcSubscriptionsTransportMainnet\n : RpcSubscriptionsTransport;\n}\n","import type { SolanaRpcSubscriptionsApi, SolanaRpcSubscriptionsApiUnstable } from '@solana/rpc-subscriptions-api';\nimport { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\nimport {\n createSubscriptionRpc,\n RpcSubscriptionsApiMethods,\n type RpcSubscriptionsTransport,\n} from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport { DEFAULT_RPC_SUBSCRIPTIONS_CONFIG } from './rpc-default-config';\nimport {\n createDefaultSolanaRpcSubscriptionsChannelCreator,\n DefaultRpcSubscriptionsChannelConfig,\n} from './rpc-subscriptions-channel';\nimport type { RpcSubscriptionsFromTransport } from './rpc-subscriptions-clusters';\nimport { createDefaultRpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\ntype Config = DefaultRpcSubscriptionsChannelConfig;\n\nfunction createSolanaRpcSubscriptionsImpl(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n const transport = createDefaultRpcSubscriptionsTransport({\n createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ ...config, url: clusterUrl }),\n });\n return createSolanaRpcSubscriptionsFromTransport(transport);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(clusterUrl, config);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API,\n * including its unstable methods, given a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(\n clusterUrl,\n config,\n );\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * the supplied {@link RpcSubscriptionsTransport}.\n */\nexport function createSolanaRpcSubscriptionsFromTransport<\n TTransport extends RpcSubscriptionsTransport,\n TApi extends RpcSubscriptionsApiMethods = SolanaRpcSubscriptionsApi,\n>(transport: TTransport) {\n return createSubscriptionRpc({\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_SUBSCRIPTIONS_CONFIG),\n transport,\n }) as RpcSubscriptionsFromTransport;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SolanaError } from '@solana/errors';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Removes all duplicated {@link MessageSigner | MessageSigners} and\n * {@link TransactionSigner | TransactionSigners} from a provided array\n * by comparing their {@link Address | addresses}.\n *\n * @internal\n */\nexport function deduplicateSigners(\n signers: readonly TSigner[],\n): readonly TSigner[] {\n const deduplicated: Record = {};\n signers.forEach(signer => {\n if (!deduplicated[signer.address]) {\n deduplicated[signer.address] = signer;\n } else if (deduplicated[signer.address] !== signer) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, {\n address: signer.address,\n });\n }\n });\n return Object.values(deduplicated);\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionModifyingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that potentially modifies the provided {@link Transaction | Transactions}\n * before signing them.\n *\n * For instance, this enables wallets to inject additional instructions into the\n * transaction before signing them. For each transaction, instead of returning a\n * {@link SignatureDictionary}, its\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} function\n * returns an updated {@link Transaction} with a potentially modified set of instructions and\n * signature dictionary. The returned transaction must be within the transaction size limit,\n * and include a `lifetimeConstraint`.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignTransactions: async (\n * transactions: Transaction[]\n * ): Promise<(Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the provided transactions.\n * - **First signers**. For a given transaction, a modifying signer must always\n * be used before a partial signer as the former will likely modify the\n * transaction and thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided,\n * the second signer may invalidate the signature of the first one. However,\n * modifying signers may decide not to modify a transaction based on the\n * existence of signatures for that transaction.\n *\n * @see {@link isTransactionModifyingSigner}\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport type TransactionModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport function isTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionModifyingSigner {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionModifyingSigner}\n */\nexport function assertIsTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionModifyingSigner {\n if (!isTransactionModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionPartialSigner#signTransactions | signTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionPartialSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link Transaction | Transactions}\n * without modifying their content. It defines a\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * function that returns a {@link SignatureDictionary} for each provided transaction.\n *\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionPartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signTransactions: async (\n * transactions: Transaction[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. It returns a signature dictionary for each provided\n * transaction without modifying them, making it possible for multiple\n * partial signers to sign the same transaction in parallel.\n * - **Flexible order**. The order in which we use these signers for\n * a given transaction doesn’t matter.\n *\n * @see {@link isTransactionPartialSigner}\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport type TransactionPartialSigner = Readonly<{\n address: Address;\n signTransactions(\n transactions: readonly (Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[],\n config?: TransactionPartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionPartialSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionPartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport function isTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionPartialSigner {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionPartialSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionPartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionPartialSigner}\n */\nexport function assertIsTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionPartialSigner {\n if (!isTransactionPartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { Transaction, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionSendingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs one or multiple transactions\n * before sending them immediately to the blockchain.\n *\n * It defines a {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions}\n * function that returns the transaction signature (i.e. its identifier) for each provided\n * {@link Transaction}.\n *\n * This interface is required for PDA wallets and other types of wallets that don't provide an\n * interface for signing transactions without sending them.\n *\n * Note that it is also possible for such signers to modify the provided transactions\n * before signing and sending them. This enables use cases where the modified transactions\n * cannot be shared with the app and thus must be sent directly.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signAndSendTransactions: async (transactions: Transaction[]): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Single signer**. Since this signer also sends the provided transactions,\n * we can only use a single {@link TransactionSendingSigner} for a given set of transactions.\n * - **Last signer**. Trivially, that signer must also be the last one used.\n * - **Potential conflicts**. Since signers may decide to modify the given\n * transactions before sending them, they may invalidate previous signatures.\n * However, signers may decide not to modify a transaction based\n * on the existence of signatures for that transaction.\n * - **Potential confirmation**. Whilst this is not required by this interface,\n * it is also worth noting that most wallets will also wait for the transaction\n * to be confirmed (typically with a `confirmed` commitment)\n * before notifying the app that they are done.\n *\n * @see {@link isTransactionSendingSigner}\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport type TransactionSendingSigner = Readonly<{\n address: Address;\n signAndSendTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionSendingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSendingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport function isTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSendingSigner {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSendingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSendingSigner}\n */\nexport function assertIsTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSendingSigner {\n if (!isTransactionSendingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a signer capable of signing transactions.\n *\n * @see {@link TransactionModifyingSigner} For signers that can modify transactions before signing them.\n * @see {@link TransactionPartialSigner} For signers that can be used in parallel.\n * @see {@link TransactionSendingSigner} For signers that send transactions after signing them.\n * @see {@link isTransactionSigner}\n * @see {@link assertIsTransactionSigner}\n */\nexport type TransactionSigner =\n | TransactionModifyingSigner\n | TransactionPartialSigner\n | TransactionSendingSigner;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSigner}\n */\nexport function isTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSigner {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSigner}\n */\nexport function assertIsTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSigner {\n if (!isTransactionSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionVersion,\n} from '@solana/transaction-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionMessageWithFeePayerSigner } from './fee-payer-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * An extension of the {@link AccountMeta} type that allows us to store {@link TransactionSigner | TransactionSigners} inside it.\n *\n * Note that, because this type represents a signer, it must use one the following two roles:\n * - {@link AccountRole.READONLY_SIGNER}\n * - {@link AccountRole.WRITABLE_SIGNER}\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner} to use within the account meta.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole } from '@solana/instructions';\n * import { generateKeyPairSigner, AccountSignerMeta } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const account: AccountSignerMeta = {\n * address: signer.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer,\n * };\n * ```\n */\nexport interface AccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> extends AccountMeta {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\n/**\n * A union type that supports base account metas as well as {@link AccountSignerMeta | signer account metas}.\n */\ntype AccountMetaWithSigner =\n | AccountLookupMeta\n | AccountMeta\n | AccountSignerMeta;\n\n/**\n * Composable type that allows {@link AccountSignerMeta | AccountSignerMetas} to be used inside the instruction's `accounts` array\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { generateKeyPairSigner, InstructionWithSigners } from '@solana/signers';\n *\n * const [authority, buffer] = await Promise.all([\n * generateKeyPairSigner(),\n * generateKeyPairSigner(),\n * ]);\n * const instruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [\n * // The authority is a signer account.\n * {\n * address: authority.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer: authority,\n * },\n * // The buffer is a writable account.\n * { address: buffer.address, role: AccountRole.WRITABLE },\n * ],\n * };\n * ```\n */\nexport type InstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Pick, 'accounts'>;\n\n/**\n * A {@link BaseTransactionMessage} type extension that accept {@link TransactionSigner | TransactionSigners}.\n *\n * Namely, it allows:\n * - a {@link TransactionSigner} to be used as the fee payer and\n * - {@link InstructionWithSigners} to be used in its instructions.\n *\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, InstructionWithSigners, TransactionMessageWithSigners } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const firstInstruction: Instruction = { ... };\n * const secondInstruction: InstructionWithSigners = { ... };\n * const transactionMessage: BaseTransactionMessage & TransactionMessageWithSigners = {\n * feePayer: signer,\n * instructions: [firstInstruction, secondInstruction],\n * }\n * ```\n */\nexport type TransactionMessageWithSigners<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Partial | TransactionMessageWithFeePayerSigner> &\n Pick<\n BaseTransactionMessage>,\n 'instructions'\n >;\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside the account metas of an {@link InstructionWithSigners | instruction}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n *\n * @example\n * ```ts\n * import { InstructionWithSigners, getSignersFromInstruction } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const instructionWithSigners: InstructionWithSigners = {\n * accounts: [\n * { address: signerA.address, signer: signerA, ... },\n * { address: signerB.address, signer: signerB, ... },\n * { address: signerA.address, signer: signerA, ... },\n * ],\n * };\n *\n * const instructionSigners = getSignersFromInstruction(instructionWithSigners);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromInstruction(\n instruction: InstructionWithSigners,\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : [])),\n );\n}\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside a given {@link TransactionMessageWithSigners | transaction message}.\n *\n * This includes any {@link TransactionSigner | TransactionSigners} stored\n * as the fee payer or in the instructions of the transaction message.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { InstructionWithSigners, TransactionMessageWithSigners, getSignersFromTransactionMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const firstInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerA.address, signer: signerA, ... }],\n * };\n * const secondInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerB.address, signer: signerB, ... }],\n * };\n * const transactionMessage: TransactionMessageWithSigners = {\n * feePayer: signerA,\n * instructions: [firstInstruction, secondInstruction],\n * }\n *\n * const transactionSigners = getSignersFromTransactionMessage(transactionMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromTransactionMessage<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TTransactionMessage extends TransactionMessageWithSigners = TransactionMessageWithSigners<\n TAddress,\n TSigner\n >,\n>(transaction: TTransactionMessage): readonly TSigner[] {\n return deduplicateSigners([\n ...(transaction.feePayer && isTransactionSigner(transaction.feePayer) ? [transaction.feePayer as TSigner] : []),\n ...transaction.instructions.flatMap(getSignersFromInstruction),\n ]);\n}\n","import { Address } from '@solana/addresses';\nimport { Instruction, isSignerRole } from '@solana/instructions';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { AccountSignerMeta, InstructionWithSigners, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of an instruction when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TInstruction - The inferred type of the instruction provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { addSignersToInstruction, TransactionSigner } from '@solana/signers';\n *\n * const instruction: Instruction = {\n * accounts: [\n * { address: '1111' as Address, role: AccountRole.READONLY_SIGNER },\n * { address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER },\n * ],\n * // ...\n * };\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const instructionWithSigners = addSignersToInstruction(\n * [signerA, signerB],\n * instruction\n * );\n *\n * // instructionWithSigners.accounts[0].signer === signerA\n * // instructionWithSigners.accounts[1].signer === signerB\n * ```\n */\nexport function addSignersToInstruction(\n signers: TransactionSigner[],\n instruction: TInstruction | (InstructionWithSigners & TInstruction),\n): InstructionWithSigners & TInstruction {\n if (!instruction.accounts || instruction.accounts.length === 0) {\n return instruction as InstructionWithSigners & TInstruction;\n }\n\n const signerByAddress = new Map(deduplicateSigners(signers).map(signer => [signer.address, signer]));\n return Object.freeze({\n ...instruction,\n accounts: instruction.accounts.map(account => {\n const signer = signerByAddress.get(account.address);\n if (!isSignerRole(account.role) || 'signer' in account || !signer) {\n return account;\n }\n return Object.freeze({ ...account, signer } as AccountSignerMeta);\n }),\n });\n}\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of all instructions inside a transaction message and/or\n * the transaction message fee payer, when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { addSignersToTransactionMessage, TransactionSigner } from '@solana/signers';\n *\n * const instructionA: Instruction = {\n * accounts: [{ address: '1111' as Address, role: AccountRole.READONLY_SIGNER }],\n * // ...\n * };\n * const instructionB: Instruction = {\n * accounts: [{ address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER }],\n * // ...\n * };\n * const transactionMessage: BaseTransactionMessage = {\n * instructions: [instructionA, instructionB],\n * // ...\n * }\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const transactionMessageWithSigners = addSignersToTransactionMessage(\n * [signerA, signerB],\n * transactionMessage\n * );\n *\n * // transactionMessageWithSigners.instructions[0].accounts[0].signer === signerA\n * // transactionMessageWithSigners.instructions[1].accounts[0].signer === signerB\n * ```\n */\nexport function addSignersToTransactionMessage(\n signers: TransactionSigner[],\n transactionMessage: TTransactionMessage | (TransactionMessageWithSigners & TTransactionMessage),\n): TransactionMessageWithSigners & TTransactionMessage {\n const feePayerSigner = hasAddressOnlyFeePayer(transactionMessage)\n ? signers.find(signer => signer.address === transactionMessage.feePayer.address)\n : undefined;\n\n if (!feePayerSigner && transactionMessage.instructions.length === 0) {\n return transactionMessage as TransactionMessageWithSigners & TTransactionMessage;\n }\n\n return Object.freeze({\n ...transactionMessage,\n ...(feePayerSigner ? { feePayer: feePayerSigner } : null),\n instructions: transactionMessage.instructions.map(instruction => addSignersToInstruction(signers, instruction)),\n });\n}\n\nfunction hasAddressOnlyFeePayer(\n message: BaseTransactionMessage & Partial,\n): message is BaseTransactionMessage & { feePayer: { address: Address } } {\n return (\n !!message &&\n 'feePayer' in message &&\n !!message.feePayer &&\n typeof message.feePayer.address === 'string' &&\n !isTransactionSigner(message.feePayer)\n );\n}\n","import { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Alternative to {@link TransactionMessageWithFeePayer} that uses a {@link TransactionSigner} for the fee payer.\n *\n * @typeParam TAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner}.\n *\n * @example\n * ```ts\n * import { TransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, TransactionMessageWithFeePayerSigner } from '@solana/signers';\n *\n * const transactionMessage: TransactionMessage & TransactionMessageWithFeePayerSigner = {\n * feePayer: await generateKeyPairSigner(),\n * instructions: [],\n * version: 0,\n * };\n * ```\n */\nexport interface TransactionMessageWithFeePayerSigner<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> {\n readonly feePayer: TSigner;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Sets the fee payer of a {@link TransactionMessage | transaction message}\n * using a {@link TransactionSigner}.\n *\n * @typeParam TFeePayerAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { pipe } from '@solana/functional';\n * import { generateKeyPairSigner, setTransactionMessageFeePayerSigner } from '@solana/signers';\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const feePayer = await generateKeyPairSigner();\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(signer, message),\n * );\n * ```\n */\nexport function setTransactionMessageFeePayerSigner<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial &\n TransactionMessage,\n>(\n feePayer: TransactionSigner,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayerSigner {\n Object.freeze(feePayer);\n const out = { ...transactionMessage, feePayer };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayerSigner;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessagePartialSigner#signMessages | signMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessagePartialSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link SignableMessage | SignableMessages}\n * without modifying their content.\n *\n * It defines a {@link MessagePartialSigner#signMessages | signMessages} function\n * that returns a {@link SignatureDictionary} for each provided message.\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessagePartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. When multiple signers sign the same message, we can\n * perform this operation in parallel to obtain all their signatures.\n * - **Flexible order**. The order in which we use these signers\n * for a given message doesn’t matter.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessagePartialSigner}\n * @see {@link assertIsMessagePartialSigner}\n */\nexport type MessagePartialSigner = Readonly<{\n address: Address;\n signMessages(\n messages: readonly SignableMessage[],\n config?: MessagePartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessagePartialSigner({ address, signMessages: async () => {} }); // true\n * isMessagePartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessagePartialSigner}\n */\nexport function isMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessagePartialSigner {\n return 'signMessages' in value && typeof value.signMessages === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessagePartialSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessagePartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessagePartialSigner}\n */\nexport function assertIsMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessagePartialSigner {\n if (!isMessagePartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SolanaError } from '@solana/errors';\nimport { createKeyPairFromBytes, createKeyPairFromPrivateKeyBytes, generateKeyPair, signBytes } from '@solana/keys';\nimport { partiallySignTransaction } from '@solana/transactions';\n\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a signer that uses a {@link CryptoKeyPair} to sign messages and transactions.\n *\n * It implements both the {@link MessagePartialSigner} and {@link TransactionPartialSigner}\n * interfaces and keeps track of the {@link CryptoKeyPair} instance used\n * to sign messages and transactions.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = generateKeyPairSigner();\n * signer.address; // Address;\n * signer.keyPair; // CryptoKeyPair;\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * ```\n *\n * @see {@link generateKeyPairSigner}\n * @see {@link createSignerFromKeyPair}\n * @see {@link createKeyPairSignerFromBytes}\n * @see {@link createKeyPairSignerFromPrivateKeyBytes}\n * @see {@link isKeyPairSigner}\n * @see {@link assertIsKeyPairSigner}\n */\nexport type KeyPairSigner = MessagePartialSigner &\n TransactionPartialSigner & { keyPair: CryptoKeyPair };\n\n/**\n * Checks whether the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, isKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * isKeyPairSigner(signer); // true\n * isKeyPairSigner({ address: address('1234..5678') }); // false\n * ```\n */\nexport function isKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is KeyPairSigner {\n return (\n 'keyPair' in value &&\n typeof value.keyPair === 'object' &&\n isMessagePartialSigner(value) &&\n isTransactionPartialSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, assertIsKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * assertIsKeyPairSigner(signer); // void\n * assertIsKeyPairSigner({ address: address('1234..5678') }); // Throws an error.\n * ```\n */\nexport function assertIsKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is KeyPairSigner {\n if (!isKeyPairSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, {\n address: value.address,\n });\n }\n}\n\n/**\n * Creates a {@link KeyPairSigner} from a provided {@link CryptoKeyPair}.\n *\n * The {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * functions of the returned signer will use the private key of the provided\n * key pair to sign messages and transactions.\n *\n * Note that both the {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions} implementations\n * are parallelized, meaning that they will sign all provided messages and transactions in parallel.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { createSignerFromKeyPair, KeyPairSigner } from '@solana/signers';\n *\n * const keyPair: CryptoKeyPair = await generateKeyPair();\n * const signer: KeyPairSigner = await createSignerFromKeyPair(keyPair);\n * ```\n */\nexport async function createSignerFromKeyPair(keyPair: CryptoKeyPair): Promise {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const out: KeyPairSigner = {\n address,\n keyPair,\n signMessages: messages =>\n Promise.all(\n messages.map(async message =>\n Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) }),\n ),\n ),\n signTransactions: transactions =>\n Promise.all(\n transactions.map(async transaction => {\n const signedTransaction = await partiallySignTransaction([keyPair], transaction);\n // we know that the address has signed `signedTransaction` because it comes from the keypair\n return Object.freeze({ [address]: signedTransaction.signatures[address]! });\n }),\n ),\n };\n\n return Object.freeze(out);\n}\n\n/**\n * Generates a signer capable of signing messages and transactions by generating\n * a {@link CryptoKeyPair} and creating a {@link KeyPairSigner} from it.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * ```\n *\n * @see {@link createSignerFromKeyPair}\n */\nexport async function generateKeyPairSigner(): Promise {\n return await createSignerFromKeyPair(await generateKeyPair());\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 64-bytes `Uint8Array` secret key (private key and public key).\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairSignerFromBytes } from '@solana/signers';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a KeyPairSigner from the bytes.\n * const signer = await createKeyPairSignerFromBytes(keypairBytes);\n * ```\n *\n * @see {@link createKeyPairSignerFromPrivateKeyBytes} if you only have the 32-bytes private key instead.\n */\nexport async function createKeyPairSignerFromBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromBytes(bytes, extractable));\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 32-bytes `Uint8Array` private key.\n *\n * @example\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairSignerFromPrivateKeyBytes } from '@solana/signers';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedSigner = await createKeyPairSignerFromPrivateKeyBytes(seed);\n * ```\n *\n * @see {@link createKeyPairSignerFromBytes} if you have the 64-bytes secret key instead (private key and public key).\n */\nexport async function createKeyPairSignerFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromPrivateKeyBytes(bytes, extractable));\n}\n","import { Address, isAddress } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessageModifyingSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that _potentially_ modifies the content\n * of the provided {@link SignableMessage | SignableMessages} before signing them.\n *\n * For instance, this enables wallets to prefix or suffix nonces to the messages they sign.\n * For each message, instead of returning a {@link SignatureDictionary}, the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} function\n * returns an updated {@link SignableMessage} with a potentially modified content and signature dictionary.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessageModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the content of the message.\n * - **First signers**. For a given message, a modifying signer must always be used\n * before a partial signer as the former will likely modify the message and\n * thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided, the second\n * signer may invalidate the signature of the first one. However, modifying signers\n * may decide not to modify a message based on the existence of signatures for that message.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessageModifyingSigner}\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport type MessageModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignMessages(\n messages: readonly SignableMessage[],\n config?: MessageModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport function isMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageModifyingSigner {\n return (\n isAddress(value.address) &&\n 'modifyAndSignMessages' in value &&\n typeof value.modifyAndSignMessages === 'function'\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageModifyingSigner}\n */\nexport function assertIsMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageModifyingSigner {\n if (!isMessageModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isMessageModifyingSigner, MessageModifyingSigner } from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\n\n/**\n * Defines a signer capable of signing messages.\n *\n * @see {@link MessageModifyingSigner} For signers that can modify messages before signing them.\n * @see {@link MessagePartialSigner} For signers that can be used in parallel.\n * @see {@link isMessageSigner}\n * @see {@link assertIsMessageSigner}\n */\nexport type MessageSigner =\n | MessageModifyingSigner\n | MessagePartialSigner;\n\n/**\n * Checks whether the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageSigner({ address, signMessages: async () => {} }); // true\n * isMessageSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageSigner}\n */\nexport function isMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageSigner {\n return isMessagePartialSigner(value) || isMessageModifyingSigner(value);\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessageSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageSigner}\n */\nexport function assertIsMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageSigner {\n if (!isMessageSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { MessagePartialSigner } from './message-partial-signer';\nimport { TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a Noop (No-Operation) signer that pretends to partially sign messages and transactions.\n *\n * For a given {@link Address}, a Noop Signer can be created to offer an implementation of both\n * the {@link MessagePartialSigner} and {@link TransactionPartialSigner} interfaces such that\n * they do not sign anything. Namely, signing a transaction or a message with a `NoopSigner`\n * will return an empty `SignatureDictionary`.\n *\n * @typeParam TAddress - Supply a string literal to define a Noop signer having a particular address.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * // ^ Both messageSignatures and transactionSignatures are empty.\n * ```\n *\n * @remarks\n * This signer may be useful:\n *\n * - For testing purposes.\n * - For indicating that a given account is a signer and taking the responsibility to provide\n * the signature for that account ourselves. For instance, if we need to send the transaction\n * to a server that will sign it and send it for us.\n *\n * @see {@link createNoopSigner}\n */\nexport type NoopSigner = MessagePartialSigner &\n TransactionPartialSigner;\n\n/**\n * Creates a {@link NoopSigner} from the provided {@link Address}.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * ```\n */\nexport function createNoopSigner(address: Address): NoopSigner {\n const out: NoopSigner = {\n address,\n signMessages: messages => Promise.resolve(messages.map(() => Object.freeze({}))),\n signTransactions: transactions => Promise.resolve(transactions.map(() => Object.freeze({}))),\n };\n\n return Object.freeze(out);\n}\n","import { OffchainMessageWithRequiredSignatories } from '@solana/offchain-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isMessageSigner, MessageSigner } from './message-signer';\n\n/**\n * Represents a {@link Signer} that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatorySigner = MessageSigner;\n\n/**\n * Extracts and deduplicates all {@link MessageSigner | MessageSigners} stored inside a given\n * {@link OffchainMessageWithSigners | offchain message}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link MessageSigner | MessageSigners}.\n * @typeParam TOffchainMessage - The inferred type of the offchain message provided.\n *\n * @example\n * ```ts\n * import { OffchainMessageWithSigners, getSignersFromOffchainMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signMessages: async () => {} };\n * const signerB = { address: address('2222..2222'), modifyAndSignMessages: async () => {} };\n * const OffchainMessage: OffchainMessageWithSigners = {\n * /* ... *\\/\n * requiredSignatories: [signerA, signerB],\n * };\n *\n * const messageSigners = getSignersFromOffchainMessage(offchainMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromOffchainMessage({\n requiredSignatories,\n}: OffchainMessageWithRequiredSignatories): readonly MessageSigner[] {\n const messageSigners = requiredSignatories.filter(isMessageSigner);\n return deduplicateSigners(messageSigners);\n}\n","import {\n assertIsFullySignedOffchainMessageEnvelope,\n compileOffchainMessageEnvelope,\n FullySignedOffchainMessageEnvelope,\n OffchainMessage,\n OffchainMessageEnvelope,\n OffchainMessageSignatory,\n OffchainMessageWithRequiredSignatories,\n} from '@solana/offchain-messages';\n\nimport {\n isMessageModifyingSigner,\n MessageModifyingSigner,\n MessageModifyingSignerConfig,\n} from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner, MessagePartialSignerConfig } from './message-partial-signer';\nimport { MessageSigner } from './message-signer';\nimport { getSignersFromOffchainMessage, OffchainMessageSignatorySigner } from './offchain-message-signer';\nimport { SignableMessage } from './signable-message';\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope.\n *\n * It first uses all {@link MessageModifyingSigner | MessageModifyingSigners} sequentially before\n * using all {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link MessageModifyingSigner} if no other signer implements that interface. Otherwise, it will\n * be used as a {@link MessagePartialSigner}.\n *\n * @example\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @see {@link signOffchainMessageWithSigners}\n */\nexport async function partiallySignOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeMessageSigners(\n getSignersFromOffchainMessage(offchainMessage),\n );\n return await signModifyingAndPartialMessageSigners(offchainMessage, modifyingSigners, partialSigners, config);\n}\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope before asserting that all signatures required\n * by the message are present.\n *\n * This function delegates to the {@link partiallySignOffchainMessageWithSigners} function\n * in order to extract signers from the offchain message and sign it.\n *\n * @example\n * ```ts\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage);\n *\n * // With additional config.\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the offchain message is fully signed.\n * mySignedOffchainMessageEnvelope satisfies FullySignedOffchainMessageEnvelope;\n * ```\n *\n * @see {@link partiallySignOffchainMessageWithSigners}\n */\nexport async function signOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, config);\n assertIsFullySignedOffchainMessageEnvelope(signedOffchainMessageEnvelope);\n return signedOffchainMessageEnvelope;\n}\n\n/**\n * Identifies each provided {@link MessageSigner} and categorizes them into their respective types.\n * When a signer implements multiple interfaces, it will try to used to most powerful interface but\n * fall back to the least powerful interface when necessary.\n *\n * For instance, if a signer implements {@link MessageSigner} and {@link MessageModifyingSigner},\n * it will be categorized as a `MessageModifyingSigner`.\n */\nfunction categorizeMessageSigners(signers: readonly MessageSigner[]): Readonly<{\n modifyingSigners: readonly MessageModifyingSigner[];\n partialSigners: readonly MessagePartialSigner[];\n}> {\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyMessageModifyingSigners(signers);\n\n // Use any remaining signers as partial signers.\n const partialSigners = signers\n .filter(isMessagePartialSigner)\n .filter(signer => !(modifyingSigners as typeof signers).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners });\n}\n\n/** Identifies the best signers to use as MessageModifyingSigners, if any */\nfunction identifyMessageModifyingSigners(\n signers: readonly (MessageModifyingSigner | MessagePartialSigner)[],\n): readonly MessageModifyingSigner[] {\n // Ensure there are any MessageModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isMessageModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isMessagePartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs an offchain message using the provided\n * {@link MessageModifyingSigner | MessageModifyingSigners} sequentially followed by the\n * {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n */\nasync function signModifyingAndPartialMessageSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n modifyingSigners: readonly MessageModifyingSigner[] = [],\n partialSigners: readonly MessagePartialSigner[] = [],\n config?: MessageModifyingSignerConfig,\n): Promise {\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n const offchainMessageEnvelope: SignableMessage = compileOffchainMessageEnvelope(offchainMessage);\n\n // Handle modifying signers sequentially.\n const modifiedOffchainMessage = await modifyingSigners.reduce(async (offchainMessageEnvelope, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [message] = await modifyingSigner.modifyAndSignMessages([await offchainMessageEnvelope], config);\n return Object.freeze(message);\n }, Promise.resolve(offchainMessageEnvelope));\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signMessages([modifiedOffchainMessage], config);\n return signatures;\n }),\n );\n\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n return Object.freeze({\n ...modifiedOffchainMessage,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedOffchainMessage.signatures ?? {}),\n ),\n } as OffchainMessageEnvelope);\n}\n","import {\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { isTransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a transaction message with exactly one {@link TransactionSendingSigner}.\n *\n * This type is used to narrow the type of transaction messages that have been\n * checked to have exactly one sending signer.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithSingleSendingSigner } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithSingleSendingSigner;\n * ```\n *\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport type TransactionMessageWithSingleSendingSigner = Brand<\n TransactionMessageWithSigners,\n 'TransactionMessageWithSingleSendingSigner'\n>;\n\n/**\n * Checks whether the provided transaction has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using {@link signAndSendTransactionMessageWithSigners} to provide\n * a fallback strategy in case the transaction message cannot be send using this function.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * isTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners,\n * signTransactionMessageWithSigners,\n * } from '@solana/signers';\n * import { getBase64EncodedWireTransaction } from '@solana/transactions';\n *\n * let transactionSignature: SignatureBytes;\n * if (isTransactionMessageWithSingleSendingSigner(transactionMessage)) {\n * transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * } else {\n * const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);\n * const encodedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * transactionSignature = await rpc.sendTransaction(encodedTransaction).send();\n * }\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport function isTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transaction: TTransactionMessage): transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n try {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Asserts that the provided transaction message has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using the {@link signAndSendTransactionMessageWithSigners} function\n * to ensure it will be able to select the correct signer to send the transaction.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * assertIsTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners\n * } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n */\nexport function assertIsTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transaction: TTransactionMessage,\n): asserts transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n const signers = getSignersFromTransactionMessage(transaction);\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n\n if (sendingSigners.length === 0) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n // When identifying if there are multiple sending signers, we only need to check for\n // sending signers that do not implement other transaction signer interfaces as\n // they will be used as these other signer interfaces in case of a conflict.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer),\n );\n\n if (sendingOnlySigners.length > 1) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS);\n }\n}\n","import { SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport {\n assertIsFullySignedTransaction,\n compileTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithinSizeLimit,\n TransactionWithLifetime,\n} from '@solana/transactions';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport {\n isTransactionModifyingSigner,\n TransactionModifyingSigner,\n TransactionModifyingSignerConfig,\n} from './transaction-modifying-signer';\nimport {\n isTransactionPartialSigner,\n TransactionPartialSigner,\n TransactionPartialSignerConfig,\n} from './transaction-partial-signer';\nimport {\n isTransactionSendingSigner,\n TransactionSendingSigner,\n TransactionSendingSignerConfig,\n} from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { assertIsTransactionMessageWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction.\n *\n * It first uses all {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before\n * using all {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link TransactionModifyingSigner} if no other signer implements that interface.\n * Otherwise, it will be used as a {@link TransactionPartialSigner}.\n *\n * @example\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Finally, note that this function ignores {@link TransactionSendingSigner | TransactionSendingSigners}\n * as it does not send the transaction. Check out the {@link signAndSendTransactionMessageWithSigners}\n * function for more details on how to use sending signers.\n *\n * @see {@link signTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function partiallySignTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transactionMessage).filter(isTransactionSigner)),\n { identifySendingSigner: false },\n );\n\n return await signModifyingAndPartialTransactionSigners(\n transactionMessage,\n modifyingSigners,\n partialSigners,\n config,\n );\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction before asserting\n * that all signatures required by the transaction are present.\n *\n * This function delegates to the {@link partiallySignTransactionMessageWithSigners} function\n * in order to extract signers from the transaction message and sign the transaction.\n *\n * @example\n * ```ts\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage);\n *\n * // With additional config.\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the transaction is fully signed.\n * mySignedTransaction satisfies FullySignedTransaction;\n * ```\n *\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function signTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, config);\n assertIsFullySignedTransaction(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to sign it before sending it immediately to the blockchain.\n *\n * It returns the signature of the sent transaction (i.e. its identifier) as bytes.\n *\n * @example\n * ```ts\n * import { signAndSendTransactionMessageWithSigners } from '@solana/signers';\n *\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n *\n * // With additional config.\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Similarly to the {@link partiallySignTransactionMessageWithSigners} function, it first uses all\n * {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before using all\n * {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n * It then sends the transaction using the {@link TransactionSendingSigner} it identified.\n *\n * Composite transaction signers are treated such that at least one sending signer is used if any.\n * When a {@link TransactionSigner} implements more than one interface, we use it as a:\n *\n * - {@link TransactionSendingSigner}, if no other {@link TransactionSendingSigner} exists.\n * - {@link TransactionModifyingSigner}, if no other {@link TransactionModifyingSigner} exists.\n * - {@link TransactionPartialSigner}, otherwise.\n *\n * The provided transaction must contain exactly one {@link TransactionSendingSigner} inside its account metas.\n * If more than one composite signers implement the {@link TransactionSendingSigner} interface,\n * one of them will be selected as the sending signer. Otherwise, if multiple\n * {@link TransactionSendingSigner | TransactionSendingSigners} must be selected, the function will throw an error.\n *\n * If you'd like to assert that a transaction makes use of exactly one {@link TransactionSendingSigner}\n * _before_ calling this function, you may use the {@link assertIsTransactionMessageWithSingleSendingSigner} function.\n *\n * Alternatively, you may use the {@link isTransactionMessageWithSingleSendingSigner} function to provide a\n * fallback in case the transaction does not contain any sending signer.\n *\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signTransactionMessageWithSigners}\n *\n */\nexport async function signAndSendTransactionMessageWithSigners(\n transaction: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionSendingSignerConfig,\n): Promise {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n\n const abortSignal = config?.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transaction).filter(isTransactionSigner)),\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n config,\n );\n\n if (!sendingSigner) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], config);\n abortSignal?.throwIfAborted();\n\n return signature;\n}\n\n/**\n * Identifies each provided TransactionSigner and categorizes them into their respective types.\n * When a signer implements multiple interface, it will try to used to most powerful interface\n * but fallback to the least powerful interface when necessary.\n * For instance, if a signer implements TransactionSendingSigner and TransactionModifyingSigner,\n * it will be categorized as a TransactionSendingSigner if and only if no other signers implement\n * the TransactionSendingSigner interface.\n */\nfunction categorizeTransactionSigners(\n signers: readonly TransactionSigner[],\n config: { identifySendingSigner?: boolean } = {},\n): Readonly<{\n modifyingSigners: readonly TransactionModifyingSigner[];\n partialSigners: readonly TransactionPartialSigner[];\n sendingSigner: TransactionSendingSigner | null;\n}> {\n // Identify the unique sending signer that should be used.\n const identifySendingSigner = config.identifySendingSigner ?? true;\n const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;\n\n // Now, focus on the other signers.\n // I.e. the modifying or partial signers that are not the identified sending signer.\n // Note that any other sending only signers will be discarded.\n const otherSigners = signers.filter(\n (signer): signer is TransactionModifyingSigner | TransactionPartialSigner =>\n signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer)),\n );\n\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);\n\n // Use any remaining signers as partial signers.\n const partialSigners = otherSigners\n .filter(isTransactionPartialSigner)\n .filter(signer => !(modifyingSigners as typeof otherSigners).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });\n}\n\n/** Identifies the best signer to use as a TransactionSendingSigner, if any */\nfunction identifyTransactionSendingSigner(signers: readonly TransactionSigner[]): TransactionSendingSigner | null {\n // Ensure there are any TransactionSendingSigners in the first place.\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n if (sendingSigners.length === 0) return null;\n\n // Prefer sending signers that do not offer other interfaces.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer),\n );\n if (sendingOnlySigners.length > 0) {\n return sendingOnlySigners[0];\n }\n\n // Otherwise, choose any sending signer.\n return sendingSigners[0];\n}\n\n/** Identifies the best signers to use as TransactionModifyingSigners, if any */\nfunction identifyTransactionModifyingSigners(\n signers: readonly (TransactionModifyingSigner | TransactionPartialSigner)[],\n): readonly TransactionModifyingSigner[] {\n // Ensure there are any TransactionModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isTransactionModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isTransactionPartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs a transaction using the provided TransactionModifyingSigners\n * sequentially followed by the TransactionPartialSigners in parallel.\n */\nasync function signModifyingAndPartialTransactionSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n config?: TransactionModifyingSignerConfig,\n): Promise {\n // serialize the transaction\n const transaction = compileTransaction(transactionMessage);\n\n // Handle modifying signers sequentially.\n const modifiedTransaction = (await modifyingSigners.reduce(\n async (transaction, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], config);\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise>,\n )) as Transaction & TransactionWithinSizeLimit & TransactionWithLifetime;\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], config);\n return signatures;\n }),\n );\n\n return Object.freeze({\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {}),\n ),\n });\n}\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import { TextEncoder } from '@solana/text-encoding-impl';\n\nimport { SignatureDictionary } from './types';\n\n/**\n * Defines a message that needs signing and its current set of signatures if any.\n *\n * This interface allows {@link MessageModifyingSigner | MessageModifyingSigners}\n * to decide on whether or not they should modify the provided message depending\n * on whether or not signatures already exist for such message.\n *\n * It also helps create a more consistent API by providing a structure analogous\n * to transactions which also keep track of their {@link SignatureDictionary}.\n *\n * @example\n * ```ts\n * import { createSignableMessage } from '@solana/signers';\n *\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * message.content; // The content of the message as bytes.\n * message.signatures; // The current set of signatures for this message.\n * ```\n *\n * @see {@link createSignableMessage}\n */\nexport type SignableMessage = Readonly<{\n content: Uint8Array;\n signatures: SignatureDictionary;\n}>;\n\n/**\n * Creates a {@link SignableMessage} from a `Uint8Array` or a UTF-8 string.\n *\n * It optionally accepts a signature dictionary if the message already contains signatures.\n *\n * @example\n * ```ts\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * const messageFromText = createSignableMessage('Hello world!');\n * const messageWithSignatures = createSignableMessage('Hello world!', {\n * [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes,\n * });\n * ```\n */\nexport function createSignableMessage(\n content: Uint8Array | string,\n signatures: SignatureDictionary = {},\n): SignableMessage {\n return Object.freeze({\n content: typeof content === 'string' ? new TextEncoder().encode(content) : content,\n signatures: Object.freeze({ ...signatures }),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { GetEpochInfoApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport type { Commitment } from '@solana/rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the block height as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /** The block height after which to reject the promise */\n lastValidBlockHeight: bigint;\n}) => Promise;\n\ntype CreateBlockHeightExceedencePromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that throws when the network progresses past the block height after which the\n * supplied blockhash is considered expired for use as a transaction lifetime specifier.\n *\n * When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the\n * network until that blockhash expires. All blockhashes have a block height after which they are\n * considered to have expired.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getBlockHeightExceedencePromise({ lastValidBlockHeight });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error(\n * `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` +\n * `It is now ${e.context.currentBlockHeight}`,\n * );\n * // Re-sign and retry the transaction.\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'devnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'testnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'mainnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({\n abortSignal: callerAbortSignal,\n commitment,\n lastValidBlockHeight,\n }): Promise {\n callerAbortSignal.throwIfAborted();\n const abortController = new AbortController();\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {\n const { absoluteSlot, blockHeight } = await rpc\n .getEpochInfo({ commitment })\n .send({ abortSignal: abortController.signal });\n return {\n blockHeight,\n differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight,\n };\n }\n try {\n const [slotNotifications, { blockHeight: initialBlockHeight, differenceBetweenSlotHeightAndBlockHeight }] =\n await Promise.all([\n rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),\n getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight(),\n ]);\n callerAbortSignal.throwIfAborted();\n let currentBlockHeight = initialBlockHeight;\n if (currentBlockHeight <= lastValidBlockHeight) {\n let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;\n for await (const slotNotification of slotNotifications) {\n const { slot } = slotNotification;\n if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {\n // Before making a final decision, recheck the actual block height.\n const {\n blockHeight: recheckedBlockHeight,\n differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight,\n } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();\n currentBlockHeight = recheckedBlockHeight;\n if (currentBlockHeight > lastValidBlockHeight) {\n // Verified; the block height has been exceeded.\n break;\n } else {\n // The block height has not been exceeded, which implies that the\n // difference between the slot height and the block height has grown\n // (ie. some blocks have been skipped since we started). Recalibrate the\n // difference and keep waiting.\n lastKnownDifferenceBetweenSlotHeightAndBlockHeight =\n currentDifferenceBetweenSlotHeightAndBlockHeight;\n }\n }\n }\n }\n callerAbortSignal.throwIfAborted();\n throw new SolanaError(SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, {\n currentBlockHeight,\n lastValidBlockHeight,\n });\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport type { GetAccountInfoApi, Rpc } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions } from '@solana/rpc-subscriptions';\nimport type { Base64EncodedDataResponse, Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transaction-messages';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the nonce account details as of the highest slot that has reached this level of\n * commitment.\n */\n commitment: Commitment;\n /**\n * The value of the nonce that we would expect to see in the nonce account in order for any\n * transaction with that nonce-based lifetime to be considered valid.\n */\n currentNonceValue: Nonce;\n /** The address of the account in which the currently-valid nonce value is stored */\n nonceAccountAddress: Address;\n}) => Promise;\n\ntype CreateNonceInvalidationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\n/**\n * Creates a promise that throws when the value stored in a nonce account is not the expected one.\n *\n * When a transaction's lifetime is tied to the value stored in a nonce account, that transaction\n * can be landed on the network until the nonce is advanced to a new value.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getNonceInvalidationPromise({\n * currentNonceValue,\n * nonceAccountAddress,\n * });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) {\n * console.error(`The nonce has advanced to ${e.context.actualNonceValue}`);\n * // Re-sign and retry the transaction.\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(`No nonce account was found at ${nonceAccountAddress}`);\n * }\n * throw e;\n * }\n * ```\n */\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'devnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'testnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'mainnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue: expectedNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes) as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new SolanaError(SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, {\n nonceAccountAddress,\n });\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { getSolanaErrorFromTransactionError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { GetSignatureStatusesApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { type Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * The level of commitment the transaction must have achieved in order for the promise to\n * resolve.\n */\n commitment: Commitment;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}) => Promise;\n\ntype CreateRecentSignatureConfirmationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that resolves when a recently-landed transaction achieves the target\n * confirmation commitment, and throws when the transaction fails with an error.\n *\n * The status of recently-landed transactions is available in the network's status cache. This\n * confirmation strategy will only yield a result if the signature is still in the status cache. To\n * fetch the status of transactions older than those available in the status cache, use the\n * {@link GetSignatureStatusesApi.getSignatureStatuses} method setting the\n * `searchTransactionHistory` configuration param to `true`.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getRecentSignatureConfirmationPromise({\n * commitment,\n * signature,\n * });\n * console.log(`The transaction with signature \\`${signature}\\` has achieved a commitment level of \\`${commitment}\\``);\n * } catch (e) {\n * console.error(`The transaction with signature \\`${signature}\\` failed`, e.cause);\n * throw e;\n * }\n * ```\n */\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'devnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'testnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'mainnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n throw getSolanaErrorFromTransactionError(signatureStatusNotification.value.err);\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (signatureStatus?.err) {\n throw getSolanaErrorFromTransactionError(signatureStatus.err);\n } else if (\n signatureStatus?.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n /**\n * The timeout promise will throw after 30 seconds when the commitment is `processed`, and 60\n * seconds otherwise.\n */\n commitment: Commitment;\n}>;\n\n/**\n * When no other heuristic exists to infer that a transaction has expired, you can use this promise\n * factory with a commitment level. It throws after 30 seconds when the commitment is `processed`,\n * and 60 seconds otherwise. You would typically race this with another confirmation strategy.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { safeRace } from '@solana/promises';\n * import { getTimeoutPromise } from '@solana/transaction-confirmation';\n *\n * try {\n * await safeRace([getCustomTransactionConfirmationPromise(/* ... *\\/), getTimeoutPromise({ commitment })]);\n * } catch (e) {\n * if (e instanceof DOMException && e.name === 'TimeoutError') {\n * console.log('Could not confirm transaction after a timeout');\n * }\n * throw e;\n * }\n * ```\n */\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType;\n}\n\ntype WithNonNullableAbortSignal = Omit & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal) => readonly Promise[],\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await safeRace([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport {\n getSignatureFromTransaction,\n Transaction,\n TransactionWithBlockhashLifetime,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './confirmation-strategy-racer';\nimport { getTimeoutPromise } from './confirmation-strategy-timeout';\n\nexport type TransactionWithLastValidBlockHeight = Omit & {\n lifetimeConstraint: Omit;\n};\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom nonce\n * transaction confirmation strategy.\n *\n * @example\n * ```ts\n * import { waitForDurableNonceTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForDurableNonceTransactionConfirmation({\n * getNonceInvalidationPromise({ abortSignal, commitment, currentNonceValue, nonceAccountAddress }) {\n * // Return a promise that rejects when a nonce becomes invalid.\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.lifetimeConstraint.nonceAccountAddress,\n }),\n ];\n },\n );\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom confirmation\n * strategy for recently-landed transactions.\n *\n * @example\n * ```ts\n * import { waitForRecentTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForRecentTransactionConfirmation({\n * getBlockHeightExceedencePromise({ abortSignal, commitment, lastValidBlockHeight }) {\n * // Return a promise that rejects when the blockhash's block height has been exceeded\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({\n abortSignal,\n commitment,\n getBlockHeightExceedencePromise,\n transaction,\n }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n commitment,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n },\n );\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n },\n );\n}\n","import type { Address } from '@solana/addresses';\nimport type { Signature } from '@solana/keys';\nimport type { RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { Commitment, Lamports } from '@solana/rpc-types';\nimport { waitForRecentTransactionConfirmationUntilTimeout } from '@solana/transaction-confirmation';\n\ntype RequestAndConfirmAirdropConfig = Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: (\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) => Promise;\n lamports: Lamports;\n recipientAddress: Address;\n rpc: Rpc;\n}>;\n\nexport async function requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: RequestAndConfirmAirdropConfig): Promise {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import type { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createRecentSignatureConfirmationPromiseFactory,\n getTimeoutPromise,\n waitForRecentTransactionConfirmationUntilTimeout,\n} from '@solana/transaction-confirmation';\n\nimport { requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT } from './airdrop-internal';\n\ntype AirdropFunction = (\n config: Omit<\n Parameters[0],\n 'confirmSignatureOnlyTransaction' | 'rpc'\n >,\n) => Promise;\n\ntype AirdropFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link RequestAirdropApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to airdrop a certain amount of {@link Lamports} to a Solana\n * address.\n *\n * > [!NOTE] This only works on test clusters.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit';\n *\n * const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899'));\n * const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900'));\n *\n * const airdrop = airdropFactory({ rpc, rpcSubscriptions });\n *\n * await airdrop({\n * commitment: 'confirmed',\n * recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'),\n * lamports: lamports(10_000_000n),\n * });\n * ```\n */\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'devnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'mainnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'testnet'>): AirdropFunction;\nexport function airdropFactory({\n rpc,\n rpcSubscriptions,\n}: AirdropFactoryConfig): AirdropFunction {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmSignatureOnlyTransaction(\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n }\n return async function airdrop(config) {\n return await requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n","import {\n assertAccountsDecoded,\n assertAccountsExist,\n type FetchAccountsConfig,\n fetchJsonParsedAccounts,\n} from '@solana/accounts';\nimport type { Address } from '@solana/addresses';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport { type AddressesByLookupTableAddress } from '@solana/transaction-messages';\n\ntype FetchedAddressLookup = {\n addresses: Address[];\n};\n\n/**\n * Given a list of addresses belonging to address lookup tables, returns a map of lookup table\n * addresses to an ordered array of the addresses they contain.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function fetchAddressesForLookupTables(\n lookupTableAddresses: Address[],\n rpc: Rpc,\n config?: FetchAccountsConfig,\n): Promise {\n if (lookupTableAddresses.length === 0) {\n return {};\n }\n\n const fetchedLookupTables = await fetchJsonParsedAccounts(\n rpc,\n lookupTableAddresses,\n config,\n );\n\n assertAccountsDecoded(fetchedLookupTables);\n assertAccountsExist(fetchedLookupTables);\n\n return fetchedLookupTables.reduce((acc, lookup) => {\n return {\n ...acc,\n [lookup.address]: lookup.data.addresses,\n };\n }, {});\n}\n","import { type FetchAccountsConfig } from '@solana/accounts';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n decompileTransactionMessage,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithLifetime,\n} from '@solana/transaction-messages';\n\nimport { fetchAddressesForLookupTables } from './fetch-lookup-tables';\n\ntype DecompileTransactionMessageFetchingLookupTablesConfig = FetchAccountsConfig & {\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Returns a {@link TransactionMessage} from a {@link CompiledTransactionMessage}. If any of the\n * accounts in the compiled message require an address lookup table to find their address, this\n * function will use the supplied RPC instance to fetch the contents of the address lookup table\n * from the network.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function decompileTransactionMessageFetchingLookupTables(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n rpc: Rpc,\n config?: DecompileTransactionMessageFetchingLookupTablesConfig,\n): Promise {\n const lookupTables =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? compiledTransactionMessage.addressTableLookups\n : [];\n const lookupTableAddresses = lookupTables.map(l => l.lookupTableAddress);\n\n const { lastValidBlockHeight, ...fetchAccountsConfig } = config ?? {};\n const addressesByLookupTableAddress =\n lookupTableAddresses.length > 0\n ? await fetchAddressesForLookupTables(lookupTableAddresses, rpc, fetchAccountsConfig)\n : {};\n\n return decompileTransactionMessage(compiledTransactionMessage, {\n addressesByLookupTableAddress,\n lastValidBlockHeight,\n });\n}\n","import type { Lamports } from '@solana/rpc-types';\n\n/**\n * Calculates the minimum {@link Lamports | lamports} required to make an account rent exempt for a\n * given data size, without performing an RPC call.\n *\n * Values are sourced from the on-chain rent parameters in the Solana runtime:\n * https://github.com/anza-xyz/solana-sdk/blob/c07f692e41d757057c8700211a9300cdcd6d33b1/rent/src/lib.rs#L93-L97\n *\n * Note that this logic may change, or be incorrect depending on the cluster you are connected to.\n * You can always use the RPC method `getMinimumBalanceForRentExemption` to get the current value.\n *\n * @param space The number of bytes of account data.\n */\nexport function getMinimumBalanceForRentExemption(space: bigint): Lamports {\n const RENT = {\n ACCOUNT_STORAGE_OVERHEAD: 128n,\n DEFAULT_EXEMPTION_THRESHOLD: 2n,\n DEFAULT_LAMPORTS_PER_BYTE_YEAR: 3_480n,\n } as const;\n const requiredLamports =\n (RENT.ACCOUNT_STORAGE_OVERHEAD + space) *\n RENT.DEFAULT_LAMPORTS_PER_BYTE_YEAR *\n RENT.DEFAULT_EXEMPTION_THRESHOLD;\n return requiredLamports as Lamports;\n}\n","import type { Signature } from '@solana/keys';\nimport type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n TransactionWithLastValidBlockHeight,\n waitForDurableNonceTransactionConfirmation,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getBase64EncodedWireTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: (\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: (\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight;\n}\n\ninterface SendTransactionBaseConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc;\n transaction: SendableTransaction & Transaction;\n}\n\ntype SendTransactionConfigWithoutEncoding = Omit<\n NonNullable[1]>,\n 'encoding'\n>;\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding,\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nexport async function sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionBaseConfig): Promise {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport async function sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { getSolanaErrorFromTransactionError, isSolanaError, SOLANA_ERROR__INVALID_NONCE } from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport type { GetAccountInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { commitmentComparator } from '@solana/rpc-types';\nimport {\n createNonceInvalidationPromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n waitForDurableNonceTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getSignatureFromTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmDurableNonceTransactionFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime,\n config: Omit<\n Parameters[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmDurableNonceTransactionFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link AccountNotificationsApi} and the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a nonce-based transaction to the network and to wait\n * until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * isSolanaError,\n * sendAndConfirmDurableNonceTransactionFactory,\n * SOLANA_ERROR__INVALID_NONCE,\n * SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n * } from '@solana/kit';\n *\n * const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(\n * 'The lifetime specified by this transaction refers to a nonce account ' +\n * `\\`${e.context.nonceAccountAddress}\\` that does not exist`,\n * );\n * } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n * console.error('This transaction depends on a nonce that is no longer valid');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'devnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'testnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'mainnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig): SendAndConfirmDurableNonceTransactionFunction {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions } as Parameters<\n typeof createNonceInvalidationPromiseFactory\n >[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n\n /**\n * Creates a wrapped version of getNonceInvalidationPromise that handles the race condition\n * where the nonce account update notification arrives before the signature confirmation.\n *\n * When the nonce changes, we check if our transaction actually landed on-chain.\n * If it did, we don't throw - letting the signature confirmation promise continue.\n */\n function createNonceInvalidationPromiseHandlingRaceCondition(\n signature: Signature,\n ): typeof getNonceInvalidationPromise {\n return async function wrappedGetNonceInvalidationPromise(config) {\n try {\n return await getNonceInvalidationPromise(config);\n } catch (e) {\n // If nonce became invalid, check if our transaction actually landed\n if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n let status;\n try {\n const { value: statuses } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: config.abortSignal });\n status = statuses[0];\n } catch {\n // RPC failed - propagate the original nonce error\n throw e;\n }\n\n if (status === null || status === undefined) {\n // Transaction doesn't exist - nonce was truly invalid\n throw e;\n }\n\n // Check if status meets required commitment\n if (\n status.confirmationStatus !== null &&\n commitmentComparator(status.confirmationStatus, config.commitment) >= 0\n ) {\n // Transaction failed on-chain, throw the error from the transaction\n if (status.err !== null) {\n throw getSolanaErrorFromTransactionError(status.err);\n }\n // Transaction succeeded, resolve the promise successfully\n return;\n }\n\n // Commitment not met yet - return a never-resolving promise\n // This lets the signature confirmation promise continue\n return await new Promise(() => {});\n }\n throw e;\n }\n };\n }\n\n async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n const wrappedGetNonceInvalidationPromise = createNonceInvalidationPromiseHandlingRaceCondition(\n getSignatureFromTransaction(config.transaction),\n );\n\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise: wrappedGetNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmDurableNonceTransaction(transaction, config) {\n await sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { GetEpochInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createBlockHeightExceedencePromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n TransactionWithLastValidBlockHeight,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight,\n config: Omit<\n Parameters[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} and the {@link SlotNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a blockhash-based transaction to the network and to\n * wait until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit';\n *\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error('This transaction depends on a blockhash that has expired');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'devnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'testnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'mainnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig): SendAndConfirmTransactionWithBlockhashLifetimeFunction {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmRecentTransaction(\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmTransaction(transaction, config) {\n await sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendTransactionWithoutConfirmingFunction = (\n transaction: SendableTransaction & Transaction,\n config: Omit[0], 'rpc' | 'transaction'>,\n) => Promise;\n\ninterface SendTransactionWithoutConfirmingFactoryConfig {\n /** An object that supports the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}\n\n/**\n * Returns a function that you can call to send a transaction with any kind of lifetime to the\n * network without waiting for it to be confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * sendTransactionWithoutConfirmingFactory,\n * SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n * } from '@solana/kit';\n *\n * const sendTransaction = sendTransactionWithoutConfirmingFactory({ rpc });\n *\n * try {\n * await sendTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) {\n * console.error('The transaction failed in simulation', e.cause);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendTransactionWithoutConfirmingFactory({\n rpc,\n}: SendTransactionWithoutConfirmingFactoryConfig): SendTransactionWithoutConfirmingFunction {\n return async function sendTransactionWithoutConfirming(transaction, config) {\n await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n rpc,\n transaction,\n });\n };\n}\n","/**\n * Solana USDC Balance Monitor\n *\n * Checks USDC balance on Solana mainnet with caching.\n * Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).\n */\n\nimport { address as solAddress, createSolanaRpc } from \"@solana/kit\";\n\nconst SOLANA_USDC_MINT = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nconst SOLANA_DEFAULT_RPC = \"https://api.mainnet-beta.solana.com\";\nconst BALANCE_TIMEOUT_MS = 10_000;\nconst CACHE_TTL_MS = 30_000;\n\nexport type SolanaBalanceInfo = {\n balance: bigint;\n balanceUSD: string;\n assetSymbol: string;\n isLow: boolean;\n isEmpty: boolean;\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SolanaSufficiencyResult = {\n sufficient: boolean;\n info: SolanaBalanceInfo;\n shortfall?: string;\n};\n\nexport class SolanaBalanceMonitor {\n private readonly rpc: ReturnType;\n private readonly walletAddress: string;\n private cachedBalance: bigint | null = null;\n private cachedAt = 0;\n\n constructor(walletAddress: string, rpcUrl?: string) {\n this.walletAddress = walletAddress;\n const url = rpcUrl || process[\"env\"].CLAWROUTER_SOLANA_RPC_URL || SOLANA_DEFAULT_RPC;\n this.rpc = createSolanaRpc(url);\n }\n\n async checkBalance(): Promise {\n const now = Date.now();\n if (\n this.cachedBalance !== null &&\n this.cachedBalance > 0n &&\n now - this.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(this.cachedBalance);\n }\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n const balance = await this.fetchBalance();\n if (balance > 0n) {\n this.cachedBalance = balance;\n this.cachedAt = now;\n }\n return this.buildInfo(balance);\n }\n\n deductEstimated(amountMicros: bigint): void {\n if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {\n this.cachedBalance -= amountMicros;\n }\n }\n\n invalidate(): void {\n this.cachedBalance = null;\n this.cachedAt = 0;\n }\n\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSDC(shortfall),\n };\n }\n\n /**\n * Format USDC amount (in micros) as \"$X.XX\".\n */\n formatUSDC(amountMicros: bigint): string {\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n getAssetSymbol(): string {\n return \"USDC\";\n }\n\n /**\n * Check native SOL balance (in lamports). Useful for detecting users who\n * funded with SOL instead of USDC.\n */\n async checkSolBalance(): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n try {\n const owner = solAddress(this.walletAddress);\n const response = await this.rpc.getBalance(owner).send({ abortSignal: controller.signal });\n return BigInt(response.value);\n } catch {\n return 0n;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async fetchBalance(): Promise {\n const owner = solAddress(this.walletAddress);\n const mint = solAddress(SOLANA_USDC_MINT);\n\n // The public Solana RPC frequently returns empty token account lists even\n // for funded wallets. Retry once on empty before accepting $0 as truth.\n for (let attempt = 0; attempt < 2; attempt++) {\n const result = await this.fetchBalanceOnce(owner, mint);\n if (result > 0n || attempt === 1) return result;\n await new Promise((r) => setTimeout(r, 1_000));\n }\n return 0n;\n }\n\n private async fetchBalanceOnce(\n owner: ReturnType,\n mint: ReturnType,\n ): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n\n try {\n const response = await this.rpc\n .getTokenAccountsByOwner(owner, { mint }, { encoding: \"jsonParsed\" })\n .send({ abortSignal: controller.signal });\n\n if (response.value.length === 0) return 0n;\n\n let total = 0n;\n for (const account of response.value) {\n const parsed = account.account.data as {\n parsed: { info: { tokenAmount: { amount: string } } };\n };\n total += BigInt(parsed.parsed.info.tokenAmount.amount);\n }\n return total;\n } catch (err) {\n throw new Error(\n `Failed to fetch Solana USDC balance: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n private buildInfo(balance: bigint): SolanaBalanceInfo {\n const dollars = Number(balance) / 1_000_000;\n return {\n balance,\n balanceUSD: `$${dollars.toFixed(2)}`,\n assetSymbol: \"USDC\",\n isLow: balance < 1_000_000n,\n isEmpty: balance < 100n,\n walletAddress: this.walletAddress,\n };\n }\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n};\n\nexport function getMintEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintCodec(): FixedSizeCodec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n\nexport function getMintSize(): number {\n return 82;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getTokenEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenCodec(): FixedSizeCodec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n\nexport function getTokenSize(): number {\n return 165;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n} from '../instructions';\n\nexport const TOKEN_PROGRAM_ADDRESS =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n\nexport enum TokenAccount {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyTokenAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenAccount {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return TokenAccount.Mint;\n }\n if (data.length === 165) {\n return TokenAccount.Token;\n }\n if (data.length === 355) {\n return TokenAccount.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token account.'\n );\n}\n\nexport enum TokenInstruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n}\n\nexport function identifyTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return TokenInstruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return TokenInstruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return TokenInstruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return TokenInstruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return TokenInstruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return TokenInstruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return TokenInstruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return TokenInstruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return TokenInstruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return TokenInstruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return TokenInstruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return TokenInstruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return TokenInstruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return TokenInstruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return TokenInstruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return TokenInstruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return TokenInstruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return TokenInstruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return TokenInstruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return TokenInstruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return TokenInstruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return TokenInstruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return TokenInstruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return TokenInstruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return TokenInstruction.UiAmountToAmount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token instruction.'\n );\n}\n\nexport type ParsedTokenInstruction<\n TProgram extends string = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n> =\n | ({\n instructionType: TokenInstruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: TokenInstruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: TokenInstruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: TokenInstruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: TokenInstruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: TokenInstruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: TokenInstruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: TokenInstruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: TokenInstruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: TokenInstruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: TokenInstruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: TokenInstruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: TokenInstruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: TokenInstruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: TokenInstruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: TokenInstruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: TokenInstruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: TokenInstruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type TokenError =\n | typeof TOKEN_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_ERROR__ALREADY_IN_USE\n | typeof TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__FIXED_SUPPLY\n | typeof TOKEN_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_ERROR__INVALID_MINT\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_STATE\n | typeof TOKEN_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_ERROR__MINT_MISMATCH\n | typeof TOKEN_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_ERROR__OVERFLOW\n | typeof TOKEN_ERROR__OWNER_MISMATCH\n | typeof TOKEN_ERROR__UNINITIALIZED_STATE;\n\nlet tokenErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n tokenErrorMessages = {\n [TOKEN_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getTokenErrorMessage(code: TokenError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (tokenErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isTokenError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU32Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAdvanceNonceAccountInstruction,\n type ParsedAllocateInstruction,\n type ParsedAllocateWithSeedInstruction,\n type ParsedAssignInstruction,\n type ParsedAssignWithSeedInstruction,\n type ParsedAuthorizeNonceAccountInstruction,\n type ParsedCreateAccountInstruction,\n type ParsedCreateAccountWithSeedInstruction,\n type ParsedInitializeNonceAccountInstruction,\n type ParsedTransferSolInstruction,\n type ParsedTransferSolWithSeedInstruction,\n type ParsedUpgradeNonceAccountInstruction,\n type ParsedWithdrawNonceAccountInstruction,\n} from '../instructions';\n\nexport const SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport enum SystemAccount {\n Nonce,\n}\n\nexport enum SystemInstruction {\n CreateAccount,\n Assign,\n TransferSol,\n CreateAccountWithSeed,\n AdvanceNonceAccount,\n WithdrawNonceAccount,\n InitializeNonceAccount,\n AuthorizeNonceAccount,\n Allocate,\n AllocateWithSeed,\n AssignWithSeed,\n TransferSolWithSeed,\n UpgradeNonceAccount,\n}\n\nexport function identifySystemInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): SystemInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU32Encoder().encode(0), 0)) {\n return SystemInstruction.CreateAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(1), 0)) {\n return SystemInstruction.Assign;\n }\n if (containsBytes(data, getU32Encoder().encode(2), 0)) {\n return SystemInstruction.TransferSol;\n }\n if (containsBytes(data, getU32Encoder().encode(3), 0)) {\n return SystemInstruction.CreateAccountWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(4), 0)) {\n return SystemInstruction.AdvanceNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(5), 0)) {\n return SystemInstruction.WithdrawNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(6), 0)) {\n return SystemInstruction.InitializeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(7), 0)) {\n return SystemInstruction.AuthorizeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(8), 0)) {\n return SystemInstruction.Allocate;\n }\n if (containsBytes(data, getU32Encoder().encode(9), 0)) {\n return SystemInstruction.AllocateWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(10), 0)) {\n return SystemInstruction.AssignWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(11), 0)) {\n return SystemInstruction.TransferSolWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(12), 0)) {\n return SystemInstruction.UpgradeNonceAccount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a system instruction.'\n );\n}\n\nexport type ParsedSystemInstruction<\n TProgram extends string = '11111111111111111111111111111111',\n> =\n | ({\n instructionType: SystemInstruction.CreateAccount;\n } & ParsedCreateAccountInstruction)\n | ({\n instructionType: SystemInstruction.Assign;\n } & ParsedAssignInstruction)\n | ({\n instructionType: SystemInstruction.TransferSol;\n } & ParsedTransferSolInstruction)\n | ({\n instructionType: SystemInstruction.CreateAccountWithSeed;\n } & ParsedCreateAccountWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AdvanceNonceAccount;\n } & ParsedAdvanceNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.WithdrawNonceAccount;\n } & ParsedWithdrawNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.InitializeNonceAccount;\n } & ParsedInitializeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.AuthorizeNonceAccount;\n } & ParsedAuthorizeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.Allocate;\n } & ParsedAllocateInstruction)\n | ({\n instructionType: SystemInstruction.AllocateWithSeed;\n } & ParsedAllocateWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AssignWithSeed;\n } & ParsedAssignWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.TransferSolWithSeed;\n } & ParsedTransferSolWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.UpgradeNonceAccount;\n } & ParsedUpgradeNonceAccountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\n\n/** AccountAlreadyInUse: an account with the same address already exists */\nexport const SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE = 0x0; // 0\n/** ResultWithNegativeLamports: account does not have enough SOL to perform the operation */\nexport const SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS = 0x1; // 1\n/** InvalidProgramId: cannot assign account to this program id */\nexport const SYSTEM_ERROR__INVALID_PROGRAM_ID = 0x2; // 2\n/** InvalidAccountDataLength: cannot allocate account data of this length */\nexport const SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH = 0x3; // 3\n/** MaxSeedLengthExceeded: length of requested seed is too long */\nexport const SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED = 0x4; // 4\n/** AddressWithSeedMismatch: provided address does not match addressed derived from seed */\nexport const SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH = 0x5; // 5\n/** NonceNoRecentBlockhashes: advancing stored nonce requires a populated RecentBlockhashes sysvar */\nexport const SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES = 0x6; // 6\n/** NonceBlockhashNotExpired: stored nonce is still in recent_blockhashes */\nexport const SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED = 0x7; // 7\n/** NonceUnexpectedBlockhashValue: specified nonce does not match stored nonce */\nexport const SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE = 0x8; // 8\n\nexport type SystemError =\n | typeof SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE\n | typeof SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH\n | typeof SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH\n | typeof SYSTEM_ERROR__INVALID_PROGRAM_ID\n | typeof SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED\n | typeof SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES\n | typeof SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE\n | typeof SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS;\n\nlet systemErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n systemErrorMessages = {\n [SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE]: `an account with the same address already exists`,\n [SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH]: `provided address does not match addressed derived from seed`,\n [SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH]: `cannot allocate account data of this length`,\n [SYSTEM_ERROR__INVALID_PROGRAM_ID]: `cannot assign account to this program id`,\n [SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED]: `length of requested seed is too long`,\n [SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED]: `stored nonce is still in recent_blockhashes`,\n [SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES]: `advancing stored nonce requires a populated RecentBlockhashes sysvar`,\n [SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE]: `specified nonce does not match stored nonce`,\n [SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS]: `account does not have enough SOL to perform the operation`,\n };\n}\n\nexport function getSystemErrorMessage(code: SystemError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (systemErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isSystemError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n SYSTEM_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n BASE_ACCOUNT_SIZE,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\nimport {\n getAccountMetaFactory,\n type InstructionWithByteDelta,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ACCOUNT_DISCRIMINATOR = 0;\n\nexport function getCreateAccountDiscriminatorBytes() {\n return getU32Encoder().encode(CREATE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNewAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNewAccount extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountNewAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAccountInstructionData = {\n discriminator: number;\n lamports: bigint;\n space: bigint;\n programAddress: Address;\n};\n\nexport type CreateAccountInstructionDataArgs = {\n lamports: number | bigint;\n space: number | bigint;\n programAddress: Address;\n};\n\nexport function getCreateAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU32Encoder()],\n ['lamports', getU64Encoder()],\n ['space', getU64Encoder()],\n ['programAddress', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: CREATE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU32Decoder()],\n ['lamports', getU64Decoder()],\n ['space', getU64Decoder()],\n ['programAddress', getAddressDecoder()],\n ]);\n}\n\nexport function getCreateAccountInstructionDataCodec(): FixedSizeCodec<\n CreateAccountInstructionDataArgs,\n CreateAccountInstructionData\n> {\n return combineCodec(\n getCreateAccountInstructionDataEncoder(),\n getCreateAccountInstructionDataDecoder()\n );\n}\n\nexport type CreateAccountInput<\n TAccountPayer extends string = string,\n TAccountNewAccount extends string = string,\n> = {\n payer: TransactionSigner;\n newAccount: TransactionSigner;\n lamports: CreateAccountInstructionDataArgs['lamports'];\n space: CreateAccountInstructionDataArgs['space'];\n programAddress: CreateAccountInstructionDataArgs['programAddress'];\n};\n\nexport function getCreateAccountInstruction<\n TAccountPayer extends string,\n TAccountNewAccount extends string,\n TProgramAddress extends Address = typeof SYSTEM_PROGRAM_ADDRESS,\n>(\n input: CreateAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n> &\n InstructionWithByteDelta {\n // Program address.\n const programAddress = config?.programAddress ?? SYSTEM_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n newAccount: { value: input.newAccount ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Bytes created or reallocated by the instruction.\n const byteDelta: number = [Number(args.space) + BASE_ACCOUNT_SIZE].reduce(\n (a, b) => a + b,\n 0\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'omitted');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.newAccount),\n ],\n byteDelta,\n data: getCreateAccountInstructionDataEncoder().encode(\n args as CreateAccountInstructionDataArgs\n ),\n programAddress,\n } as CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n > &\n InstructionWithByteDelta);\n}\n\nexport type ParsedCreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n payer: TAccountMetas[0];\n newAccount: TAccountMetas[1];\n };\n data: CreateAccountInstructionData;\n};\n\nexport function parseCreateAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAccountInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { payer: getNextAccount(), newAccount: getNextAccount() },\n data: getCreateAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import { getCreateAccountInstruction } from '@solana-program/system';\nimport {\n Address,\n InstructionPlan,\n OptionOrNullable,\n sequentialInstructionPlan,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n getInitializeMint2Instruction,\n getMintSize,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\n// RPC `getMinimumBalanceForRentExemption` for 82 bytes, which is token mint size\n// Hardcoded to avoid requiring an RPC request each time\nconst MINIMUM_BALANCE_FOR_MINT = 1461600;\n\nexport type CreateMintInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** New mint account to create. */\n newMint: TransactionSigner;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n /**\n * Optional override for the amount of Lamports to fund the mint account with.\n * @default 1461600\n * */\n mintAccountLamports?: number;\n};\n\ntype CreateMintInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n};\n\nexport function getCreateMintInstructionPlan(\n input: CreateMintInstructionPlanInput,\n config?: CreateMintInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAccountInstruction(\n {\n payer: input.payer,\n newAccount: input.newMint,\n lamports: input.mintAccountLamports ?? MINIMUM_BALANCE_FOR_MINT,\n space: getMintSize(),\n programAddress: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n },\n {\n programAddress: config?.systemProgram,\n }\n ),\n getInitializeMint2Instruction(\n {\n mint: input.newMint.address,\n decimals: input.decimals,\n mintAuthority: input.mintAuthority,\n freezeAuthority: input.freezeAuthority,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getMintToCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype MintToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to mint to.\n * Will be created if it does not already exist.\n * Note: Use {@link getMintToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n ata: Address;\n /** Wallet address for the associated token account. */\n owner: Address;\n /** The token mint for the associated token account. */\n mint: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: Address | TransactionSigner;\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype MintToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getMintToATAInstructionPlan(\n input: MintToATAInstructionPlanInput,\n config?: MintToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.ata,\n owner: input.owner,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n // mint to this token account\n getMintToCheckedInstruction(\n {\n mint: input.mint,\n token: input.ata,\n mintAuthority: input.mintAuthority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype MintToATAInstructionPlanAsyncInput = Omit<\n MintToATAInstructionPlanInput,\n 'ata'\n>;\n\nexport async function getMintToATAInstructionPlanAsync(\n input: MintToATAInstructionPlanAsyncInput,\n config?: MintToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.owner,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getMintToATAInstructionPlan(\n {\n ...input,\n ata: ataAddress,\n },\n config\n );\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getTransferCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype TransferToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** The token mint to transfer. */\n mint: Address;\n /** The source account for the transfer. */\n source: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n /** Associated token account address to transfer to.\n * Will be created if it does not already exist.\n * Note: Use {@link getTransferToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n destination: Address;\n /** Wallet address for the destination. */\n recipient: Address;\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype TransferToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getTransferToATAInstructionPlan(\n input: TransferToATAInstructionPlanInput,\n config?: TransferToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.destination,\n owner: input.recipient,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n getTransferCheckedInstruction(\n {\n source: input.source,\n mint: input.mint,\n destination: input.destination,\n authority: input.authority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype TransferToATAInstructionPlanAsyncInput = Omit<\n TransferToATAInstructionPlanInput,\n 'destination'\n>;\n\nexport async function getTransferToATAInstructionPlanAsync(\n input: TransferToATAInstructionPlanAsyncInput,\n config?: TransferToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.recipient,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getTransferToATAInstructionPlan(\n {\n ...input,\n destination: ataAddress,\n },\n config\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n TransferFeeConfig,\n WithheldWithdraw,\n CloseMint,\n InterestRate,\n PermanentDelegate,\n ConfidentialTransferMint,\n TransferHookProgramId,\n ConfidentialTransferFeeConfig,\n MetadataPointer,\n GroupPointer,\n GroupMemberPointer,\n ScaledUiAmount,\n Pause,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** Authenticated encryption containing an account balance. */\nexport type DecryptableBalance = ReadonlyUint8Array;\n\nexport type DecryptableBalanceArgs = DecryptableBalance;\n\nexport function getDecryptableBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 36);\n}\n\nexport function getDecryptableBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 36);\n}\n\nexport function getDecryptableBalanceCodec(): FixedSizeCodec<\n DecryptableBalanceArgs,\n DecryptableBalance\n> {\n return combineCodec(\n getDecryptableBalanceEncoder(),\n getDecryptableBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** ElGamal ciphertext containing an account balance. */\nexport type EncryptedBalance = ReadonlyUint8Array;\n\nexport type EncryptedBalanceArgs = EncryptedBalance;\n\nexport function getEncryptedBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 64);\n}\n\nexport function getEncryptedBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 64);\n}\n\nexport function getEncryptedBalanceCodec(): FixedSizeCodec<\n EncryptedBalanceArgs,\n EncryptedBalance\n> {\n return combineCodec(\n getEncryptedBalanceEncoder(),\n getEncryptedBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getF64Decoder,\n getF64Encoder,\n getI16Decoder,\n getI16Encoder,\n getMapDecoder,\n getMapEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n getEncryptedBalanceDecoder,\n getEncryptedBalanceEncoder,\n getTransferFeeDecoder,\n getTransferFeeEncoder,\n type AccountState,\n type AccountStateArgs,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n type EncryptedBalance,\n type EncryptedBalanceArgs,\n type TransferFee,\n type TransferFeeArgs,\n} from '.';\n\nexport type Extension =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFee;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFee;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: Option
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalance;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalance;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalance;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalance;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountState }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: Option
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: Option
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: Option
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: Option
;\n /** Optional account address that holds the group. */\n groupAddress: Option
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: bigint;\n /** The maximum number of group members. */\n maxSize: bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: Option
;\n /** Optional account address that holds the member. */\n memberAddress: Option
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: bigint;\n newMultiplier: number;\n }\n | { __kind: 'PausableConfig'; authority: Option
; paused: boolean }\n | { __kind: 'PausableAccount' };\n\nexport type ExtensionArgs =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: number | bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFeeArgs;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFeeArgs;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: number | bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: OptionOrNullable
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalanceArgs;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalanceArgs;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalanceArgs;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalanceArgs;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: number | bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: number | bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountStateArgs }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: number | bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: number | bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: OptionOrNullable
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: OptionOrNullable
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the group. */\n groupAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: number | bigint;\n /** The maximum number of group members. */\n maxSize: number | bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the member. */\n memberAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: number | bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: number | bigint;\n newMultiplier: number;\n }\n | {\n __kind: 'PausableConfig';\n authority: OptionOrNullable
;\n paused: boolean;\n }\n | { __kind: 'PausableAccount' };\n\nexport function getExtensionEncoder(): Encoder {\n return getDiscriminatedUnionEncoder(\n [\n ['Uninitialized', getUnitEncoder()],\n [\n 'TransferFeeConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['transferFeeConfigAuthority', getAddressEncoder()],\n ['withdrawWithheldAuthority', getAddressEncoder()],\n ['withheldAmount', getU64Encoder()],\n ['olderTransferFee', getTransferFeeEncoder()],\n ['newerTransferFee', getTransferFeeEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getU64Encoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addEncoderSizePrefix(\n getStructEncoder([['closeAuthority', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addEncoderSizePrefix(\n getStructEncoder([\n ['approved', getBooleanEncoder()],\n ['elgamalPubkey', getAddressEncoder()],\n ['pendingBalanceLow', getEncryptedBalanceEncoder()],\n ['pendingBalanceHigh', getEncryptedBalanceEncoder()],\n ['availableBalance', getEncryptedBalanceEncoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['allowConfidentialCredits', getBooleanEncoder()],\n ['allowNonConfidentialCredits', getBooleanEncoder()],\n ['pendingBalanceCreditCounter', getU64Encoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['actualPendingBalanceCreditCounter', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addEncoderSizePrefix(\n getStructEncoder([['state', getAccountStateEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'MemoTransfer',\n addEncoderSizePrefix(\n getStructEncoder([\n ['requireIncomingTransferMemos', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferable',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'InterestBearingConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['rateAuthority', getAddressEncoder()],\n ['initializationTimestamp', getU64Encoder()],\n ['preUpdateAverageRate', getI16Encoder()],\n ['lastUpdateTimestamp', getU64Encoder()],\n ['currentRate', getI16Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'CpiGuard',\n addEncoderSizePrefix(\n getStructEncoder([['lockCpi', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addEncoderSizePrefix(\n getStructEncoder([['delegate', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'TransferHook',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['programId', getAddressEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addEncoderSizePrefix(\n getStructEncoder([['transferring', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressEncoder()],\n ['harvestToMintEnabled', getBooleanEncoder()],\n ['withheldAmount', getEncryptedBalanceEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getEncryptedBalanceEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MetadataPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenMetadata',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n [\n 'additionalMetadata',\n getMapEncoder(\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())\n ),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroup',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['size', getU64Encoder()],\n ['maxSize', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addEncoderSizePrefix(\n getStructEncoder([\n ['mint', getAddressEncoder()],\n ['group', getAddressEncoder()],\n ['memberNumber', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitEncoder()],\n [\n 'ScaledUiAmountConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['multiplier', getF64Encoder()],\n ['newMultiplierEffectiveTimestamp', getU64Encoder()],\n ['newMultiplier', getF64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'PausableConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['PausableAccount', getUnitEncoder()],\n ],\n { size: getU16Encoder() }\n );\n}\n\nexport function getExtensionDecoder(): Decoder {\n return getDiscriminatedUnionDecoder(\n [\n ['Uninitialized', getUnitDecoder()],\n [\n 'TransferFeeConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['transferFeeConfigAuthority', getAddressDecoder()],\n ['withdrawWithheldAuthority', getAddressDecoder()],\n ['withheldAmount', getU64Decoder()],\n ['olderTransferFee', getTransferFeeDecoder()],\n ['newerTransferFee', getTransferFeeDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getU64Decoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addDecoderSizePrefix(\n getStructDecoder([['closeAuthority', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addDecoderSizePrefix(\n getStructDecoder([\n ['approved', getBooleanDecoder()],\n ['elgamalPubkey', getAddressDecoder()],\n ['pendingBalanceLow', getEncryptedBalanceDecoder()],\n ['pendingBalanceHigh', getEncryptedBalanceDecoder()],\n ['availableBalance', getEncryptedBalanceDecoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['allowConfidentialCredits', getBooleanDecoder()],\n ['allowNonConfidentialCredits', getBooleanDecoder()],\n ['pendingBalanceCreditCounter', getU64Decoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['actualPendingBalanceCreditCounter', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addDecoderSizePrefix(\n getStructDecoder([['state', getAccountStateDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'MemoTransfer',\n addDecoderSizePrefix(\n getStructDecoder([\n ['requireIncomingTransferMemos', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferable',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'InterestBearingConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['rateAuthority', getAddressDecoder()],\n ['initializationTimestamp', getU64Decoder()],\n ['preUpdateAverageRate', getI16Decoder()],\n ['lastUpdateTimestamp', getU64Decoder()],\n ['currentRate', getI16Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'CpiGuard',\n addDecoderSizePrefix(\n getStructDecoder([['lockCpi', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addDecoderSizePrefix(\n getStructDecoder([['delegate', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'TransferHook',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['programId', getAddressDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addDecoderSizePrefix(\n getStructDecoder([['transferring', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressDecoder()],\n ['harvestToMintEnabled', getBooleanDecoder()],\n ['withheldAmount', getEncryptedBalanceDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getEncryptedBalanceDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MetadataPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenMetadata',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n [\n 'additionalMetadata',\n getMapDecoder(\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())\n ),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroup',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['size', getU64Decoder()],\n ['maxSize', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addDecoderSizePrefix(\n getStructDecoder([\n ['mint', getAddressDecoder()],\n ['group', getAddressDecoder()],\n ['memberNumber', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitDecoder()],\n [\n 'ScaledUiAmountConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['multiplier', getF64Decoder()],\n ['newMultiplierEffectiveTimestamp', getU64Decoder()],\n ['newMultiplier', getF64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'PausableConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['PausableAccount', getUnitDecoder()],\n ],\n { size: getU16Decoder() }\n );\n}\n\nexport function getExtensionCodec(): Codec {\n return combineCodec(getExtensionEncoder(), getExtensionDecoder());\n}\n\n// Data Enum Helpers.\nexport function extension(\n kind: 'Uninitialized'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MintCloseAuthority',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MintCloseAuthority'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferMint',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n>;\nexport function extension(\n kind: 'ConfidentialTransferAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n>;\nexport function extension(\n kind: 'DefaultAccountState',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'DefaultAccountState'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ImmutableOwner',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ImmutableOwner'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MemoTransfer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MemoTransfer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferable',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferable'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'InterestBearingConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n>;\nexport function extension(\n kind: 'CpiGuard',\n data: GetDiscriminatedUnionVariantContent\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PermanentDelegate',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PermanentDelegate'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferableAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n>;\nexport function extension(\n kind: 'TransferHook',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHook'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferHookAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHookAccount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferFee',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n>;\nexport function extension(\n kind: 'ConfidentialTransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n>;\nexport function extension(\n kind: 'MetadataPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MetadataPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenMetadata',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenMetadata'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroup',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroup'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupMemberPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupMemberPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroupMember',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroupMember'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialMintBurn'\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialMintBurn'\n>;\nexport function extension(\n kind: 'ScaledUiAmountConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n>;\nexport function extension(\n kind: 'PausableConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PausableConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PausableAccount'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: K,\n data?: Data\n) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isExtension(\n kind: K,\n value: Extension\n): value is Extension & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n getU16Decoder,\n getU16Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\n/**\n * Extensions that can be applied to mints or accounts. Mint extensions must\n * only be applied to mint accounts, and account extensions must only be\n * applied to token holding accounts.\n */\nexport enum ExtensionType {\n Uninitialized,\n TransferFeeConfig,\n TransferFeeAmount,\n MintCloseAuthority,\n ConfidentialTransferMint,\n ConfidentialTransferAccount,\n DefaultAccountState,\n ImmutableOwner,\n MemoTransfer,\n NonTransferable,\n InterestBearingConfig,\n CpiGuard,\n PermanentDelegate,\n NonTransferableAccount,\n TransferHook,\n TransferHookAccount,\n ConfidentialTransferFee,\n ConfidentialTransferFeeAmount,\n ScaledUiAmountConfig,\n PausableConfig,\n PausableAccount,\n MetadataPointer,\n TokenMetadata,\n GroupPointer,\n TokenGroup,\n GroupMemberPointer,\n TokenGroupMember,\n}\n\nexport type ExtensionTypeArgs = ExtensionType;\n\nexport function getExtensionTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(ExtensionType, { size: getU16Encoder() });\n}\n\nexport function getExtensionTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(ExtensionType, { size: getU16Decoder() });\n}\n\nexport function getExtensionTypeCodec(): FixedSizeCodec<\n ExtensionTypeArgs,\n ExtensionType\n> {\n return combineCodec(getExtensionTypeEncoder(), getExtensionTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getU32Decoder,\n getU32Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n} from '@solana/kit';\n\n/** Fields in the metadata account, used for updating. */\nexport type TokenMetadataField =\n | { __kind: 'Name' }\n | { __kind: 'Symbol' }\n | { __kind: 'Uri' }\n | { __kind: 'Key'; fields: readonly [string] };\n\nexport type TokenMetadataFieldArgs = TokenMetadataField;\n\nexport function getTokenMetadataFieldEncoder(): Encoder {\n return getDiscriminatedUnionEncoder([\n ['Name', getUnitEncoder()],\n ['Symbol', getUnitEncoder()],\n ['Uri', getUnitEncoder()],\n [\n 'Key',\n getStructEncoder([\n [\n 'fields',\n getTupleEncoder([\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldDecoder(): Decoder {\n return getDiscriminatedUnionDecoder([\n ['Name', getUnitDecoder()],\n ['Symbol', getUnitDecoder()],\n ['Uri', getUnitDecoder()],\n [\n 'Key',\n getStructDecoder([\n [\n 'fields',\n getTupleDecoder([\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldCodec(): Codec<\n TokenMetadataFieldArgs,\n TokenMetadataField\n> {\n return combineCodec(\n getTokenMetadataFieldEncoder(),\n getTokenMetadataFieldDecoder()\n );\n}\n\n// Data Enum Helpers.\nexport function tokenMetadataField(\n kind: 'Name'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Symbol'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Uri'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Key',\n data: GetDiscriminatedUnionVariantContent<\n TokenMetadataFieldArgs,\n '__kind',\n 'Key'\n >['fields']\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField<\n K extends TokenMetadataFieldArgs['__kind'],\n Data,\n>(kind: K, data?: Data) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isTokenMetadataField(\n kind: K,\n value: TokenMetadataField\n): value is TokenMetadataField & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport type TransferFee = {\n /** First epoch where the transfer fee takes effect. */\n epoch: bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport type TransferFeeArgs = {\n /** First epoch where the transfer fee takes effect. */\n epoch: number | bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: number | bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport function getTransferFeeEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['epoch', getU64Encoder()],\n ['maximumFee', getU64Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ]);\n}\n\nexport function getTransferFeeDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['epoch', getU64Decoder()],\n ['maximumFee', getU64Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ]);\n}\n\nexport function getTransferFeeCodec(): FixedSizeCodec<\n TransferFeeArgs,\n TransferFee\n> {\n return combineCodec(getTransferFeeEncoder(), getTransferFeeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n padLeftEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getExtensionDecoder,\n getExtensionEncoder,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n /** The extensions activated on the mint account. */\n extensions: Option>;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n /** The extensions activated on the mint account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getMintEncoder(): Encoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintDecoder(): Decoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintCodec(): Codec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Encoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getExtensionDecoder,\n getExtensionEncoder,\n type AccountState,\n type AccountStateArgs,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n /** The extensions activated on the token account. */\n extensions: Option>;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n /** The extensions activated on the token account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getTokenEncoder(): Encoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): Decoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenCodec(): Codec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApplyConfidentialPendingBalanceInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveConfidentialTransferAccountInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedConfidentialDepositInstruction,\n type ParsedConfidentialTransferInstruction,\n type ParsedConfidentialTransferWithFeeInstruction,\n type ParsedConfidentialWithdrawInstruction,\n type ParsedConfigureConfidentialTransferAccountInstruction,\n type ParsedCreateNativeMintInstruction,\n type ParsedDisableConfidentialCreditsInstruction,\n type ParsedDisableCpiGuardInstruction,\n type ParsedDisableHarvestToMintInstruction,\n type ParsedDisableMemoTransfersInstruction,\n type ParsedDisableNonConfidentialCreditsInstruction,\n type ParsedEmitTokenMetadataInstruction,\n type ParsedEmptyConfidentialTransferAccountInstruction,\n type ParsedEnableConfidentialCreditsInstruction,\n type ParsedEnableCpiGuardInstruction,\n type ParsedEnableHarvestToMintInstruction,\n type ParsedEnableMemoTransfersInstruction,\n type ParsedEnableNonConfidentialCreditsInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction,\n type ParsedHarvestWithheldTokensToMintInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeConfidentialTransferFeeInstruction,\n type ParsedInitializeConfidentialTransferMintInstruction,\n type ParsedInitializeDefaultAccountStateInstruction,\n type ParsedInitializeGroupMemberPointerInstruction,\n type ParsedInitializeGroupPointerInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeInterestBearingMintInstruction,\n type ParsedInitializeMetadataPointerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintCloseAuthorityInstruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedInitializeNonTransferableMintInstruction,\n type ParsedInitializePausableConfigInstruction,\n type ParsedInitializePermanentDelegateInstruction,\n type ParsedInitializeScaledUiAmountMintInstruction,\n type ParsedInitializeTokenGroupInstruction,\n type ParsedInitializeTokenGroupMemberInstruction,\n type ParsedInitializeTokenMetadataInstruction,\n type ParsedInitializeTransferFeeConfigInstruction,\n type ParsedInitializeTransferHookInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedPauseInstruction,\n type ParsedReallocateInstruction,\n type ParsedRemoveTokenMetadataKeyInstruction,\n type ParsedResumeInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSetTransferFeeInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferCheckedWithFeeInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n type ParsedUpdateConfidentialTransferMintInstruction,\n type ParsedUpdateDefaultAccountStateInstruction,\n type ParsedUpdateGroupMemberPointerInstruction,\n type ParsedUpdateGroupPointerInstruction,\n type ParsedUpdateMetadataPointerInstruction,\n type ParsedUpdateMultiplierScaledUiMintInstruction,\n type ParsedUpdateRateInterestBearingMintInstruction,\n type ParsedUpdateTokenGroupMaxSizeInstruction,\n type ParsedUpdateTokenGroupUpdateAuthorityInstruction,\n type ParsedUpdateTokenMetadataFieldInstruction,\n type ParsedUpdateTokenMetadataUpdateAuthorityInstruction,\n type ParsedUpdateTransferHookInstruction,\n type ParsedWithdrawExcessLamportsInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsInstruction,\n type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromMintInstruction,\n} from '../instructions';\n\nexport const TOKEN_2022_PROGRAM_ADDRESS =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n\nexport enum Token2022Account {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyToken2022Account(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Account {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return Token2022Account.Mint;\n }\n if (data.length === 165) {\n return Token2022Account.Token;\n }\n if (data.length === 355) {\n return Token2022Account.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token-2022 account.'\n );\n}\n\nexport enum Token2022Instruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n InitializeMintCloseAuthority,\n InitializeTransferFeeConfig,\n TransferCheckedWithFee,\n WithdrawWithheldTokensFromMint,\n WithdrawWithheldTokensFromAccounts,\n HarvestWithheldTokensToMint,\n SetTransferFee,\n InitializeConfidentialTransferMint,\n UpdateConfidentialTransferMint,\n ConfigureConfidentialTransferAccount,\n ApproveConfidentialTransferAccount,\n EmptyConfidentialTransferAccount,\n ConfidentialDeposit,\n ConfidentialWithdraw,\n ConfidentialTransfer,\n ApplyConfidentialPendingBalance,\n EnableConfidentialCredits,\n DisableConfidentialCredits,\n EnableNonConfidentialCredits,\n DisableNonConfidentialCredits,\n ConfidentialTransferWithFee,\n InitializeDefaultAccountState,\n UpdateDefaultAccountState,\n Reallocate,\n EnableMemoTransfers,\n DisableMemoTransfers,\n CreateNativeMint,\n InitializeNonTransferableMint,\n InitializeInterestBearingMint,\n UpdateRateInterestBearingMint,\n EnableCpiGuard,\n DisableCpiGuard,\n InitializePermanentDelegate,\n InitializeTransferHook,\n UpdateTransferHook,\n InitializeConfidentialTransferFee,\n WithdrawWithheldTokensFromMintForConfidentialTransferFee,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFee,\n HarvestWithheldTokensToMintForConfidentialTransferFee,\n EnableHarvestToMint,\n DisableHarvestToMint,\n WithdrawExcessLamports,\n InitializeMetadataPointer,\n UpdateMetadataPointer,\n InitializeGroupPointer,\n UpdateGroupPointer,\n InitializeGroupMemberPointer,\n UpdateGroupMemberPointer,\n InitializeScaledUiAmountMint,\n UpdateMultiplierScaledUiMint,\n InitializePausableConfig,\n Pause,\n Resume,\n InitializeTokenMetadata,\n UpdateTokenMetadataField,\n RemoveTokenMetadataKey,\n UpdateTokenMetadataUpdateAuthority,\n EmitTokenMetadata,\n InitializeTokenGroup,\n UpdateTokenGroupMaxSize,\n UpdateTokenGroupUpdateAuthority,\n InitializeTokenGroupMember,\n}\n\nexport function identifyToken2022Instruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Instruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return Token2022Instruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return Token2022Instruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return Token2022Instruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return Token2022Instruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return Token2022Instruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return Token2022Instruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return Token2022Instruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return Token2022Instruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return Token2022Instruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return Token2022Instruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return Token2022Instruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return Token2022Instruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return Token2022Instruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return Token2022Instruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return Token2022Instruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return Token2022Instruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return Token2022Instruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return Token2022Instruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return Token2022Instruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return Token2022Instruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return Token2022Instruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return Token2022Instruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return Token2022Instruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return Token2022Instruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return Token2022Instruction.UiAmountToAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(25), 0)) {\n return Token2022Instruction.InitializeMintCloseAuthority;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferFeeConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.TransferCheckedWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.SetTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.ConfigureConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.ApproveConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EmptyConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.ConfidentialDeposit;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(6), 1)\n ) {\n return Token2022Instruction.ConfidentialWithdraw;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(7), 1)\n ) {\n return Token2022Instruction.ConfidentialTransfer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(8), 1)\n ) {\n return Token2022Instruction.ApplyConfidentialPendingBalance;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(9), 1)\n ) {\n return Token2022Instruction.EnableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(10), 1)\n ) {\n return Token2022Instruction.DisableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(11), 1)\n ) {\n return Token2022Instruction.EnableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(12), 1)\n ) {\n return Token2022Instruction.DisableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(13), 1)\n ) {\n return Token2022Instruction.ConfidentialTransferWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeDefaultAccountState;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateDefaultAccountState;\n }\n if (containsBytes(data, getU8Encoder().encode(29), 0)) {\n return Token2022Instruction.Reallocate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableMemoTransfers;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableMemoTransfers;\n }\n if (containsBytes(data, getU8Encoder().encode(31), 0)) {\n return Token2022Instruction.CreateNativeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(32), 0)) {\n return Token2022Instruction.InitializeNonTransferableMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateRateInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableCpiGuard;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableCpiGuard;\n }\n if (containsBytes(data, getU8Encoder().encode(35), 0)) {\n return Token2022Instruction.InitializePermanentDelegate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EnableHarvestToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.DisableHarvestToMint;\n }\n if (containsBytes(data, getU8Encoder().encode(38), 0)) {\n return Token2022Instruction.WithdrawExcessLamports;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeScaledUiAmountMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMultiplierScaledUiMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializePausableConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.Pause;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.Resume;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([210, 225, 30, 162, 88, 184, 77, 141]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenMetadata;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([221, 233, 49, 45, 181, 202, 220, 200]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataField;\n }\n if (\n containsBytes(data, new Uint8Array([234, 18, 32, 56, 89, 141, 37, 181]), 0)\n ) {\n return Token2022Instruction.RemoveTokenMetadataKey;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([250, 166, 180, 250, 13, 12, 184, 70]),\n 0\n )\n ) {\n return Token2022Instruction.EmitTokenMetadata;\n }\n if (\n containsBytes(data, new Uint8Array([121, 113, 108, 39, 54, 51, 0, 4]), 0)\n ) {\n return Token2022Instruction.InitializeTokenGroup;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([108, 37, 171, 143, 248, 30, 18, 110]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupMaxSize;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([161, 105, 88, 1, 237, 221, 216, 203]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([152, 32, 222, 176, 223, 237, 116, 134]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenGroupMember;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token-2022 instruction.'\n );\n}\n\nexport type ParsedToken2022Instruction<\n TProgram extends string = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n> =\n | ({\n instructionType: Token2022Instruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: Token2022Instruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: Token2022Instruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: Token2022Instruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: Token2022Instruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: Token2022Instruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: Token2022Instruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: Token2022Instruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: Token2022Instruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: Token2022Instruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: Token2022Instruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: Token2022Instruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: Token2022Instruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMintCloseAuthority;\n } & ParsedInitializeMintCloseAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferFeeConfig;\n } & ParsedInitializeTransferFeeConfigInstruction)\n | ({\n instructionType: Token2022Instruction.TransferCheckedWithFee;\n } & ParsedTransferCheckedWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMint;\n } & ParsedWithdrawWithheldTokensFromMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n } & ParsedWithdrawWithheldTokensFromAccountsInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMint;\n } & ParsedHarvestWithheldTokensToMintInstruction)\n | ({\n instructionType: Token2022Instruction.SetTransferFee;\n } & ParsedSetTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferMint;\n } & ParsedInitializeConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateConfidentialTransferMint;\n } & ParsedUpdateConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.ConfigureConfidentialTransferAccount;\n } & ParsedConfigureConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveConfidentialTransferAccount;\n } & ParsedApproveConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.EmptyConfidentialTransferAccount;\n } & ParsedEmptyConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialDeposit;\n } & ParsedConfidentialDepositInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialWithdraw;\n } & ParsedConfidentialWithdrawInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransfer;\n } & ParsedConfidentialTransferInstruction)\n | ({\n instructionType: Token2022Instruction.ApplyConfidentialPendingBalance;\n } & ParsedApplyConfidentialPendingBalanceInstruction)\n | ({\n instructionType: Token2022Instruction.EnableConfidentialCredits;\n } & ParsedEnableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableConfidentialCredits;\n } & ParsedDisableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.EnableNonConfidentialCredits;\n } & ParsedEnableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableNonConfidentialCredits;\n } & ParsedDisableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransferWithFee;\n } & ParsedConfidentialTransferWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeDefaultAccountState;\n } & ParsedInitializeDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateDefaultAccountState;\n } & ParsedUpdateDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.Reallocate;\n } & ParsedReallocateInstruction)\n | ({\n instructionType: Token2022Instruction.EnableMemoTransfers;\n } & ParsedEnableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.DisableMemoTransfers;\n } & ParsedDisableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.CreateNativeMint;\n } & ParsedCreateNativeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeNonTransferableMint;\n } & ParsedInitializeNonTransferableMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeInterestBearingMint;\n } & ParsedInitializeInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateRateInterestBearingMint;\n } & ParsedUpdateRateInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.EnableCpiGuard;\n } & ParsedEnableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.DisableCpiGuard;\n } & ParsedDisableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePermanentDelegate;\n } & ParsedInitializePermanentDelegateInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferHook;\n } & ParsedInitializeTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTransferHook;\n } & ParsedUpdateTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferFee;\n } & ParsedInitializeConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n } & ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.EnableHarvestToMint;\n } & ParsedEnableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.DisableHarvestToMint;\n } & ParsedDisableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawExcessLamports;\n } & ParsedWithdrawExcessLamportsInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMetadataPointer;\n } & ParsedInitializeMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMetadataPointer;\n } & ParsedUpdateMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupPointer;\n } & ParsedInitializeGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupPointer;\n } & ParsedUpdateGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupMemberPointer;\n } & ParsedInitializeGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupMemberPointer;\n } & ParsedUpdateGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeScaledUiAmountMint;\n } & ParsedInitializeScaledUiAmountMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMultiplierScaledUiMint;\n } & ParsedUpdateMultiplierScaledUiMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePausableConfig;\n } & ParsedInitializePausableConfigInstruction)\n | ({\n instructionType: Token2022Instruction.Pause;\n } & ParsedPauseInstruction)\n | ({\n instructionType: Token2022Instruction.Resume;\n } & ParsedResumeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenMetadata;\n } & ParsedInitializeTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataField;\n } & ParsedUpdateTokenMetadataFieldInstruction)\n | ({\n instructionType: Token2022Instruction.RemoveTokenMetadataKey;\n } & ParsedRemoveTokenMetadataKeyInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n } & ParsedUpdateTokenMetadataUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.EmitTokenMetadata;\n } & ParsedEmitTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroup;\n } & ParsedInitializeTokenGroupInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupMaxSize;\n } & ParsedUpdateTokenGroupMaxSizeInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n } & ParsedUpdateTokenGroupUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroupMember;\n } & ParsedInitializeTokenGroupMemberInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_2022_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_2022_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_2022_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_2022_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_2022_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_2022_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_2022_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_2022_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_2022_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_2022_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_2022_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_2022_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_2022_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type Token2022Error =\n | typeof TOKEN_2022_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_2022_ERROR__ALREADY_IN_USE\n | typeof TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__FIXED_SUPPLY\n | typeof TOKEN_2022_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_2022_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_2022_ERROR__INVALID_MINT\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_STATE\n | typeof TOKEN_2022_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_2022_ERROR__MINT_MISMATCH\n | typeof TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_2022_ERROR__OVERFLOW\n | typeof TOKEN_2022_ERROR__OWNER_MISMATCH\n | typeof TOKEN_2022_ERROR__UNINITIALIZED_STATE;\n\nlet token2022ErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n token2022ErrorMessages = {\n [TOKEN_2022_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_2022_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_2022_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_2022_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_2022_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_2022_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_2022_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_2022_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_2022_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_2022_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_2022_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_2022_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_2022_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getToken2022ErrorMessage(code: Token2022Error): string {\n if (process.env.NODE_ENV !== 'production') {\n return (token2022ErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isToken2022Error(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_2022_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR = 27;\n\nexport function getApplyConfidentialPendingBalanceDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR\n );\n}\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 8;\n\nexport function getApplyConfidentialPendingBalanceConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApplyConfidentialPendingBalanceInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalance;\n};\n\nexport type ApplyConfidentialPendingBalanceInstructionDataArgs = {\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n};\n\nexport function getApplyConfidentialPendingBalanceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataCodec(): FixedSizeCodec<\n ApplyConfidentialPendingBalanceInstructionDataArgs,\n ApplyConfidentialPendingBalanceInstructionData\n> {\n return combineCodec(\n getApplyConfidentialPendingBalanceInstructionDataEncoder(),\n getApplyConfidentialPendingBalanceInstructionDataDecoder()\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n expectedPendingBalanceCreditCounter: ApplyConfidentialPendingBalanceInstructionDataArgs['expectedPendingBalanceCreditCounter'];\n newDecryptableAvailableBalance: ApplyConfidentialPendingBalanceInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getApplyConfidentialPendingBalanceInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApplyConfidentialPendingBalanceInput,\n config?: { programAddress?: TProgramAddress }\n): ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getApplyConfidentialPendingBalanceInstructionDataEncoder().encode(\n args as ApplyConfidentialPendingBalanceInstructionDataArgs\n ),\n programAddress,\n } as ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: ApplyConfidentialPendingBalanceInstructionData;\n};\n\nexport function parseApplyConfidentialPendingBalanceInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApplyConfidentialPendingBalanceInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getApplyConfidentialPendingBalanceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getApproveConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 3;\n\nexport function getApproveConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type ApproveConfidentialTransferAccountInstructionDataArgs = {};\n\nexport function getApproveConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ApproveConfidentialTransferAccountInstructionDataArgs,\n ApproveConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getApproveConfidentialTransferAccountInstructionDataEncoder(),\n getApproveConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ApproveConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account to approve. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n};\n\nexport function getApproveConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getApproveConfidentialTransferAccountInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account to approve. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[2];\n };\n data: ApproveConfidentialTransferAccountInstructionData;\n};\n\nexport function parseApproveConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getApproveConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CONFIDENTIAL_DEPOSIT_DISCRIMINATOR = 27;\n\nexport function getConfidentialDepositDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_DEPOSIT_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 5;\n\nexport function getConfidentialDepositConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialDepositInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to deposit. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ConfidentialDepositInstructionDataArgs = {\n /** The amount of tokens to deposit. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getConfidentialDepositInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_DEPOSIT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialDepositInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getConfidentialDepositInstructionDataCodec(): FixedSizeCodec<\n ConfidentialDepositInstructionDataArgs,\n ConfidentialDepositInstructionData\n> {\n return combineCodec(\n getConfidentialDepositInstructionDataEncoder(),\n getConfidentialDepositInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialDepositInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialDepositInstructionDataArgs['amount'];\n decimals: ConfidentialDepositInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialDepositInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialDepositInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialDepositInstructionDataEncoder().encode(\n args as ConfidentialDepositInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: ConfidentialDepositInstructionData;\n};\n\nexport function parseConfidentialDepositInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialDepositInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialDepositInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 7;\n\nexport function getConfidentialTransferConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferInstructionDataArgs,\n ConfidentialTransferInstructionData\n> {\n return combineCodec(\n getConfidentialTransferInstructionDataEncoder(),\n getConfidentialTransferInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['equalityProofInstructionOffset'];\n ciphertextValidityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['ciphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n ciphertextValidityRecord: {\n value: input.ciphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.ciphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferInstructionDataEncoder().encode(\n args as ConfidentialTransferInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[6] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[7];\n };\n data: ConfidentialTransferInstructionData;\n};\n\nexport function parseConfidentialTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferInstruction {\n if (instruction.accounts.length < 8) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n ciphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 13;\n\nexport function getConfidentialTransferWithFeeConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountTransferAmountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountFeeSigmaRecord extends string | AccountMeta = string,\n TAccountFeeCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord extends string\n ? ReadonlyAccount\n : TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferWithFeeInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferWithFeeInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n [\n 'transferAmountCiphertextValidityProofInstructionOffset',\n getI8Encoder(),\n ],\n ['feeSigmaProofInstructionOffset', getI8Encoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['transferAmountCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['feeSigmaProofInstructionOffset', getI8Decoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferWithFeeInstructionDataArgs,\n ConfidentialTransferWithFeeInstructionData\n> {\n return combineCodec(\n getConfidentialTransferWithFeeInstructionDataEncoder(),\n getConfidentialTransferWithFeeInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferWithFeeInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountTransferAmountCiphertextValidityRecord extends string = string,\n TAccountFeeSigmaRecord extends string = string,\n TAccountFeeCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: Address;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: Address;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferWithFeeInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['equalityProofInstructionOffset'];\n transferAmountCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['transferAmountCiphertextValidityProofInstructionOffset'];\n feeSigmaProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeSigmaProofInstructionOffset'];\n feeCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeCiphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferWithFeeInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountTransferAmountCiphertextValidityRecord extends string,\n TAccountFeeSigmaRecord extends string,\n TAccountFeeCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferWithFeeInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n transferAmountCiphertextValidityRecord: {\n value: input.transferAmountCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n feeSigmaRecord: { value: input.feeSigmaRecord ?? null, isWritable: false },\n feeCiphertextValidityRecord: {\n value: input.feeCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.transferAmountCiphertextValidityRecord),\n getAccountMeta(accounts.feeSigmaRecord),\n getAccountMeta(accounts.feeCiphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferWithFeeInstructionDataEncoder().encode(\n args as ConfidentialTransferWithFeeInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: TAccountMetas[6] | undefined;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: TAccountMetas[7] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[8] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[9];\n };\n data: ConfidentialTransferWithFeeInstructionData;\n};\n\nexport function parseConfidentialTransferWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferWithFeeInstruction {\n if (instruction.accounts.length < 10) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n transferAmountCiphertextValidityRecord: getNextOptionalAccount(),\n feeSigmaRecord: getNextOptionalAccount(),\n feeCiphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_WITHDRAW_DISCRIMINATOR = 27;\n\nexport function getConfidentialWithdrawDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_WITHDRAW_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 6;\n\nexport function getConfidentialWithdrawConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialWithdrawInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to withdraw. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialWithdrawInstructionDataArgs = {\n /** The amount of tokens to withdraw. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialWithdrawInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_WITHDRAW_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialWithdrawInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialWithdrawInstructionDataCodec(): FixedSizeCodec<\n ConfidentialWithdrawInstructionDataArgs,\n ConfidentialWithdrawInstructionData\n> {\n return combineCodec(\n getConfidentialWithdrawInstructionDataEncoder(),\n getConfidentialWithdrawInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialWithdrawInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialWithdrawInstructionDataArgs['amount'];\n decimals: ConfidentialWithdrawInstructionDataArgs['decimals'];\n newDecryptableAvailableBalance: ConfidentialWithdrawInstructionDataArgs['newDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['equalityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialWithdrawInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialWithdrawInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialWithdrawInstructionDataEncoder().encode(\n args as ConfidentialWithdrawInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[2] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[3] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[4] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[5];\n };\n data: ConfidentialWithdrawInstructionData;\n};\n\nexport function parseConfidentialWithdrawInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialWithdrawInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialWithdrawInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getConfigureConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 2;\n\nexport function getConfigureConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfigureConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalance;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type ConfigureConfidentialTransferAccountInstructionDataArgs = {\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalanceArgs;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getConfigureConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['decryptableZeroBalance', getDecryptableBalanceEncoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['decryptableZeroBalance', getDecryptableBalanceDecoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ConfigureConfidentialTransferAccountInstructionDataArgs,\n ConfigureConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getConfigureConfidentialTransferAccountInstructionDataEncoder(),\n getConfigureConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n decryptableZeroBalance: ConfigureConfidentialTransferAccountInstructionDataArgs['decryptableZeroBalance'];\n maximumPendingBalanceCreditCounter: ConfigureConfidentialTransferAccountInstructionDataArgs['maximumPendingBalanceCreditCounter'];\n proofInstructionOffset: ConfigureConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfigureConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfigureConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfigureConfidentialTransferAccountInstructionDataEncoder().encode(\n args as ConfigureConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[3] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[4];\n };\n data: ConfigureConfidentialTransferAccountInstructionData;\n};\n\nexport function parseConfigureConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfigureConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CREATE_NATIVE_MINT_DISCRIMINATOR = 31;\n\nexport function getCreateNativeMintDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_NATIVE_MINT_DISCRIMINATOR);\n}\n\nexport type CreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNativeMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNativeMint extends string\n ? WritableAccount\n : TAccountNativeMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateNativeMintInstructionData = { discriminator: number };\n\nexport type CreateNativeMintInstructionDataArgs = {};\n\nexport function getCreateNativeMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CREATE_NATIVE_MINT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateNativeMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateNativeMintInstructionDataCodec(): FixedSizeCodec<\n CreateNativeMintInstructionDataArgs,\n CreateNativeMintInstructionData\n> {\n return combineCodec(\n getCreateNativeMintInstructionDataEncoder(),\n getCreateNativeMintInstructionDataDecoder()\n );\n}\n\nexport type CreateNativeMintInput<\n TAccountPayer extends string = string,\n TAccountNativeMint extends string = string,\n TAccountSystemProgram extends string = string,\n> = {\n /** Funding account (must be a system account) */\n payer: TransactionSigner;\n /** The native mint address */\n nativeMint: Address;\n /** System program for mint account funding */\n systemProgram?: Address;\n};\n\nexport function getCreateNativeMintInstruction<\n TAccountPayer extends string,\n TAccountNativeMint extends string,\n TAccountSystemProgram extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CreateNativeMintInput<\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n nativeMint: { value: input.nativeMint ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.nativeMint),\n getAccountMeta(accounts.systemProgram),\n ],\n data: getCreateNativeMintInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >);\n}\n\nexport type ParsedCreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account) */\n payer: TAccountMetas[0];\n /** The native mint address */\n nativeMint: TAccountMetas[1];\n /** System program for mint account funding */\n systemProgram: TAccountMetas[2];\n };\n data: CreateNativeMintInstructionData;\n};\n\nexport function parseCreateNativeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateNativeMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n nativeMint: getNextAccount(),\n systemProgram: getNextAccount(),\n },\n data: getCreateNativeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 10;\n\nexport function getDisableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableConfidentialCreditsInstructionDataArgs,\n DisableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableConfidentialCreditsInstructionDataEncoder(),\n getDisableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getDisableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 1;\n\nexport function getDisableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type DisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type DisableCpiGuardInstructionDataArgs = {};\n\nexport function getDisableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n DisableCpiGuardInstructionDataArgs,\n DisableCpiGuardInstructionData\n> {\n return combineCodec(\n getDisableCpiGuardInstructionDataEncoder(),\n getDisableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type DisableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableCpiGuardInstructionData;\n};\n\nexport function parseDisableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getDisableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getDisableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type DisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type DisableHarvestToMintInstructionDataArgs = {};\n\nexport function getDisableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n DisableHarvestToMintInstructionDataArgs,\n DisableHarvestToMintInstructionData\n> {\n return combineCodec(\n getDisableHarvestToMintInstructionDataEncoder(),\n getDisableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type DisableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: DisableHarvestToMintInstructionData;\n};\n\nexport function parseDisableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getDisableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getDisableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 1;\n\nexport function getDisableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type DisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type DisableMemoTransfersInstructionDataArgs = {};\n\nexport function getDisableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n DisableMemoTransfersInstructionDataArgs,\n DisableMemoTransfersInstructionData\n> {\n return combineCodec(\n getDisableMemoTransfersInstructionDataEncoder(),\n getDisableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type DisableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableMemoTransfersInstructionData;\n};\n\nexport function parseDisableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 12;\n\nexport function getDisableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableNonConfidentialCreditsInstructionDataArgs,\n DisableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableNonConfidentialCreditsInstructionDataEncoder(),\n getDisableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMIT_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 250, 166, 180, 250, 13, 12, 184, 70,\n]);\n\nexport function getEmitTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(EMIT_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type EmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? ReadonlyAccount\n : TAccountMetadata,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmitTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Start of range of data to emit */\n start: Option;\n /** End of range of data to emit */\n end: Option;\n};\n\nexport type EmitTokenMetadataInstructionDataArgs = {\n /** Start of range of data to emit */\n start?: OptionOrNullable;\n /** End of range of data to emit */\n end?: OptionOrNullable;\n};\n\nexport function getEmitTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['start', getOptionEncoder(getU64Encoder())],\n ['end', getOptionEncoder(getU64Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: EMIT_TOKEN_METADATA_DISCRIMINATOR,\n start: value.start ?? none(),\n end: value.end ?? none(),\n })\n );\n}\n\nexport function getEmitTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['start', getOptionDecoder(getU64Decoder())],\n ['end', getOptionDecoder(getU64Decoder())],\n ]);\n}\n\nexport function getEmitTokenMetadataInstructionDataCodec(): Codec<\n EmitTokenMetadataInstructionDataArgs,\n EmitTokenMetadataInstructionData\n> {\n return combineCodec(\n getEmitTokenMetadataInstructionDataEncoder(),\n getEmitTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type EmitTokenMetadataInput = {\n metadata: Address;\n start?: EmitTokenMetadataInstructionDataArgs['start'];\n end?: EmitTokenMetadataInstructionDataArgs['end'];\n};\n\nexport function getEmitTokenMetadataInstruction<\n TAccountMetadata extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmitTokenMetadataInput,\n config?: { programAddress?: TProgramAddress }\n): EmitTokenMetadataInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.metadata)],\n data: getEmitTokenMetadataInstructionDataEncoder().encode(\n args as EmitTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as EmitTokenMetadataInstruction);\n}\n\nexport type ParsedEmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n };\n data: EmitTokenMetadataInstructionData;\n};\n\nexport function parseEmitTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmitTokenMetadataInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount() },\n data: getEmitTokenMetadataInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getEmptyConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 4;\n\nexport function getEmptyConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmptyConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type EmptyConfidentialTransferAccountInstructionDataArgs = {\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getEmptyConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n EmptyConfidentialTransferAccountInstructionDataArgs,\n EmptyConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getEmptyConfidentialTransferAccountInstructionDataEncoder(),\n getEmptyConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type EmptyConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n proofInstructionOffset: EmptyConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getEmptyConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmptyConfidentialTransferAccountInput<\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEmptyConfidentialTransferAccountInstructionDataEncoder().encode(\n args as EmptyConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[1];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[2] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: EmptyConfidentialTransferAccountInstructionData;\n};\n\nexport function parseEmptyConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmptyConfidentialTransferAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getEmptyConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 9;\n\nexport function getEnableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableConfidentialCreditsInstructionDataArgs,\n EnableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableConfidentialCreditsInstructionDataEncoder(),\n getEnableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getEnableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 0;\n\nexport function getEnableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type EnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type EnableCpiGuardInstructionDataArgs = {};\n\nexport function getEnableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n EnableCpiGuardInstructionDataArgs,\n EnableCpiGuardInstructionData\n> {\n return combineCodec(\n getEnableCpiGuardInstructionDataEncoder(),\n getEnableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type EnableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableCpiGuardInstructionData;\n};\n\nexport function parseEnableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getEnableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getEnableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type EnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type EnableHarvestToMintInstructionDataArgs = {};\n\nexport function getEnableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n EnableHarvestToMintInstructionDataArgs,\n EnableHarvestToMintInstructionData\n> {\n return combineCodec(\n getEnableHarvestToMintInstructionDataEncoder(),\n getEnableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type EnableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: EnableHarvestToMintInstructionData;\n};\n\nexport function parseEnableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getEnableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getEnableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 0;\n\nexport function getEnableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type EnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type EnableMemoTransfersInstructionDataArgs = {};\n\nexport function getEnableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n EnableMemoTransfersInstructionDataArgs,\n EnableMemoTransfersInstructionData\n> {\n return combineCodec(\n getEnableMemoTransfersInstructionDataEncoder(),\n getEnableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type EnableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableMemoTransfersInstructionData;\n};\n\nexport function parseEnableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 11;\n\nexport function getEnableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableNonConfidentialCreditsInstructionDataArgs,\n EnableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableNonConfidentialCreditsInstructionDataEncoder(),\n getEnableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR = 26;\n\nexport function getHarvestWithheldTokensToMintDiscriminatorBytes() {\n return getU8Encoder().encode(HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR);\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getHarvestWithheldTokensToMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type HarvestWithheldTokensToMintInstructionDataArgs = {};\n\nexport function getHarvestWithheldTokensToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintInstructionDataArgs,\n HarvestWithheldTokensToMintInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintInstructionDataEncoder(),\n getHarvestWithheldTokensToMintInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintInput<\n TAccountMint extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n sources: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.sources.map((address) => ({\n address,\n role: AccountRole.WRITABLE,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as HarvestWithheldTokensToMintInstruction);\n}\n\nexport type ParsedHarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData =\n { discriminator: number; confidentialTransferFeeDiscriminator: number };\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs =\n {};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs,\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(),\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n sources?: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintForConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.sources ?? []).map(\n (address) => ({ address, role: AccountRole.WRITABLE })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getInitializeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferFeeInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: Option
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferFeeInstructionDataArgs = {\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: OptionOrNullable
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferFeeInstructionDataArgs,\n InitializeConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferFeeInstructionDataEncoder(),\n getInitializeConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferFeeInstructionDataArgs['authority'];\n withdrawWithheldAuthorityElGamalPubkey: InitializeConfidentialTransferFeeInstructionDataArgs['withdrawWithheldAuthorityElGamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferFeeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferFeeInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferFeeInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferFeeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getInitializeConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: Option
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferMintInstructionDataArgs = {\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: OptionOrNullable
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferMintInstructionDataArgs,\n InitializeConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferMintInstructionDataEncoder(),\n getInitializeConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferMintInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferMintInstructionDataArgs['authority'];\n autoApproveNewAccounts: InitializeConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: InitializeConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferMintInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferMintInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferMintInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getInitializeDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 0;\n\nexport function getInitializeDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type InitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type InitializeDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getInitializeDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n InitializeDefaultAccountStateInstructionDataArgs,\n InitializeDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getInitializeDefaultAccountStateInstructionDataEncoder(),\n getInitializeDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type InitializeDefaultAccountStateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n state: InitializeDefaultAccountStateInstructionDataArgs['state'];\n};\n\nexport function getInitializeDefaultAccountStateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeDefaultAccountStateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeDefaultAccountStateInstructionDataEncoder().encode(\n args as InitializeDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as InitializeDefaultAccountStateInstruction);\n}\n\nexport type ParsedInitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeDefaultAccountStateInstructionData;\n};\n\nexport function parseInitializeDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeDefaultAccountStateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getInitializeGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The public key for the account that can update the group member address. */\n authority: Option
;\n /** The account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type InitializeGroupMemberPointerInstructionDataArgs = {\n /** The public key for the account that can update the group member address. */\n authority: OptionOrNullable
;\n /** The account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupMemberPointerInstructionDataArgs,\n InitializeGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupMemberPointerInstructionDataEncoder(),\n getInitializeGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupMemberPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupMemberPointerInstructionDataArgs['authority'];\n memberAddress: InitializeGroupMemberPointerInstructionDataArgs['memberAddress'];\n};\n\nexport function getInitializeGroupMemberPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupMemberPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupMemberPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupMemberPointerInstructionDataEncoder().encode(\n args as InitializeGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupMemberPointerInstruction);\n}\n\nexport type ParsedInitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupMemberPointerInstructionData;\n};\n\nexport function parseInitializeGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupMemberPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getInitializeGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The public key for the account that can update the group address. */\n authority: Option
;\n /** The account address that holds the group. */\n groupAddress: Option
;\n};\n\nexport type InitializeGroupPointerInstructionDataArgs = {\n /** The public key for the account that can update the group address. */\n authority: OptionOrNullable
;\n /** The account address that holds the group. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupPointerInstructionDataArgs,\n InitializeGroupPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupPointerInstructionDataEncoder(),\n getInitializeGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupPointerInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupPointerInstructionDataArgs['authority'];\n groupAddress: InitializeGroupPointerInstructionDataArgs['groupAddress'];\n };\n\nexport function getInitializeGroupPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupPointerInstructionDataEncoder().encode(\n args as InitializeGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupPointerInstruction);\n}\n\nexport type ParsedInitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupPointerInstructionData;\n};\n\nexport function parseInitializeGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getI16Decoder,\n getI16Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getInitializeInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The public key for the account that can update the rate */\n rateAuthority: Option
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport type InitializeInterestBearingMintInstructionDataArgs = {\n /** The public key for the account that can update the rate */\n rateAuthority: OptionOrNullable
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport function getInitializeInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n [\n 'rateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n [\n 'rateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getInitializeInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n InitializeInterestBearingMintInstructionDataArgs,\n InitializeInterestBearingMintInstructionData\n> {\n return combineCodec(\n getInitializeInterestBearingMintInstructionDataEncoder(),\n getInitializeInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeInterestBearingMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n rateAuthority: InitializeInterestBearingMintInstructionDataArgs['rateAuthority'];\n rate: InitializeInterestBearingMintInstructionDataArgs['rate'];\n};\n\nexport function getInitializeInterestBearingMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeInterestBearingMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeInterestBearingMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeInterestBearingMintInstructionDataEncoder().encode(\n args as InitializeInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeInterestBearingMintInstruction);\n}\n\nexport type ParsedInitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeInterestBearingMintInstructionData;\n};\n\nexport function parseInitializeInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeInterestBearingMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getInitializeMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The public key for the account that can update the metadata address. */\n authority: Option
;\n /** The account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type InitializeMetadataPointerInstructionDataArgs = {\n /** The public key for the account that can update the metadata address. */\n authority: OptionOrNullable
;\n /** The account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getInitializeMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeMetadataPointerInstructionDataArgs,\n InitializeMetadataPointerInstructionData\n> {\n return combineCodec(\n getInitializeMetadataPointerInstructionDataEncoder(),\n getInitializeMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeMetadataPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeMetadataPointerInstructionDataArgs['authority'];\n metadataAddress: InitializeMetadataPointerInstructionDataArgs['metadataAddress'];\n};\n\nexport function getInitializeMetadataPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMetadataPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMetadataPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMetadataPointerInstructionDataEncoder().encode(\n args as InitializeMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeMetadataPointerInstruction);\n}\n\nexport type ParsedInitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMetadataPointerInstructionData;\n};\n\nexport function parseInitializeMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMetadataPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR = 25;\n\nexport function getInitializeMintCloseAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type InitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintCloseAuthorityInstructionData = {\n discriminator: number;\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: Option
;\n};\n\nexport type InitializeMintCloseAuthorityInstructionDataArgs = {\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getInitializeMintCloseAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['closeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['closeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataCodec(): Codec<\n InitializeMintCloseAuthorityInstructionDataArgs,\n InitializeMintCloseAuthorityInstructionData\n> {\n return combineCodec(\n getInitializeMintCloseAuthorityInstructionDataEncoder(),\n getInitializeMintCloseAuthorityInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintCloseAuthorityInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n closeAuthority: InitializeMintCloseAuthorityInstructionDataArgs['closeAuthority'];\n};\n\nexport function getInitializeMintCloseAuthorityInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintCloseAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintCloseAuthorityInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMintCloseAuthorityInstructionDataEncoder().encode(\n args as InitializeMintCloseAuthorityInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintCloseAuthorityInstruction);\n}\n\nexport type ParsedInitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMintCloseAuthorityInstructionData;\n};\n\nexport function parseInitializeMintCloseAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintCloseAuthorityInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMintCloseAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR = 32;\n\nexport function getInitializeNonTransferableMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeNonTransferableMintInstructionData = {\n discriminator: number;\n};\n\nexport type InitializeNonTransferableMintInstructionDataArgs = {};\n\nexport function getInitializeNonTransferableMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeNonTransferableMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeNonTransferableMintInstructionDataCodec(): FixedSizeCodec<\n InitializeNonTransferableMintInstructionDataArgs,\n InitializeNonTransferableMintInstructionData\n> {\n return combineCodec(\n getInitializeNonTransferableMintInstructionDataEncoder(),\n getInitializeNonTransferableMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeNonTransferableMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint account to initialize. */\n mint: Address;\n};\n\nexport function getInitializeNonTransferableMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeNonTransferableMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeNonTransferableMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeNonTransferableMintInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeNonTransferableMintInstruction);\n}\n\nexport type ParsedInitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeNonTransferableMintInstructionData;\n};\n\nexport function parseInitializeNonTransferableMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeNonTransferableMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeNonTransferableMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR = 44;\n\nexport function getInitializePausableConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR = 0;\n\nexport function getInitializePausableConfigPausableDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR\n );\n}\n\nexport type InitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePausableConfigInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n /** The authority that can pause and resume the mint. */\n authority: Option
;\n};\n\nexport type InitializePausableConfigInstructionDataArgs = {\n /** The authority that can pause and resume the mint. */\n authority: OptionOrNullable
;\n};\n\nexport function getInitializePausableConfigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR,\n pausableDiscriminator: INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePausableConfigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializePausableConfigInstructionDataCodec(): FixedSizeCodec<\n InitializePausableConfigInstructionDataArgs,\n InitializePausableConfigInstructionData\n> {\n return combineCodec(\n getInitializePausableConfigInstructionDataEncoder(),\n getInitializePausableConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializePausableConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n authority: InitializePausableConfigInstructionDataArgs['authority'];\n};\n\nexport function getInitializePausableConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePausableConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePausableConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePausableConfigInstructionDataEncoder().encode(\n args as InitializePausableConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializePausableConfigInstruction);\n}\n\nexport type ParsedInitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializePausableConfigInstructionData;\n};\n\nexport function parseInitializePausableConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePausableConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePausableConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR = 35;\n\nexport function getInitializePermanentDelegateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR);\n}\n\nexport type InitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePermanentDelegateInstructionData = {\n discriminator: number;\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport type InitializePermanentDelegateInstructionDataArgs = {\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport function getInitializePermanentDelegateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['delegate', getAddressEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePermanentDelegateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['delegate', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializePermanentDelegateInstructionDataCodec(): FixedSizeCodec<\n InitializePermanentDelegateInstructionDataArgs,\n InitializePermanentDelegateInstructionData\n> {\n return combineCodec(\n getInitializePermanentDelegateInstructionDataEncoder(),\n getInitializePermanentDelegateInstructionDataDecoder()\n );\n}\n\nexport type InitializePermanentDelegateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n delegate: InitializePermanentDelegateInstructionDataArgs['delegate'];\n};\n\nexport function getInitializePermanentDelegateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePermanentDelegateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePermanentDelegateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePermanentDelegateInstructionDataEncoder().encode(\n args as InitializePermanentDelegateInstructionDataArgs\n ),\n programAddress,\n } as InitializePermanentDelegateInstruction);\n}\n\nexport type ParsedInitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializePermanentDelegateInstructionData;\n};\n\nexport function parseInitializePermanentDelegateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePermanentDelegateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePermanentDelegateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getF64Decoder,\n getF64Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 43;\n\nexport function getInitializeScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeScaledUiAmountMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeScaledUiAmountMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The authority that can update the multiplier */\n authority: Option
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport type InitializeScaledUiAmountMintInstructionDataArgs = {\n /** The authority that can update the multiplier */\n authority: OptionOrNullable
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport function getInitializeScaledUiAmountMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Decoder()],\n ]);\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataCodec(): FixedSizeCodec<\n InitializeScaledUiAmountMintInstructionDataArgs,\n InitializeScaledUiAmountMintInstructionData\n> {\n return combineCodec(\n getInitializeScaledUiAmountMintInstructionDataEncoder(),\n getInitializeScaledUiAmountMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeScaledUiAmountMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeScaledUiAmountMintInstructionDataArgs['authority'];\n multiplier: InitializeScaledUiAmountMintInstructionDataArgs['multiplier'];\n};\n\nexport function getInitializeScaledUiAmountMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeScaledUiAmountMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeScaledUiAmountMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeScaledUiAmountMintInstructionDataEncoder().encode(\n args as InitializeScaledUiAmountMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeScaledUiAmountMintInstruction);\n}\n\nexport type ParsedInitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeScaledUiAmountMintInstructionData;\n};\n\nexport function parseInitializeScaledUiAmountMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeScaledUiAmountMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeScaledUiAmountMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_DISCRIMINATOR = new Uint8Array([\n 121, 113, 108, 39, 54, 51, 0, 4,\n]);\n\nexport function getInitializeTokenGroupDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Update authority for the group */\n updateAuthority: Option
;\n /** The maximum number of group members */\n maxSize: bigint;\n};\n\nexport type InitializeTokenGroupInstructionDataArgs = {\n /** Update authority for the group */\n updateAuthority: OptionOrNullable
;\n /** The maximum number of group members */\n maxSize: number | bigint;\n};\n\nexport function getInitializeTokenGroupInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTokenGroupInstructionDataCodec(): Codec<\n InitializeTokenGroupInstructionDataArgs,\n InitializeTokenGroupInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupInstructionDataEncoder(),\n getInitializeTokenGroupInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupInput<\n TAccountGroup extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n group: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n updateAuthority: InitializeTokenGroupInstructionDataArgs['updateAuthority'];\n maxSize: InitializeTokenGroupInstructionDataArgs['maxSize'];\n};\n\nexport function getInitializeTokenGroupInstruction<\n TAccountGroup extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupInput<\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenGroupInstructionDataEncoder().encode(\n args as InitializeTokenGroupInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n mint: TAccountMetas[1];\n mintAuthority: TAccountMetas[2];\n };\n data: InitializeTokenGroupInstructionData;\n};\n\nexport function parseInitializeTokenGroupInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n group: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR = new Uint8Array([\n 152, 32, 222, 176, 223, 237, 116, 134,\n]);\n\nexport function getInitializeTokenGroupMemberDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMember extends string | AccountMeta = string,\n TAccountMemberMint extends string | AccountMeta = string,\n TAccountMemberMintAuthority extends string | AccountMeta = string,\n TAccountGroup extends string | AccountMeta = string,\n TAccountGroupUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMember extends string\n ? WritableAccount\n : TAccountMember,\n TAccountMemberMint extends string\n ? ReadonlyAccount\n : TAccountMemberMint,\n TAccountMemberMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMemberMintAuthority,\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountGroupUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupMemberInstructionData = {\n discriminator: ReadonlyUint8Array;\n};\n\nexport type InitializeTokenGroupMemberInstructionDataArgs = {};\n\nexport function getInitializeTokenGroupMemberInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getBytesEncoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataDecoder(): Decoder {\n return getStructDecoder([['discriminator', getBytesDecoder()]]);\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataCodec(): Codec<\n InitializeTokenGroupMemberInstructionDataArgs,\n InitializeTokenGroupMemberInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupMemberInstructionDataEncoder(),\n getInitializeTokenGroupMemberInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupMemberInput<\n TAccountMember extends string = string,\n TAccountMemberMint extends string = string,\n TAccountMemberMintAuthority extends string = string,\n TAccountGroup extends string = string,\n TAccountGroupUpdateAuthority extends string = string,\n> = {\n member: Address;\n memberMint: Address;\n memberMintAuthority: TransactionSigner;\n group: Address;\n groupUpdateAuthority: TransactionSigner;\n};\n\nexport function getInitializeTokenGroupMemberInstruction<\n TAccountMember extends string,\n TAccountMemberMint extends string,\n TAccountMemberMintAuthority extends string,\n TAccountGroup extends string,\n TAccountGroupUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupMemberInput<\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n member: { value: input.member ?? null, isWritable: true },\n memberMint: { value: input.memberMint ?? null, isWritable: false },\n memberMintAuthority: {\n value: input.memberMintAuthority ?? null,\n isWritable: false,\n },\n group: { value: input.group ?? null, isWritable: true },\n groupUpdateAuthority: {\n value: input.groupUpdateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.member),\n getAccountMeta(accounts.memberMint),\n getAccountMeta(accounts.memberMintAuthority),\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.groupUpdateAuthority),\n ],\n data: getInitializeTokenGroupMemberInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n member: TAccountMetas[0];\n memberMint: TAccountMetas[1];\n memberMintAuthority: TAccountMetas[2];\n group: TAccountMetas[3];\n groupUpdateAuthority: TAccountMetas[4];\n };\n data: InitializeTokenGroupMemberInstructionData;\n};\n\nexport function parseInitializeTokenGroupMemberInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupMemberInstruction {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n member: getNextAccount(),\n memberMint: getNextAccount(),\n memberMintAuthority: getNextAccount(),\n group: getNextAccount(),\n groupUpdateAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupMemberInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 210, 225, 30, 162, 88, 184, 77, 141,\n]);\n\nexport function getInitializeTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type InitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlyAccount\n : TAccountUpdateAuthority,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport type InitializeTokenMetadataInstructionDataArgs = {\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport function getInitializeTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_METADATA_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getInitializeTokenMetadataInstructionDataCodec(): Codec<\n InitializeTokenMetadataInstructionDataArgs,\n InitializeTokenMetadataInstructionData\n> {\n return combineCodec(\n getInitializeTokenMetadataInstructionDataEncoder(),\n getInitializeTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenMetadataInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n name: InitializeTokenMetadataInstructionDataArgs['name'];\n symbol: InitializeTokenMetadataInstructionDataArgs['symbol'];\n uri: InitializeTokenMetadataInstructionDataArgs['uri'];\n};\n\nexport function getInitializeTokenMetadataInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenMetadataInput<\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenMetadataInstructionDataEncoder().encode(\n args as InitializeTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n mint: TAccountMetas[2];\n mintAuthority: TAccountMetas[3];\n };\n data: InitializeTokenMetadataInstructionData;\n};\n\nexport function parseInitializeTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenMetadataInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n metadata: getNextAccount(),\n updateAuthority: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenMetadataInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR = 26;\n\nexport function getInitializeTransferFeeConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferFeeConfigTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferFeeConfigInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: Option
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: Option
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type InitializeTransferFeeConfigInstructionDataArgs = {\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: OptionOrNullable
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: OptionOrNullable
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getInitializeTransferFeeConfigInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeConfigAuthority', getOptionEncoder(getAddressEncoder())],\n ['withdrawWithheldAuthority', getOptionEncoder(getAddressEncoder())],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR,\n transferFeeDiscriminator:\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeConfigAuthority', getOptionDecoder(getAddressDecoder())],\n ['withdrawWithheldAuthority', getOptionDecoder(getAddressDecoder())],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataCodec(): Codec<\n InitializeTransferFeeConfigInstructionDataArgs,\n InitializeTransferFeeConfigInstructionData\n> {\n return combineCodec(\n getInitializeTransferFeeConfigInstructionDataEncoder(),\n getInitializeTransferFeeConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferFeeConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n transferFeeConfigAuthority: InitializeTransferFeeConfigInstructionDataArgs['transferFeeConfigAuthority'];\n withdrawWithheldAuthority: InitializeTransferFeeConfigInstructionDataArgs['withdrawWithheldAuthority'];\n transferFeeBasisPoints: InitializeTransferFeeConfigInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: InitializeTransferFeeConfigInstructionDataArgs['maximumFee'];\n};\n\nexport function getInitializeTransferFeeConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferFeeConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferFeeConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferFeeConfigInstructionDataEncoder().encode(\n args as InitializeTransferFeeConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferFeeConfigInstruction);\n}\n\nexport type ParsedInitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferFeeConfigInstructionData;\n};\n\nexport function parseInitializeTransferFeeConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferFeeConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferFeeConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getInitializeTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The public key for the account that can update the program id */\n authority: Option
;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type InitializeTransferHookInstructionDataArgs = {\n /** The public key for the account that can update the program id */\n authority: OptionOrNullable
;\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getInitializeTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeTransferHookInstructionDataCodec(): FixedSizeCodec<\n InitializeTransferHookInstructionDataArgs,\n InitializeTransferHookInstructionData\n> {\n return combineCodec(\n getInitializeTransferHookInstructionDataEncoder(),\n getInitializeTransferHookInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferHookInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeTransferHookInstructionDataArgs['authority'];\n programId: InitializeTransferHookInstructionDataArgs['programId'];\n };\n\nexport function getInitializeTransferHookInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferHookInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferHookInstructionDataEncoder().encode(\n args as InitializeTransferHookInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferHookInstruction);\n}\n\nexport type ParsedInitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferHookInstructionData;\n};\n\nexport function parseInitializeTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferHookInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const PAUSE_DISCRIMINATOR = 44;\n\nexport function getPauseDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_DISCRIMINATOR);\n}\n\nexport const PAUSE_PAUSABLE_DISCRIMINATOR = 1;\n\nexport function getPausePausableDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type PauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type PauseInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type PauseInstructionDataArgs = {};\n\nexport function getPauseInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: PAUSE_DISCRIMINATOR,\n pausableDiscriminator: PAUSE_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getPauseInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getPauseInstructionDataCodec(): FixedSizeCodec<\n PauseInstructionDataArgs,\n PauseInstructionData\n> {\n return combineCodec(\n getPauseInstructionDataEncoder(),\n getPauseInstructionDataDecoder()\n );\n}\n\nexport type PauseInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can pause the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getPauseInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: PauseInput,\n config?: { programAddress?: TProgramAddress }\n): PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getPauseInstructionDataEncoder().encode({}),\n programAddress,\n } as PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedPauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can pause the mint. */\n authority: TAccountMetas[1];\n };\n data: PauseInstructionData;\n};\n\nexport function parsePauseInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedPauseInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getPauseInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getExtensionTypeDecoder,\n getExtensionTypeEncoder,\n type ExtensionType,\n type ExtensionTypeArgs,\n} from '../types';\n\nexport const REALLOCATE_DISCRIMINATOR = 29;\n\nexport function getReallocateDiscriminatorBytes() {\n return getU8Encoder().encode(REALLOCATE_DISCRIMINATOR);\n}\n\nexport type ReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountPayer extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ReallocateInstructionData = {\n discriminator: number;\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport type ReallocateInstructionDataArgs = {\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport function getReallocateInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n [\n 'newExtensionTypes',\n getArrayEncoder(getExtensionTypeEncoder(), { size: 'remainder' }),\n ],\n ]),\n (value) => ({ ...value, discriminator: REALLOCATE_DISCRIMINATOR })\n );\n}\n\nexport function getReallocateInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n [\n 'newExtensionTypes',\n getArrayDecoder(getExtensionTypeDecoder(), { size: 'remainder' }),\n ],\n ]);\n}\n\nexport function getReallocateInstructionDataCodec(): Codec<\n ReallocateInstructionDataArgs,\n ReallocateInstructionData\n> {\n return combineCodec(\n getReallocateInstructionDataEncoder(),\n getReallocateInstructionDataDecoder()\n );\n}\n\nexport type ReallocateInput<\n TAccountToken extends string = string,\n TAccountPayer extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to reallocate. */\n token: Address;\n /** The payer account to fund reallocation. */\n payer: TransactionSigner;\n /** System program for reallocation funding. */\n systemProgram?: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n newExtensionTypes: ReallocateInstructionDataArgs['newExtensionTypes'];\n multiSigners?: Array;\n};\n\nexport function getReallocateInstruction<\n TAccountToken extends string,\n TAccountPayer extends string,\n TAccountSystemProgram extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ReallocateInput<\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n payer: { value: input.payer ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getReallocateInstructionDataEncoder().encode(\n args as ReallocateInstructionDataArgs\n ),\n programAddress,\n } as ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to reallocate. */\n token: TAccountMetas[0];\n /** The payer account to fund reallocation. */\n payer: TAccountMetas[1];\n /** System program for reallocation funding. */\n systemProgram: TAccountMetas[2];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ReallocateInstructionData;\n};\n\nexport function parseReallocateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedReallocateInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n payer: getNextAccount(),\n systemProgram: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getReallocateInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR = new Uint8Array([\n 234, 18, 32, 56, 89, 141, 37, 181,\n]);\n\nexport function getRemoveTokenMetadataKeyDiscriminatorBytes() {\n return getBytesEncoder().encode(REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR);\n}\n\nexport type RemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RemoveTokenMetadataKeyInstructionData = {\n discriminator: ReadonlyUint8Array;\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport type RemoveTokenMetadataKeyInstructionDataArgs = {\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent?: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport function getRemoveTokenMetadataKeyInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['idempotent', getBooleanEncoder()],\n ['key', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR,\n idempotent: value.idempotent ?? false,\n })\n );\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['idempotent', getBooleanDecoder()],\n ['key', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataCodec(): Codec<\n RemoveTokenMetadataKeyInstructionDataArgs,\n RemoveTokenMetadataKeyInstructionData\n> {\n return combineCodec(\n getRemoveTokenMetadataKeyInstructionDataEncoder(),\n getRemoveTokenMetadataKeyInstructionDataDecoder()\n );\n}\n\nexport type RemoveTokenMetadataKeyInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n idempotent?: RemoveTokenMetadataKeyInstructionDataArgs['idempotent'];\n key: RemoveTokenMetadataKeyInstructionDataArgs['key'];\n};\n\nexport function getRemoveTokenMetadataKeyInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RemoveTokenMetadataKeyInput,\n config?: { programAddress?: TProgramAddress }\n): RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getRemoveTokenMetadataKeyInstructionDataEncoder().encode(\n args as RemoveTokenMetadataKeyInstructionDataArgs\n ),\n programAddress,\n } as RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedRemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: RemoveTokenMetadataKeyInstructionData;\n};\n\nexport function parseRemoveTokenMetadataKeyInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRemoveTokenMetadataKeyInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getRemoveTokenMetadataKeyInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const RESUME_DISCRIMINATOR = 44;\n\nexport function getResumeDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_DISCRIMINATOR);\n}\n\nexport const RESUME_PAUSABLE_DISCRIMINATOR = 2;\n\nexport function getResumePausableDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type ResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ResumeInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type ResumeInstructionDataArgs = {};\n\nexport function getResumeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: RESUME_DISCRIMINATOR,\n pausableDiscriminator: RESUME_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getResumeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getResumeInstructionDataCodec(): FixedSizeCodec<\n ResumeInstructionDataArgs,\n ResumeInstructionData\n> {\n return combineCodec(\n getResumeInstructionDataEncoder(),\n getResumeInstructionDataDecoder()\n );\n}\n\nexport type ResumeInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can resume the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getResumeInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ResumeInput,\n config?: { programAddress?: TProgramAddress }\n): ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getResumeInstructionDataEncoder().encode({}),\n programAddress,\n } as ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can resume the mint. */\n authority: TAccountMetas[1];\n };\n data: ResumeInstructionData;\n};\n\nexport function parseResumeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedResumeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getResumeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SET_TRANSFER_FEE_DISCRIMINATOR = 26;\n\nexport function getSetTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport const SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getSetTransferFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport type SetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountTransferFeeConfigAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountTransferFeeConfigAuthority extends string\n ? ReadonlyAccount\n : TAccountTransferFeeConfigAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetTransferFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type SetTransferFeeInstructionDataArgs = {\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getSetTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_TRANSFER_FEE_DISCRIMINATOR,\n transferFeeDiscriminator: SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getSetTransferFeeInstructionDataCodec(): FixedSizeCodec<\n SetTransferFeeInstructionDataArgs,\n SetTransferFeeInstructionData\n> {\n return combineCodec(\n getSetTransferFeeInstructionDataEncoder(),\n getSetTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type SetTransferFeeInput<\n TAccountMint extends string = string,\n TAccountTransferFeeConfigAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority:\n | Address\n | TransactionSigner;\n transferFeeBasisPoints: SetTransferFeeInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: SetTransferFeeInstructionDataArgs['maximumFee'];\n multiSigners?: Array;\n};\n\nexport function getSetTransferFeeInstruction<\n TAccountMint extends string,\n TAccountTransferFeeConfigAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n transferFeeConfigAuthority: {\n value: input.transferFeeConfigAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.transferFeeConfigAuthority),\n ...remainingAccounts,\n ],\n data: getSetTransferFeeInstructionDataEncoder().encode(\n args as SetTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n >);\n}\n\nexport type ParsedSetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority: TAccountMetas[1];\n };\n data: SetTransferFeeInstructionData;\n};\n\nexport function parseSetTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetTransferFeeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n transferFeeConfigAuthority: getNextAccount(),\n },\n data: getSetTransferFeeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR = 26;\n\nexport function getTransferCheckedWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getTransferCheckedWithFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type TransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedWithFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: bigint;\n};\n\nexport type TransferCheckedWithFeeInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: number | bigint;\n};\n\nexport function getTransferCheckedWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['fee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR,\n transferFeeDiscriminator:\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getTransferCheckedWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['fee', getU64Decoder()],\n ]);\n}\n\nexport function getTransferCheckedWithFeeInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedWithFeeInstructionDataArgs,\n TransferCheckedWithFeeInstructionData\n> {\n return combineCodec(\n getTransferCheckedWithFeeInstructionDataEncoder(),\n getTransferCheckedWithFeeInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedWithFeeInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: Address;\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: Address;\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedWithFeeInstructionDataArgs['amount'];\n decimals: TransferCheckedWithFeeInstructionDataArgs['decimals'];\n fee: TransferCheckedWithFeeInstructionDataArgs['fee'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedWithFeeInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedWithFeeInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedWithFeeInstructionDataEncoder().encode(\n args as TransferCheckedWithFeeInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: TAccountMetas[0];\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[1];\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedWithFeeInstructionData;\n};\n\nexport function parseTransferCheckedWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedWithFeeInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getUpdateConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 1;\n\nexport function getUpdateConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type UpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type UpdateConfidentialTransferMintInstructionDataArgs = {\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getUpdateConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n UpdateConfidentialTransferMintInstructionDataArgs,\n UpdateConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getUpdateConfidentialTransferMintInstructionDataEncoder(),\n getUpdateConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateConfidentialTransferMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n autoApproveNewAccounts: UpdateConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: UpdateConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getUpdateConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getUpdateConfidentialTransferMintInstructionDataEncoder().encode(\n args as UpdateConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateConfidentialTransferMintInstructionData;\n};\n\nexport function parseUpdateConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateConfidentialTransferMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getUpdateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 1;\n\nexport function getUpdateDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type UpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFreezeAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFreezeAuthority extends string\n ? ReadonlyAccount\n : TAccountFreezeAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type UpdateDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getUpdateDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n UpdateDefaultAccountStateInstructionDataArgs,\n UpdateDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getUpdateDefaultAccountStateInstructionDataEncoder(),\n getUpdateDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type UpdateDefaultAccountStateInput<\n TAccountMint extends string = string,\n TAccountFreezeAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority:\n | Address\n | TransactionSigner;\n state: UpdateDefaultAccountStateInstructionDataArgs['state'];\n multiSigners?: Array;\n};\n\nexport function getUpdateDefaultAccountStateInstruction<\n TAccountMint extends string,\n TAccountFreezeAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n freezeAuthority: {\n value: input.freezeAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.freezeAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateDefaultAccountStateInstructionDataEncoder().encode(\n args as UpdateDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n >);\n}\n\nexport type ParsedUpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority: TAccountMetas[1];\n };\n data: UpdateDefaultAccountStateInstructionData;\n};\n\nexport function parseUpdateDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateDefaultAccountStateInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), freezeAuthority: getNextAccount() },\n data: getUpdateDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getUpdateGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupMemberPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupMemberPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupMemberPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The new account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type UpdateGroupMemberPointerInstructionDataArgs = {\n /** The new account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupMemberPointerInstructionDataArgs,\n UpdateGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupMemberPointerInstructionDataEncoder(),\n getUpdateGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupMemberPointerInput<\n TAccountMint extends string = string,\n TAccountGroupMemberPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority:\n | Address\n | TransactionSigner;\n memberAddress: UpdateGroupMemberPointerInstructionDataArgs['memberAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupMemberPointerInstruction<\n TAccountMint extends string,\n TAccountGroupMemberPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupMemberPointerInput<\n TAccountMint,\n TAccountGroupMemberPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupMemberPointerAuthority: {\n value: input.groupMemberPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupMemberPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupMemberPointerInstructionDataEncoder().encode(\n args as UpdateGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupMemberPointerInstructionData;\n};\n\nexport function parseUpdateGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupMemberPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupMemberPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getUpdateGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupPointerAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The new account address that holds the group configurations. */\n groupAddress: Option
;\n};\n\nexport type UpdateGroupPointerInstructionDataArgs = {\n /** The new account address that holds the group configurations. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupPointerInstructionDataArgs,\n UpdateGroupPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupPointerInstructionDataEncoder(),\n getUpdateGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupPointerInput<\n TAccountMint extends string = string,\n TAccountGroupPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority:\n | Address\n | TransactionSigner;\n groupAddress: UpdateGroupPointerInstructionDataArgs['groupAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupPointerInstruction<\n TAccountMint extends string,\n TAccountGroupPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupPointerAuthority: {\n value: input.groupPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupPointerInstructionDataEncoder().encode(\n args as UpdateGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupPointerInstructionData;\n};\n\nexport function parseUpdateGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getUpdateMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountMetadataPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountMetadataPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountMetadataPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The new account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type UpdateMetadataPointerInstructionDataArgs = {\n /** The new account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getUpdateMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateMetadataPointerInstructionDataArgs,\n UpdateMetadataPointerInstructionData\n> {\n return combineCodec(\n getUpdateMetadataPointerInstructionDataEncoder(),\n getUpdateMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateMetadataPointerInput<\n TAccountMint extends string = string,\n TAccountMetadataPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority:\n | Address\n | TransactionSigner;\n metadataAddress: UpdateMetadataPointerInstructionDataArgs['metadataAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMetadataPointerInstruction<\n TAccountMint extends string,\n TAccountMetadataPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMetadataPointerInput<\n TAccountMint,\n TAccountMetadataPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n metadataPointerAuthority: {\n value: input.metadataPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.metadataPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateMetadataPointerInstructionDataEncoder().encode(\n args as UpdateMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n >);\n}\n\nexport type ParsedUpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority: TAccountMetas[1];\n };\n data: UpdateMetadataPointerInstructionData;\n};\n\nexport function parseUpdateMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMetadataPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n metadataPointerAuthority: getNextAccount(),\n },\n data: getUpdateMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getF64Decoder,\n getF64Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR = 43;\n\nexport function getUpdateMultiplierScaledUiMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateMultiplierScaledUiMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? WritableAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMultiplierScaledUiMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: bigint;\n};\n\nexport type UpdateMultiplierScaledUiMintInstructionDataArgs = {\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: number | bigint;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n ['multiplier', getF64Encoder()],\n ['effectiveTimestamp', getI64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n ['multiplier', getF64Decoder()],\n ['effectiveTimestamp', getI64Decoder()],\n ]);\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataCodec(): FixedSizeCodec<\n UpdateMultiplierScaledUiMintInstructionDataArgs,\n UpdateMultiplierScaledUiMintInstructionData\n> {\n return combineCodec(\n getUpdateMultiplierScaledUiMintInstructionDataEncoder(),\n getUpdateMultiplierScaledUiMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The multiplier authority. */\n authority: Address | TransactionSigner;\n multiplier: UpdateMultiplierScaledUiMintInstructionDataArgs['multiplier'];\n effectiveTimestamp: UpdateMultiplierScaledUiMintInstructionDataArgs['effectiveTimestamp'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMultiplierScaledUiMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateMultiplierScaledUiMintInstructionDataEncoder().encode(\n args as UpdateMultiplierScaledUiMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The multiplier authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateMultiplierScaledUiMintInstructionData;\n};\n\nexport function parseUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMultiplierScaledUiMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateMultiplierScaledUiMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI16Decoder,\n getI16Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getUpdateRateInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateRateInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRateAuthority extends string\n ? WritableAccount\n : TAccountRateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateRateInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The interest rate to update. */\n rate: number;\n};\n\nexport type UpdateRateInterestBearingMintInstructionDataArgs = {\n /** The interest rate to update. */\n rate: number;\n};\n\nexport function getUpdateRateInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n UpdateRateInterestBearingMintInstructionDataArgs,\n UpdateRateInterestBearingMintInstructionData\n> {\n return combineCodec(\n getUpdateRateInterestBearingMintInstructionDataEncoder(),\n getUpdateRateInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateRateInterestBearingMintInput<\n TAccountMint extends string = string,\n TAccountRateAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint rate authority. */\n rateAuthority:\n | Address\n | TransactionSigner;\n rate: UpdateRateInterestBearingMintInstructionDataArgs['rate'];\n multiSigners?: Array;\n};\n\nexport function getUpdateRateInterestBearingMintInstruction<\n TAccountMint extends string,\n TAccountRateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateRateInterestBearingMintInput<\n TAccountMint,\n TAccountRateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rateAuthority: { value: input.rateAuthority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rateAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateRateInterestBearingMintInstructionDataEncoder().encode(\n args as UpdateRateInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n >);\n}\n\nexport type ParsedUpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint rate authority. */\n rateAuthority: TAccountMetas[1];\n };\n data: UpdateRateInterestBearingMintInstructionData;\n};\n\nexport function parseUpdateRateInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateRateInterestBearingMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rateAuthority: getNextAccount() },\n data: getUpdateRateInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR = new Uint8Array([\n 108, 37, 171, 143, 248, 30, 18, 110,\n]);\n\nexport function getUpdateTokenGroupMaxSizeDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR);\n}\n\nexport type UpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupMaxSizeInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New max size for the group */\n maxSize: bigint;\n};\n\nexport type UpdateTokenGroupMaxSizeInstructionDataArgs = {\n /** New max size for the group */\n maxSize: number | bigint;\n};\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataCodec(): Codec<\n UpdateTokenGroupMaxSizeInstructionDataArgs,\n UpdateTokenGroupMaxSizeInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupMaxSizeInstructionDataEncoder(),\n getUpdateTokenGroupMaxSizeInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupMaxSizeInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n updateAuthority: TransactionSigner;\n maxSize: UpdateTokenGroupMaxSizeInstructionDataArgs['maxSize'];\n};\n\nexport function getUpdateTokenGroupMaxSizeInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupMaxSizeInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupMaxSizeInstructionDataEncoder().encode(\n args as UpdateTokenGroupMaxSizeInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupMaxSizeInstructionData;\n};\n\nexport function parseUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupMaxSizeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupMaxSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR = new Uint8Array(\n [161, 105, 88, 1, 237, 221, 216, 203]\n);\n\nexport function getUpdateTokenGroupUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionDataArgs = {\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenGroupUpdateAuthorityInstructionDataArgs,\n UpdateTokenGroupUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n /** Current update authority */\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenGroupUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenGroupUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n /** Current update authority */\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupUpdateAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getTokenMetadataFieldDecoder,\n getTokenMetadataFieldEncoder,\n type TokenMetadataField,\n type TokenMetadataFieldArgs,\n} from '../types';\n\nexport const UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR = new Uint8Array([\n 221, 233, 49, 45, 181, 202, 220, 200,\n]);\n\nexport function getUpdateTokenMetadataFieldDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR);\n}\n\nexport type UpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataFieldInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Field to update in the metadata. */\n field: TokenMetadataField;\n /** Value to write for the field. */\n value: string;\n};\n\nexport type UpdateTokenMetadataFieldInstructionDataArgs = {\n /** Field to update in the metadata. */\n field: TokenMetadataFieldArgs;\n /** Value to write for the field. */\n value: string;\n};\n\nexport function getUpdateTokenMetadataFieldInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['field', getTokenMetadataFieldEncoder()],\n ['value', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['field', getTokenMetadataFieldDecoder()],\n ['value', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataCodec(): Codec<\n UpdateTokenMetadataFieldInstructionDataArgs,\n UpdateTokenMetadataFieldInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataFieldInstructionDataEncoder(),\n getUpdateTokenMetadataFieldInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataFieldInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n field: UpdateTokenMetadataFieldInstructionDataArgs['field'];\n value: UpdateTokenMetadataFieldInstructionDataArgs['value'];\n};\n\nexport function getUpdateTokenMetadataFieldInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataFieldInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataFieldInstructionDataEncoder().encode(\n args as UpdateTokenMetadataFieldInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataFieldInstructionData;\n};\n\nexport function parseUpdateTokenMetadataFieldInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataFieldInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataFieldInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR =\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]);\n\nexport function getUpdateTokenMetadataUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionDataArgs = {\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenMetadataUpdateAuthorityInstructionDataArgs,\n UpdateTokenMetadataUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenMetadataUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenMetadataUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getUpdateTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 1;\n\nexport function getUpdateTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type UpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type UpdateTransferHookInstructionDataArgs = {\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getUpdateTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTransferHookInstructionDataCodec(): FixedSizeCodec<\n UpdateTransferHookInstructionDataArgs,\n UpdateTransferHookInstructionData\n> {\n return combineCodec(\n getUpdateTransferHookInstructionDataEncoder(),\n getUpdateTransferHookInstructionDataDecoder()\n );\n}\n\nexport type UpdateTransferHookInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The transfer hook authority. */\n authority: Address | TransactionSigner;\n programId: UpdateTransferHookInstructionDataArgs['programId'];\n multiSigners?: Array;\n};\n\nexport function getUpdateTransferHookInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateTransferHookInstructionDataEncoder().encode(\n args as UpdateTransferHookInstructionDataArgs\n ),\n programAddress,\n } as UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The transfer hook authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateTransferHookInstructionData;\n};\n\nexport function parseUpdateTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTransferHookInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR = 38;\n\nexport function getWithdrawExcessLamportsDiscriminatorBytes() {\n return getU8Encoder().encode(WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR);\n}\n\nexport type WithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceAccount extends string | AccountMeta = string,\n TAccountDestinationAccount extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceAccount extends string\n ? WritableAccount\n : TAccountSourceAccount,\n TAccountDestinationAccount extends string\n ? WritableAccount\n : TAccountDestinationAccount,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawExcessLamportsInstructionData = { discriminator: number };\n\nexport type WithdrawExcessLamportsInstructionDataArgs = {};\n\nexport function getWithdrawExcessLamportsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawExcessLamportsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getWithdrawExcessLamportsInstructionDataCodec(): FixedSizeCodec<\n WithdrawExcessLamportsInstructionDataArgs,\n WithdrawExcessLamportsInstructionData\n> {\n return combineCodec(\n getWithdrawExcessLamportsInstructionDataEncoder(),\n getWithdrawExcessLamportsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawExcessLamportsInput<\n TAccountSourceAccount extends string = string,\n TAccountDestinationAccount extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** Account holding excess lamports. */\n sourceAccount: Address;\n /** Destination account for withdrawn lamports. */\n destinationAccount: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawExcessLamportsInstruction<\n TAccountSourceAccount extends string,\n TAccountDestinationAccount extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawExcessLamportsInput<\n TAccountSourceAccount,\n TAccountDestinationAccount,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceAccount: { value: input.sourceAccount ?? null, isWritable: true },\n destinationAccount: {\n value: input.destinationAccount ?? null,\n isWritable: true,\n },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceAccount),\n getAccountMeta(accounts.destinationAccount),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawExcessLamportsInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Account holding excess lamports. */\n sourceAccount: TAccountMetas[0];\n /** Destination account for withdrawn lamports. */\n destinationAccount: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: WithdrawExcessLamportsInstructionData;\n};\n\nexport function parseWithdrawExcessLamportsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawExcessLamportsInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceAccount: getNextAccount(),\n destinationAccount: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawExcessLamportsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromAccountsDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getWithdrawWithheldTokensFromAccountsTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport type WithdrawWithheldTokensFromAccountsInstructionDataArgs = {\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsInstructionDataArgs['numTokenAccounts'];\n multiSigners?: Array;\n sources: Array
;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = [\n ...(args.multiSigners ?? []).map((signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })),\n ...args.sources.map((address) => ({ address, role: AccountRole.WRITABLE })),\n ];\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromAccountsInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['numTokenAccounts'];\n proofInstructionOffset: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type WithdrawWithheldTokensFromMintInstructionDataArgs = {};\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintInstructionDataArgs,\n WithdrawWithheldTokensFromMintInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromMintInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account if proof is read from record */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n proofInstructionOffset: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account if proof is read from record */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","import {\n type GetAccountInfoApi,\n type Rpc,\n Address,\n UnixTimestamp,\n unwrapOption,\n} from '@solana/kit';\nimport { fetchSysvarClock } from '@solana/sysvars';\nimport { fetchMint } from './generated';\n\n// Constants\nconst ONE_IN_BASIS_POINTS = 10000;\nconst SECONDS_PER_YEAR = 60 * 60 * 24 * 365.24;\n\n/**\n * Calculates the exponent for the interest rate formula.\n * @param t1 - The start time in seconds.\n * @param t2 - The end time in seconds.\n * @param r - The interest rate in basis points.\n *\n * @returns The calculated exponent.\n */\nfunction calculateExponentForTimesAndRate(t1: number, t2: number, r: number) {\n const timespan = t2 - t1;\n if (timespan < 0) {\n throw new Error('Invalid timespan: end time before start time');\n }\n\n const numerator = r * timespan;\n const exponent = numerator / (SECONDS_PER_YEAR * ONE_IN_BASIS_POINTS);\n return Math.exp(exponent);\n}\n\n/**\n * Calculates the total scale factor for an interest bearing token by combining two exponential functions:\n * One for the period between initialization and last update using the pre-update average rate,\n * and another for the period between last update and current time using the current rate.\n *\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points before last update\n * @param currentRate Current interest rate in basis points\n *\n * @returns The total scale factor as a product of the two exponential functions\n */\nfunction calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n}: {\n currentTimestamp: number;\n lastUpdateTimestamp: number;\n initializationTimestamp: number;\n preUpdateAverageRate: number;\n currentRate: number;\n}): number {\n // Calculate pre-update exponent\n const preUpdateExp = calculateExponentForTimesAndRate(\n initializationTimestamp,\n lastUpdateTimestamp,\n preUpdateAverageRate\n );\n\n // Calculate post-update exponent\n const postUpdateExp = calculateExponentForTimesAndRate(\n lastUpdateTimestamp,\n currentTimestamp,\n currentRate\n );\n\n return preUpdateExp * postUpdateExp;\n}\n\n/**\n * Calculates the decimal factor for a given number of decimals\n * @param decimals - Number of decimals\n * @returns The decimal factor (e.g., 100 for 2 decimals)\n */\nfunction getDecimalFactor(decimals: number): number {\n return Math.pow(10, decimals);\n}\n\n/**\n * Retrieves the current timestamp from the Solana clock sysvar.\n * @param rpc - The Solana rpc object.\n * @returns A promise that resolves to the current timestamp in seconds.\n * @throws An error if the sysvar clock cannot be fetched or parsed.\n */\nasync function getSysvarClockTimestamp(\n rpc: Rpc\n): Promise {\n const info = await fetchSysvarClock(rpc);\n if (!info) {\n throw new Error('Failed to fetch sysvar clock');\n }\n return info.unixTimestamp;\n}\n\n// ========== INTEREST BEARING MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with interest bearing extension without simulating a transaction\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n * In general to calculate compounding interest over a period of time, the formula is:\n * A = P * e^(r * t) where\n * A = final amount after interest\n * P = principal amount (initial investment)\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n * e = mathematical constant (~2.718)\n *\n * In this case, we are calculating the total scale factor for the interest bearing extension which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 and r2 are the interest rates before and after the last update, and t1 and t2 are the times in years between\n * the initialization timestamp and the last update timestamp, and between the last update timestamp and the current timestamp.\n *\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (1 basis point = 0.01%) before last update\n * @param currentRate Current interest rate in basis points\n *\n * @return Amount scaled by accrued interest as a string with appropriate decimal places\n */\nexport function amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): string {\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Scale the amount by the total interest factor\n const scaledAmount = Number(amount) * totalScale;\n const decimalFactor = getDecimalFactor(decimals);\n\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert an amount with interest back to the original amount without interest\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n *\n * @param uiAmount UI Amount (principal plus continuously compounding interest) to be converted back to original principal\n * @param decimals Number of decimals for the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (hundredths of a percent) before the last update\n * @param currentRate Current interest rate in basis points\n *\n * In general to calculate the principal from the UI amount, the formula is:\n * P = A / (e^(r * t)) where\n * P = principal\n * A = UI amount\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n *\n * In this case, we are calculating the principal by dividing the UI amount by the total scale factor which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 is the pre-update average rate, r2 is the current rate, t1 is the time in years between the initialization timestamp and the last update timestamp,\n * and t2 is the time in years between the last update timestamp and the current timestamp.\n * then to calculate the principal, we divide the UI amount by the total scale factor:\n * P = A / totalScale\n *\n * @return Original amount (principal) without interest\n */\nexport function uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Calculate original principal by dividing the UI amount by the total scale\n const originalPrincipal = uiAmountScaled / totalScale;\n return BigInt(Math.trunc(originalPrincipal));\n}\n\n// ========== SCALED UI AMOUNT MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with scaled UI amount extension\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param multiplier Multiplier to scale the amount\n * @return Scaled UI amount as a string\n */\nexport function amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n multiplier: number\n): string {\n const scaledAmount = Number(amount) * multiplier;\n const decimalFactor = getDecimalFactor(decimals);\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert a UI amount back to the raw amount for a mint with a scaled UI amount extension\n * @param uiAmount UI Amount to be converted back to raw amount\n * @param decimals Number of decimals for the mint\n * @param multiplier Multiplier for the scaled UI amount\n *\n * @return Raw amount\n */\nexport function uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n multiplier: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n const rawAmount = uiAmountScaled / multiplier;\n return BigInt(Math.trunc(rawAmount));\n}\n\n// ========== MAIN ENTRY POINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint without simulating a transaction\n * This implements the same logic as `process_amount_to_ui_amount` in\n * solana-labs/solana-program-library/token/program-2022/src/processor.rs\n * and `process_amount_to_ui_amount` in solana-labs/solana-program-library/token/program/src/processor.rs\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param amount Amount of tokens to be converted to Ui Amount\n *\n * @return Ui Amount generated\n */\nexport async function amountToUiAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n amount: bigint\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const amountNumber = Number(amount);\n const decimalsFactor = getDecimalFactor(accountInfo.data.decimals);\n return (amountNumber / decimalsFactor).toString();\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n\n/**\n * Convert a UI amount back to the raw amount\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param uiAmount UI Amount to be converted back to raw amount\n *\n * @return Raw amount\n */\nexport async function uiAmountToAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n uiAmount: string\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const uiAmountScaled =\n parseFloat(uiAmount) * getDecimalFactor(accountInfo.data.decimals);\n return BigInt(Math.trunc(uiAmountScaled));\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n","import {\n Address,\n Instruction,\n isNone,\n isOption,\n TransactionSigner,\n wrapNullable,\n} from '@solana/kit';\nimport {\n ExtensionArgs,\n getDisableMemoTransfersInstruction,\n getEnableMemoTransfersInstruction,\n getEnableCpiGuardInstruction,\n getDisableCpiGuardInstruction,\n getInitializeConfidentialTransferMintInstruction,\n getInitializeDefaultAccountStateInstruction,\n getInitializeGroupMemberPointerInstruction,\n getInitializeGroupPointerInstruction,\n getInitializeInterestBearingMintInstruction,\n getInitializeMetadataPointerInstruction,\n getInitializeMintCloseAuthorityInstruction,\n getInitializeTokenGroupInstruction,\n getInitializeTokenMetadataInstruction,\n getInitializeTransferFeeConfigInstruction,\n getInitializeNonTransferableMintInstruction,\n getInitializeTransferHookInstruction,\n getInitializePermanentDelegateInstruction,\n getInitializeScaledUiAmountMintInstruction,\n getInitializeConfidentialTransferFeeInstruction,\n getInitializePausableConfigInstruction,\n} from './generated';\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _before_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPreInitializeInstructionsForMintExtensions(\n mint: Address,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'ConfidentialTransferMint':\n return [\n getInitializeConfidentialTransferMintInstruction({\n mint,\n ...extension,\n }),\n ];\n case 'DefaultAccountState':\n return [\n getInitializeDefaultAccountStateInstruction({\n mint,\n state: extension.state,\n }),\n ];\n case 'TransferFeeConfig':\n return [\n getInitializeTransferFeeConfigInstruction({\n mint,\n transferFeeConfigAuthority: extension.transferFeeConfigAuthority,\n withdrawWithheldAuthority: extension.withdrawWithheldAuthority,\n transferFeeBasisPoints:\n extension.newerTransferFee.transferFeeBasisPoints,\n maximumFee: extension.newerTransferFee.maximumFee,\n }),\n ];\n case 'MetadataPointer':\n return [\n getInitializeMetadataPointerInstruction({\n mint,\n authority: extension.authority,\n metadataAddress: extension.metadataAddress,\n }),\n ];\n case 'InterestBearingConfig':\n return [\n getInitializeInterestBearingMintInstruction({\n mint,\n rateAuthority: extension.rateAuthority,\n rate: extension.currentRate,\n }),\n ];\n case 'ScaledUiAmountConfig':\n return [\n getInitializeScaledUiAmountMintInstruction({\n mint,\n authority: extension.authority,\n multiplier: extension.multiplier,\n }),\n ];\n case 'PausableConfig':\n return [\n getInitializePausableConfigInstruction({\n mint,\n authority: extension.authority,\n }),\n ];\n case 'GroupPointer':\n return [\n getInitializeGroupPointerInstruction({\n mint,\n authority: extension.authority,\n groupAddress: extension.groupAddress,\n }),\n ];\n case 'GroupMemberPointer':\n return [\n getInitializeGroupMemberPointerInstruction({\n mint,\n authority: extension.authority,\n memberAddress: extension.memberAddress,\n }),\n ];\n case 'NonTransferable':\n return getInitializeNonTransferableMintInstruction({ mint });\n case 'TransferHook':\n return [\n getInitializeTransferHookInstruction({\n mint,\n authority: extension.authority,\n programId: extension.programId,\n }),\n ];\n case 'PermanentDelegate':\n return getInitializePermanentDelegateInstruction({\n mint,\n delegate: extension.delegate,\n });\n case 'ConfidentialTransferFee':\n return [\n getInitializeConfidentialTransferFeeInstruction({\n mint,\n authority: extension.authority,\n withdrawWithheldAuthorityElGamalPubkey: extension.elgamalPubkey,\n }),\n ];\n case 'MintCloseAuthority':\n return getInitializeMintCloseAuthorityInstruction({\n closeAuthority: extension.closeAuthority,\n mint,\n });\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _after_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPostInitializeInstructionsForMintExtensions(\n mint: Address,\n authority: TransactionSigner,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension): Instruction[] => {\n switch (extension.__kind) {\n case 'TokenMetadata':\n // eslint-disable-next-line no-case-declarations\n const tokenMetadataUpdateAuthority = isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority);\n if (isNone(tokenMetadataUpdateAuthority)) {\n return [];\n }\n return [\n getInitializeTokenMetadataInstruction({\n metadata: mint,\n updateAuthority: tokenMetadataUpdateAuthority.value,\n mint,\n mintAuthority: authority,\n name: extension.name,\n symbol: extension.symbol,\n uri: extension.uri,\n }),\n ];\n case 'TokenGroup':\n return [\n getInitializeTokenGroupInstruction({\n group: mint,\n updateAuthority: isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority),\n mint,\n mintAuthority: authority,\n maxSize: extension.maxSize,\n }),\n ];\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a token address, its owner and a list of token extensions, returns a list\n * of instructions that MUST be run _after_ the `initializeAccount` instruction\n * to properly initialize the given extensions on the token account.\n */\nexport function getPostInitializeInstructionsForTokenExtensions(\n token: Address,\n owner: TransactionSigner | Address,\n extensions: ExtensionArgs[],\n multiSigners?: TransactionSigner[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'MemoTransfer':\n return [\n extension.requireIncomingTransferMemos\n ? getEnableMemoTransfersInstruction({ owner, token, multiSigners })\n : getDisableMemoTransfersInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n case 'CpiGuard':\n return [\n extension.lockCpi\n ? getEnableCpiGuardInstruction({ owner, token, multiSigners })\n : getDisableCpiGuardInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n default:\n return [];\n }\n });\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst TOKEN_BASE_SIZE = 165;\n\nexport function getTokenSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return TOKEN_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n );\n return TOKEN_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n padLeftEncoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst MINT_BASE_SIZE = 82;\n\nexport function getMintSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return MINT_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n );\n return MINT_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","/**\n * Token program addresses for SPL Token and Token-2022\n * These addresses are the same across all Solana networks (mainnet, devnet, testnet)\n */\nexport const TOKEN_PROGRAM_ADDRESS = \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\";\nexport const TOKEN_2022_PROGRAM_ADDRESS = \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\";\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS = \"ComputeBudget111111111111111111111111111111\";\nexport const MEMO_PROGRAM_ADDRESS = \"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\";\n\n/**\n * Phantom/Solflare Lighthouse program address\n * Phantom and Solflare wallets inject Lighthouse instructions for user protection on mainnet transactions.\n * - Phantom adds 1 Lighthouse instruction (4th instruction)\n * - Solflare adds 2 Lighthouse instructions (4th and 5th instructions)\n * We allow these as optional instructions to support these wallets.\n * See: https://github.com/coinbase/x402/issues/828\n */\nexport const LIGHTHOUSE_PROGRAM_ADDRESS = \"L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95\";\n\n/**\n * Default RPC URLs for Solana networks\n */\nexport const DEVNET_RPC_URL = \"https://api.devnet.solana.com\";\nexport const TESTNET_RPC_URL = \"https://api.testnet.solana.com\";\nexport const MAINNET_RPC_URL = \"https://api.mainnet-beta.solana.com\";\nexport const DEVNET_WS_URL = \"wss://api.devnet.solana.com\";\nexport const TESTNET_WS_URL = \"wss://api.testnet.solana.com\";\nexport const MAINNET_WS_URL = \"wss://api.mainnet-beta.solana.com\";\n\n/**\n * USDC token mint addresses (default stablecoin)\n */\nexport const USDC_MAINNET_ADDRESS = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nexport const USDC_DEVNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\";\nexport const USDC_TESTNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\"; // Same as devnet\n\n/**\n * Compute budget configuration\n * All prices are in microlamports (1 lamport = 1,000,000 microlamports)\n */\nexport const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;\nexport const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 5_000_000; // 5 lamports\nexport const DEFAULT_COMPUTE_UNIT_LIMIT = 20_000;\n\n/**\n * How long a transaction is held in the duplicate settlement cache (ms).\n * Covers the Solana blockhash lifetime (~60-90s) with margin.\n */\nexport const SETTLEMENT_TTL_MS = 120_000;\n\n/**\n * Solana address validation regex (base58, 32-44 characters)\n */\nexport const SVM_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * CAIP-2 network identifiers for Solana (V2)\n */\nexport const SOLANA_MAINNET_CAIP2 = \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\";\nexport const SOLANA_DEVNET_CAIP2 = \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\";\nexport const SOLANA_TESTNET_CAIP2 = \"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z\";\n\n/**\n * V1 to V2 network identifier mappings (for backwards compatibility)\n * V1 used simple names like solana, V2 uses CAIP-2\n */\nexport const V1_TO_V2_NETWORK_MAP: Record = {\n solana: SOLANA_MAINNET_CAIP2,\n \"solana-devnet\": SOLANA_DEVNET_CAIP2,\n \"solana-testnet\": SOLANA_TESTNET_CAIP2,\n};\n","import {\n getBase64Encoder,\n getTransactionDecoder,\n getCompiledTransactionMessageDecoder,\n type Transaction,\n createSolanaRpc,\n devnet,\n testnet,\n mainnet,\n type RpcDevnet,\n type SolanaRpcApiDevnet,\n type RpcTestnet,\n type SolanaRpcApiTestnet,\n type RpcMainnet,\n type SolanaRpcApiMainnet,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { TOKEN_2022_PROGRAM_ADDRESS } from \"@solana-program/token-2022\";\nimport type { Network } from \"@x402/core/types\";\nimport {\n SVM_ADDRESS_REGEX,\n DEVNET_RPC_URL,\n TESTNET_RPC_URL,\n MAINNET_RPC_URL,\n USDC_MAINNET_ADDRESS,\n USDC_DEVNET_ADDRESS,\n USDC_TESTNET_ADDRESS,\n SOLANA_MAINNET_CAIP2,\n SOLANA_DEVNET_CAIP2,\n SOLANA_TESTNET_CAIP2,\n V1_TO_V2_NETWORK_MAP,\n} from \"./constants\";\nimport type { ExactSvmPayloadV1 } from \"./types\";\n\n/**\n * Normalize network identifier to CAIP-2 format\n * Handles both V1 names (solana, solana-devnet) and V2 CAIP-2 format\n *\n * @param network - Network identifier (V1 or V2 format)\n * @returns CAIP-2 network identifier\n */\nexport function normalizeNetwork(network: Network): string {\n // If it's already CAIP-2 format (contains \":\"), validate it's supported\n if (network.includes(\":\")) {\n const supported = [SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];\n if (!supported.includes(network)) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return network;\n }\n\n // Otherwise, it's a V1 network name, convert to CAIP-2\n const caip2Network = V1_TO_V2_NETWORK_MAP[network];\n if (!caip2Network) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return caip2Network;\n}\n\n/**\n * Validate Solana address format\n *\n * @param address - Base58 encoded address string\n * @returns true if address is valid, false otherwise\n */\nexport function validateSvmAddress(address: string): boolean {\n return SVM_ADDRESS_REGEX.test(address);\n}\n\n/**\n * Decode a base64 encoded transaction from an SVM payload\n *\n * @param svmPayload - The SVM payload containing a base64 encoded transaction\n * @returns Decoded Transaction object\n */\nexport function decodeTransactionFromPayload(svmPayload: ExactSvmPayloadV1): Transaction {\n try {\n const base64Encoder = getBase64Encoder();\n const transactionBytes = base64Encoder.encode(svmPayload.transaction);\n const transactionDecoder = getTransactionDecoder();\n return transactionDecoder.decode(transactionBytes);\n } catch (error) {\n console.error(\"Error decoding transaction:\", error);\n throw new Error(\"invalid_exact_svm_payload_transaction\");\n }\n}\n\n/**\n * Extract the token sender (owner of the source token account) from a TransferChecked instruction\n *\n * @param transaction - The decoded transaction\n * @returns The token payer address as a base58 string\n */\nexport function getTokenPayerFromTransaction(transaction: Transaction): string {\n const compiled = getCompiledTransactionMessageDecoder().decode(transaction.messageBytes);\n const staticAccounts = compiled.staticAccounts ?? [];\n const instructions = compiled.instructions ?? [];\n\n for (const ix of instructions) {\n const programIndex = ix.programAddressIndex;\n const programAddress = staticAccounts[programIndex].toString();\n\n // Check if this is a token program instruction\n if (\n programAddress === TOKEN_PROGRAM_ADDRESS.toString() ||\n programAddress === TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n const accountIndices: number[] = ix.accountIndices ?? [];\n // TransferChecked account order: [source, mint, destination, owner, ...]\n if (accountIndices.length >= 4) {\n const ownerIndex = accountIndices[3];\n const ownerAddress = staticAccounts[ownerIndex].toString();\n if (ownerAddress) return ownerAddress;\n }\n }\n }\n\n return \"\";\n}\n\n/**\n * Create an RPC client for the specified network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @param customRpcUrl - Optional custom RPC URL\n * @returns RPC client for the specified network\n */\nexport function createRpcClient(\n network: Network,\n customRpcUrl?: string,\n):\n | RpcDevnet\n | RpcTestnet\n | RpcMainnet {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_DEVNET_CAIP2: {\n const url = customRpcUrl || DEVNET_RPC_URL;\n return createSolanaRpc(devnet(url)) as RpcDevnet;\n }\n case SOLANA_TESTNET_CAIP2: {\n const url = customRpcUrl || TESTNET_RPC_URL;\n return createSolanaRpc(testnet(url)) as RpcTestnet;\n }\n case SOLANA_MAINNET_CAIP2: {\n const url = customRpcUrl || MAINNET_RPC_URL;\n return createSolanaRpc(mainnet(url)) as RpcMainnet;\n }\n default:\n throw new Error(`Unsupported network: ${network}`);\n }\n}\n\n/**\n * Get the default USDC mint address for a network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @returns USDC mint address for the network\n */\nexport function getUsdcAddress(network: Network): string {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_MAINNET_CAIP2:\n return USDC_MAINNET_ADDRESS;\n case SOLANA_DEVNET_CAIP2:\n return USDC_DEVNET_ADDRESS;\n case SOLANA_TESTNET_CAIP2:\n return USDC_TESTNET_ADDRESS;\n default:\n throw new Error(`No USDC address configured for network: ${network}`);\n }\n}\n\n/**\n * Convert a decimal amount to token smallest units\n *\n * @param decimalAmount - The decimal amount (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n const amount = parseFloat(decimalAmount);\n if (isNaN(amount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n // Convert to smallest unit (e.g., for USDC with 6 decimals: 0.10 * 10^6 = 100000)\n const [intPart, decPart = \"\"] = String(amount).split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n return tokenAmount;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedRequestHeapFrameInstruction,\n type ParsedRequestUnitsInstruction,\n type ParsedSetComputeUnitLimitInstruction,\n type ParsedSetComputeUnitPriceInstruction,\n type ParsedSetLoadedAccountsDataSizeLimitInstruction,\n} from '../instructions';\n\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS =\n 'ComputeBudget111111111111111111111111111111' as Address<'ComputeBudget111111111111111111111111111111'>;\n\nexport enum ComputeBudgetInstruction {\n RequestUnits,\n RequestHeapFrame,\n SetComputeUnitLimit,\n SetComputeUnitPrice,\n SetLoadedAccountsDataSizeLimit,\n}\n\nexport function identifyComputeBudgetInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ComputeBudgetInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return ComputeBudgetInstruction.RequestUnits;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return ComputeBudgetInstruction.RequestHeapFrame;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitLimit;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitPrice;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n }\n throw new Error(\n 'The provided instruction could not be identified as a computeBudget instruction.'\n );\n}\n\nexport type ParsedComputeBudgetInstruction<\n TProgram extends string = 'ComputeBudget111111111111111111111111111111',\n> =\n | ({\n instructionType: ComputeBudgetInstruction.RequestUnits;\n } & ParsedRequestUnitsInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.RequestHeapFrame;\n } & ParsedRequestHeapFrameInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitLimit;\n } & ParsedSetComputeUnitLimitInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitPrice;\n } & ParsedSetComputeUnitPriceInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n } & ParsedSetLoadedAccountsDataSizeLimitInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_HEAP_FRAME_DISCRIMINATOR = 1;\n\nexport function getRequestHeapFrameDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_HEAP_FRAME_DISCRIMINATOR);\n}\n\nexport type RequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestHeapFrameInstructionData = {\n discriminator: number;\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport type RequestHeapFrameInstructionDataArgs = {\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport function getRequestHeapFrameInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['bytes', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_HEAP_FRAME_DISCRIMINATOR })\n );\n}\n\nexport function getRequestHeapFrameInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['bytes', getU32Decoder()],\n ]);\n}\n\nexport function getRequestHeapFrameInstructionDataCodec(): FixedSizeCodec<\n RequestHeapFrameInstructionDataArgs,\n RequestHeapFrameInstructionData\n> {\n return combineCodec(\n getRequestHeapFrameInstructionDataEncoder(),\n getRequestHeapFrameInstructionDataDecoder()\n );\n}\n\nexport type RequestHeapFrameInput = {\n bytes: RequestHeapFrameInstructionDataArgs['bytes'];\n};\n\nexport function getRequestHeapFrameInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestHeapFrameInput,\n config?: { programAddress?: TProgramAddress }\n): RequestHeapFrameInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestHeapFrameInstructionDataEncoder().encode(\n args as RequestHeapFrameInstructionDataArgs\n ),\n programAddress,\n } as RequestHeapFrameInstruction);\n}\n\nexport type ParsedRequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: RequestHeapFrameInstructionData;\n};\n\nexport function parseRequestHeapFrameInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestHeapFrameInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestHeapFrameInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_UNITS_DISCRIMINATOR = 0;\n\nexport function getRequestUnitsDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_UNITS_DISCRIMINATOR);\n}\n\nexport type RequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestUnitsInstructionData = {\n discriminator: number;\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport type RequestUnitsInstructionDataArgs = {\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport function getRequestUnitsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ['additionalFee', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_UNITS_DISCRIMINATOR })\n );\n}\n\nexport function getRequestUnitsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ['additionalFee', getU32Decoder()],\n ]);\n}\n\nexport function getRequestUnitsInstructionDataCodec(): FixedSizeCodec<\n RequestUnitsInstructionDataArgs,\n RequestUnitsInstructionData\n> {\n return combineCodec(\n getRequestUnitsInstructionDataEncoder(),\n getRequestUnitsInstructionDataDecoder()\n );\n}\n\nexport type RequestUnitsInput = {\n units: RequestUnitsInstructionDataArgs['units'];\n additionalFee: RequestUnitsInstructionDataArgs['additionalFee'];\n};\n\nexport function getRequestUnitsInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestUnitsInput,\n config?: { programAddress?: TProgramAddress }\n): RequestUnitsInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestUnitsInstructionDataEncoder().encode(\n args as RequestUnitsInstructionDataArgs\n ),\n programAddress,\n } as RequestUnitsInstruction);\n}\n\nexport type ParsedRequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = { programAddress: Address; data: RequestUnitsInstructionData };\n\nexport function parseRequestUnitsInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestUnitsInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestUnitsInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR = 2;\n\nexport function getSetComputeUnitLimitDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitLimitInstructionData = {\n discriminator: number;\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport type SetComputeUnitLimitInstructionDataArgs = {\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport function getSetComputeUnitLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitLimitInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitLimitInstructionDataArgs,\n SetComputeUnitLimitInstructionData\n> {\n return combineCodec(\n getSetComputeUnitLimitInstructionDataEncoder(),\n getSetComputeUnitLimitInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitLimitInput = {\n units: SetComputeUnitLimitInstructionDataArgs['units'];\n};\n\nexport function getSetComputeUnitLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitLimitInstructionDataEncoder().encode(\n args as SetComputeUnitLimitInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitLimitInstruction);\n}\n\nexport type ParsedSetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitLimitInstructionData;\n};\n\nexport function parseSetComputeUnitLimitInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR = 3;\n\nexport function getSetComputeUnitPriceDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitPriceInstructionData = {\n discriminator: number;\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: bigint;\n};\n\nexport type SetComputeUnitPriceInstructionDataArgs = {\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: number | bigint;\n};\n\nexport function getSetComputeUnitPriceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['microLamports', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitPriceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['microLamports', getU64Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitPriceInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitPriceInstructionDataArgs,\n SetComputeUnitPriceInstructionData\n> {\n return combineCodec(\n getSetComputeUnitPriceInstructionDataEncoder(),\n getSetComputeUnitPriceInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitPriceInput = {\n microLamports: SetComputeUnitPriceInstructionDataArgs['microLamports'];\n};\n\nexport function getSetComputeUnitPriceInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitPriceInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitPriceInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitPriceInstructionDataEncoder().encode(\n args as SetComputeUnitPriceInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitPriceInstruction);\n}\n\nexport type ParsedSetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitPriceInstructionData;\n};\n\nexport function parseSetComputeUnitPriceInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitPriceInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitPriceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR = 4;\n\nexport function getSetLoadedAccountsDataSizeLimitDiscriminatorBytes() {\n return getU8Encoder().encode(\n SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetLoadedAccountsDataSizeLimitInstructionData = {\n discriminator: number;\n accountDataSizeLimit: number;\n};\n\nexport type SetLoadedAccountsDataSizeLimitInstructionDataArgs = {\n accountDataSizeLimit: number;\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['accountDataSizeLimit', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['accountDataSizeLimit', getU32Decoder()],\n ]);\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataCodec(): FixedSizeCodec<\n SetLoadedAccountsDataSizeLimitInstructionDataArgs,\n SetLoadedAccountsDataSizeLimitInstructionData\n> {\n return combineCodec(\n getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(),\n getSetLoadedAccountsDataSizeLimitInstructionDataDecoder()\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInput = {\n accountDataSizeLimit: SetLoadedAccountsDataSizeLimitInstructionDataArgs['accountDataSizeLimit'];\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetLoadedAccountsDataSizeLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetLoadedAccountsDataSizeLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetLoadedAccountsDataSizeLimitInstructionDataEncoder().encode(\n args as SetLoadedAccountsDataSizeLimitInstructionDataArgs\n ),\n programAddress,\n } as SetLoadedAccountsDataSizeLimitInstruction);\n}\n\nexport type ParsedSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetLoadedAccountsDataSizeLimitInstructionData;\n};\n\nexport function parseSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string,\n>(\n instruction: Instruction & InstructionWithData\n): ParsedSetLoadedAccountsDataSizeLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetLoadedAccountsDataSizeLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * A provisory compute unit limit is used to indicate that the transaction\n * should be estimated for compute units before being sent to the network.\n *\n * Setting it to zero ensures the transaction fails unless it is properly estimated.\n */\nexport const PROVISORY_COMPUTE_UNIT_LIMIT = 0;\n\n/**\n * The maximum compute unit limit that can be set for a transaction.\n */\nexport const MAX_COMPUTE_UNIT_LIMIT = 1_400_000;\n","import {\n BaseTransactionMessage,\n getU32Decoder,\n getU64Decoder,\n Instruction,\n MicroLamports,\n ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n COMPUTE_BUDGET_PROGRAM_ADDRESS,\n ComputeBudgetInstruction,\n identifyComputeBudgetInstruction,\n SetComputeUnitLimitInstruction,\n SetComputeUnitPriceInstruction,\n} from './generated';\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message\n * and its set limit, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndexAndUnits(\n transactionMessage: BaseTransactionMessage\n): { index: number; units: number } | null {\n const index = getSetComputeUnitLimitInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const units = getU32Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n );\n\n return { index, units };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitLimitInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitLimit` instruction.\n */\nexport function isSetComputeUnitLimitInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitLimitInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitLimit\n );\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message\n * and its set micro-lamports, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndexAndMicroLamports(\n transactionMessage: BaseTransactionMessage\n): { index: number; microLamports: MicroLamports } | null {\n const index = getSetComputeUnitPriceInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const microLamports = getU64Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n ) as MicroLamports;\n\n return { index, microLamports };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitPriceInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitPrice` instruction.\n */\nexport function isSetComputeUnitPriceInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitPriceInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitPrice\n );\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n} from '@solana/kit';\nimport { PROVISORY_COMPUTE_UNIT_LIMIT } from './constants';\nimport { getSetComputeUnitLimitInstruction } from './generated';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\n\n/**\n * Appends a `SetComputeUnitLimit` instruction with a provisory\n * compute unit limit to a given transaction message\n * if and only if it does not already have one.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * fillProvisorySetComputeUnitLimitInstruction,\n * // ...\n * );\n * ```\n */\nexport function fillProvisorySetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(transactionMessage: TTransactionMessage) {\n return updateOrAppendSetComputeUnitLimitInstruction(\n (previousUnits) =>\n previousUnits === null ? PROVISORY_COMPUTE_UNIT_LIMIT : previousUnits,\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitLimit` instruction in a transaction message\n * with the given units, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param units - The new compute unit limit, or a function that takes the previous\n * compute unit limit and returns the new limit.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitLimitInstruction(\n * // E.g. Keep the current limit if it is set, otherwise set it to the maximum.\n * (currentUnits) => currentUnits === null ? MAX_COMPUTE_UNIT_LIMIT : currentUnits,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n units: number | ((previousUnits: number | null) => number),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getUnits = (previousUnits: number | null): number =>\n typeof units === 'function' ? units(previousUnits) : units;\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: getUnits(null) }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, units: previousUnits } = instructionDetails;\n const newUnits = getUnits(previousUnits);\n if (newUnits === previousUnits) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitLimitInstruction({ units: newUnits });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport {\n MAX_COMPUTE_UNIT_LIMIT,\n PROVISORY_COMPUTE_UNIT_LIMIT,\n} from './constants';\nimport {\n EstimateComputeUnitLimitFactoryFunction,\n EstimateComputeUnitLimitFactoryFunctionConfig,\n} from './estimateComputeLimitInternal';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\n\ntype EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction = <\n TTransactionMessage extends BaseTransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\n/**\n * Given a transaction message, if it does not have an explicit compute unit limit,\n * estimates the compute unit limit and updates the transaction message with\n * the estimated limit. Otherwise, returns the transaction message unchanged.\n *\n * It requires a function that estimates the compute unit limit.\n *\n * @example\n * ```ts\n * const estimateAndUpdateCUs = estimateAndUpdateProvisoryComputeUnitLimitFactory(\n * estimateComputeUnitLimitFactory({ rpc })\n * );\n *\n * const transactionMessageWithCUs = await estimateAndUpdateCUs(transactionMessage);\n * ```\n *\n * @see {@link estimateAndUpdateProvisoryComputeUnitLimitFactory}\n */\nexport function estimateAndUpdateProvisoryComputeUnitLimitFactory(\n estimateComputeUnitLimit: EstimateComputeUnitLimitFactoryFunction\n): EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction {\n return async function fn(transactionMessage, config) {\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n // If the transaction message already has a compute unit limit instruction\n // which is set to a specific value — i.e. not 0 or the maximum limit —\n // we don't need to estimate the compute unit limit.\n if (\n instructionDetails &&\n instructionDetails.units !== PROVISORY_COMPUTE_UNIT_LIMIT &&\n instructionDetails.units !== MAX_COMPUTE_UNIT_LIMIT\n ) {\n return transactionMessage;\n }\n\n return updateOrAppendSetComputeUnitLimitInstruction(\n await estimateComputeUnitLimit(transactionMessage, config),\n transactionMessage\n );\n };\n}\n","import {\n BaseTransactionMessage,\n Commitment,\n compileTransaction,\n getBase64EncodedWireTransaction,\n isSolanaError,\n isTransactionMessageWithDurableNonceLifetime,\n pipe,\n Rpc,\n SimulateTransactionApi,\n Slot,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaError,\n Transaction,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\nimport { MAX_COMPUTE_UNIT_LIMIT } from './constants';\n\nexport type EstimateComputeUnitLimitFactoryConfig = Readonly<{\n /** An object that supports the {@link SimulateTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}>;\n\nexport type EstimateComputeUnitLimitFactoryFunction = (\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\nexport type EstimateComputeUnitLimitFactoryFunctionConfig = {\n abortSignal?: AbortSignal;\n /**\n * Compute the estimate as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\ntype EstimateComputeUnitLimitConfig =\n EstimateComputeUnitLimitFactoryFunctionConfig &\n Readonly<{\n rpc: Rpc;\n transactionMessage: BaseTransactionMessage &\n TransactionMessageWithFeePayer;\n }>;\n\n/**\n * Simulates a transaction message on the network and returns the number of compute units it\n * consumed during simulation.\n *\n * The estimate this function returns can be used to set a compute unit limit on the transaction.\n * Correctly budgeting a compute unit limit for your transaction message can increase the probability\n * that your transaction will be accepted for processing.\n *\n * If you don't declare a compute unit limit on your transaction, validators will assume an upper\n * limit of 200K compute units (CU) per instruction. Since validators have an incentive to pack as\n * many transactions into each block as possible, they may choose to include transactions that they\n * know will fit into the remaining compute budget for the current block over transactions that\n * might not. For this reason, you should set a compute unit limit on each of your transaction\n * messages, whenever possible.\n *\n * ## Example\n *\n * ```ts\n * import { getSetComputeLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const getComputeUnitEstimateForTransactionMessage =\n * getComputeUnitEstimateForTransactionMessageFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume.\n * const computeUnitsEstimate =\n * await getComputeUnitEstimateForTransactionMessage(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeLimitInstruction({ units: computeUnitsEstimate }),\n * transactionMessage,\n * );\n * ```\n *\n * > [!WARNING]\n * > The compute unit estimate is just that – an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n */\nexport async function estimateComputeUnitLimit({\n transactionMessage,\n ...configs\n}: EstimateComputeUnitLimitConfig): Promise {\n const replaceRecentBlockhash =\n !isTransactionMessageWithDurableNonceLifetime(transactionMessage);\n const transaction = pipe(\n transactionMessage,\n (m) =>\n updateOrAppendSetComputeUnitLimitInstruction(MAX_COMPUTE_UNIT_LIMIT, m),\n compileTransaction\n );\n\n return await simulateTransactionAndGetConsumedUnits({\n transaction,\n replaceRecentBlockhash,\n ...configs,\n });\n}\n\ntype SimulateTransactionAndGetConsumedUnitsConfig = Omit<\n EstimateComputeUnitLimitConfig,\n 'transactionMessage'\n> &\n Readonly<{ replaceRecentBlockhash?: boolean; transaction: Transaction }>;\n\nasync function simulateTransactionAndGetConsumedUnits({\n abortSignal,\n rpc,\n transaction,\n ...simulateConfig\n}: SimulateTransactionAndGetConsumedUnitsConfig): Promise {\n const wireTransactionBytes = getBase64EncodedWireTransaction(transaction);\n\n try {\n const {\n value: { err: transactionError, unitsConsumed },\n } = await rpc\n .simulateTransaction(wireTransactionBytes, {\n ...simulateConfig,\n encoding: 'base64',\n sigVerify: false,\n })\n .send({ abortSignal });\n if (unitsConsumed == null) {\n // This should never be hit, because all RPCs should support `unitsConsumed` by now.\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n );\n }\n // FIXME(https://github.com/anza-xyz/agave/issues/1295): The simulation response returns\n // compute units as a u64, but the `SetComputeLimit` instruction only accepts a u32. Until\n // this changes, downcast it.\n const downcastUnitsConsumed =\n unitsConsumed > 4_294_967_295n ? 4_294_967_295 : Number(unitsConsumed);\n if (transactionError) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n {\n cause: transactionError,\n unitsConsumed: downcastUnitsConsumed,\n }\n );\n }\n return downcastUnitsConsumed;\n } catch (e) {\n if (\n isSolanaError(\n e,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n )\n )\n throw e;\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n { cause: e }\n );\n }\n}\n","import {\n estimateComputeUnitLimit,\n EstimateComputeUnitLimitFactoryConfig,\n EstimateComputeUnitLimitFactoryFunction,\n} from './estimateComputeLimitInternal';\n\n/**\n * Use this utility to estimate the actual compute unit cost of a given transaction message.\n *\n * Correctly budgeting a compute unit limit for your transaction message can increase the\n * probability that your transaction will be accepted for processing. If you don't declare a compute\n * unit limit on your transaction, validators will assume an upper limit of 200K compute units (CU)\n * per instruction.\n *\n * Since validators have an incentive to pack as many transactions into each block as possible, they\n * may choose to include transactions that they know will fit into the remaining compute budget for\n * the current block over transactions that might not. For this reason, you should set a compute\n * unit limit on each of your transaction messages, whenever possible.\n *\n * > [!WARNING]\n * > The compute unit estimate is just that -- an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n *\n * > [!INFO]\n * > In the event that a transaction message does not already have a `SetComputeUnitLimit`\n * > instruction, this function will add one before simulation. This ensures that the compute unit\n * > consumption of the `SetComputeUnitLimit` instruction itself is included in the estimate.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, estimateComputeUnitLimitFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const estimateComputeUnitLimit = estimateComputeUnitLimitFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume. This is done by\n * // simulating the transaction and grabbing the estimated compute units from the result.\n * const estimatedUnits = await estimateComputeUnitLimit(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeUnitLimitInstruction({ units: estimatedUnits }),\n * transactionMessage,\n * );\n * ```\n */\nexport function estimateComputeUnitLimitFactory({\n rpc,\n}: EstimateComputeUnitLimitFactoryConfig): EstimateComputeUnitLimitFactoryFunction {\n return async function estimateComputeUnitLimitFactoryFunction(\n transactionMessage,\n config\n ) {\n return await estimateComputeUnitLimit({\n ...config,\n rpc,\n transactionMessage,\n });\n };\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n MicroLamports,\n} from '@solana/kit';\nimport { getSetComputeUnitPriceInstruction } from './generated';\nimport { getSetComputeUnitPriceInstructionIndexAndMicroLamports } from './internal';\n\n/**\n * Sets the compute unit price of a transaction message in micro-Lamports.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * (m) => setTransactionMessageComputeUnitPrice(10_000, m),\n * // ...\n * );\n * ```\n */\nexport function setTransactionMessageComputeUnitPrice<\n TTransactionMessage extends BaseTransactionMessage,\n>(microLamports: number | bigint, transactionMessage: TTransactionMessage) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({ microLamports }),\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitPrice` instruction in a transaction message\n * with the given micro-Lamports, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param microLamports - The new compute unit price, or a function that\n * takes the previous price and returns the new one.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitPriceInstruction(\n * // E.g. double the current price or set it to 10_000 if it isn't set.\n * (currentPrice) => currentPrice === null ? 10_000 : currentPrice * 2,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitPriceInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n microLamports:\n | MicroLamports\n | ((previousMicroLamports: MicroLamports | null) => MicroLamports),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getMicroLamports = (\n previousMicroLamports: MicroLamports | null\n ): MicroLamports =>\n typeof microLamports === 'function'\n ? microLamports(previousMicroLamports)\n : microLamports;\n const instructionDetails =\n getSetComputeUnitPriceInstructionIndexAndMicroLamports(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({\n microLamports: getMicroLamports(null),\n }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, microLamports: previousMicroLamports } = instructionDetails;\n const newMicroLamports = getMicroLamports(previousMicroLamports);\n if (newMicroLamports === previousMicroLamports) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitPriceInstruction({\n microLamports: newMicroLamports,\n });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../signer\";\nimport type { ExactSvmPayloadV2 } from \"../../types\";\nimport { createRpcClient } from \"../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme.\n */\nexport class ExactSvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClient instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClient instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise> {\n const rpc = createRpcClient(paymentRequirements.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, paymentRequirements.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: paymentRequirements.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: paymentRequirements.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(paymentRequirements.amount),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = paymentRequirements.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV2 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n}\n","/**\n * V1 exports for the SVM mechanism\n */\nexport { ExactSvmSchemeV1 } from \"../exact/v1\";\n\nexport const NETWORKS: string[] = [\"solana\", \"solana-devnet\", \"solana-testnet\"];\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport type { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../../signer\";\nimport type { ExactSvmPayloadV1 } from \"../../../types\";\nimport { createRpcClient } from \"../../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactSvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClientV1 instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClientV1 instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const rpc = createRpcClient(selectedV1.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, selectedV1.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: selectedV1.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: selectedV1.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(selectedV1.maxAmountRequired),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = selectedV1.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV1 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientSvmSigner } from \"../../signer\";\nimport { ExactSvmScheme } from \"./scheme\";\nimport { ExactSvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering SVM schemes to an x402Client\n */\nexport interface SvmClientConfig {\n /**\n * The SVM signer to use for creating payment payloads\n */\n signer: ClientSvmSigner;\n\n /**\n * Optional payment requirements selector function\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional specific networks to register\n */\n networks?: Network[];\n}\n\n/**\n * Registers SVM payment schemes to an existing x402Client instance.\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for SVM client registration\n * @returns The client instance for chaining\n */\nexport function registerExactSvmScheme(client: x402Client, config: SvmClientConfig): x402Client {\n // Register V2 scheme\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach(network => {\n client.register(network, new ExactSvmScheme(config.signer));\n });\n } else {\n client.register(\"solana:*\", new ExactSvmScheme(config.signer));\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactSvmSchemeV1(config.signer));\n });\n\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * Local x402 Proxy Server\n *\n * Sits between OpenClaw's pi-ai (which makes standard OpenAI-format requests)\n * and BlockRun's API (which requires x402 micropayments).\n *\n * Flow:\n * pi-ai → http://localhost:{port}/v1/chat/completions\n * → proxy forwards to https://blockrun.ai/api/v1/chat/completions\n * → gets 402 → @x402/fetch signs payment → retries\n * → streams response back to pi-ai\n *\n * Optimizations (v0.3.0):\n * - SSE heartbeat: for streaming requests, sends headers + heartbeat immediately\n * before the x402 flow, preventing OpenClaw's 10-15s timeout from firing.\n * - Response dedup: hashes request bodies and caches responses for 30s,\n * preventing double-charging when OpenClaw retries after timeout.\n * - Smart routing: when model is \"blockrun/auto\", classify query and pick cheapest model.\n * - Usage logging: log every request as JSON line to ~/.openclaw/blockrun/logs/\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\n\n// Per-request payment tracking via AsyncLocalStorage (safe for concurrent requests).\n// The x402 onAfterPaymentCreation hook writes the actual payment amount into the\n// request-scoped store, and the logging code reads it after payFetch completes.\nconst paymentStore = new AsyncLocalStorage<{ amountUsd: number; amountUsdText: string }>();\nimport { finished } from \"node:stream\";\nimport type { AddressInfo } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdir, writeFile, readFile, stat as fsStat } from \"node:fs/promises\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { createPublicClient, http } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { x402Client } from \"@x402/fetch\";\nimport { createPayFetchWithPreAuth } from \"./payment-preauth.js\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { toClientEvmSigner } from \"@x402/evm\";\nimport {\n route,\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n DEFAULT_ROUTING_CONFIG,\n type RouterOptions,\n type RoutingDecision,\n type RoutingConfig,\n type ModelPricing,\n type Tier,\n} from \"./router/index.js\";\nimport { classifyByRules } from \"./router/rules.js\";\nimport {\n BLOCKRUN_MODELS,\n OPENCLAW_MODELS,\n resolveModelAlias,\n getModelContextWindow,\n isReasoningModel,\n supportsToolCalling,\n supportsVision,\n} from \"./models.js\";\nimport { logUsage, type UsageEntry } from \"./logger.js\";\nimport { getStats, clearStats } from \"./stats.js\";\nimport { RequestDeduplicator } from \"./dedup.js\";\nimport { ResponseCache, type ResponseCacheConfig } from \"./response-cache.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport type { SolanaBalanceMonitor } from \"./solana-balance.js\";\nimport {\n DEFAULT_BASE_PAYMENT_ASSET,\n fetchBasePaymentAssets,\n type BasePaymentAsset,\n} from \"./payment-asset.js\";\n\n/** Union type for chain-agnostic balance monitoring */\ntype AnyBalanceMonitor = BalanceMonitor | SolanaBalanceMonitor;\nimport { resolvePaymentChain } from \"./auth.js\";\nimport { compressContext, shouldCompress, type NormalizedMessage } from \"./compression/index.js\";\n// Error classes available for programmatic use but not used in proxy\n// (universal free fallback means we don't throw balance errors anymore)\n// import { InsufficientFundsError, EmptyWalletError } from \"./errors.js\";\nimport { USER_AGENT, VERSION } from \"./version.js\";\nimport {\n SessionStore,\n getSessionId,\n deriveSessionId,\n hashRequestContent,\n type SessionConfig,\n} from \"./session.js\";\nimport { checkForUpdates } from \"./updater.js\";\nimport { loadExcludeList } from \"./exclude-models.js\";\nimport { PROXY_PORT } from \"./config.js\";\nimport { SessionJournal } from \"./journal.js\";\n\nconst BLOCKRUN_API = \"https://blockrun.ai/api\";\nconst BLOCKRUN_SOLANA_API = \"https://sol.blockrun.ai/api\";\nconst IMAGE_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"images\");\n// Routing profile models - virtual models that trigger intelligent routing\nconst AUTO_MODEL = \"blockrun/auto\";\n\nconst ROUTING_PROFILES = new Set([\n \"blockrun/eco\",\n \"eco\",\n \"blockrun/auto\",\n \"auto\",\n \"blockrun/premium\",\n \"premium\",\n]);\nconst FREE_MODEL = \"free/gpt-oss-120b\"; // Last-resort single free model fallback\nconst FREE_MODELS = new Set([\n \"free/gpt-oss-120b\",\n \"free/gpt-oss-20b\",\n \"free/nemotron-ultra-253b\",\n \"free/nemotron-3-super-120b\",\n \"free/nemotron-super-49b\",\n \"free/deepseek-v3.2\",\n \"free/mistral-large-3-675b\",\n \"free/qwen3-coder-480b\",\n \"free/devstral-2-123b\",\n \"free/glm-4.7\",\n \"free/llama-4-maverick\",\n]);\n/**\n * Map free/xxx model IDs to nvidia/xxx for upstream BlockRun API.\n * The \"free/\" prefix is a ClawRouter convention for the /model picker;\n * BlockRun server expects \"nvidia/\" prefix.\n */\nfunction toUpstreamModelId(modelId: string): string {\n if (modelId.startsWith(\"free/\")) {\n return \"nvidia/\" + modelId.slice(\"free/\".length);\n }\n return modelId;\n}\nconst MAX_MESSAGES = 200; // BlockRun API limit - truncate older messages if exceeded\nconst CONTEXT_LIMIT_KB = 5120; // Server-side limit: 5MB in KB\nconst HEARTBEAT_INTERVAL_MS = 2_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 180_000; // 3 minutes (allows for on-chain tx + LLM response)\nconst PER_MODEL_TIMEOUT_MS = 60_000; // 60s per individual model attempt (fallback to next on exceed)\nconst MAX_FALLBACK_ATTEMPTS = 5; // Maximum models to try in fallback chain (increased from 3 to ensure cheap models are tried)\nconst HEALTH_CHECK_TIMEOUT_MS = 2_000; // Timeout for checking existing proxy\nconst RATE_LIMIT_COOLDOWN_MS = 60_000; // 60 seconds cooldown for rate-limited models\nconst OVERLOAD_COOLDOWN_MS = 15_000; // 15 seconds cooldown for overloaded providers\nconst PORT_RETRY_ATTEMPTS = 5; // Max attempts to bind port (handles TIME_WAIT)\nconst PORT_RETRY_DELAY_MS = 1_000; // Delay between retry attempts\nconst MODEL_BODY_READ_TIMEOUT_MS = 300_000; // 5 minutes for model responses (reasoning models are slow)\nconst ERROR_BODY_READ_TIMEOUT_MS = 30_000; // 30 seconds for error/partner body reads\n\nasync function readBodyWithTimeout(\n body: ReadableStream | null,\n timeoutMs: number = MODEL_BODY_READ_TIMEOUT_MS,\n): Promise {\n if (!body) return [];\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n\n let timer: ReturnType | undefined;\n try {\n while (true) {\n const result = await Promise.race([\n reader.read(),\n new Promise((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"Body read timeout\")), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (result.done) break;\n chunks.push(result.value);\n }\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n\n return chunks;\n}\n\n/**\n * Transform upstream payment errors into user-friendly messages.\n * Parses the raw x402 error and formats it nicely.\n */\nfunction transformPaymentError(\n errorBody: string,\n opts?: { baseAssetSymbol?: string; baseAssetDecimals?: number },\n): string {\n const baseAssetSymbol = opts?.baseAssetSymbol || DEFAULT_BASE_PAYMENT_ASSET.symbol;\n const baseAssetDecimals = opts?.baseAssetDecimals ?? DEFAULT_BASE_PAYMENT_ASSET.decimals;\n const formatRawAssetAmount = (amountRaw: bigint, decimals: number): string => {\n const divisor = 10n ** BigInt(decimals);\n const whole = amountRaw / divisor;\n const remainder = amountRaw % divisor;\n const scaledFraction = decimals >= 6\n ? remainder / 10n ** BigInt(decimals - 6)\n : remainder * 10n ** BigInt(6 - decimals);\n return `${whole.toString()}.${scaledFraction.toString().padStart(6, \"0\")}`;\n };\n try {\n // Try to parse the error JSON\n const parsed = JSON.parse(errorBody) as {\n error?: string;\n details?: string;\n // blockrun-sol (Solana) format uses code+debug instead of details\n code?: string;\n debug?: string;\n payer?: string;\n };\n\n // Check if this is a payment verification error\n if (parsed.error === \"Payment verification failed\" && parsed.details) {\n // Extract the nested JSON from details\n // Format: \"Verification failed: {json}\\n\"\n const match = parsed.details.match(/Verification failed:\\s*(\\{.*\\})/s);\n if (match) {\n const innerJson = JSON.parse(match[1]) as {\n invalidMessage?: string;\n invalidReason?: string;\n payer?: string;\n };\n\n if (innerJson.invalidReason === \"insufficient_funds\" && innerJson.invalidMessage) {\n // Parse \"insufficient balance: 251 < 11463\"\n const balanceMatch = innerJson.invalidMessage.match(\n /insufficient balance:\\s*(\\d+)\\s*<\\s*(\\d+)/i,\n );\n if (balanceMatch) {\n const currentRaw = BigInt(balanceMatch[1]);\n const requiredRaw = BigInt(balanceMatch[2]);\n const currentUSD = formatRawAssetAmount(currentRaw, baseAssetDecimals);\n const requiredUSD = formatRawAssetAmount(requiredRaw, baseAssetDecimals);\n const wallet = innerJson.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n return JSON.stringify({\n error: {\n message: `Insufficient ${baseAssetSymbol} balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,\n type: \"insufficient_funds\",\n wallet: wallet,\n current_balance_usd: currentUSD,\n required_usd: requiredUSD,\n help: `Fund wallet ${shortWallet} with ${baseAssetSymbol} on Base, or use free model: /model free`,\n },\n });\n }\n }\n\n // Handle invalid_payload errors (signature issues, malformed payment)\n if (innerJson.invalidReason === \"invalid_payload\") {\n return JSON.stringify({\n error: {\n message: \"Payment signature invalid. This may be a temporary issue.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n // Handle transaction simulation failures (Solana on-chain validation)\n if (innerJson.invalidReason === \"transaction_simulation_failed\") {\n console.error(\n `[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage || \"unknown\"}`,\n );\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, check your Solana USDC balance or try: /model free\",\n },\n });\n }\n }\n }\n\n // Handle blockrun-sol (Solana) format: code=PAYMENT_INVALID + debug=invalidReason string\n if (\n parsed.error === \"Payment verification failed\" &&\n parsed.code === \"PAYMENT_INVALID\" &&\n parsed.debug\n ) {\n const debugLower = parsed.debug.toLowerCase();\n const wallet = parsed.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n if (debugLower.includes(\"insufficient\")) {\n return JSON.stringify({\n error: {\n message: \"Insufficient Solana USDC balance.\",\n type: \"insufficient_funds\",\n wallet,\n help: `Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base`,\n },\n });\n }\n\n if (\n debugLower.includes(\"transaction_simulation_failed\") ||\n debugLower.includes(\"simulation\")\n ) {\n console.error(`[ClawRouter] Solana transaction simulation failed: ${parsed.debug}`);\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n\n if (debugLower.includes(\"invalid signature\") || debugLower.includes(\"invalid_signature\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment signature invalid.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n if (debugLower.includes(\"expired\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment expired. Retrying.\",\n type: \"expired\",\n help: \"This is usually temporary.\",\n },\n });\n }\n\n // Unknown Solana verification error — surface the debug reason\n console.error(\n `[ClawRouter] Solana payment verification failed: ${parsed.debug} payer=${wallet}`,\n );\n return JSON.stringify({\n error: {\n message: `Solana payment verification failed: ${parsed.debug}`,\n type: \"payment_invalid\",\n wallet,\n help: \"Try again or switch to Base: /wallet base\",\n },\n });\n }\n\n // Handle settlement failures (gas estimation, on-chain errors)\n if (\n parsed.error === \"Settlement failed\" ||\n parsed.error === \"Payment settlement failed\" ||\n parsed.details?.includes(\"Settlement failed\") ||\n parsed.details?.includes(\"transaction_simulation_failed\")\n ) {\n const details = parsed.details || \"\";\n const gasError = details.includes(\"unable to estimate gas\");\n\n return JSON.stringify({\n error: {\n message: gasError\n ? \"Payment failed: network congestion or gas issue. Try again.\"\n : \"Payment settlement failed. Try again in a moment.\",\n type: \"settlement_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n } catch {\n // If parsing fails, return original\n }\n return errorBody;\n}\n\nfunction formatStableAmount(amountRaw: bigint, decimals: number): string {\n const divisor = 10n ** BigInt(decimals);\n const whole = amountRaw / divisor;\n const remainder = amountRaw % divisor;\n const scaledFraction =\n decimals >= 6\n ? remainder / 10n ** BigInt(decimals - 6)\n : remainder * 10n ** BigInt(6 - decimals);\n return `${whole.toString()}.${scaledFraction.toString().padStart(6, \"0\")}`;\n}\n\n/**\n * Semantic error categories from upstream provider responses.\n * Used to distinguish auth failures from rate limits from server errors\n * so each category can be handled independently without cross-contamination.\n */\nexport type ErrorCategory =\n | \"auth_failure\" // 401, 403: Wrong key or forbidden — don't retry with same key\n | \"quota_exceeded\" // 403 with plan/quota body: Plan limit hit\n | \"rate_limited\" // 429: Actual throttling — 60s cooldown\n | \"overloaded\" // 529, 503+overload body: Provider capacity — 15s cooldown\n | \"server_error\" // 5xx general: Transient — fallback immediately\n | \"payment_error\" // 402: x402 payment or funds issue\n | \"config_error\"; // 400, 413: Bad request content — skip this model\n\n/**\n * Classify an upstream error response into a semantic category.\n * Returns null if the status+body is not a provider-side issue worth retrying.\n */\nexport function categorizeError(status: number, body: string): ErrorCategory | null {\n if (status === 401) return \"auth_failure\";\n if (status === 402) return \"payment_error\";\n if (status === 403) {\n if (/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)) return \"quota_exceeded\";\n return \"auth_failure\"; // generic 403 = forbidden = likely auth issue\n }\n if (status === 429) return \"rate_limited\";\n if (status === 529) return \"overloaded\";\n if (status === 503 && /overload|capacity|too.*many.*request/i.test(body)) return \"overloaded\";\n if (status >= 500) return \"server_error\";\n if (status === 400 || status === 413) {\n // Only fallback on content-size or billing patterns; bare 400 = our bug, don't cycle\n if (PROVIDER_ERROR_PATTERNS.some((p) => p.test(body))) return \"config_error\";\n return null;\n }\n return null;\n}\n\n/**\n * Track rate-limited models to avoid hitting them again.\n * Maps model ID to the timestamp when the rate limit was hit.\n */\nconst rateLimitedModels = new Map();\n\n/** Per-model overload tracking (529/503 capacity errors) — shorter cooldown than rate limits. */\nconst overloadedModels = new Map();\n\n/** Per-model error category counts (in-memory, resets on restart). */\ntype ProviderErrorCounts = {\n auth_failure: number;\n quota_exceeded: number;\n rate_limited: number;\n overloaded: number;\n server_error: number;\n payment_error: number;\n config_error: number;\n};\nconst perProviderErrors = new Map();\n\n/** Record an error category hit for a model. */\nfunction recordProviderError(modelId: string, category: ErrorCategory): void {\n if (!perProviderErrors.has(modelId)) {\n perProviderErrors.set(modelId, {\n auth_failure: 0,\n quota_exceeded: 0,\n rate_limited: 0,\n overloaded: 0,\n server_error: 0,\n payment_error: 0,\n config_error: 0,\n });\n }\n perProviderErrors.get(modelId)![category]++;\n}\n\n/**\n * Check if a model is currently rate-limited (in cooldown period).\n */\nfunction isRateLimited(modelId: string): boolean {\n const hitTime = rateLimitedModels.get(modelId);\n if (!hitTime) return false;\n\n const elapsed = Date.now() - hitTime;\n if (elapsed >= RATE_LIMIT_COOLDOWN_MS) {\n rateLimitedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Mark a model as rate-limited.\n */\nfunction markRateLimited(modelId: string): void {\n rateLimitedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`);\n}\n\n/**\n * Mark a model as temporarily overloaded (529/503 capacity).\n * Shorter cooldown than rate limits since capacity restores quickly.\n */\nfunction markOverloaded(modelId: string): void {\n overloadedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`);\n}\n\n/** Check if a model is in its overload cooldown period. */\nfunction isOverloaded(modelId: string): boolean {\n const hitTime = overloadedModels.get(modelId);\n if (!hitTime) return false;\n if (Date.now() - hitTime >= OVERLOAD_COOLDOWN_MS) {\n overloadedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Reorder models to put rate-limited ones at the end.\n */\nfunction prioritizeNonRateLimited(models: string[]): string[] {\n const available: string[] = [];\n const degraded: string[] = [];\n\n for (const model of models) {\n if (isRateLimited(model) || isOverloaded(model)) {\n degraded.push(model);\n } else {\n available.push(model);\n }\n }\n\n return [...available, ...degraded];\n}\n\n/**\n * Check if response socket is writable (prevents write-after-close errors).\n * Returns true only if all conditions are safe for writing.\n */\nfunction canWrite(res: ServerResponse): boolean {\n return (\n !res.writableEnded &&\n !res.destroyed &&\n res.socket !== null &&\n !res.socket.destroyed &&\n res.socket.writable\n );\n}\n\n/**\n * Safe write with backpressure handling.\n * Returns true if write succeeded, false if socket is closed or write failed.\n */\nfunction safeWrite(res: ServerResponse, data: string | Buffer): boolean {\n if (!canWrite(res)) {\n const bytes = typeof data === \"string\" ? Buffer.byteLength(data) : data.length;\n console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`);\n return false;\n }\n return res.write(data);\n}\n\n// Extra buffer for balance check (on top of estimateAmount's 20% buffer)\n// Total effective buffer: 1.2 * 1.5 = 1.8x (80% safety margin)\n// This prevents x402 payment failures after streaming headers are sent,\n// which would trigger OpenClaw's 5-24 hour billing cooldown.\nconst BALANCE_CHECK_BUFFER = 1.5;\n\n/**\n * Get the proxy port from pre-loaded configuration.\n * Port is validated at module load time, this just returns the cached value.\n */\nexport function getProxyPort(): number {\n return PROXY_PORT;\n}\n\n/**\n * Check if a proxy is already running on the given port.\n * Returns the wallet address if running, undefined otherwise.\n */\nasync function checkExistingProxy(\n port: number,\n): Promise<\n | {\n wallet: string;\n paymentChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n }\n | undefined\n> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);\n\n try {\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const data = (await response.json()) as {\n status?: string;\n wallet?: string;\n paymentChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n paymentAsset?: string;\n paymentAssetSymbol?: string;\n paymentAssetDecimals?: number;\n };\n if (data.status === \"ok\" && data.wallet) {\n return {\n wallet: data.wallet,\n paymentChain: data.paymentChain,\n paymentAssets: data.paymentAssets,\n selectedPaymentAsset: data.selectedPaymentAsset ?? data.paymentAsset,\n };\n }\n }\n return undefined;\n } catch {\n clearTimeout(timeoutId);\n return undefined;\n }\n}\n\n/**\n * Error patterns that indicate a provider-side issue (not user's fault).\n * These errors should trigger fallback to the next model in the chain.\n */\nconst PROVIDER_ERROR_PATTERNS = [\n /billing/i,\n /insufficient.*balance/i,\n /credits/i,\n /quota.*exceeded/i,\n /rate.*limit/i,\n /model.*unavailable/i,\n /model.*not.*available/i,\n /service.*unavailable/i,\n /capacity/i,\n /overloaded/i,\n /temporarily.*unavailable/i,\n /api.*key.*invalid/i,\n /authentication.*failed/i,\n /request too large/i,\n /request.*size.*exceeds/i,\n /payload too large/i,\n /payment.*verification.*failed/i,\n /model.*not.*allowed/i,\n /unknown.*model/i,\n];\n\n/**\n * \"Successful\" response bodies that are actually provider degradation placeholders.\n * Some upstream providers occasionally return these with HTTP 200.\n */\nconst DEGRADED_RESPONSE_PATTERNS = [\n /the ai service is temporarily overloaded/i,\n /service is temporarily overloaded/i,\n /please try again in a moment/i,\n];\n\n/**\n * Known low-quality loop signatures seen during provider degradation windows.\n */\nconst DEGRADED_LOOP_PATTERNS = [\n /the boxed is the response\\./i,\n /the response is the text\\./i,\n /the final answer is the boxed\\./i,\n];\n\nfunction extractAssistantContent(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") return undefined;\n const record = payload as Record;\n const choices = record.choices;\n if (!Array.isArray(choices) || choices.length === 0) return undefined;\n\n const firstChoice = choices[0];\n if (!firstChoice || typeof firstChoice !== \"object\") return undefined;\n const choice = firstChoice as Record;\n const message = choice.message;\n if (!message || typeof message !== \"object\") return undefined;\n const content = (message as Record).content;\n return typeof content === \"string\" ? content : undefined;\n}\n\nfunction hasKnownLoopSignature(text: string): boolean {\n const matchCount = DEGRADED_LOOP_PATTERNS.reduce(\n (count, pattern) => (pattern.test(text) ? count + 1 : count),\n 0,\n );\n if (matchCount >= 2) return true;\n\n // Generic repetitive loop fallback for short repeated lines.\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n if (lines.length < 8) return false;\n\n const counts = new Map();\n for (const line of lines) {\n counts.set(line, (counts.get(line) ?? 0) + 1);\n }\n\n const maxRepeat = Math.max(...counts.values());\n const uniqueRatio = counts.size / lines.length;\n return maxRepeat >= 3 && uniqueRatio <= 0.45;\n}\n\n/**\n * Detect degraded 200-response payloads that should trigger model fallback.\n * Returns a short reason when fallback should happen, otherwise undefined.\n */\nexport function detectDegradedSuccessResponse(body: string): string | undefined {\n const trimmed = body.trim();\n if (!trimmed) return undefined;\n\n // Plain-text placeholder response.\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(trimmed))) {\n return \"degraded response: overloaded placeholder\";\n }\n\n // Plain-text looping garbage response.\n if (hasKnownLoopSignature(trimmed)) {\n return \"degraded response: repetitive loop output\";\n }\n\n try {\n const parsed = JSON.parse(trimmed) as Record;\n\n // Some providers return JSON error payloads with HTTP 200.\n const errorField = parsed.error;\n let errorText = \"\";\n if (typeof errorField === \"string\") {\n errorText = errorField;\n } else if (errorField && typeof errorField === \"object\") {\n const errObj = errorField as Record;\n errorText = [\n typeof errObj.message === \"string\" ? errObj.message : \"\",\n typeof errObj.type === \"string\" ? errObj.type : \"\",\n typeof errObj.code === \"string\" ? errObj.code : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n }\n if (errorText && PROVIDER_ERROR_PATTERNS.some((pattern) => pattern.test(errorText))) {\n return `degraded response: ${errorText.slice(0, 120)}`;\n }\n\n // Successful wrapper with bad assistant content.\n const assistantContent = extractAssistantContent(parsed);\n if (!assistantContent) return undefined;\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(assistantContent))) {\n return \"degraded response: overloaded assistant content\";\n }\n if (hasKnownLoopSignature(assistantContent)) {\n return \"degraded response: repetitive assistant loop\";\n }\n } catch {\n // Not JSON - handled by plaintext checks above.\n }\n\n return undefined;\n}\n\n/**\n * Valid message roles for OpenAI-compatible APIs.\n * Some clients send non-standard roles (e.g., \"developer\" instead of \"system\").\n */\nconst VALID_ROLES = new Set([\"system\", \"user\", \"assistant\", \"tool\", \"function\"]);\n\n/**\n * Role mappings for non-standard roles.\n * Maps client-specific roles to standard OpenAI roles.\n */\nconst ROLE_MAPPINGS: Record = {\n developer: \"system\", // OpenAI's newer API uses \"developer\" for system messages\n model: \"assistant\", // Some APIs use \"model\" instead of \"assistant\"\n};\n\ntype ChatMessage = { role: string; content: string | unknown };\n\n/**\n * Anthropic tool ID pattern: only alphanumeric, underscore, and hyphen allowed.\n * Error: \"messages.X.content.Y.tool_use.id: String should match pattern '^[a-zA-Z0-9_-]+$'\"\n */\nconst VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\n/**\n * Sanitize a tool ID to match Anthropic's required pattern.\n * Replaces invalid characters with underscores.\n */\nfunction sanitizeToolId(id: string | undefined): string | undefined {\n if (!id || typeof id !== \"string\") return id;\n if (VALID_TOOL_ID_PATTERN.test(id)) return id;\n\n // Replace invalid characters with underscores\n return id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n}\n\n/**\n * Type for messages with tool calls (OpenAI format).\n */\ntype MessageWithTools = ChatMessage & {\n tool_calls?: Array<{ id?: string; type?: string; function?: unknown }>;\n tool_call_id?: string;\n};\n\n/**\n * Type for content blocks that may contain tool IDs (Anthropic format in OpenAI wrapper).\n */\ntype ContentBlock = {\n type?: string;\n id?: string;\n tool_use_id?: string;\n [key: string]: unknown;\n};\n\n/**\n * Sanitize all tool IDs in messages to match Anthropic's pattern.\n * Handles both OpenAI format (tool_calls, tool_call_id) and content block formats.\n */\nfunction sanitizeToolIds(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const sanitized = messages.map((msg) => {\n const typedMsg = msg as MessageWithTools;\n let msgChanged = false;\n let newMsg = { ...msg } as MessageWithTools;\n\n // Sanitize tool_calls[].id in assistant messages\n if (typedMsg.tool_calls && Array.isArray(typedMsg.tool_calls)) {\n const newToolCalls = typedMsg.tool_calls.map((tc) => {\n if (tc.id && typeof tc.id === \"string\") {\n const sanitized = sanitizeToolId(tc.id);\n if (sanitized !== tc.id) {\n msgChanged = true;\n return { ...tc, id: sanitized };\n }\n }\n return tc;\n });\n if (msgChanged) {\n newMsg = { ...newMsg, tool_calls: newToolCalls };\n }\n }\n\n // Sanitize tool_call_id in tool messages\n if (typedMsg.tool_call_id && typeof typedMsg.tool_call_id === \"string\") {\n const sanitized = sanitizeToolId(typedMsg.tool_call_id);\n if (sanitized !== typedMsg.tool_call_id) {\n msgChanged = true;\n newMsg = { ...newMsg, tool_call_id: sanitized };\n }\n }\n\n // Sanitize content blocks if content is an array (Anthropic-style content)\n if (Array.isArray(typedMsg.content)) {\n const newContent = (typedMsg.content as ContentBlock[]).map((block) => {\n if (!block || typeof block !== \"object\") return block;\n\n let blockChanged = false;\n let newBlock = { ...block };\n\n // tool_use blocks have \"id\"\n if (block.type === \"tool_use\" && block.id && typeof block.id === \"string\") {\n const sanitized = sanitizeToolId(block.id);\n if (sanitized !== block.id) {\n blockChanged = true;\n newBlock = { ...newBlock, id: sanitized };\n }\n }\n\n // tool_result blocks have \"tool_use_id\"\n if (\n block.type === \"tool_result\" &&\n block.tool_use_id &&\n typeof block.tool_use_id === \"string\"\n ) {\n const sanitized = sanitizeToolId(block.tool_use_id);\n if (sanitized !== block.tool_use_id) {\n blockChanged = true;\n newBlock = { ...newBlock, tool_use_id: sanitized };\n }\n }\n\n if (blockChanged) {\n msgChanged = true;\n return newBlock;\n }\n return block;\n });\n\n if (msgChanged) {\n newMsg = { ...newMsg, content: newContent };\n }\n }\n\n if (msgChanged) {\n hasChanges = true;\n return newMsg;\n }\n return msg;\n });\n\n return hasChanges ? sanitized : messages;\n}\n\n/**\n * Normalize message roles to standard OpenAI format.\n * Converts non-standard roles (e.g., \"developer\") to valid ones.\n */\nfunction normalizeMessageRoles(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n if (VALID_ROLES.has(msg.role)) return msg;\n\n const mappedRole = ROLE_MAPPINGS[msg.role];\n if (mappedRole) {\n hasChanges = true;\n return { ...msg, role: mappedRole };\n }\n\n // Unknown role - default to \"user\" to avoid API errors\n hasChanges = true;\n return { ...msg, role: \"user\" };\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Normalize messages for Google models.\n * Google's Gemini API requires the first non-system message to be from \"user\".\n * If conversation starts with \"assistant\"/\"model\", prepend a placeholder user message.\n */\n\nfunction normalizeMessagesForGoogle(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n // Find first non-system message\n let firstNonSystemIdx = -1;\n for (let i = 0; i < messages.length; i++) {\n if (messages[i].role !== \"system\") {\n firstNonSystemIdx = i;\n break;\n }\n }\n\n // If no non-system messages, return as-is\n if (firstNonSystemIdx === -1) return messages;\n\n const firstRole = messages[firstNonSystemIdx].role;\n\n // If first non-system message is already \"user\", no change needed\n if (firstRole === \"user\") return messages;\n\n // If first non-system message is \"assistant\" or \"model\", prepend a user message\n if (firstRole === \"assistant\" || firstRole === \"model\") {\n const normalized = [...messages];\n normalized.splice(firstNonSystemIdx, 0, {\n role: \"user\",\n content: \"(continuing conversation)\",\n });\n return normalized;\n }\n\n return messages;\n}\n\n/**\n * Check if a model is a Google model that requires message normalization.\n */\nfunction isGoogleModel(modelId: string): boolean {\n return modelId.startsWith(\"google/\") || modelId.startsWith(\"gemini\");\n}\n\n/**\n * Extended message type for thinking-enabled conversations.\n */\ntype ExtendedChatMessage = ChatMessage & {\n tool_calls?: unknown[];\n reasoning_content?: unknown;\n};\n\n/**\n * Normalize messages for thinking-enabled requests.\n * When thinking/extended_thinking is enabled, assistant messages with tool_calls\n * must have reasoning_content (can be empty string if not present).\n * Error: \"400 thinking is enabled but reasoning_content is missing in assistant tool call message\"\n */\nfunction normalizeMessagesForThinking(messages: ExtendedChatMessage[]): ExtendedChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n // Skip if not assistant or already has reasoning_content\n if (msg.role !== \"assistant\" || msg.reasoning_content !== undefined) {\n return msg;\n }\n\n // Check for OpenAI format: tool_calls array\n const hasOpenAIToolCalls =\n msg.tool_calls && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;\n\n // Check for Anthropic format: content array with tool_use blocks\n const hasAnthropicToolUse =\n Array.isArray(msg.content) &&\n (msg.content as Array<{ type?: string }>).some((block) => block?.type === \"tool_use\");\n\n if (hasOpenAIToolCalls || hasAnthropicToolUse) {\n hasChanges = true;\n return { ...msg, reasoning_content: \"\" };\n }\n return msg;\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Remove \"blockrun\" branding from system messages before sending upstream.\n *\n * OpenClaw embeds `model=blockrun/auto` and `default_model=blockrun/auto` in its\n * system prompt Runtime section. LLMs pick up \"blockrun\" and adopt it as their\n * identity (e.g. \"I'm Blockrun\"), overriding the user's SOUL.md persona.\n *\n * This function replaces `blockrun/` references with the actual resolved\n * model name, and strips any remaining \"blockrun/\" prefix so the upstream LLM\n * never sees \"blockrun\" as an identity to adopt.\n */\nexport function debrandSystemMessages(\n messages: ChatMessage[],\n resolvedModel: string,\n): ChatMessage[] {\n // Routing profile names that get replaced with the actual model\n const PROFILE_NAMES = [\"auto\", \"free\", \"eco\", \"premium\"];\n const profilePattern = new RegExp(`\\\\bblockrun/(${PROFILE_NAMES.join(\"|\")})\\\\b`, \"gi\");\n // Also handle \"blockrun//\" → \"/\"\n const prefixPattern = /\\bblockrun\\/(?=[a-z])/gi;\n\n let hasChanges = false;\n const result = messages.map((msg) => {\n if (msg.role !== \"system\" || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n\n // Replace routing profiles (blockrun/auto etc.) with resolved model\n const afterProfiles = content.replace(profilePattern, resolvedModel);\n\n // Replace remaining blockrun/ prefix (e.g. blockrun/openai/gpt-4o → openai/gpt-4o)\n const afterPrefix = afterProfiles.replace(prefixPattern, \"\");\n\n if (afterPrefix !== content) {\n hasChanges = true;\n content = afterPrefix;\n }\n\n return content !== msg.content ? { ...msg, content } : msg;\n });\n\n return hasChanges ? result : messages;\n}\n\n/**\n * Result of truncating messages.\n */\ntype TruncationResult = {\n messages: T[];\n wasTruncated: boolean;\n originalCount: number;\n truncatedCount: number;\n};\n\n/**\n * Truncate messages to stay under BlockRun's MAX_MESSAGES limit.\n * Keeps all system messages and the most recent conversation history.\n * Returns the messages and whether truncation occurred.\n */\nfunction truncateMessages(messages: T[]): TruncationResult {\n if (!messages || messages.length <= MAX_MESSAGES) {\n return {\n messages,\n wasTruncated: false,\n originalCount: messages?.length ?? 0,\n truncatedCount: messages?.length ?? 0,\n };\n }\n\n // Separate system messages from conversation\n const systemMsgs = messages.filter((m) => m.role === \"system\");\n const conversationMsgs = messages.filter((m) => m.role !== \"system\");\n\n // Keep all system messages + most recent conversation messages\n const maxConversation = MAX_MESSAGES - systemMsgs.length;\n const truncatedConversation = conversationMsgs.slice(-maxConversation);\n\n const result = [...systemMsgs, ...truncatedConversation];\n\n console.log(\n `[ClawRouter] Truncated messages: ${messages.length} → ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`,\n );\n\n return {\n messages: result,\n wasTruncated: true,\n originalCount: messages.length,\n truncatedCount: result.length,\n };\n}\n\n// Kimi/Moonshot models use special Unicode tokens for thinking boundaries.\n// Pattern: <|begin▁of▁thinking|>content<|end▁of▁thinking|>\n// The | is fullwidth vertical bar (U+FF5C), ▁ is lower one-eighth block (U+2581).\n\n// Match full Kimi thinking blocks: <|begin...|>content<|end...|>\nconst KIMI_BLOCK_RE = /<[||][^<>]*begin[^<>]*[||]>[\\s\\S]*?<[||][^<>]*end[^<>]*[||]>/gi;\n\n// Match standalone Kimi tokens like <|end▁of▁thinking|>\nconst KIMI_TOKEN_RE = /<[||][^<>]*[||]>/g;\n\n// Standard thinking tags that may leak through from various models\nconst THINKING_TAG_RE = /<\\s*\\/?\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>/gi;\n\n// Full thinking blocks: content\nconst THINKING_BLOCK_RE =\n /<\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>[\\s\\S]*?<\\s*\\/\\s*(?:think(?:ing)?|thought|antthinking)\\s*>/gi;\n\n/**\n * Strip thinking tokens and blocks from model response content.\n * Handles both Kimi-style Unicode tokens and standard XML-style tags.\n *\n * NOTE: DSML tags (<|DSML|...>) are NOT stripped - those are tool calls\n * that should be handled by the API, not hidden from users.\n */\nfunction stripThinkingTokens(content: string): string {\n if (!content) return content;\n // Strip full Kimi thinking blocks first (begin...end with content)\n let cleaned = content.replace(KIMI_BLOCK_RE, \"\");\n // Strip remaining standalone Kimi tokens\n cleaned = cleaned.replace(KIMI_TOKEN_RE, \"\");\n // Strip full thinking blocks (...)\n cleaned = cleaned.replace(THINKING_BLOCK_RE, \"\");\n // Strip remaining standalone thinking tags\n cleaned = cleaned.replace(THINKING_TAG_RE, \"\");\n return cleaned;\n}\n\n/** Callback info for low balance warning */\nexport type LowBalanceInfo = {\n balanceUSD: string;\n walletAddress: string;\n assetSymbol: string;\n};\n\n/** Callback info for insufficient funds error */\nexport type InsufficientFundsInfo = {\n balanceUSD: string;\n requiredUSD: string;\n walletAddress: string;\n assetSymbol: string;\n};\n\n/**\n * Wallet config: either a plain EVM private key string, or the full\n * resolution object from resolveOrGenerateWalletKey() which may include\n * Solana keys. Using the full object prevents callers from accidentally\n * forgetting to forward Solana key bytes.\n */\nexport type WalletConfig = string | { key: string; solanaPrivateKeyBytes?: Uint8Array };\n\nexport type PaymentChain = \"base\" | \"solana\";\n\nexport type ProxyOptions = {\n wallet: WalletConfig;\n apiBase?: string;\n /** Payment chain: \"base\" (default) or \"solana\". Can also be set via CLAWROUTER_PAYMENT_CHAIN env var. */\n paymentChain?: PaymentChain;\n /** Port to listen on (default: 8402) */\n port?: number;\n routingConfig?: Partial;\n /** Request timeout in ms (default: 180000 = 3 minutes). Covers on-chain tx + LLM response. */\n requestTimeoutMs?: number;\n /** Skip balance checks (for testing only). Default: false */\n skipBalanceCheck?: boolean;\n /** Override the balance monitor with a mock (for testing only). */\n _balanceMonitorOverride?: AnyBalanceMonitor;\n /**\n * Session persistence config. When enabled, maintains model selection\n * across requests within a session to prevent mid-task model switching.\n */\n sessionConfig?: Partial;\n /**\n * Auto-compress large requests to reduce network usage.\n * When enabled, requests are automatically compressed using\n * LLM-safe context compression (15-40% reduction).\n * Default: true\n */\n autoCompressRequests?: boolean;\n /**\n * Threshold in KB to trigger auto-compression (default: 180).\n * Requests larger than this are compressed before sending.\n * Set to 0 to compress all requests.\n */\n compressionThresholdKB?: number;\n /**\n * Response caching config. When enabled, identical requests return\n * cached responses instead of making new API calls.\n * Default: enabled with 10 minute TTL, 200 max entries.\n */\n cacheConfig?: ResponseCacheConfig;\n /**\n * Maximum total spend (in USD) per session run.\n * Default: undefined (no limit). Example: 0.5 = $0.50 per session.\n */\n maxCostPerRunUsd?: number;\n /**\n * How to enforce the per-run cost cap.\n * - 'graceful' (default): when budget runs low, downgrade to cheaper models; use free model\n * as last resort. Only hard-stops when no model can serve the request.\n * - 'strict': immediately return 429 once the session spend reaches the cap.\n */\n maxCostPerRunMode?: \"graceful\" | \"strict\";\n /**\n * Set of model IDs to exclude from routing.\n * Excluded models are filtered out of fallback chains.\n * Loaded from ~/.openclaw/blockrun/exclude-models.json\n */\n excludeModels?: Set;\n onReady?: (port: number) => void;\n onError?: (error: Error) => void;\n onPayment?: (info: { model: string; amount: string; network: string }) => void;\n onRouted?: (decision: RoutingDecision) => void;\n /** Called when balance drops below $1.00 (warning, request still proceeds) */\n onLowBalance?: (info: LowBalanceInfo) => void;\n /** Called when balance is insufficient for a request (request fails) */\n onInsufficientFunds?: (info: InsufficientFundsInfo) => void;\n};\n\nexport type ProxyHandle = {\n port: number;\n baseUrl: string;\n walletAddress: string;\n solanaAddress?: string;\n paymentAsset?: BasePaymentAsset;\n paymentAssets?: BasePaymentAsset[];\n balanceMonitor: AnyBalanceMonitor;\n close: () => Promise;\n};\n\n/**\n * Build model pricing map from BLOCKRUN_MODELS.\n */\nfunction buildModelPricing(): Map {\n const map = new Map();\n for (const m of BLOCKRUN_MODELS) {\n if (m.id === AUTO_MODEL) continue; // skip meta-model\n map.set(m.id, { inputPrice: m.inputPrice, outputPrice: m.outputPrice });\n }\n return map;\n}\n\ntype ModelListEntry = {\n id: string;\n object: \"model\";\n created: number;\n owned_by: string;\n};\n\n/**\n * Build `/v1/models` response entries from the full OpenClaw model registry.\n * This includes alias IDs (e.g., `flash`, `kimi`) so `/model ` works reliably.\n */\nexport function buildProxyModelList(\n createdAt: number = Math.floor(Date.now() / 1000),\n): ModelListEntry[] {\n const seen = new Set();\n return OPENCLAW_MODELS.filter((model) => {\n if (seen.has(model.id)) return false;\n seen.add(model.id);\n return true;\n }).map((model) => ({\n id: model.id,\n object: \"model\",\n created: createdAt,\n owned_by: model.id.includes(\"/\") ? (model.id.split(\"/\")[0] ?? \"blockrun\") : \"blockrun\",\n }));\n}\n\n/**\n * Merge partial routing config overrides with defaults.\n */\nfunction mergeRoutingConfig(overrides?: Partial): RoutingConfig {\n if (!overrides) return DEFAULT_ROUTING_CONFIG;\n return {\n ...DEFAULT_ROUTING_CONFIG,\n ...overrides,\n classifier: { ...DEFAULT_ROUTING_CONFIG.classifier, ...overrides.classifier },\n scoring: { ...DEFAULT_ROUTING_CONFIG.scoring, ...overrides.scoring },\n tiers: { ...DEFAULT_ROUTING_CONFIG.tiers, ...overrides.tiers },\n overrides: { ...DEFAULT_ROUTING_CONFIG.overrides, ...overrides.overrides },\n };\n}\n\n/**\n * Estimate stablecoin cost for a request based on model pricing.\n * Returns amount string in USD micros (6-decimal integer, i.e. 1 = $0.000001) or undefined if unknown.\n * This is an internal unit used for balance checks; conversion to on-chain token units happens elsewhere.\n */\nfunction estimateAmount(\n modelId: string,\n bodyLength: number,\n maxTokens: number,\n): string | undefined {\n const model = BLOCKRUN_MODELS.find((m) => m.id === modelId);\n if (!model) return undefined;\n\n // Rough estimate: ~4 chars per token for input\n const estimatedInputTokens = Math.ceil(bodyLength / 4);\n const estimatedOutputTokens = maxTokens || model.maxOutput || 4096;\n\n const costUsd =\n (estimatedInputTokens / 1_000_000) * model.inputPrice +\n (estimatedOutputTokens / 1_000_000) * model.outputPrice;\n\n // Convert to USD micros (6-decimal integer), add 20% buffer for estimation error\n // Minimum 1000 ($0.001) to match CDP Facilitator's enforced minimum payment\n const amountMicros = Math.max(1000, Math.ceil(costUsd * 1.2 * 1_000_000));\n return amountMicros.toString();\n}\n\n// Image pricing table (must match server's IMAGE_MODELS in blockrun/src/lib/models.ts)\n// Server applies 5% margin on top of these prices.\nconst IMAGE_PRICING: Record }> = {\n \"openai/dall-e-3\": {\n default: 0.04,\n sizes: { \"1024x1024\": 0.04, \"1792x1024\": 0.08, \"1024x1792\": 0.08 },\n },\n \"openai/gpt-image-1\": {\n default: 0.02,\n sizes: { \"1024x1024\": 0.02, \"1536x1024\": 0.04, \"1024x1536\": 0.04 },\n },\n \"black-forest/flux-1.1-pro\": { default: 0.04 },\n \"google/nano-banana\": { default: 0.05 },\n \"google/nano-banana-pro\": {\n default: 0.1,\n sizes: { \"1024x1024\": 0.1, \"2048x2048\": 0.1, \"4096x4096\": 0.15 },\n },\n};\n\n/**\n * Estimate the cost of an image generation/editing request.\n * Matches server-side calculateImagePrice() including 5% margin.\n */\nfunction estimateImageCost(model: string, size?: string, n: number = 1): number {\n const pricing = IMAGE_PRICING[model];\n if (!pricing) return 0.04 * n * 1.05; // fallback: assume $0.04/image + margin\n const sizePrice = size && pricing.sizes ? pricing.sizes[size] : undefined;\n const pricePerImage = sizePrice ?? pricing.default;\n return pricePerImage * n * 1.05; // 5% server margin\n}\n\n/**\n * Proxy a partner API request through x402 payment flow.\n *\n * Simplified proxy for partner endpoints (/v1/x/*, /v1/partner/*).\n * No smart routing, SSE, compression, or sessions — just collect body,\n * forward via payFetch (which handles 402 automatically), and stream back.\n */\nasync function proxyPartnerRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n getActualPaymentUsd: () => number,\n): Promise {\n const startTime = Date.now();\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const body = Buffer.concat(bodyChunks);\n\n // Forward headers (strip hop-by-hop)\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") headers[key] = value;\n }\n if (!headers[\"content-type\"]) headers[\"content-type\"] = \"application/json\";\n headers[\"user-agent\"] = USER_AGENT;\n\n console.log(`[ClawRouter] Partner request: ${req.method} ${req.url}`);\n\n const upstream = await payFetch(upstreamUrl, {\n method: req.method ?? \"POST\",\n headers,\n body: body.length > 0 ? new Uint8Array(body) : undefined,\n });\n\n // Forward response headers\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\") return;\n responseHeaders[key] = value;\n });\n\n res.writeHead(upstream.status, responseHeaders);\n\n // Stream response body\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body, ERROR_BODY_READ_TIMEOUT_MS);\n for (const chunk of chunks) {\n safeWrite(res, Buffer.from(chunk));\n }\n }\n\n res.end();\n\n const latencyMs = Date.now() - startTime;\n console.log(`[ClawRouter] Partner response: ${upstream.status} (${latencyMs}ms)`);\n\n // Log partner usage with actual x402 payment amount (previously logged cost: 0)\n const partnerCost = getActualPaymentUsd();\n logUsage({\n timestamp: new Date().toISOString(),\n model: \"partner\",\n tier: \"PARTNER\",\n cost: partnerCost,\n baselineCost: partnerCost,\n savings: 0,\n latencyMs,\n partnerId:\n (req.url?.split(\"?\")[0] ?? \"\").replace(/^\\/v1\\//, \"\").replace(/\\//g, \"_\") || \"unknown\",\n service: \"partner\",\n }).catch(() => {});\n}\n\n/**\n * Read a local image file and return it as a base64 data URI.\n * Supports ~/ home directory expansion.\n */\nfunction readImageFileAsDataUri(filePath: string): string {\n const resolved = filePath.startsWith(\"~/\") ? join(homedir(), filePath.slice(2)) : filePath;\n\n if (!existsSync(resolved)) {\n throw new Error(`Image file not found: ${resolved}`);\n }\n\n const ext = resolved.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mimeMap: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n };\n const mime = mimeMap[ext] ?? \"image/png\";\n const data = readFileSync(resolved);\n return `data:${mime};base64,${data.toString(\"base64\")}`;\n}\n\n/**\n * Upload a base64 data URI to catbox.moe and return a public URL.\n * Google image models (nano-banana) return data URIs instead of hosted URLs,\n * which breaks Telegram and other clients that can't render raw base64.\n */\nasync function uploadDataUriToHost(dataUri: string): Promise {\n const match = dataUri.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (!match) throw new Error(\"Invalid data URI format\");\n const [, mimeType, b64Data] = match;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType.split(\"/\")[1] ?? \"png\");\n\n const buffer = Buffer.from(b64Data, \"base64\");\n const blob = new Blob([buffer], { type: mimeType });\n\n const form = new FormData();\n form.append(\"reqtype\", \"fileupload\");\n form.append(\"fileToUpload\", blob, `image.${ext}`);\n\n const uploadController = new AbortController();\n const uploadTimeout = setTimeout(() => uploadController.abort(), 30_000);\n try {\n const resp = await fetch(\"https://catbox.moe/user/api.php\", {\n method: \"POST\",\n body: form,\n signal: uploadController.signal,\n });\n\n if (!resp.ok) throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);\n const result = await resp.text();\n if (result.startsWith(\"https://\")) {\n return result.trim();\n }\n throw new Error(`catbox.moe upload failed: ${result}`);\n } finally {\n clearTimeout(uploadTimeout);\n }\n}\n\n/**\n * Start the local x402 proxy server.\n *\n * If a proxy is already running on the target port, reuses it instead of failing.\n * Port can be configured via BLOCKRUN_PROXY_PORT environment variable.\n *\n * Returns a handle with the assigned port, base URL, and a close function.\n */\nexport async function startProxy(options: ProxyOptions): Promise {\n // Normalize wallet config: string = EVM-only, object = full resolution\n const walletKey = typeof options.wallet === \"string\" ? options.wallet : options.wallet.key;\n const solanaPrivateKeyBytes =\n typeof options.wallet === \"string\" ? undefined : options.wallet.solanaPrivateKeyBytes;\n\n // Payment chain: options > env var > persisted file > default \"base\".\n // No dynamic switching — user selects chain via /wallet solana or /wallet base.\n const paymentChain = options.paymentChain ?? (await resolvePaymentChain());\n const apiBase =\n options.apiBase ??\n (paymentChain === \"solana\" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API);\n let activeBasePaymentAssets =\n paymentChain === \"base\"\n ? (await fetchBasePaymentAssets(apiBase).catch(() => undefined)) ?? [DEFAULT_BASE_PAYMENT_ASSET]\n : [DEFAULT_BASE_PAYMENT_ASSET];\n let activeBasePaymentAsset = activeBasePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET;\n let lastSelectedBasePaymentAsset = activeBasePaymentAsset;\n if (paymentChain === \"solana\" && !solanaPrivateKeyBytes) {\n console.warn(\n `[ClawRouter] ⚠ Payment chain is Solana but no mnemonic found — falling back to Base (EVM).`,\n );\n console.warn(\n `[ClawRouter] To fix: run \"npx @blockrun/clawrouter wallet recover\" if your mnemonic exists,`,\n );\n console.warn(`[ClawRouter] or run \"npx @blockrun/clawrouter chain base\" to switch to EVM.`);\n } else if (paymentChain === \"solana\") {\n console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`);\n }\n\n // Determine port: options.port > env var > default\n const listenPort = options.port ?? getProxyPort();\n\n const buildReuseHandle = async (existingProxyData: {\n wallet: string;\n paymentChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n }): Promise => {\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const baseUrl = `http://127.0.0.1:${listenPort}`;\n\n if (existingProxyData.wallet !== account.address) {\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxyData.wallet}, but current config uses ${account.address}. Reusing existing proxy.`,\n );\n }\n\n if (existingProxyData.paymentChain) {\n if (existingProxyData.paymentChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${existingProxyData.paymentChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n } else if (paymentChain !== \"base\") {\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`,\n );\n throw new Error(\n `Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n\n let reuseSolanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n reuseSolanaAddress = solanaSigner.address;\n }\n\n let reuseBalanceMonitor: AnyBalanceMonitor;\n if (paymentChain === \"solana\" && reuseSolanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n reuseBalanceMonitor = new SolanaBalanceMonitor(reuseSolanaAddress);\n } else {\n if (existingProxyData.paymentAssets?.length) {\n activeBasePaymentAssets = existingProxyData.paymentAssets;\n }\n const selectedPaymentAssetId =\n typeof existingProxyData.selectedPaymentAsset === \"string\"\n ? existingProxyData.selectedPaymentAsset.toLowerCase()\n : existingProxyData.selectedPaymentAsset?.asset?.toLowerCase();\n const selectedPaymentAsset = selectedPaymentAssetId\n ? activeBasePaymentAssets.find((asset) => asset.asset.toLowerCase() === selectedPaymentAssetId)\n : undefined;\n if (selectedPaymentAsset) {\n activeBasePaymentAsset = selectedPaymentAsset;\n lastSelectedBasePaymentAsset = selectedPaymentAsset;\n }\n reuseBalanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset);\n }\n\n options.onReady?.(listenPort);\n\n return {\n port: listenPort,\n baseUrl,\n walletAddress: existingProxyData.wallet,\n solanaAddress: reuseSolanaAddress,\n paymentAsset: paymentChain === \"base\" ? activeBasePaymentAsset : undefined,\n paymentAssets: paymentChain === \"base\" ? activeBasePaymentAssets : undefined,\n balanceMonitor: reuseBalanceMonitor,\n close: async () => {\n // No-op: we didn't start this proxy, so we shouldn't close it\n },\n };\n };\n\n // Check if a proxy is already running on this port\n const existingProxy = await checkExistingProxy(listenPort);\n if (existingProxy) {\n return buildReuseHandle(existingProxy);\n }\n\n // Create x402 payment client with EVM scheme (always available)\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const evmPublicClient = createPublicClient({ chain: base, transport: http() });\n const evmSigner = toClientEvmSigner(account, evmPublicClient);\n const x402 = new x402Client();\n registerExactEvmScheme(x402, { signer: evmSigner });\n\n // Register Solana scheme if key is available\n // Uses registerExactSvmScheme helper which registers:\n // - solana:* wildcard (catches any CAIP-2 Solana network)\n // - V1 compat names: \"solana\", \"solana-devnet\", \"solana-testnet\"\n let solanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { registerExactSvmScheme } = await import(\"@x402/svm/exact/client\");\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n solanaAddress = solanaSigner.address;\n registerExactSvmScheme(x402, { signer: solanaSigner });\n console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`);\n }\n\n // Log which chain is used for each payment and capture actual payment amount\n x402.onAfterPaymentCreation(async (context) => {\n const network = context.selectedRequirements.network;\n if (network.startsWith(\"eip155\")) {\n activeBasePaymentAssets =\n (await fetchBasePaymentAssets(apiBase).catch(() => undefined)) ?? activeBasePaymentAssets;\n const refreshedActiveAsset = activeBasePaymentAssets.find(\n (asset) => asset.asset.toLowerCase() === activeBasePaymentAsset.asset.toLowerCase(),\n );\n if (refreshedActiveAsset) {\n activeBasePaymentAsset = refreshedActiveAsset;\n }\n }\n const chain = network.startsWith(\"eip155\")\n ? \"Base (EVM)\"\n : network.startsWith(\"solana\")\n ? \"Solana\"\n : network;\n const amountRaw = BigInt(context.selectedRequirements.amount || \"0\");\n const selectedRequirementsWithDecimals = context.selectedRequirements as { decimals?: number };\n const amountDecimals =\n selectedRequirementsWithDecimals.decimals ??\n (network.startsWith(\"eip155\") ? activeBasePaymentAsset.decimals : 6);\n const amountUsdText = formatStableAmount(amountRaw, amountDecimals);\n const amountUsd = Number.parseFloat(amountUsdText);\n // Write to request-scoped store (if available)\n const store = paymentStore.getStore();\n if (store) {\n store.amountUsd = amountUsd;\n store.amountUsdText = amountUsdText;\n }\n console.log(`[ClawRouter] Payment signed on ${chain} (${network}) — $${amountUsdText}`);\n });\n\n const payFetch = createPayFetchWithPreAuth(fetch, x402, undefined, {\n skipPreAuth: paymentChain === \"solana\",\n });\n\n // Create balance monitor for pre-request checks (lazy import to avoid loading @solana/kit on Base chain)\n let balanceMonitor: AnyBalanceMonitor;\n if (options._balanceMonitorOverride) {\n balanceMonitor = options._balanceMonitorOverride;\n } else if (paymentChain === \"solana\" && solanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n balanceMonitor = new SolanaBalanceMonitor(solanaAddress);\n } else {\n balanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset);\n }\n\n // Build router options (100% local — no external API calls for routing)\n const routingConfig = mergeRoutingConfig(options.routingConfig);\n const modelPricing = buildModelPricing();\n const routerOpts: RouterOptions = {\n config: routingConfig,\n modelPricing,\n };\n\n // Request deduplicator (shared across all requests)\n const deduplicator = new RequestDeduplicator();\n\n // Response cache for identical requests (longer TTL than dedup)\n const responseCache = new ResponseCache(options.cacheConfig);\n\n // Session store for model persistence (prevents mid-task model switching)\n const sessionStore = new SessionStore(options.sessionConfig);\n\n // Session journal for memory (enables agents to recall earlier work)\n const sessionJournal = new SessionJournal();\n\n // Track active connections for graceful cleanup\n const connections = new Set();\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n // Wrap in paymentStore.run() so x402 hook can write actual payment amount per-request\n paymentStore.run({ amountUsd: 0, amountUsdText: \"0.000000\" }, async () => {\n // Add stream error handlers to prevent server crashes\n req.on(\"error\", (err) => {\n console.error(`[ClawRouter] Request stream error: ${err.message}`);\n // Don't throw - just log and let request handler deal with it\n });\n\n res.on(\"error\", (err) => {\n console.error(`[ClawRouter] Response stream error: ${err.message}`);\n // Don't try to write to failed socket - just log\n });\n\n // Finished wrapper for guaranteed cleanup on response completion/error\n finished(res, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Response finished with error: ${err.message}`);\n }\n // Note: heartbeatInterval cleanup happens in res.on(\"close\") handler\n // Note: completed and dedup cleanup happens in the res.on(\"close\") handler below\n });\n\n // Request finished wrapper for complete stream lifecycle tracking\n finished(req, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Request finished with error: ${err.message}`);\n }\n });\n\n // Health check with optional balance info\n if (req.url === \"/health\" || req.url?.startsWith(\"/health?\")) {\n const url = new URL(req.url, \"http://localhost\");\n const full = url.searchParams.get(\"full\") === \"true\";\n\n const response: Record = {\n status: \"ok\",\n wallet: account.address,\n paymentChain,\n };\n if (paymentChain === \"base\") {\n response.paymentAsset = activeBasePaymentAsset.asset;\n response.paymentAssetSymbol = activeBasePaymentAsset.symbol;\n response.paymentAssetDecimals = activeBasePaymentAsset.decimals;\n response.paymentAssets = activeBasePaymentAssets;\n response.selectedPaymentAsset = lastSelectedBasePaymentAsset.asset;\n response.selectedPaymentAssetSymbol = lastSelectedBasePaymentAsset.symbol;\n }\n if (solanaAddress) {\n response.solana = solanaAddress;\n }\n\n if (full) {\n try {\n if (paymentChain === \"base\") {\n const assetBalances = await Promise.all(\n activeBasePaymentAssets.map(async (asset) => {\n const monitor = new BalanceMonitor(account.address, asset);\n const balanceInfo = await monitor.checkBalance();\n return {\n asset: asset.asset,\n symbol: asset.symbol,\n decimals: asset.decimals,\n balance: balanceInfo.balanceUSD,\n isLow: balanceInfo.isLow,\n isEmpty: balanceInfo.isEmpty,\n };\n }),\n );\n response.assetBalances = assetBalances;\n response.balance = assetBalances[0]?.balance ?? \"$0.00\";\n response.isLow = assetBalances[0]?.isLow ?? true;\n response.isEmpty = assetBalances.every((asset) => asset.isEmpty);\n } else {\n const balanceInfo = await balanceMonitor.checkBalance();\n response.balance = balanceInfo.balanceUSD;\n response.isLow = balanceInfo.isLow;\n response.isEmpty = balanceInfo.isEmpty;\n }\n } catch {\n response.balanceError = \"Could not fetch balance\";\n }\n }\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(response));\n return;\n }\n\n // Cache stats endpoint\n if (req.url === \"/cache\" || req.url?.startsWith(\"/cache?\")) {\n const stats = responseCache.getStats();\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(JSON.stringify(stats, null, 2));\n return;\n }\n\n // Stats clear endpoint - delete all log files\n if (req.url === \"/stats\" && req.method === \"DELETE\") {\n try {\n const result = await clearStats();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ cleared: true, deletedFiles: result.deletedFiles }));\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // Stats API endpoint - returns JSON for programmatic access\n if (req.url === \"/stats\" || req.url?.startsWith(\"/stats?\")) {\n try {\n const url = new URL(req.url, \"http://localhost\");\n const days = parseInt(url.searchParams.get(\"days\") || \"7\", 10);\n const stats = await getStats(Math.min(days, 30));\n\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(\n JSON.stringify(\n {\n ...stats,\n providerErrors: Object.fromEntries(perProviderErrors),\n },\n null,\n 2,\n ),\n );\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to get stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // --- Handle /v1/models locally (no upstream call needed) ---\n if (req.url === \"/v1/models\" && req.method === \"GET\") {\n const models = buildProxyModelList();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ object: \"list\", data: models }));\n return;\n }\n\n // --- Serve locally cached images (~/.openclaw/blockrun/images/) ---\n if (req.url?.startsWith(\"/images/\") && req.method === \"GET\") {\n const filename = req.url\n .slice(\"/images/\".length)\n .split(\"?\")[0]!\n .replace(/[^a-zA-Z0-9._-]/g, \"\");\n if (!filename) {\n res.writeHead(400);\n res.end(\"Bad request\");\n return;\n }\n const filePath = join(IMAGE_DIR, filename);\n try {\n const s = await fsStat(filePath);\n if (!s.isFile()) throw new Error(\"not a file\");\n const ext = filename.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mime: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n };\n const data = await readFile(filePath);\n res.writeHead(200, {\n \"Content-Type\": mime[ext] ?? \"application/octet-stream\",\n \"Content-Length\": data.length,\n });\n res.end(data);\n } catch {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image not found\" }));\n }\n return;\n }\n\n // --- Handle /v1/images/generations: proxy with x402 payment + save data URIs locally ---\n // NOTE: image generation endpoints bypass maxCostPerRun budget tracking entirely.\n // Cost is charged via x402 micropayment directly — no session accumulation or cap enforcement.\n if (req.url === \"/v1/images/generations\" && req.method === \"POST\") {\n const imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const reqBody = Buffer.concat(chunks);\n // Parse request for usage logging\n let imgModel = \"unknown\";\n let imgCost = 0;\n try {\n const parsed = JSON.parse(reqBody.toString());\n imgModel = parsed.model || \"openai/dall-e-3\";\n const n = parsed.n || 1;\n imgCost = estimateImageCost(imgModel, parsed.size, n);\n } catch {\n /* use defaults */\n }\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/generations`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image generation usage with actual x402 payment (previously missing entirely)\n const imgActualCost = paymentStore.getStore()?.amountUsd ?? imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: imgModel,\n tier: \"IMAGE\",\n cost: imgActualCost,\n baselineCost: imgActualCost,\n savings: 0,\n latencyMs: Date.now() - imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image generation error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image generation failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle /v1/images/image2image: proxy with x402 payment + save images locally ---\n // Accepts image as: data URI, local file path, ~/path, or HTTP(S) URL\n if (req.url === \"/v1/images/image2image\" && req.method === \"POST\") {\n const img2imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const rawBody = Buffer.concat(chunks);\n\n // Resolve image/mask fields: file paths and URLs → data URIs\n let reqBody: string;\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgModel = \"openai/gpt-image-1\";\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgCost = 0;\n try {\n const parsed = JSON.parse(rawBody.toString());\n for (const field of [\"image\", \"mask\"] as const) {\n const val = parsed[field];\n if (typeof val !== \"string\" || !val) continue;\n if (val.startsWith(\"data:\")) {\n // Already a data URI — pass through\n } else if (val.startsWith(\"https://\") || val.startsWith(\"http://\")) {\n // Download URL → data URI\n const imgResp = await fetch(val);\n if (!imgResp.ok)\n throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const buf = Buffer.from(await imgResp.arrayBuffer());\n parsed[field] = `data:${contentType};base64,${buf.toString(\"base64\")}`;\n console.log(\n `[ClawRouter] img2img: downloaded ${field} URL → data URI (${buf.length} bytes)`,\n );\n } else {\n // Local file path → data URI\n parsed[field] = readImageFileAsDataUri(val);\n console.log(`[ClawRouter] img2img: read ${field} file → data URI`);\n }\n }\n // Default model if not specified\n if (!parsed.model) parsed.model = \"openai/gpt-image-1\";\n img2imgModel = parsed.model;\n img2imgCost = estimateImageCost(img2imgModel, parsed.size, parsed.n || 1);\n reqBody = JSON.stringify(parsed);\n } catch (parseErr) {\n const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\", details: msg }));\n return;\n }\n\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image editing usage with actual x402 payment (previously missing entirely)\n const img2imgActualCost = paymentStore.getStore()?.amountUsd ?? img2imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost,\n baselineCost: img2imgActualCost,\n savings: 0,\n latencyMs: Date.now() - img2imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image editing error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image editing failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle partner API paths (/v1/x/*, /v1/partner/*) ---\n if (req.url?.match(/^\\/v1\\/(?:x|partner)\\//)) {\n try {\n await proxyPartnerRequest(\n req,\n res,\n apiBase,\n payFetch,\n () => paymentStore.getStore()?.amountUsd ?? 0,\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Partner proxy error: ${error.message}`, type: \"partner_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Only proxy paths starting with /v1\n if (!req.url?.startsWith(\"/v1\")) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not found\" }));\n return;\n }\n\n try {\n await proxyRequest(\n req,\n res,\n apiBase,\n payFetch,\n options,\n routerOpts,\n deduplicator,\n balanceMonitor,\n sessionStore,\n responseCache,\n sessionJournal,\n () => activeBasePaymentAsset.symbol,\n () => activeBasePaymentAssets,\n (asset) => {\n lastSelectedBasePaymentAsset = asset;\n activeBasePaymentAsset = asset;\n },\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Proxy error: ${error.message}`, type: \"proxy_error\" },\n }),\n );\n } else if (!res.writableEnded) {\n // Headers already sent (streaming) — send error as SSE event\n res.write(\n `data: ${JSON.stringify({ error: { message: error.message, type: \"proxy_error\" } })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n }\n }\n }); // end paymentStore.run()\n });\n\n // Listen on configured port with retry logic for TIME_WAIT handling\n // When gateway restarts quickly, the port may still be in TIME_WAIT state.\n // We retry with delay instead of incorrectly assuming a proxy is running.\n const tryListen = (attempt: number): Promise => {\n return new Promise((resolveAttempt, rejectAttempt) => {\n const onError = async (err: NodeJS.ErrnoException) => {\n server.removeListener(\"error\", onError);\n\n if (err.code === \"EADDRINUSE\") {\n // Port is in use - check if a proxy is actually running\n const existingProxy2 = await checkExistingProxy(listenPort);\n if (existingProxy2) {\n // Proxy is actually running - this is fine, reuse it\n console.log(`[ClawRouter] Existing proxy detected on port ${listenPort}, reusing`);\n rejectAttempt({\n code: \"REUSE_EXISTING\",\n wallet: existingProxy2.wallet,\n existingChain: existingProxy2.paymentChain,\n paymentAssets: existingProxy2.paymentAssets,\n selectedPaymentAsset: existingProxy2.selectedPaymentAsset,\n });\n return;\n }\n\n // Port is in TIME_WAIT (no proxy responding) - retry after delay\n if (attempt < PORT_RETRY_ATTEMPTS) {\n console.log(\n `[ClawRouter] Port ${listenPort} in TIME_WAIT, retrying in ${PORT_RETRY_DELAY_MS}ms (attempt ${attempt}/${PORT_RETRY_ATTEMPTS})`,\n );\n rejectAttempt({ code: \"RETRY\", attempt });\n return;\n }\n\n // Max retries exceeded\n console.error(\n `[ClawRouter] Port ${listenPort} still in use after ${PORT_RETRY_ATTEMPTS} attempts`,\n );\n rejectAttempt(err);\n return;\n }\n\n rejectAttempt(err);\n };\n\n server.once(\"error\", onError);\n server.listen(listenPort, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onError);\n resolveAttempt();\n });\n });\n };\n\n // Retry loop for port binding\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= PORT_RETRY_ATTEMPTS; attempt++) {\n try {\n await tryListen(attempt);\n break; // Success\n } catch (err: unknown) {\n const error = err as {\n code?: string;\n wallet?: string;\n existingChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n attempt?: number;\n };\n\n if (error.code === \"REUSE_EXISTING\" && error.wallet) {\n // Validate payment chain matches (same check as pre-listen reuse path)\n if (error.existingChain && error.existingChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${error.existingChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n { cause: err },\n );\n }\n\n return buildReuseHandle({\n wallet: error.wallet,\n paymentChain: error.existingChain,\n paymentAssets: error.paymentAssets,\n selectedPaymentAsset: error.selectedPaymentAsset,\n });\n }\n\n if (error.code === \"RETRY\") {\n // Wait before retry\n await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS));\n continue;\n }\n\n // Other error - throw\n lastError = err as Error;\n break;\n }\n }\n\n if (lastError) {\n throw lastError;\n }\n\n // Server is now listening - set up remaining handlers\n const addr = server.address() as AddressInfo;\n const port = addr.port;\n const baseUrl = `http://127.0.0.1:${port}`;\n\n options.onReady?.(port);\n\n // Check for updates (non-blocking)\n checkForUpdates();\n\n // Add runtime error handler AFTER successful listen\n // This handles errors that occur during server operation (not just startup)\n server.on(\"error\", (err) => {\n console.error(`[ClawRouter] Server runtime error: ${err.message}`);\n options.onError?.(err);\n // Don't crash - log and continue\n });\n\n // Handle client connection errors (bad requests, socket errors)\n server.on(\"clientError\", (err, socket) => {\n console.error(`[ClawRouter] Client error: ${err.message}`);\n // Send 400 Bad Request if socket is still writable\n if (socket.writable && !socket.destroyed) {\n socket.end(\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\");\n }\n });\n\n // Track connections for graceful cleanup\n server.on(\"connection\", (socket) => {\n connections.add(socket);\n\n // Set 5-minute timeout for streaming requests\n socket.setTimeout(300_000);\n\n socket.on(\"timeout\", () => {\n console.error(`[ClawRouter] Socket timeout, destroying connection`);\n socket.destroy();\n });\n\n socket.on(\"end\", () => {\n // Half-closed by client (FIN received)\n });\n\n socket.on(\"error\", (err) => {\n console.error(`[ClawRouter] Socket error: ${err.message}`);\n });\n\n socket.on(\"close\", () => {\n connections.delete(socket);\n });\n });\n\n return {\n port,\n baseUrl,\n walletAddress: account.address,\n solanaAddress,\n paymentAsset: paymentChain === \"base\" ? activeBasePaymentAsset : undefined,\n paymentAssets: paymentChain === \"base\" ? activeBasePaymentAssets : undefined,\n balanceMonitor,\n close: () =>\n new Promise((res, rej) => {\n const timeout = setTimeout(() => {\n rej(new Error(\"[ClawRouter] Close timeout after 4s\"));\n }, 4000);\n\n sessionStore.close();\n // Destroy all active connections before closing server\n for (const socket of connections) {\n socket.destroy();\n }\n connections.clear();\n server.close((err) => {\n clearTimeout(timeout);\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n }),\n };\n}\n\n/** Result of attempting a model request */\ntype ModelRequestResult = {\n success: boolean;\n response?: Response;\n errorBody?: string;\n errorStatus?: number;\n isProviderError?: boolean;\n errorCategory?: ErrorCategory; // Semantic error classification\n};\n\n/**\n * Attempt a request with a specific model.\n * Returns the response or error details for fallback decision.\n */\nasync function tryModelRequest(\n upstreamUrl: string,\n method: string,\n headers: Record,\n body: Buffer,\n modelId: string,\n maxTokens: number,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n balanceMonitor: AnyBalanceMonitor,\n signal: AbortSignal,\n): Promise {\n // Update model in body and normalize messages\n let requestBody = body;\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(modelId);\n\n // Normalize message roles (e.g., \"developer\" -> \"system\")\n if (Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessageRoles(parsed.messages as ChatMessage[]);\n }\n\n // Remove \"blockrun\" branding from system messages so upstream LLMs don't\n // adopt \"Blockrun\" as their identity (overriding user's SOUL.md persona).\n if (Array.isArray(parsed.messages)) {\n parsed.messages = debrandSystemMessages(parsed.messages as ChatMessage[], modelId);\n }\n\n // Truncate messages to stay under BlockRun's limit (200 messages)\n if (Array.isArray(parsed.messages)) {\n const truncationResult = truncateMessages(parsed.messages as ChatMessage[]);\n parsed.messages = truncationResult.messages;\n }\n\n // Sanitize tool IDs to match Anthropic's pattern (alphanumeric, underscore, hyphen only)\n if (Array.isArray(parsed.messages)) {\n parsed.messages = sanitizeToolIds(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for Google models (first non-system message must be \"user\")\n if (isGoogleModel(modelId) && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForGoogle(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for thinking-enabled requests (add reasoning_content to tool calls)\n // Check request flags AND target model - reasoning models have thinking enabled server-side\n const hasThinkingEnabled = !!(\n parsed.thinking ||\n parsed.extended_thinking ||\n isReasoningModel(modelId)\n );\n if (hasThinkingEnabled && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForThinking(parsed.messages as ExtendedChatMessage[]);\n }\n\n requestBody = Buffer.from(JSON.stringify(parsed));\n } catch {\n // If body isn't valid JSON, use as-is\n }\n\n try {\n const response = await payFetch(upstreamUrl, {\n method,\n headers,\n body: requestBody.length > 0 ? new Uint8Array(requestBody) : undefined,\n signal,\n });\n\n // Check for provider errors\n if (response.status !== 200) {\n // Clone response to read body without consuming it\n const errorBodyChunks = await readBodyWithTimeout(response.body, ERROR_BODY_READ_TIMEOUT_MS);\n const errorBody = Buffer.concat(errorBodyChunks).toString();\n const category = categorizeError(response.status, errorBody);\n\n return {\n success: false,\n errorBody,\n errorStatus: response.status,\n isProviderError: category !== null,\n errorCategory: category ?? undefined,\n };\n }\n\n // Detect provider degradation hidden inside HTTP 200 responses.\n const contentType = response.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"json\") || contentType.includes(\"text\")) {\n try {\n const clonedChunks = await readBodyWithTimeout(\n response.clone().body,\n ERROR_BODY_READ_TIMEOUT_MS,\n );\n const responseBody = Buffer.concat(clonedChunks).toString();\n const degradedReason = detectDegradedSuccessResponse(responseBody);\n if (degradedReason) {\n return {\n success: false,\n errorBody: degradedReason,\n errorStatus: 503,\n isProviderError: true,\n };\n }\n } catch {\n // Ignore body inspection failures and pass through response.\n }\n }\n\n return { success: true, response };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return {\n success: false,\n errorBody: errorMsg,\n errorStatus: 500,\n isProviderError: true, // Network errors are retryable\n };\n }\n}\n\n/**\n * Proxy a single request through x402 payment flow to BlockRun API.\n *\n * Optimizations applied in order:\n * 1. Dedup check — if same request body seen within 30s, replay cached response\n * 2. Streaming heartbeat — for stream:true, send 200 + heartbeats immediately\n * 3. Smart routing — when model is \"blockrun/auto\", pick cheapest capable model\n * 4. Fallback chain — on provider errors, try next model in tier's fallback list\n */\nasync function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n options: ProxyOptions,\n routerOpts: RouterOptions,\n deduplicator: RequestDeduplicator,\n balanceMonitor: AnyBalanceMonitor,\n sessionStore: SessionStore,\n responseCache: ResponseCache,\n sessionJournal: SessionJournal,\n getBaseAssetSymbol: () => string,\n getBasePaymentAssets: () => BasePaymentAsset[],\n onBaseAssetSelected: (asset: BasePaymentAsset) => void,\n): Promise {\n const startTime = Date.now();\n\n // Build upstream URL: /v1/chat/completions → https://blockrun.ai/api/v1/chat/completions\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n let body = Buffer.concat(bodyChunks);\n\n // Track original context size for response headers\n const originalContextSizeKB = Math.ceil(body.length / 1024);\n\n // Routing debug info is on by default; disable with x-clawrouter-debug: false\n const debugMode = req.headers[\"x-clawrouter-debug\"] !== \"false\";\n\n // --- Smart routing ---\n let routingDecision: RoutingDecision | undefined;\n let hasTools = false; // true when request includes a tools schema\n let hasVision = false; // true when request includes image_url content parts\n let isStreaming = false;\n let modelId = \"\";\n let maxTokens = 4096;\n let routingProfile: \"eco\" | \"auto\" | \"premium\" | null = null;\n let balanceFallbackNotice: string | undefined;\n let budgetDowngradeNotice: string | undefined;\n let budgetDowngradeHeaderMode: \"downgraded\" | undefined;\n let accumulatedContent = \"\"; // For session journal event extraction\n let responseInputTokens: number | undefined;\n let responseOutputTokens: number | undefined;\n let requestBalanceMonitor = balanceMonitor;\n let requestBasePaymentAsset = getBasePaymentAssets()[0];\n const isChatCompletion = req.url?.includes(\"/chat/completions\");\n\n // Extract session ID early for journal operations (header-only at this point)\n const sessionId = getSessionId(req.headers as Record);\n // Full session ID (header + content-derived) — populated once messages are parsed\n let effectiveSessionId: string | undefined = sessionId;\n\n if (isChatCompletion && body.length > 0) {\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n isStreaming = parsed.stream === true;\n modelId = (parsed.model as string) || \"\";\n maxTokens = (parsed.max_tokens as number) || 4096;\n let bodyModified = false;\n\n // Extract last user message content (used by session journal + /debug command)\n const parsedMessages = Array.isArray(parsed.messages)\n ? (parsed.messages as Array<{ role: string; content: unknown }>)\n : [];\n const lastUserMsg = [...parsedMessages].reverse().find((m) => m.role === \"user\");\n\n // Early tool detection for ALL request types (explicit model + routing profile).\n // The routing-profile branch may re-assign below (no-op since same value).\n hasTools = Array.isArray(parsed.tools) && (parsed.tools as unknown[]).length > 0;\n const rawLastContent = lastUserMsg?.content;\n const lastContent =\n typeof rawLastContent === \"string\"\n ? rawLastContent\n : Array.isArray(rawLastContent)\n ? (rawLastContent as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n\n // --- Session Journal: Inject context if needed ---\n // Check if the last user message asks about past work\n if (sessionId && parsedMessages.length > 0) {\n const messages = parsedMessages;\n\n if (sessionJournal.needsContext(lastContent)) {\n const journalText = sessionJournal.format(sessionId);\n if (journalText) {\n // Find system message and prepend journal, or add a new system message\n const sysIdx = messages.findIndex((m) => m.role === \"system\");\n if (sysIdx >= 0 && typeof messages[sysIdx].content === \"string\") {\n messages[sysIdx] = {\n ...messages[sysIdx],\n content: journalText + \"\\n\\n\" + messages[sysIdx].content,\n };\n } else {\n messages.unshift({ role: \"system\", content: journalText });\n }\n parsed.messages = messages;\n bodyModified = true;\n console.log(\n `[ClawRouter] Injected session journal (${journalText.length} chars) for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n }\n\n // --- /debug command: return routing diagnostics without calling upstream ---\n if (lastContent.startsWith(\"/debug\")) {\n const debugPrompt = lastContent.slice(\"/debug\".length).trim() || \"hello\";\n const messages = parsed.messages as Array<{ role: string; content: unknown }>;\n const systemMsg = messages?.find((m) => m.role === \"system\");\n const systemPrompt = typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n const fullText = `${systemPrompt ?? \"\"} ${debugPrompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // Determine routing profile\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n const profileName = normalizedModel.replace(\"blockrun/\", \"\");\n const debugProfile = (\n [\"eco\", \"auto\", \"premium\"].includes(profileName) ? profileName : \"auto\"\n ) as \"eco\" | \"auto\" | \"premium\";\n\n // Run scoring\n const scoring = classifyByRules(\n debugPrompt,\n systemPrompt,\n estimatedTokens,\n DEFAULT_ROUTING_CONFIG.scoring,\n );\n\n // Run full routing decision\n const debugRouting = route(debugPrompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: debugProfile,\n });\n\n // Format dimension scores\n const dimLines = (scoring.dimensions ?? [])\n .map((d) => {\n const nameStr = (d.name + \":\").padEnd(24);\n const scoreStr = d.score.toFixed(2).padStart(6);\n const sigStr = d.signal ? ` [${d.signal}]` : \"\";\n return ` ${nameStr}${scoreStr}${sigStr}`;\n })\n .join(\"\\n\");\n\n // Session info\n const sess = sessionId ? sessionStore.getSession(sessionId) : undefined;\n const sessLine = sess\n ? `Session: ${sessionId!.slice(0, 8)}... → pinned: ${sess.model} (${sess.requestCount} requests)`\n : sessionId\n ? `Session: ${sessionId.slice(0, 8)}... → no pinned model`\n : \"Session: none\";\n\n const { simpleMedium, mediumComplex, complexReasoning } =\n DEFAULT_ROUTING_CONFIG.scoring.tierBoundaries;\n\n const debugText = [\n \"ClawRouter Debug\",\n \"\",\n `Profile: ${debugProfile} | Tier: ${debugRouting.tier} | Model: ${debugRouting.model}`,\n `Confidence: ${debugRouting.confidence.toFixed(2)} | Cost: $${debugRouting.costEstimate.toFixed(4)} | Savings: ${(debugRouting.savings * 100).toFixed(0)}%`,\n `Reasoning: ${debugRouting.reasoning}`,\n \"\",\n `Scoring (weighted: ${scoring.score.toFixed(3)})`,\n dimLines,\n \"\",\n `Tier Boundaries: SIMPLE <${simpleMedium.toFixed(2)} | MEDIUM <${mediumComplex.toFixed(2)} | COMPLEX <${complexReasoning.toFixed(2)} | REASONING >=${complexReasoning.toFixed(2)}`,\n \"\",\n sessLine,\n ].join(\"\\n\");\n\n // Build synthetic OpenAI chat completion response\n const completionId = `chatcmpl-debug-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n const syntheticResponse = {\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: debugText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n\n if (isStreaming) {\n // SSE streaming response\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n const sseChunk = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n delta: { role: \"assistant\", content: debugText },\n finish_reason: null,\n },\n ],\n };\n const sseDone = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }],\n };\n res.write(`data: ${JSON.stringify(sseChunk)}\\n\\n`);\n res.write(`data: ${JSON.stringify(sseDone)}\\n\\n`);\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(syntheticResponse));\n }\n console.log(`[ClawRouter] /debug command → ${debugRouting.tier} | ${debugRouting.model}`);\n return;\n }\n\n // --- /imagegen command: generate an image via BlockRun image API ---\n if (lastContent.startsWith(\"/imagegen\")) {\n const imageArgs = lastContent.slice(\"/imagegen\".length).trim();\n\n // Parse optional flags: /imagegen --model dall-e-3 --size 1792x1024 a cute cat\n let imageModel = \"google/nano-banana\";\n let imageSize = \"1024x1024\";\n let imagePrompt = imageArgs;\n\n // Extract --model flag\n const modelMatch = imageArgs.match(/--model\\s+(\\S+)/);\n if (modelMatch) {\n const raw = modelMatch[1];\n // Resolve shorthand aliases\n const IMAGE_MODEL_ALIASES: Record = {\n \"dall-e-3\": \"openai/dall-e-3\",\n dalle3: \"openai/dall-e-3\",\n dalle: \"openai/dall-e-3\",\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n flux: \"black-forest/flux-1.1-pro\",\n \"flux-pro\": \"black-forest/flux-1.1-pro\",\n banana: \"google/nano-banana\",\n \"nano-banana\": \"google/nano-banana\",\n \"banana-pro\": \"google/nano-banana-pro\",\n \"nano-banana-pro\": \"google/nano-banana-pro\",\n };\n imageModel = IMAGE_MODEL_ALIASES[raw] ?? raw;\n imagePrompt = imagePrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n // Extract --size flag\n const sizeMatch = imageArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (sizeMatch) {\n imageSize = sizeMatch[1];\n imagePrompt = imagePrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n if (!imagePrompt) {\n const errorText = [\n \"Usage: /imagegen \",\n \"\",\n \"Options:\",\n \" --model Model to use (default: nano-banana)\",\n \" --size Image size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" nano-banana Google Gemini Flash — $0.05/image\",\n \" banana-pro Google Gemini Pro — $0.10/image (up to 4K)\",\n \" dall-e-3 OpenAI DALL-E 3 — $0.04/image\",\n \" gpt-image OpenAI GPT Image 1 — $0.02/image\",\n \" flux Black Forest Flux 1.1 Pro — $0.04/image\",\n \"\",\n \"Examples:\",\n \" /imagegen a cat wearing sunglasses\",\n \" /imagegen --model dall-e-3 a futuristic city at sunset\",\n \" /imagegen --model banana-pro --size 2048x2048 mountain landscape\",\n ].join(\"\\n\");\n\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: errorText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: errorText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n console.log(`[ClawRouter] /imagegen command → showing usage help`);\n return;\n }\n\n // Call upstream image generation API\n console.log(\n `[ClawRouter] /imagegen command → ${imageModel} (${imageSize}): ${imagePrompt.slice(0, 80)}...`,\n );\n try {\n const imageUpstreamUrl = `${apiBase}/v1/images/generations`;\n const imageBody = JSON.stringify({\n model: imageModel,\n prompt: imagePrompt,\n size: imageSize,\n n: 1,\n });\n const imageResponse = await payFetch(imageUpstreamUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: imageBody,\n });\n\n const imageResult = (await imageResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!imageResponse.ok || imageResult.error) {\n const errMsg =\n typeof imageResult.error === \"string\"\n ? imageResult.error\n : ((imageResult.error as { message?: string })?.message ??\n `HTTP ${imageResponse.status}`);\n responseText = `Image generation failed: ${errMsg}`;\n console.log(`[ClawRouter] /imagegen error: ${errMsg}`);\n } else {\n const images = imageResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image generation returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /imagegen: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\n \"Image generated but upload failed. Try again or use --model dall-e-3.\",\n );\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${imageModel} | Size: ${imageSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /imagegen success: ${images.length} image(s) generated`);\n // Log /imagegen usage with actual x402 payment\n const imagegenActualCost =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(imageModel, imageSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: imageModel,\n tier: \"IMAGE\",\n cost: imagegenActualCost,\n baselineCost: imagegenActualCost,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n // Return as synthetic chat completion\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: responseText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: responseText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /imagegen error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image generation failed: ${errMsg}`, type: \"image_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // --- /img2img command: edit an image via BlockRun image2image API ---\n if (lastContent.startsWith(\"/img2img\")) {\n const imgArgs = lastContent.slice(\"/img2img\".length).trim();\n\n let img2imgModel = \"openai/gpt-image-1\";\n let img2imgSize = \"1024x1024\";\n let imagePath: string | null = null;\n let maskPath: string | null = null;\n let img2imgPrompt = imgArgs;\n\n const imageMatch = imgArgs.match(/--image\\s+(\\S+)/);\n if (imageMatch) {\n imagePath = imageMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--image\\s+\\S+/, \"\").trim();\n }\n\n const maskMatch = imgArgs.match(/--mask\\s+(\\S+)/);\n if (maskMatch) {\n maskPath = maskMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--mask\\s+\\S+/, \"\").trim();\n }\n\n const img2imgSizeMatch = imgArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (img2imgSizeMatch) {\n img2imgSize = img2imgSizeMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n const img2imgModelMatch = imgArgs.match(/--model\\s+(\\S+)/);\n if (img2imgModelMatch) {\n const raw = img2imgModelMatch[1];\n const IMG2IMG_ALIASES: Record = {\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n };\n img2imgModel = IMG2IMG_ALIASES[raw] ?? raw;\n img2imgPrompt = img2imgPrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n const usageText = [\n \"Usage: /img2img --image \",\n \"\",\n \"Options:\",\n \" --image Source image path (required)\",\n \" --mask Mask image path (optional, white = area to edit)\",\n \" --model Model (default: gpt-image-1)\",\n \" --size Output size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" gpt-image-1 OpenAI GPT Image 1 — $0.02/image\",\n \"\",\n \"Examples:\",\n \" /img2img --image ~/photo.png change background to starry sky\",\n \" /img2img --image ./cat.jpg --mask ./mask.png remove the background\",\n \" /img2img --image /tmp/portrait.png --size 1536x1024 add a hat\",\n ].join(\"\\n\");\n\n const sendImg2ImgText = (text: string) => {\n const completionId = `chatcmpl-img2img-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: { role: \"assistant\", content: text }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/img2img\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n };\n\n if (!imagePath || !img2imgPrompt) {\n sendImg2ImgText(usageText);\n return;\n }\n\n let imageDataUri: string;\n let maskDataUri: string | undefined;\n try {\n imageDataUri = readImageFileAsDataUri(imagePath);\n if (maskPath) maskDataUri = readImageFileAsDataUri(maskPath);\n } catch (fileErr) {\n const fileErrMsg = fileErr instanceof Error ? fileErr.message : String(fileErr);\n sendImg2ImgText(`Failed to read image file: ${fileErrMsg}`);\n return;\n }\n\n console.log(\n `[ClawRouter] /img2img → ${img2imgModel} (${img2imgSize}): ${img2imgPrompt.slice(0, 80)}`,\n );\n\n try {\n const img2imgBody = JSON.stringify({\n model: img2imgModel,\n prompt: img2imgPrompt,\n image: imageDataUri,\n ...(maskDataUri ? { mask: maskDataUri } : {}),\n size: img2imgSize,\n n: 1,\n });\n\n const img2imgResponse = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: img2imgBody,\n });\n\n const img2imgResult = (await img2imgResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!img2imgResponse.ok || img2imgResult.error) {\n const errMsg =\n typeof img2imgResult.error === \"string\"\n ? img2imgResult.error\n : ((img2imgResult.error as { message?: string })?.message ??\n `HTTP ${img2imgResponse.status}`);\n responseText = `Image editing failed: ${errMsg}`;\n console.log(`[ClawRouter] /img2img error: ${errMsg}`);\n } else {\n const images = img2imgResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image editing returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /img2img: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\"Image edited but upload failed. Try again.\");\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${img2imgModel} | Size: ${img2imgSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /img2img success: ${images.length} image(s)`);\n // Log /img2img usage with actual x402 payment\n const img2imgActualCost2 =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(img2imgModel, img2imgSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost2,\n baselineCost: img2imgActualCost2,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n sendImg2ImgText(responseText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /img2img error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image editing failed: ${errMsg}`, type: \"img2img_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Force stream: false — BlockRun API doesn't support streaming yet\n // ClawRouter handles SSE heartbeat simulation for upstream compatibility\n if (parsed.stream === true) {\n parsed.stream = false;\n bodyModified = true;\n }\n\n // Normalize model name for comparison (trim whitespace, lowercase)\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n\n // Resolve model aliases (e.g., \"claude\" -> \"anthropic/claude-sonnet-4-6\")\n const resolvedModel = resolveModelAlias(normalizedModel);\n const wasAlias = resolvedModel !== normalizedModel;\n\n // Check both normalizedModel and resolvedModel — OpenClaw may send \"openai/eco\"\n // which resolveModelAlias strips to \"eco\" (a valid routing profile)\n const isRoutingProfile =\n ROUTING_PROFILES.has(normalizedModel) || ROUTING_PROFILES.has(resolvedModel);\n\n // Extract routing profile type (free/eco/auto/premium)\n if (isRoutingProfile) {\n const profileName = resolvedModel.replace(\"blockrun/\", \"\");\n routingProfile = profileName as \"eco\" | \"auto\" | \"premium\";\n }\n\n // Debug: log received model name\n console.log(\n `[ClawRouter] Received model: \"${parsed.model}\" -> normalized: \"${normalizedModel}\"${wasAlias ? ` -> alias: \"${resolvedModel}\"` : \"\"}${routingProfile ? `, profile: ${routingProfile}` : \"\"}`,\n );\n\n // For explicit model requests, always canonicalize the model ID before upstream calls.\n // This ensures case/whitespace variants (e.g. \"DEEPSEEK/...\" or \" model \") route correctly.\n if (!isRoutingProfile) {\n if (parsed.model !== resolvedModel) {\n parsed.model = resolvedModel;\n bodyModified = true;\n }\n modelId = resolvedModel;\n }\n\n // Handle routing profiles (free/eco/auto/premium)\n if (isRoutingProfile) {\n {\n // eco/auto/premium - use tier routing\n // Check for session persistence - use pinned model if available\n // Fall back to deriving a session ID from message content when OpenClaw\n // doesn't send an explicit x-session-id header (the default behaviour).\n effectiveSessionId =\n getSessionId(req.headers as Record) ??\n deriveSessionId(parsedMessages);\n const existingSession = effectiveSessionId\n ? sessionStore.getSession(effectiveSessionId)\n : undefined;\n\n // Extract prompt from last user message (handles both string and Anthropic array content)\n const rawPrompt = lastUserMsg?.content;\n const prompt =\n typeof rawPrompt === \"string\"\n ? rawPrompt\n : Array.isArray(rawPrompt)\n ? (rawPrompt as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n const systemMsg = parsedMessages.find((m) => m.role === \"system\");\n const systemPrompt =\n typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n\n // Tool detection — when tools are present, force agentic tiers for reliable tool use\n const tools = parsed.tools as unknown[] | undefined;\n hasTools = Array.isArray(tools) && tools.length > 0;\n\n if (hasTools && tools) {\n console.log(`[ClawRouter] Tools detected (${tools.length}), forcing agentic tiers`);\n }\n\n // Vision detection: scan messages for image_url content parts\n hasVision = parsedMessages.some((m) => {\n if (Array.isArray(m.content)) {\n return (m.content as Array<{ type: string }>).some((p) => p.type === \"image_url\");\n }\n return false;\n });\n if (hasVision) {\n console.log(`[ClawRouter] Vision content detected, filtering to vision-capable models`);\n }\n\n // Always route based on current request content\n routingDecision = route(prompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: routingProfile ?? undefined,\n hasTools,\n });\n\n // Keep agentic routing when tools are present, even for SIMPLE queries.\n // Tool-using requests need models with reliable function-call support;\n // demoting to non-agentic tiers causes fallback to models that refuse\n // tool schemas (gemini-flash-lite, deepseek) or lack tool support entirely.\n if (hasTools && routingDecision.tier === \"SIMPLE\") {\n console.log(\n `[ClawRouter] SIMPLE+tools: keeping agentic model ${routingDecision.model} (tools need reliable function-call support)`,\n );\n }\n\n if (existingSession) {\n // Never downgrade: only upgrade the session when the current request needs a higher\n // tier. This fixes the OpenClaw startup-message bias (the startup message always\n // scores low-complexity, which previously pinned all subsequent real queries to a\n // cheap model) while still preventing mid-task model switching on simple follow-ups.\n const tierRank: Record = {\n SIMPLE: 0,\n MEDIUM: 1,\n COMPLEX: 2,\n REASONING: 3,\n };\n const existingRank = tierRank[existingSession.tier] ?? 0;\n const newRank = tierRank[routingDecision.tier] ?? 0;\n\n if (newRank > existingRank) {\n // Current request needs higher capability — upgrade the session\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... upgrading: ${existingSession.tier} → ${routingDecision.tier} (${routingDecision.model})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n }\n } else if (routingDecision.tier === \"SIMPLE\") {\n // SIMPLE follow-up in an active session: let it use cheap routing.\n // e.g. \"你好\" or \"thanks\" after a complex task should not inherit the\n // expensive session model or recount all context tokens on a paid model.\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... SIMPLE follow-up, using cheap model: ${routingDecision.model} (bypassing pinned ${existingSession.tier})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // routingDecision already reflects cheap model — no override needed\n } else {\n // Keep existing higher-tier model (prevent downgrade mid-task)\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... keeping pinned model: ${existingSession.model} (${existingSession.tier} >= ${routingDecision.tier})`,\n );\n parsed.model = existingSession.model;\n modelId = existingSession.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // Reflect the actual model used in the routing decision for logging/fallback\n routingDecision = {\n ...routingDecision,\n model: existingSession.model,\n tier: existingSession.tier as Tier,\n };\n }\n\n // --- Three-strike escalation: detect repetitive request patterns ---\n const lastAssistantMsg = [...parsedMessages]\n .reverse()\n .find((m) => m.role === \"assistant\");\n const assistantToolCalls = (\n lastAssistantMsg as { tool_calls?: Array<{ function?: { name?: string } }> }\n )?.tool_calls;\n const toolCallNames = Array.isArray(assistantToolCalls)\n ? assistantToolCalls\n .map((tc) => tc.function?.name)\n .filter((n): n is string => Boolean(n))\n : undefined;\n const contentHash = hashRequestContent(prompt, toolCallNames);\n const shouldEscalate = sessionStore.recordRequestHash(effectiveSessionId!, contentHash);\n\n if (shouldEscalate) {\n const activeTierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n const escalation = sessionStore.escalateSession(\n effectiveSessionId!,\n activeTierConfigs,\n );\n if (escalation) {\n console.log(\n `[ClawRouter] ⚡ 3-strike escalation: ${existingSession.model} → ${escalation.model} (${existingSession.tier} → ${escalation.tier})`,\n );\n parsed.model = escalation.model;\n modelId = escalation.model;\n routingDecision = {\n ...routingDecision,\n model: escalation.model,\n tier: escalation.tier as Tier,\n };\n }\n }\n } else {\n // No session — pin this routing decision for future requests\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... pinned to model: ${routingDecision.model}`,\n );\n }\n }\n\n options.onRouted?.(routingDecision);\n }\n }\n\n // Ensure effectiveSessionId is set for explicit model requests via content hash fallback.\n // Routing profile requests already derive session ID from message content (see line above).\n // Explicit model requests (openai/gpt-4o, anthropic/claude-*, etc.) without an\n // x-session-id header would otherwise have no session ID → maxCostPerRun not tracked.\n if (!effectiveSessionId && parsedMessages.length > 0) {\n effectiveSessionId = deriveSessionId(parsedMessages);\n }\n\n // Rebuild body if modified — map free/xxx → nvidia/xxx for upstream\n if (bodyModified) {\n if (parsed.model && typeof parsed.model === \"string\") {\n parsed.model = toUpstreamModelId(parsed.model);\n }\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Log routing errors so they're not silently swallowed\n const errorMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Routing error: ${errorMsg}`);\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n options.onError?.(new Error(`Routing failed: ${errorMsg}`));\n }\n }\n\n // --- Auto-compression ---\n // Compress large requests to reduce network usage and improve performance\n const autoCompress = options.autoCompressRequests ?? true;\n const compressionThreshold = options.compressionThresholdKB ?? 180;\n const requestSizeKB = Math.ceil(body.length / 1024);\n\n if (autoCompress && requestSizeKB > compressionThreshold) {\n try {\n console.log(\n `[ClawRouter] Request size ${requestSizeKB}KB exceeds threshold ${compressionThreshold}KB, applying compression...`,\n );\n\n // Parse messages for compression\n const parsed = JSON.parse(body.toString()) as {\n messages?: NormalizedMessage[];\n [key: string]: unknown;\n };\n\n if (parsed.messages && parsed.messages.length > 0 && shouldCompress(parsed.messages)) {\n // Apply compression with conservative settings\n const compressionResult = await compressContext(parsed.messages, {\n enabled: true,\n preserveRaw: false, // Don't need originals in proxy\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // Disabled: requires model to understand codebook\n paths: false, // Disabled: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // Disabled: may lose important context\n dynamicCodebook: false, // Disabled: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false,\n },\n });\n\n const compressedSizeKB = Math.ceil(compressionResult.compressedChars / 1024);\n const savings = (((requestSizeKB - compressedSizeKB) / requestSizeKB) * 100).toFixed(1);\n\n console.log(\n `[ClawRouter] Compressed ${requestSizeKB}KB → ${compressedSizeKB}KB (${savings}% reduction)`,\n );\n\n // Update request body with compressed messages\n parsed.messages = compressionResult.messages;\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Compression failed - continue with original request\n console.warn(\n `[ClawRouter] Compression failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // --- Response cache check (long-term, 10min TTL) ---\n const cacheKey = ResponseCache.generateKey(body);\n const reqHeaders: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (typeof value === \"string\") reqHeaders[key] = value;\n }\n if (responseCache.shouldCache(body, reqHeaders)) {\n const cachedResponse = responseCache.get(cacheKey);\n if (cachedResponse) {\n console.log(`[ClawRouter] Cache HIT for ${cachedResponse.model} (saved API call)`);\n res.writeHead(cachedResponse.status, cachedResponse.headers);\n res.end(cachedResponse.body);\n return;\n }\n }\n\n // --- Dedup check (short-term, 30s TTL for retries) ---\n const dedupKey = RequestDeduplicator.hash(body);\n\n // Check dedup cache (catches retries within 30s)\n const cached = deduplicator.getCached(dedupKey);\n if (cached) {\n res.writeHead(cached.status, cached.headers);\n res.end(cached.body);\n return;\n }\n\n // Check in-flight — wait for the original request to complete\n const inflight = deduplicator.getInflight(dedupKey);\n if (inflight) {\n const result = await inflight;\n res.writeHead(result.status, result.headers);\n res.end(result.body);\n return;\n }\n\n // Register this request as in-flight\n deduplicator.markInflight(dedupKey);\n\n // --- Pre-request balance check ---\n // Estimate cost and check if wallet has sufficient balance\n // Skip if skipBalanceCheck is set (for testing) or if using free model\n let estimatedCostMicros: bigint | undefined;\n // Use `let` so the balance-fallback path can update this when modelId is switched to a free model.\n let isFreeModel = FREE_MODELS.has(modelId ?? \"\");\n\n if (modelId && !options.skipBalanceCheck && !isFreeModel) {\n const estimated = estimateAmount(modelId, body.length, maxTokens);\n if (estimated) {\n estimatedCostMicros = BigInt(estimated);\n\n // Apply extra buffer for balance check to prevent x402 failures after streaming starts.\n // This is aggressive to avoid triggering OpenClaw's 5-24 hour billing cooldown.\n const bufferedCostMicros =\n (estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100))) / 100n;\n\n if (balanceMonitor instanceof BalanceMonitor) {\n const baseAssets = getBasePaymentAssets();\n let selected:\n | {\n asset: BasePaymentAsset;\n monitor: BalanceMonitor;\n sufficiency: Awaited>;\n }\n | undefined;\n\n for (const asset of baseAssets) {\n const monitor = balanceMonitor.getSharedMonitorForAsset(asset);\n const sufficiency = await monitor.checkSufficient(bufferedCostMicros);\n if (!selected) {\n selected = { asset, monitor, sufficiency };\n }\n if (sufficiency.sufficient) {\n selected = { asset, monitor, sufficiency };\n break;\n }\n }\n\n if (selected) {\n requestBasePaymentAsset = selected.asset;\n requestBalanceMonitor = selected.monitor;\n onBaseAssetSelected(selected.asset);\n console.log(\n `[ClawRouter] Base payment asset selected: ${selected.asset.symbol} (${selected.sufficiency.info.balanceUSD})`,\n );\n }\n }\n\n // Check balance before proceeding (using buffered amount)\n const sufficiency = await requestBalanceMonitor.checkSufficient(bufferedCostMicros);\n\n if (sufficiency.info.isEmpty || !sufficiency.sufficient) {\n // Wallet is empty or insufficient — fallback to free model\n const originalModel = modelId;\n console.log(\n `[ClawRouter] Wallet ${sufficiency.info.isEmpty ? \"empty\" : \"insufficient\"} (${sufficiency.info.balanceUSD}), falling back to free model: ${FREE_MODEL} (requested: ${originalModel})`,\n );\n modelId = FREE_MODEL;\n isFreeModel = true; // keep in sync — budget logic gates on !isFreeModel\n // Update the body with new model (map free/ → nvidia/ for upstream)\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(FREE_MODEL);\n body = Buffer.from(JSON.stringify(parsed));\n\n // Set notice to prepend to response so user knows about the fallback\n balanceFallbackNotice = sufficiency.info.isEmpty\n ? `> **⚠️ Wallet empty** — using free model. Fund your wallet to use ${originalModel}.\\n\\n`\n : `> **⚠️ Insufficient balance** (${sufficiency.info.balanceUSD}) — using free model instead of ${originalModel}.\\n\\n`;\n\n // Notify about the fallback\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n assetSymbol: sufficiency.info.assetSymbol,\n });\n } else if (sufficiency.info.isLow) {\n // Balance is low but sufficient — warn and proceed\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n assetSymbol: sufficiency.info.assetSymbol,\n });\n }\n }\n }\n\n // --- Cost cap check: strict mode hard-stop ---\n // In 'strict' mode, reject if the projected session spend (accumulated + this request's\n // estimate) would exceed the cap. Checking projected cost (not just historical) prevents\n // a single large request from overshooting the cap before it's recorded.\n // In 'graceful' mode (default), the cap is enforced via model downgrade below.\n // Must happen before streaming headers are sent.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"strict\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n // Include this request's estimated cost so even the first request is blocked\n // if it would push the session over the cap.\n const thisReqEstStr =\n estimatedCostMicros !== undefined\n ? estimatedCostMicros.toString()\n : modelId\n ? estimateAmount(modelId, body.length, maxTokens)\n : undefined;\n const thisReqEstUsd = thisReqEstStr ? Number(thisReqEstStr) / 1_000_000 : 0;\n const projectedCostUsd = runCostUsd + thisReqEstUsd;\n if (projectedCostUsd > options.maxCostPerRunUsd) {\n console.log(\n `[ClawRouter] Cost cap exceeded for session ${effectiveSessionId.slice(0, 8)}...: projected $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) > $${options.maxCostPerRunUsd} limit`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter cost cap exceeded: projected spend $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) would exceed limit $${options.maxCostPerRunUsd}`,\n type: \"cost_cap_exceeded\",\n code: \"cost_cap_exceeded\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n\n // --- Budget pre-check: block when remaining budget can't cover the request ---\n // Must happen BEFORE streaming headers (429 can't be sent after SSE headers are flushed).\n // Three cases that require a hard block rather than graceful downgrade:\n // (A) tool/COMPLEX/REASONING routing profile — free model can't substitute\n // (B) explicit model request (no routing profile) — user chose a specific model,\n // silently substituting with free model would be deceptive regardless of task type\n // Simple routing profile requests are handled later via graceful downgrade.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const isComplexOrAgentic =\n hasTools || routingDecision?.tier === \"COMPLEX\" || routingDecision?.tier === \"REASONING\";\n\n if (isComplexOrAgentic) {\n // Case A: tool/complex/agentic routing profile — check global model table\n // Intentionally exclude free models: they cannot handle complex/agentic tasks.\n const canAffordAnyNonFreeModel = BLOCKRUN_MODELS.some((m) => {\n if (FREE_MODELS.has(m.id)) return false;\n const est = estimateAmount(m.id, body.length, maxTokens);\n return est !== undefined && Number(est) / 1_000_000 <= remainingUsd;\n });\n if (!canAffordAnyNonFreeModel) {\n console.log(\n `[ClawRouter] Budget insufficient for agentic/complex session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (silent downgrade would corrupt tool/complex responses)`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n } else if (!routingDecision && modelId && !FREE_MODELS.has(modelId)) {\n // Case B: explicit model request (user chose a specific model, not a routing profile).\n // Silently substituting their choice with free model is deceptive — block instead.\n const est = estimateAmount(modelId, body.length, maxTokens);\n const canAfford = !est || Number(est) / 1_000_000 <= remainingUsd;\n if (!canAfford) {\n console.log(\n `[ClawRouter] Budget insufficient for explicit model ${modelId} in session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (user explicitly chose ${modelId})`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue using ${modelId}.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n }\n\n // --- Streaming: early header flush + heartbeat ---\n let heartbeatInterval: ReturnType | undefined;\n let headersSentEarly = false;\n\n if (isStreaming) {\n // Send 200 + SSE headers immediately, before x402 flow\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n headersSentEarly = true;\n\n // First heartbeat immediately\n safeWrite(res, \": heartbeat\\n\\n\");\n\n // Continue heartbeats every 2s while waiting for upstream\n heartbeatInterval = setInterval(() => {\n if (canWrite(res)) {\n safeWrite(res, \": heartbeat\\n\\n\");\n } else {\n // Socket closed, stop heartbeat\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n }, HEARTBEAT_INTERVAL_MS);\n }\n\n // Forward headers, stripping host, connection, and content-length\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") {\n headers[key] = value;\n }\n }\n if (!headers[\"content-type\"]) {\n headers[\"content-type\"] = \"application/json\";\n }\n headers[\"user-agent\"] = USER_AGENT;\n\n // --- Client disconnect cleanup ---\n let completed = false;\n res.on(\"close\", () => {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n // Remove from in-flight if client disconnected before completion\n if (!completed) {\n deduplicator.removeInflight(dedupKey);\n }\n });\n\n // --- Request timeout ---\n // Global controller: hard deadline for the entire request (all model attempts combined).\n // Each model attempt gets its own per-model controller (PER_MODEL_TIMEOUT_MS).\n // If a model times out individually, we fall back to the next model instead of failing.\n // Only the global timeout causes an immediate error.\n const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const globalController = new AbortController();\n const timeoutId = setTimeout(() => globalController.abort(), timeoutMs);\n\n try {\n // --- Build fallback chain ---\n // If we have a routing decision, get the full fallback chain for the tier\n // Otherwise, just use the current model (no fallback for explicit model requests)\n let modelsToTry: string[];\n const excludeList = options.excludeModels ?? loadExcludeList();\n if (routingDecision) {\n // Estimate total context: input tokens (~4 chars per token) + max output tokens\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const estimatedTotalTokens = estimatedInputTokens + maxTokens;\n\n // Use tier configs from the routing decision (set by RouterStrategy)\n const tierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n // Get full chain first, then filter by context\n const fullChain = getFallbackChain(routingDecision.tier, tierConfigs);\n const contextFiltered = getFallbackChainFiltered(\n routingDecision.tier,\n tierConfigs,\n estimatedTotalTokens,\n getModelContextWindow,\n );\n\n // Log if models were filtered out due to context limits\n const contextExcluded = fullChain.filter((m) => !contextFiltered.includes(m));\n if (contextExcluded.length > 0) {\n console.log(\n `[ClawRouter] Context filter (~${estimatedTotalTokens} tokens): excluded ${contextExcluded.join(\", \")}`,\n );\n }\n\n // Filter out user-excluded models\n const excludeFiltered = filterByExcludeList(contextFiltered, excludeList);\n const excludeExcluded = contextFiltered.filter((m) => !excludeFiltered.includes(m));\n if (excludeExcluded.length > 0) {\n console.log(\n `[ClawRouter] Exclude filter: excluded ${excludeExcluded.join(\", \")} (user preference)`,\n );\n }\n\n // Filter to models that support tool calling when request has tools.\n // Prevents models like grok-code-fast-1 from outputting tool invocations\n // as plain text JSON (the \"talking to itself\" bug).\n let toolFiltered = filterByToolCalling(excludeFiltered, hasTools, supportsToolCalling);\n const toolExcluded = excludeFiltered.filter((m) => !toolFiltered.includes(m));\n if (toolExcluded.length > 0) {\n console.log(\n `[ClawRouter] Tool-calling filter: excluded ${toolExcluded.join(\", \")} (no structured function call support)`,\n );\n }\n\n // Filter out models that declare toolCalling but fail tool compliance in practice.\n // gemini-2.5-flash-lite refuses certain tool schemas (e.g. brave search) while\n // cheaper models like nvidia/gpt-oss-120b handle them fine.\n const TOOL_NONCOMPLIANT_MODELS = [\n \"google/gemini-2.5-flash-lite\",\n \"google/gemini-3-pro-preview\",\n \"google/gemini-3.1-pro\",\n ];\n if (hasTools && toolFiltered.length > 1) {\n const compliant = toolFiltered.filter((m) => !TOOL_NONCOMPLIANT_MODELS.includes(m));\n if (compliant.length > 0 && compliant.length < toolFiltered.length) {\n const dropped = toolFiltered.filter((m) => TOOL_NONCOMPLIANT_MODELS.includes(m));\n console.log(\n `[ClawRouter] Tool-compliance filter: excluded ${dropped.join(\", \")} (unreliable tool schema handling)`,\n );\n toolFiltered = compliant;\n }\n }\n\n // Filter to models that support vision when request has image_url content\n const visionFiltered = filterByVision(toolFiltered, hasVision, supportsVision);\n const visionExcluded = toolFiltered.filter((m) => !visionFiltered.includes(m));\n if (visionExcluded.length > 0) {\n console.log(\n `[ClawRouter] Vision filter: excluded ${visionExcluded.join(\", \")} (no vision support)`,\n );\n }\n\n // Limit to MAX_FALLBACK_ATTEMPTS to prevent infinite loops\n modelsToTry = visionFiltered.slice(0, MAX_FALLBACK_ATTEMPTS);\n\n // Deprioritize rate-limited models (put them at the end)\n modelsToTry = prioritizeNonRateLimited(modelsToTry);\n } else {\n // For explicit model requests, use the requested model\n modelsToTry = modelId ? [modelId] : [];\n }\n\n // Ensure free model is the last-resort fallback for non-tool requests.\n // Skip free fallback when tools are present — nvidia/gpt-oss-120b lacks\n // tool calling support and would produce broken responses for agentic tasks.\n if (!hasTools && !modelsToTry.includes(FREE_MODEL) && !excludeList.has(FREE_MODEL)) {\n modelsToTry.push(FREE_MODEL); // last-resort free fallback\n }\n\n // --- Budget-aware routing (graceful mode) ---\n // Filter modelsToTry to only models that fit within the remaining session budget.\n // Simple tasks (no tools, non-complex tier): downgrade with visible warning.\n // Complex/agentic tasks with no affordable model: already blocked above (before streaming headers).\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const beforeFilter = [...modelsToTry];\n modelsToTry = modelsToTry.filter((m) => {\n if (FREE_MODELS.has(m)) return true; // free models always fit (no cost)\n const est = estimateAmount(m, body.length, maxTokens);\n if (!est) return true; // no pricing data → keep (permissive)\n return Number(est) / 1_000_000 <= remainingUsd;\n });\n\n const excluded = beforeFilter.filter((m) => !modelsToTry.includes(m));\n\n // Second-pass block: the pre-check caught obvious cases early (before streaming headers).\n // Here we recheck against the actual filtered modelsToTry chain. If the ONLY remaining\n // models are free, we must block rather than silently degrade for:\n // (A) complex/agentic routing profile tasks (tools / COMPLEX / REASONING tier)\n // (B) explicit model requests (user chose a specific model; free substitution is deceptive)\n // The pre-check already handles case (B) for non-streaming; this is a safety net for\n // streaming requests where SSE headers may have already been sent.\n const isComplexOrAgenticFilter =\n hasTools ||\n routingDecision?.tier === \"COMPLEX\" ||\n routingDecision?.tier === \"REASONING\" ||\n routingDecision === undefined; // explicit model: no routing profile → user chose the model\n const filteredToFreeOnly =\n modelsToTry.length > 0 && modelsToTry.every((m) => FREE_MODELS.has(m));\n\n if (isComplexOrAgenticFilter && filteredToFreeOnly) {\n const budgetSummary = `$${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget filter left only free model for complex/agentic session — blocking (${budgetSummary})`,\n );\n const errPayload = JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: remaining budget (${budgetSummary}) cannot support a complex/tool request. Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n });\n if (heartbeatInterval) clearInterval(heartbeatInterval);\n if (headersSentEarly) {\n // Streaming: inject error SSE event + [DONE] and close\n safeWrite(res, `data: ${errPayload}\\n\\ndata: [DONE]\\n\\n`);\n res.end();\n } else {\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(errPayload);\n }\n deduplicator.removeInflight(dedupKey);\n return;\n }\n\n if (excluded.length > 0) {\n const budgetSummary =\n remainingUsd > 0\n ? `$${remainingUsd.toFixed(4)} remaining`\n : `budget exhausted ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget downgrade (${budgetSummary}): excluded ${excluded.join(\", \")}`,\n );\n\n // A: Set visible warning notice — prepended to response so user sees the downgrade\n const fromModel = excluded[0];\n const usingFree = modelsToTry.length === 1 && FREE_MODELS.has(modelsToTry[0]);\n if (usingFree) {\n budgetDowngradeNotice = `> **⚠️ Budget cap reached** ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd}) — downgraded to free model. Quality may be reduced. Increase \\`maxCostPerRun\\` to continue with ${fromModel}.\\n\\n`;\n } else {\n const toModel = modelsToTry[0] ?? FREE_MODEL; // last resort\n budgetDowngradeNotice = `> **⚠️ Budget low** ($${remainingUsd > 0 ? remainingUsd.toFixed(4) : \"0.0000\"} remaining) — using ${toModel} instead of ${fromModel}.\\n\\n`;\n }\n // B: Header flag for orchestration layers (e.g. OpenClaw can pause/warn the user)\n budgetDowngradeHeaderMode = \"downgraded\";\n }\n }\n\n // --- Fallback loop: try each model until success ---\n let upstream: Response | undefined;\n let lastError: { body: string; status: number } | undefined;\n let actualModelUsed = modelId;\n const failedAttempts: Array<{ model: string; reason: string; status: number }> = [];\n\n for (let i = 0; i < modelsToTry.length; i++) {\n const tryModel = modelsToTry[i];\n const isLastAttempt = i === modelsToTry.length - 1;\n\n // Abort immediately if global deadline has already fired\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n console.log(`[ClawRouter] Trying model ${i + 1}/${modelsToTry.length}: ${tryModel}`);\n\n // Per-model abort controller — each model attempt gets its own 60s window.\n // When it fires, the fallback loop moves to the next model rather than failing.\n const modelController = new AbortController();\n const modelTimeoutId = setTimeout(() => modelController.abort(), PER_MODEL_TIMEOUT_MS);\n const combinedSignal = AbortSignal.any([globalController.signal, modelController.signal]);\n\n const result = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n combinedSignal,\n );\n clearTimeout(modelTimeoutId);\n\n // If the global deadline fired during this attempt, bail out entirely\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n // If the per-model timeout fired (but not global), treat as fallback-worthy error\n if (!result.success && modelController.signal.aborted && !isLastAttempt) {\n console.log(\n `[ClawRouter] Model ${tryModel} timed out after ${PER_MODEL_TIMEOUT_MS}ms, trying fallback`,\n );\n recordProviderError(tryModel, \"server_error\");\n continue;\n }\n\n if (result.success && result.response) {\n upstream = result.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Success with model: ${tryModel}`);\n // Accumulate estimated cost to session for maxCostPerRun tracking\n if (options.maxCostPerRunUsd && effectiveSessionId && !FREE_MODELS.has(tryModel)) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n\n // Request failed\n lastError = {\n body: result.errorBody || \"Unknown error\",\n status: result.errorStatus || 500,\n };\n failedAttempts.push({\n model: tryModel,\n reason: result.errorCategory || `HTTP ${result.errorStatus || 500}`,\n status: result.errorStatus || 500,\n });\n\n // Payment error (insufficient funds, simulation failure) — skip remaining\n // paid models, jump straight to free model. No point trying other paid\n // models with the same wallet state.\n // Must be checked BEFORE isProviderError gate: payment settlement failures\n // may return non-standard HTTP codes that categorizeError doesn't recognize,\n // causing isProviderError=false and breaking out of the fallback loop.\n const isPaymentErr =\n /payment.*verification.*failed|payment.*settlement.*failed|insufficient.*funds|transaction_simulation_failed/i.test(\n result.errorBody || \"\",\n );\n if (isPaymentErr && !FREE_MODELS.has(tryModel) && !isLastAttempt) {\n failedAttempts.push({\n ...failedAttempts[failedAttempts.length - 1],\n reason: \"payment_error\",\n });\n const freeIdx = modelsToTry.indexOf(FREE_MODEL);\n if (freeIdx > i + 1) {\n console.log(`[ClawRouter] Payment error — skipping to free model: ${FREE_MODEL}`);\n i = freeIdx - 1; // loop will increment to freeIdx\n continue;\n }\n // Free model not in chain — add it and try\n if (freeIdx === -1 && !excludeList.has(FREE_MODEL)) {\n modelsToTry.push(FREE_MODEL);\n console.log(`[ClawRouter] Payment error — appending free model: ${FREE_MODEL}`);\n continue;\n }\n }\n\n // If it's a provider error and not the last attempt, try next model\n if (result.isProviderError && !isLastAttempt) {\n const isExplicitModelError = !routingDecision;\n const isUnknownExplicitModel =\n isExplicitModelError && /unknown.*model|invalid.*model/i.test(result.errorBody || \"\");\n if (isUnknownExplicitModel) {\n console.log(\n `[ClawRouter] Explicit model error from ${tryModel}, not falling back: ${result.errorBody?.slice(0, 100)}`,\n );\n break;\n }\n\n // Record error and apply category-specific handling\n const errorCat = result.errorCategory;\n if (errorCat) {\n recordProviderError(tryModel, errorCat);\n }\n\n if (errorCat === \"rate_limited\") {\n // --- Stepped backoff retry (429) ---\n // Token-bucket rate limits often recover within milliseconds.\n // Retry once after 200ms before treating this as a model-level failure.\n if (!isLastAttempt && !globalController.signal.aborted) {\n console.log(\n `[ClawRouter] Rate-limited on ${tryModel}, retrying in 200ms before failover`,\n );\n await new Promise((resolve) => setTimeout(resolve, 200));\n if (!globalController.signal.aborted) {\n const retryController = new AbortController();\n const retryTimeoutId = setTimeout(\n () => retryController.abort(),\n PER_MODEL_TIMEOUT_MS,\n );\n const retrySignal = AbortSignal.any([\n globalController.signal,\n retryController.signal,\n ]);\n const retryResult = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n retrySignal,\n );\n clearTimeout(retryTimeoutId);\n if (retryResult.success && retryResult.response) {\n upstream = retryResult.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Rate-limit retry succeeded for: ${tryModel}`);\n if (options.maxCostPerRunUsd && effectiveSessionId && tryModel !== FREE_MODEL) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n // Retry also failed — fall through to markRateLimited\n }\n }\n markRateLimited(tryModel);\n // Check for server-side update hint in 429 response\n try {\n const parsed = JSON.parse(result.errorBody || \"{}\");\n if (parsed.update_available) {\n console.log(\"\");\n console.log(\n `\\x1b[33m⬆️ ClawRouter ${parsed.update_available} available (you have ${VERSION})\\x1b[0m`,\n );\n console.log(\n ` Run: \\x1b[36mcurl -fsSL ${parsed.update_url || \"https://blockrun.ai/ClawRouter-update\"} | bash\\x1b[0m`,\n );\n console.log(\"\");\n }\n } catch {\n /* ignore parse errors */\n }\n } else if (errorCat === \"overloaded\") {\n markOverloaded(tryModel);\n } else if (errorCat === \"auth_failure\" || errorCat === \"quota_exceeded\") {\n console.log(\n `[ClawRouter] 🔑 ${errorCat === \"auth_failure\" ? \"Auth failure\" : \"Quota exceeded\"} for ${tryModel} — check provider config`,\n );\n }\n\n console.log(\n `[ClawRouter] Provider error from ${tryModel}, trying fallback: ${result.errorBody?.slice(0, 100)}`,\n );\n continue;\n }\n\n // Not a provider error or last attempt — stop trying\n if (!result.isProviderError) {\n console.log(\n `[ClawRouter] Non-provider error from ${tryModel}, not retrying: ${result.errorBody?.slice(0, 100)}`,\n );\n }\n break;\n }\n\n // Clear timeout — request attempts completed\n clearTimeout(timeoutId);\n\n // Clear heartbeat — real data is about to flow\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // --- Emit routing debug info (opt-in via x-clawrouter-debug: true header) ---\n // For streaming: SSE comment (invisible to most clients, visible in raw stream)\n // For non-streaming: response headers added later\n if (debugMode && headersSentEarly && routingDecision) {\n const debugComment = `: x-clawrouter-debug profile=${routingProfile ?? \"auto\"} tier=${routingDecision.tier} model=${actualModelUsed} agentic=${routingDecision.agenticScore?.toFixed(2) ?? \"n/a\"} confidence=${routingDecision.confidence.toFixed(2)} reasoning=${routingDecision.reasoning}\\n\\n`;\n safeWrite(res, debugComment);\n }\n\n // Update routing decision with actual model used (for logging)\n // IMPORTANT: Recalculate cost for the actual model, not the original primary\n if (routingDecision && actualModelUsed !== routingDecision.model) {\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const newCosts = calculateModelCost(\n actualModelUsed,\n routerOpts.modelPricing,\n estimatedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n routingDecision = {\n ...routingDecision,\n model: actualModelUsed,\n reasoning: `${routingDecision.reasoning} | fallback to ${actualModelUsed}`,\n costEstimate: newCosts.costEstimate,\n baselineCost: newCosts.baselineCost,\n savings: newCosts.savings,\n };\n options.onRouted?.(routingDecision);\n\n // Update session pin to the actual model used — ensures the next request in\n // this conversation starts from the fallback model rather than retrying the\n // primary and falling back again (prevents the \"model keeps jumping\" issue).\n if (effectiveSessionId) {\n sessionStore.setSession(effectiveSessionId, actualModelUsed, routingDecision.tier);\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... updated pin to fallback: ${actualModelUsed}`,\n );\n }\n }\n\n // --- Handle case where all models failed ---\n if (!upstream) {\n // Build structured error summary listing all attempted models\n const attemptSummary =\n failedAttempts.length > 0\n ? failedAttempts.map((a) => `${a.model} (${a.reason})`).join(\", \")\n : \"unknown\";\n const structuredMessage =\n failedAttempts.length > 0\n ? `All ${failedAttempts.length} models failed. Tried: ${attemptSummary}`\n : \"All models in fallback chain failed\";\n console.log(`[ClawRouter] ${structuredMessage}`);\n const rawErrBody = lastError?.body || structuredMessage;\n const errStatus = lastError?.status || 502;\n\n // Transform payment errors into user-friendly messages\n const transformedErr = transformPaymentError(rawErrBody, {\n baseAssetSymbol: requestBasePaymentAsset.symbol,\n baseAssetDecimals: requestBasePaymentAsset.decimals,\n });\n\n if (headersSentEarly) {\n // Streaming: send error as SSE event\n // If transformed error is already JSON, parse and use it; otherwise wrap in standard format\n let errPayload: string;\n try {\n const parsed = JSON.parse(transformedErr);\n errPayload = JSON.stringify(parsed);\n } catch {\n errPayload = JSON.stringify({\n error: { message: rawErrBody, type: \"provider_error\", status: errStatus },\n });\n }\n const errEvent = `data: ${errPayload}\\n\\n`;\n safeWrite(res, errEvent);\n safeWrite(res, \"data: [DONE]\\n\\n\");\n res.end();\n\n const errBuf = Buffer.from(errEvent + \"data: [DONE]\\n\\n\");\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: errBuf,\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: send transformed error response with context headers\n res.writeHead(errStatus, {\n \"Content-Type\": \"application/json\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n res.end(transformedErr);\n\n deduplicator.complete(dedupKey, {\n status: errStatus,\n headers: { \"content-type\": \"application/json\" },\n body: Buffer.from(transformedErr),\n completedAt: Date.now(),\n });\n }\n return;\n }\n\n // --- Stream response and collect for dedup cache ---\n const responseChunks: Buffer[] = [];\n\n if (headersSentEarly) {\n // Streaming: headers already sent. Response should be 200 at this point\n // (non-200 responses are handled in the fallback loop above)\n\n // Convert non-streaming JSON response to SSE streaming format for client\n // (BlockRun API returns JSON since we forced stream:false)\n // OpenClaw expects: object=\"chat.completion.chunk\" with choices[].delta (not message)\n // We emit proper incremental deltas to match OpenAI's streaming format exactly\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n\n // Combine chunks and transform to streaming format\n const jsonBody = Buffer.concat(chunks);\n const jsonStr = jsonBody.toString();\n try {\n const rsp = JSON.parse(jsonStr) as {\n id?: string;\n object?: string;\n created?: number;\n model?: string;\n choices?: Array<{\n index?: number;\n message?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n delta?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: unknown;\n };\n\n // Extract input token count from upstream response\n if (rsp.usage && typeof rsp.usage === \"object\") {\n const u = rsp.usage as Record;\n if (typeof u.prompt_tokens === \"number\") responseInputTokens = u.prompt_tokens;\n if (typeof u.completion_tokens === \"number\") responseOutputTokens = u.completion_tokens;\n }\n\n // Build base chunk structure (reused for all chunks)\n // Match OpenAI's exact format including system_fingerprint\n const baseChunk = {\n id: rsp.id ?? `chatcmpl-${Date.now()}`,\n object: \"chat.completion.chunk\",\n created: rsp.created ?? Math.floor(Date.now() / 1000),\n model: actualModelUsed || rsp.model || \"unknown\",\n system_fingerprint: null,\n };\n\n // Process each choice (usually just one)\n if (rsp.choices && Array.isArray(rsp.choices)) {\n for (const choice of rsp.choices) {\n // Strip thinking tokens (Kimi <|...|> and standard tags)\n const rawContent = choice.message?.content ?? choice.delta?.content ?? \"\";\n const content = stripThinkingTokens(rawContent);\n const role = choice.message?.role ?? choice.delta?.role ?? \"assistant\";\n const index = choice.index ?? 0;\n\n // Accumulate content for session journal\n if (content) {\n accumulatedContent += content;\n }\n\n // Chunk 1: role only (mimics OpenAI's first chunk)\n const roleChunk = {\n ...baseChunk,\n choices: [{ index, delta: { role }, logprobs: null, finish_reason: null }],\n };\n const roleData = `data: ${JSON.stringify(roleChunk)}\\n\\n`;\n safeWrite(res, roleData);\n responseChunks.push(Buffer.from(roleData));\n\n // Chunk 1.5: balance fallback notice (tells user they got free model)\n if (balanceFallbackNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: balanceFallbackNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n balanceFallbackNotice = undefined; // Only inject once\n }\n\n // Chunk 1.6: budget downgrade notice (A: visible warning when model downgraded)\n if (budgetDowngradeNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: budgetDowngradeNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n budgetDowngradeNotice = undefined; // Only inject once\n }\n\n // Chunk 2: content (single chunk with full content)\n if (content) {\n const contentChunk = {\n ...baseChunk,\n choices: [{ index, delta: { content }, logprobs: null, finish_reason: null }],\n };\n const contentData = `data: ${JSON.stringify(contentChunk)}\\n\\n`;\n safeWrite(res, contentData);\n responseChunks.push(Buffer.from(contentData));\n }\n\n // Chunk 2b: tool_calls (forward tool calls from upstream)\n const toolCalls = choice.message?.tool_calls ?? choice.delta?.tool_calls;\n if (toolCalls && toolCalls.length > 0) {\n const toolCallChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { tool_calls: toolCalls },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const toolCallData = `data: ${JSON.stringify(toolCallChunk)}\\n\\n`;\n safeWrite(res, toolCallData);\n responseChunks.push(Buffer.from(toolCallData));\n }\n\n // Chunk 3: finish_reason (signals completion)\n const finishChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: {},\n logprobs: null,\n finish_reason:\n toolCalls && toolCalls.length > 0\n ? \"tool_calls\"\n : (choice.finish_reason ?? \"stop\"),\n },\n ],\n };\n const finishData = `data: ${JSON.stringify(finishChunk)}\\n\\n`;\n safeWrite(res, finishData);\n responseChunks.push(Buffer.from(finishData));\n }\n }\n } catch {\n // If parsing fails, send raw response as single chunk\n const sseData = `data: ${jsonStr}\\n\\n`;\n safeWrite(res, sseData);\n responseChunks.push(Buffer.from(sseData));\n }\n }\n\n // Send cost summary as SSE comment before terminator\n if (routingDecision) {\n const costComment = `: cost=$${routingDecision.costEstimate.toFixed(4)} savings=${(routingDecision.savings * 100).toFixed(0)}% model=${actualModelUsed} tier=${routingDecision.tier}\\n\\n`;\n safeWrite(res, costComment);\n responseChunks.push(Buffer.from(costComment));\n }\n\n // Send SSE terminator\n safeWrite(res, \"data: [DONE]\\n\\n\");\n responseChunks.push(Buffer.from(\"data: [DONE]\\n\\n\"));\n res.end();\n\n // Cache for dedup\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: Buffer.concat(responseChunks),\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: forward status and headers from upstream\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n // Skip hop-by-hop headers and content-encoding (fetch already decompresses)\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\")\n return;\n responseHeaders[key] = value;\n });\n\n // Add context usage headers\n responseHeaders[\"x-context-used-kb\"] = String(originalContextSizeKB);\n responseHeaders[\"x-context-limit-kb\"] = String(CONTEXT_LIMIT_KB);\n\n // Add routing debug headers (opt-in via x-clawrouter-debug: true header)\n if (debugMode && routingDecision) {\n responseHeaders[\"x-clawrouter-profile\"] = routingProfile ?? \"auto\";\n responseHeaders[\"x-clawrouter-tier\"] = routingDecision.tier;\n responseHeaders[\"x-clawrouter-model\"] = actualModelUsed;\n responseHeaders[\"x-clawrouter-confidence\"] = routingDecision.confidence.toFixed(2);\n responseHeaders[\"x-clawrouter-reasoning\"] = routingDecision.reasoning;\n if (routingDecision.agenticScore !== undefined) {\n responseHeaders[\"x-clawrouter-agentic-score\"] = routingDecision.agenticScore.toFixed(2);\n }\n }\n\n // Always include cost visibility headers when routing is active\n if (routingDecision) {\n responseHeaders[\"x-clawrouter-cost\"] = routingDecision.costEstimate.toFixed(6);\n responseHeaders[\"x-clawrouter-savings\"] = `${(routingDecision.savings * 100).toFixed(0)}%`;\n }\n\n // Collect full body for possible notice injection\n const bodyParts: Buffer[] = [];\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n for (const chunk of chunks) {\n bodyParts.push(Buffer.from(chunk));\n }\n }\n\n let responseBody = Buffer.concat(bodyParts);\n\n // Prepend balance fallback notice to response content\n if (balanceFallbackNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n balanceFallbackNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n balanceFallbackNotice = undefined;\n }\n\n // A: Prepend budget downgrade notice to response content\n if (budgetDowngradeNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n budgetDowngradeNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n budgetDowngradeNotice = undefined;\n }\n\n // Inject actualModelUsed into non-streaming response model field\n if (actualModelUsed && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as { model?: string };\n if (parsed.model !== undefined) {\n parsed.model = actualModelUsed;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip model injection */\n }\n }\n\n // B: Add budget downgrade headers for orchestration layers\n if (budgetDowngradeHeaderMode) {\n responseHeaders[\"x-clawrouter-budget-downgrade\"] = \"1\";\n responseHeaders[\"x-clawrouter-budget-mode\"] = budgetDowngradeHeaderMode;\n budgetDowngradeHeaderMode = undefined;\n }\n\n // Update content-length header since body may have changed\n responseHeaders[\"content-length\"] = String(responseBody.length);\n res.writeHead(upstream.status, responseHeaders);\n safeWrite(res, responseBody);\n responseChunks.push(responseBody);\n res.end();\n\n // Cache for dedup (short-term, 30s)\n deduplicator.complete(dedupKey, {\n status: upstream.status,\n headers: responseHeaders,\n body: responseBody,\n completedAt: Date.now(),\n });\n\n // Cache for response cache (long-term, 10min) - only successful non-streaming\n if (upstream.status === 200 && responseCache.shouldCache(body)) {\n responseCache.set(cacheKey, {\n body: responseBody,\n status: upstream.status,\n headers: responseHeaders,\n model: actualModelUsed,\n });\n console.log(\n `[ClawRouter] Cached response for ${actualModelUsed} (${responseBody.length} bytes)`,\n );\n }\n\n // Extract content and token usage from non-streaming response\n try {\n const rspJson = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n usage?: Record;\n };\n if (rspJson.choices?.[0]?.message?.content) {\n accumulatedContent = rspJson.choices[0].message.content;\n }\n if (rspJson.usage && typeof rspJson.usage === \"object\") {\n if (typeof rspJson.usage.prompt_tokens === \"number\")\n responseInputTokens = rspJson.usage.prompt_tokens;\n if (typeof rspJson.usage.completion_tokens === \"number\")\n responseOutputTokens = rspJson.usage.completion_tokens;\n }\n } catch {\n // Ignore parse errors - journal just won't have content for this response\n }\n }\n\n // --- Session Journal: Extract and record events from response ---\n if (sessionId && accumulatedContent) {\n const events = sessionJournal.extractEvents(accumulatedContent);\n if (events.length > 0) {\n sessionJournal.record(sessionId, events, actualModelUsed);\n console.log(\n `[ClawRouter] Recorded ${events.length} events to session journal for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n\n // --- Optimistic balance deduction after successful response ---\n if (estimatedCostMicros !== undefined) {\n requestBalanceMonitor.deductEstimated(estimatedCostMicros);\n }\n\n // Mark request as completed (for client disconnect cleanup)\n completed = true;\n } catch (err) {\n // Clear timeout on error\n clearTimeout(timeoutId);\n\n // Clear heartbeat on error\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // Remove in-flight entry so retries aren't blocked\n deduplicator.removeInflight(dedupKey);\n\n // Invalidate balance cache on payment failure (might be out of date)\n requestBalanceMonitor.invalidate();\n\n // Convert abort error to more descriptive timeout error\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err });\n }\n\n throw err;\n }\n\n // --- Usage logging (fire-and-forget) ---\n // Use actual x402 payment amount from the per-request AsyncLocalStorage store.\n // This is the real amount the user paid — no estimation needed.\n // Falls back to local estimate only for free models (no x402 payment).\n const logModel = routingDecision?.model ?? modelId;\n if (logModel) {\n const actualPayment = paymentStore.getStore()?.amountUsd ?? 0;\n\n // For free models (no x402 payment), use local cost calculation as fallback\n let logCost: number;\n let logBaseline: number;\n let logSavings: number;\n if (actualPayment > 0) {\n logCost = actualPayment;\n // Calculate baseline for savings comparison\n const chargedInputTokens = Math.ceil(body.length / 4);\n const modelDef = BLOCKRUN_MODELS.find((m) => m.id === logModel);\n const chargedOutputTokens = modelDef ? Math.min(maxTokens, modelDef.maxOutput) : maxTokens;\n const baseline = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n chargedOutputTokens,\n routingProfile ?? undefined,\n );\n logBaseline = baseline.baselineCost;\n logSavings = logBaseline > 0 ? Math.max(0, (logBaseline - logCost) / logBaseline) : 0;\n } else {\n // Free model — no payment, calculate locally\n const chargedInputTokens = Math.ceil(body.length / 4);\n const costs = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n logCost = costs.costEstimate;\n logBaseline = costs.baselineCost;\n logSavings = costs.savings;\n }\n\n const entry: UsageEntry = {\n timestamp: new Date().toISOString(),\n model: logModel,\n tier: routingDecision?.tier ?? \"DIRECT\",\n cost: logCost,\n baselineCost: logBaseline,\n savings: logSavings,\n latencyMs: Date.now() - startTime,\n ...(responseInputTokens !== undefined && { inputTokens: responseInputTokens }),\n ...(responseOutputTokens !== undefined && { outputTokens: responseOutputTokens }),\n };\n logUsage(entry).catch(() => {});\n }\n}\n","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\n}\n","import type {\n Abi,\n AbiParameter,\n AbiParameterToPrimitiveType,\n ExtractAbiEvents,\n} from 'abitype'\n\nimport {\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeEventTopics'\n\nexport type EncodeEventTopicsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n ///\n hasEvents = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiEvents] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >,\n allErrorNames = ContractEventName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { eventName?: eventName | allErrorNames | undefined }\n : { eventName: eventName | allErrorNames }\n : { eventName?: eventName | allErrorNames | undefined }\n> &\n (hasEvents extends true ? unknown : never)\n\nexport type EncodeEventTopicsReturnType = [Hex, ...(Hex | Hex[] | null)[]]\n\nexport type EncodeEventTopicsErrorType =\n | AbiEventNotFoundErrorType\n | EncodeArgErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nexport function encodeEventTopics<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n>(\n parameters: EncodeEventTopicsParameters,\n): EncodeEventTopicsReturnType {\n const { abi, eventName, args } = parameters as EncodeEventTopicsParameters\n\n let abiItem = abi[0]\n if (eventName) {\n const item = getAbiItem({ abi, name: eventName })\n if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'event')\n throw new AbiEventNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toEventSelector(definition as EventDefinition)\n\n let topics: (Hex | Hex[] | null)[] = []\n if (args && 'inputs' in abiItem) {\n const indexedInputs = abiItem.inputs?.filter(\n (param) => 'indexed' in param && param.indexed,\n )\n const args_ = Array.isArray(args)\n ? args\n : Object.values(args).length > 0\n ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])\n : []\n\n if (args_.length > 0) {\n topics =\n indexedInputs?.map((param, i) => {\n if (Array.isArray(args_[i]))\n return args_[i].map((_: any, j: number) =>\n encodeArg({ param, value: args_[i][j] }),\n )\n return typeof args_[i] !== 'undefined' && args_[i] !== null\n ? encodeArg({ param, value: args_[i] })\n : null\n }) ?? []\n }\n }\n return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | EncodeAbiParametersErrorType\n | FilterTypeNotSupportedErrorType\n | ErrorType\n\nfunction encodeArg({\n param,\n value,\n}: {\n param: AbiParameter\n value: AbiParameterToPrimitiveType\n}) {\n if (param.type === 'string' || param.type === 'bytes')\n return keccak256(toBytes(value as string))\n if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n throw new FilterTypeNotSupportedError(param.type)\n return encodeAbiParameters([param], [value])\n}\n","import { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n constructor(type: string) {\n super(`Filter type \"${type}\" is not supported.`, {\n name: 'FilterTypeNotSupportedError',\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n abi: abi\n eventName?: eventName | ContractEventName | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n * @default false\n */\n strict?: strict | boolean | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (undefined extends eventName\n ? {\n args?: undefined\n }\n : MaybeExtractEventArgsFromAbi extends infer eventFilterArgs\n ? {\n args?:\n | eventFilterArgs\n | (args extends eventFilterArgs ? args : never)\n | undefined\n }\n : {\n args?: undefined\n })\n\nexport type CreateContractEventFilterReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', abi, eventName, args, strict, fromBlock, toBlock>\n\nexport type CreateContractEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const { address, abi, args, eventName, fromBlock, strict, toBlock } =\n parameters as CreateContractEventFilterParameters\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n const topics = eventName\n ? encodeEventTopics({\n abi,\n args,\n eventName,\n } as unknown as EncodeEventTopicsParameters)\n : undefined\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n topics,\n },\n ],\n })\n\n return {\n abi,\n args,\n eventName,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n type: 'event',\n } as unknown as CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn, PublicRpcSchema } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n method:\n | 'eth_newFilter'\n | 'eth_newPendingTransactionFilter'\n | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n PublicRpcSchema,\n { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n id: Hex,\n) => EIP1193RequestFn\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope(\n client: Client,\n { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n const requestMap: Record = {}\n\n if (client.transport.type === 'fallback')\n client.transport.onResponse?.(\n ({\n method: method_,\n response: id,\n status,\n transport,\n }: Parameters[0]) => {\n if (status === 'success' && method === method_)\n requestMap[id as Hex] = transport.request\n },\n )\n\n return ((id) =>\n requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi } 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 type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n GetValue,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from './estimateGas.js'\n\nexport type EstimateContractGasParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n> = ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit, 'data' | 'to' | 'value'> &\n GetValue<\n abi,\n functionName,\n EstimateGasParameters extends EstimateGasParameters\n ? EstimateGasParameters['value']\n : EstimateGasParameters['value']\n > & {\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n }\n\nexport type EstimateContractGasReturnType = bigint\n\nexport type EstimateContractGasErrorType = GetContractErrorReturnType<\n EncodeFunctionDataErrorType | EstimateGasErrorType | ParseAccountErrorType\n>\n\n/**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateContractGas } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await estimateContractGas(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\nexport async function estimateContractGas<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs,\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n parameters: EstimateContractGasParameters,\n): Promise {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...request\n } = parameters as EstimateContractGasParameters\n const data = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n\n try {\n const gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n data: `${data}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...request,\n } as unknown as EstimateGasParameters)\n return gas\n } catch (error) {\n const account = request.account ? parseAccount(request.account) : undefined\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/estimateContractGas',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport { InternalRpcError, InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType = Omit<\n ContractFunctionExecutionErrorType,\n 'cause'\n> & {\n cause:\n | cause\n | ContractFunctionZeroDataErrorType\n | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError>(\n err: err,\n {\n abi,\n address,\n args,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args: any\n address?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const error = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as BaseError\n const { code, data, details, message, shortMessage } =\n error as RawContractError\n\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName })\n if (\n ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || details || message || shortMessage)) ||\n (code === InvalidInputRpcError.code &&\n details === 'execution reverted' &&\n data)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message:\n error instanceof RpcRequestError\n ? details\n : (shortMessage ?? message),\n })\n }\n return err\n })()\n\n return new ContractFunctionExecutionError(cause as BaseError, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n }) as GetContractErrorReturnType\n}\n","import type { Address } from 'abitype'\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 { BaseError } from '../../errors/base.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestParameterType,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n account?: Account | Address | undefined\n prepare?:\n | boolean\n | readonly PrepareTransactionRequestParameterType[]\n | undefined\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 FormattedEstimateGas =\n FormattedTransactionRequest\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\n | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in gas units). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n args: EstimateGasParameters,\n): Promise {\n const { account: account_ = client.account, prepare = true } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n const parameters = (() => {\n if (Array.isArray(prepare)) return prepare\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n if (account?.type !== 'local') return ['blobVersionedHashes']\n return undefined\n })()\n\n try {\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (args.to) return args.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (args.authorizationList && args.authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: args.authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = prepare\n ? ((await prepareTransactionRequest(client, {\n ...args,\n parameters,\n to,\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters)\n : args\n\n // If we get `gas` back from the prepared transaction request, which is\n // different from the `gas` we provided, it was likely filled by other means\n // during request preparation (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n // (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n if (gas && args.gas !== gas) return gas\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\n\n assertRequest(args as AssertRequestParameters)\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest,\n 'estimateGas',\n )\n\n return BigInt(\n await client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [\n request,\n block ?? client.experimental_blockTag ?? 'latest',\n rpcStateOverride,\n ]\n : block\n ? [request, block]\n : [request],\n }),\n )\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\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 type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { size } from '../data/size.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n if (size(signatureHex) !== 65) throw new Error('invalid signature length')\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise {\n return publicKeyToAddress(await recoverPublicKey({ hash, signature }))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { AuthorizationRequest } from '../../types/authorization.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type NumberToHexErrorType, numberToHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters =\n AuthorizationRequest & {\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, nonce, to } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n address,\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 { 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 { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../signature/recoverAddress.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n > = OneOf,\n //\n _signature = Hex | ByteArray | OneOf,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization:\n | authorization\n | OneOf\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n >,\n>(\n parameters: RecoverAuthorizationAddressParameters,\n): Promise {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as AuthorizationRequest),\n signature: (signature ?? authorization) as Signature,\n })\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError 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, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Estimate Gas Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'EstimateGasExecutionError',\n })\n this.cause = cause\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.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 GetEstimateGasErrorReturnType = Omit<\n EstimateGasExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError>(\n err: err,\n {\n docsPath,\n ...args\n }: Omit & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n): GetEstimateGasErrorReturnType {\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 EstimateGasExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetEstimateGasErrorReturnType\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n type EstimateFeesPerGasErrorType,\n internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type GetBlockErrorType,\n getBlock as getBlock_,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetTransactionCountErrorType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { LruMap } from '../../utils/lru.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport {\n type FillTransactionErrorType,\n type FillTransactionParameters,\n fillTransaction,\n} from '../public/fillTransaction.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\n/** @internal */\nexport const eip1559NetworkCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport const supportsFillTransaction = /*#__PURE__*/ new LruMap(128)\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType extends 'legacy'\n ? unknown\n : GetTransactionType,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick)\n>\n\nexport type PrepareTransactionRequestErrorType =\n | AccountNotFoundErrorType\n | AssertRequestErrorType\n | ParseAccountErrorType\n | GetBlockErrorType\n | GetTransactionCountErrorType\n | EstimateGasErrorType\n | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n let request = args as PrepareTransactionRequestParameters\n\n request.account ??= client.account\n request.parameters ??= defaultParameters\n\n const {\n account: account_,\n chain = client.chain,\n nonceManager,\n parameters,\n } = request\n\n const prepareTransactionRequest = (() => {\n if (typeof chain?.prepareTransactionRequest === 'function')\n return {\n fn: chain.prepareTransactionRequest,\n runAt: ['beforeFillTransaction'],\n }\n if (Array.isArray(chain?.prepareTransactionRequest))\n return {\n fn: chain.prepareTransactionRequest[0],\n runAt: chain.prepareTransactionRequest[1].runAt,\n }\n return undefined\n })()\n\n let chainId: number | undefined\n async function getChainId(): Promise {\n if (chainId) return chainId\n if (typeof request.chainId !== 'undefined') return request.chainId\n if (chain) return chain.id\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n const account = account_ ? parseAccount(account_) : account_\n\n let nonce = request.nonce\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n nonceManager\n ) {\n const chainId = await getChainId()\n nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n }\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillTransaction')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillTransaction',\n },\n )\n nonce ??= request.nonce\n }\n\n const attemptFill = (() => {\n // Do not attempt if blobs are provided.\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n request.kzg &&\n request.blobs\n )\n return false\n\n // Do not attempt if `eth_fillTransaction` is not supported.\n if (supportsFillTransaction.get(client.uid) === false) return false\n\n // Should attempt `eth_fillTransaction` if \"fees\" or \"gas\" are required to be populated,\n // otherwise, can just use the other individual calls.\n const shouldAttempt = ['fees', 'gas'].some((parameter) =>\n parameters.includes(parameter as PrepareTransactionRequestParameterType),\n )\n if (!shouldAttempt) return false\n\n // Check if `eth_fillTransaction` needs to be called.\n if (parameters.includes('chainId') && typeof request.chainId !== 'number')\n return true\n if (parameters.includes('nonce') && typeof nonce !== 'number') return true\n if (\n parameters.includes('fees') &&\n typeof request.gasPrice !== 'bigint' &&\n (typeof request.maxFeePerGas !== 'bigint' ||\n typeof (request as any).maxPriorityFeePerGas !== 'bigint')\n )\n return true\n if (parameters.includes('gas') && typeof request.gas !== 'bigint')\n return true\n return false\n })()\n\n const fillResult = attemptFill\n ? await getAction(\n client,\n fillTransaction,\n 'fillTransaction',\n )({ ...request, nonce } as FillTransactionParameters)\n .then((result) => {\n const {\n chainId,\n from,\n gas,\n gasPrice,\n nonce,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n type,\n ...rest\n } = result.transaction\n supportsFillTransaction.set(client.uid, true)\n return {\n ...request,\n ...(from ? { from } : {}),\n ...(type ? { type } : {}),\n ...(typeof chainId !== 'undefined' ? { chainId } : {}),\n ...(typeof gas !== 'undefined' ? { gas } : {}),\n ...(typeof gasPrice !== 'undefined' ? { gasPrice } : {}),\n ...(typeof nonce !== 'undefined' ? { nonce } : {}),\n ...(typeof maxFeePerBlobGas !== 'undefined'\n ? { maxFeePerBlobGas }\n : {}),\n ...(typeof maxFeePerGas !== 'undefined' ? { maxFeePerGas } : {}),\n ...(typeof maxPriorityFeePerGas !== 'undefined'\n ? { maxPriorityFeePerGas }\n : {}),\n ...('nonceKey' in rest && typeof rest.nonceKey !== 'undefined'\n ? { nonceKey: rest.nonceKey }\n : {}),\n }\n })\n .catch((e) => {\n const error = e as FillTransactionErrorType\n\n if (error.name !== 'TransactionExecutionError') return request\n\n const unsupported = error.walk?.((e) => {\n const error = e as BaseError\n return (\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n )\n })\n if (unsupported) supportsFillTransaction.set(client.uid, false)\n\n return request\n })\n : request\n\n nonce ??= fillResult.nonce\n\n request = {\n ...(fillResult as any),\n ...(account ? { from: account?.address } : {}),\n ...(nonce ? { nonce } : {}),\n }\n const { blobs, gas, kzg, type } = request\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillParameters')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillParameters',\n },\n )\n }\n\n let block: Block | undefined\n async function getBlock(): Promise {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n !nonceManager\n )\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n let isEip1559Network = eip1559NetworkCache.get(client.uid)\n if (typeof isEip1559Network === 'undefined') {\n const block = await getBlock()\n isEip1559Network = typeof block?.baseFeePerGas === 'bigint'\n eip1559NetworkCache.set(client.uid, isEip1559Network)\n }\n request.type = isEip1559Network ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof request.maxPriorityFeePerGas === 'undefined' &&\n request.maxFeePerGas &&\n request.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof request.maxFeePerGas !== 'undefined' ||\n typeof request.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n if (typeof request.gasPrice === 'undefined') {\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account,\n prepare: account?.type === 'local' ? [] : ['blobVersionedHashes'],\n } as EstimateGasParameters)\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('afterFillParameters')\n )\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'afterFillParameters',\n },\n )\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\n )\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToBigIntErrorType,\n hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChainParameter\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n | GetBlockErrorType\n | HexToBigIntErrorType\n | RequestErrorType\n | GetBlockErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n): Promise {\n return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args: EstimateMaxPriorityFeePerGasParameters & {\n block?: Block | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\n const maxPriorityFeePerGasHex = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n })\n return hexToBigInt(maxPriorityFeePerGasHex)\n } catch {\n // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n const [block, gasPrice] = await Promise.all([\n block_\n ? Promise.resolve(block_)\n : getAction(client, getBlock, 'getBlock')({}),\n getAction(client, getGasPrice, 'getGasPrice')({}),\n ])\n\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n if (maxPriorityFeePerGas < 0n) return 0n\n return maxPriorityFeePerGas\n }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n }) {\n let identifier = 'Block'\n if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n super(`${identifier} could not be found.`, { name: 'BlockNotFoundError' })\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetBlockErrorType =\n | BlockNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n includeTransactions: includeTransactions_,\n }: GetBlockParameters = {},\n): Promise> {\n const includeTransactions = includeTransactions_ ?? false\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let block: RpcBlock | null = null\n if (blockHash) {\n block = await client.request(\n {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n const format = client.chain?.formatters?.block?.format || formatBlock\n return format(block, 'getBlock')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(\n block: ExactPartial,\n _?: string | undefined,\n) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string') return transaction\n return formatTransaction(transaction)\n })\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { SignedAuthorizationList } from '../../types/authorization.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcAuthorizationList, RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n | 'blockHash'\n | 'blockNumber'\n | 'transactionIndex'\n\nexport type FormattedTransaction<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(\n transaction: ExactPartial,\n _?: string | undefined,\n) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? (transactionType as any)[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n } as Transaction\n\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\n\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity) return Number(transaction.yParity)\n\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n) return 0\n if (transaction_.v === 1n || transaction_.v === 28n) return 1\n if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n }\n\n return undefined\n })()\n\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') delete transaction_.maxFeePerBlobGas\n\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map((authorization) => ({\n address: (authorization as any).address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n })) as SignedAuthorizationList\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const gasPrice = await client.request({\n method: 'eth_gasPrice',\n })\n return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesLegacy,\n FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n type EstimateMaxPriorityFeePerGasErrorType,\n internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n type extends FeeValuesType = FeeValuesType,\n> = {\n /**\n * The type of fee values to return.\n *\n * - `legacy`: Returns the legacy gas price.\n * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n *\n * @default 'eip1559'\n */\n type?: type | FeeValuesType | undefined\n} & GetChainParameter\n\nexport type EstimateFeesPerGasReturnType<\n type extends FeeValuesType = FeeValuesType,\n> =\n | (type extends 'legacy' ? FeeValuesLegacy : never)\n | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n | BaseFeeScalarErrorType\n | EstimateMaxPriorityFeePerGasErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args?: EstimateFeesPerGasParameters | undefined,\n): Promise> {\n return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args: EstimateFeesPerGasParameters & {\n block?: Block | undefined\n request?: PrepareTransactionRequestParameters | undefined\n },\n): Promise> {\n const {\n block: block_,\n chain = client.chain,\n request,\n type = 'eip1559',\n } = args || {}\n\n const baseFeeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n return chain.fees.baseFeeMultiplier({\n block: block_ as Block,\n client,\n request,\n } as ChainFeesFnParameters)\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiply = (base: bigint) =>\n (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n BigInt(denominator)\n\n const block = block_\n ? block_\n : await getAction(client, getBlock, 'getBlock')({})\n\n if (typeof chain?.fees?.estimateFeesPerGas === 'function') {\n const fees = (await chain.fees.estimateFeesPerGas({\n block: block_ as Block,\n client,\n multiply,\n request,\n type,\n } as ChainEstimateFeesPerGasFnParameters)) as unknown as EstimateFeesPerGasReturnType\n\n if (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client,\n {\n block: block as Block,\n chain,\n request,\n },\n )\n\n const baseFeePerGas = multiply(block.baseFeePerGas)\n const maxFeePerGas =\n request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as EstimateFeesPerGasReturnType\n }\n\n const gasPrice =\n request?.gasPrice ??\n multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n return {\n gasPrice,\n } as EstimateFeesPerGasReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n /** The account address. */\n address: Address\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [\n address,\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : blockTag,\n ],\n },\n {\n dedupe: Boolean(blockNumber),\n },\n )\n return hexToNumber(count)\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 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","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\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 {\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 {\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 type { Address } from 'abitype'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { BaseFeeScalarError } from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport { getBlock } from './getBlock.js'\nimport { getChainId as getChainId_ } from './getChainId.js'\n\nexport type FillTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetAccountParameter &\n GetChainParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n }\n\nexport type FillTransactionReturnType<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = {\n raw: Hex\n transaction: FormattedTransaction<_derivedChain>\n}\n\nexport type FillTransactionErrorType =\n | GetTransactionErrorReturnType\n | ErrorType\n\n/**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { fillTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await fillTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function fillTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n): Promise> {\n const {\n account = client.account,\n accessList,\n authorizationList,\n chain = client.chain,\n blobVersionedHashes,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce: nonce_,\n nonceManager,\n to,\n type,\n value,\n ...rest\n } = parameters\n\n const nonce = await (async () => {\n if (!account) return nonce_\n if (!nonceManager) return nonce_\n if (typeof nonce_ !== 'undefined') return nonce_\n const account_ = parseAccount(account)\n const chainId = chain\n ? chain.id\n : await getAction(client, getChainId_, 'getChainId')({})\n return await nonceManager.consume({\n address: account_.address,\n chainId,\n client,\n })\n })()\n\n assertRequest(parameters)\n\n const chainFormat = chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account: account ? parseAccount(account) : undefined,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'fillTransaction',\n )\n\n try {\n const response = await client.request({\n method: 'eth_fillTransaction',\n params: [request],\n })\n const format = chain?.formatters?.transaction?.format || formatTransaction\n\n const transaction = format(response.tx)\n\n // Remove unnecessary fields.\n delete transaction.blockHash\n delete transaction.blockNumber\n delete transaction.r\n delete transaction.s\n delete transaction.transactionIndex\n delete transaction.v\n delete transaction.yParity\n\n // Rewrite fields.\n transaction.data = transaction.input\n\n // Preference supplied fees (some nodes do not take these preferences).\n if (transaction.gas) transaction.gas = parameters.gas ?? transaction.gas\n if (transaction.gasPrice)\n transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice\n if (transaction.maxFeePerBlobGas)\n transaction.maxFeePerBlobGas =\n parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas\n if (transaction.maxFeePerGas)\n transaction.maxFeePerGas =\n parameters.maxFeePerGas ?? transaction.maxFeePerGas\n if (transaction.maxPriorityFeePerGas)\n transaction.maxPriorityFeePerGas =\n parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas\n if (transaction.nonce)\n transaction.nonce = parameters.nonce ?? transaction.nonce\n\n // Build fee multiplier function.\n const feeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function') {\n const block = await getAction(client, getBlock, 'getBlock')({})\n return chain.fees.baseFeeMultiplier({\n block,\n client,\n request: parameters,\n } as ChainFeesFnParameters)\n }\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (feeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = feeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiplyFee = (base: bigint) =>\n (base * BigInt(Math.ceil(feeMultiplier * denominator))) /\n BigInt(denominator)\n\n // Apply fee multiplier.\n if (transaction.maxFeePerGas && !parameters.maxFeePerGas)\n transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas)\n if (transaction.gasPrice && !parameters.gasPrice)\n transaction.gasPrice = multiplyFee(transaction.gasPrice)\n\n return {\n raw: response.raw,\n transaction: {\n from: request.from,\n ...transaction,\n },\n }\n } catch (err) {\n throw getTransactionError(\n err as BaseError,\n {\n ...parameters,\n chain: client.chain,\n } as never,\n )\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport {\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n} from '../../errors/transaction.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 GetTransactionErrorParameters = Omit<\n SendTransactionParameters,\n 'account' | 'chain'\n> & {\n account: Account | null\n chain?: Chain | undefined\n docsPath?: string | undefined\n}\n\nexport type GetTransactionErrorReturnType = Omit<\n TransactionExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getTransactionError>(\n err: err,\n { docsPath, ...args }: GetTransactionErrorParameters,\n): GetTransactionErrorReturnType {\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 TransactionExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetTransactionErrorReturnType\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type GetLogsErrorType,\n type GetLogsParameters,\n getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n)\n\nexport type GetContractEventsReturnType<\n abi extends Abi | readonly unknown[] = readonly unknown[],\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n ///\n isPending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetContractEventsErrorType =\n | GetAbiItemErrorType\n | GetLogsErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/contract/getContractEvents#getcontractevents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetContractEventsReturnType\n> {\n const {\n abi,\n address,\n args,\n blockHash,\n eventName,\n fromBlock,\n toBlock,\n strict,\n } = parameters\n const event = eventName\n ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n : undefined\n const events = !event\n ? (abi as Abi).filter((x) => x.type === 'event')\n : undefined\n return getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n blockHash,\n event,\n events,\n fromBlock,\n toBlock,\n strict,\n } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","// TODO(v3): checksum address.\n\nimport type { Abi, AbiEvent, AbiEventParameter, Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractEventName, GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport { toBytes } from '../encoding/toBytes.js'\nimport { formatLog } from '../formatters/log.js'\nimport { keccak256 } from '../hash/keccak256.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type DecodeEventLogErrorType,\n decodeEventLog,\n} from './decodeEventLog.js'\n\nexport type ParseEventLogsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n allArgs = GetEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n {\n EnableUnion: true\n IndexedOnly: false\n Required: false\n }\n >,\n> = {\n /** Contract ABI. */\n abi: abi\n /** Arguments for the event. */\n args?: allArgs | undefined\n /** Contract event. */\n eventName?:\n | eventName\n | ContractEventName\n | ContractEventName[]\n | undefined\n /** List of logs. */\n logs: (Log | RpcLog)[]\n strict?: strict | boolean | undefined\n}\n\nexport type ParseEventLogsReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n derivedEventName extends\n | ContractEventName\n | undefined = eventName extends ContractEventName[]\n ? eventName[number]\n : eventName,\n> = Log[]\n\nexport type ParseEventLogsErrorType = DecodeEventLogErrorType | ErrorType\n\n/**\n * Extracts & decodes logs matching the provided signature(s) (`abi` + optional `eventName`)\n * from a set of opaque logs.\n *\n * @param parameters - {@link ParseEventLogsParameters}\n * @returns The logs. {@link ParseEventLogsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { parseEventLogs } from 'viem/op-stack'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const receipt = await getTransactionReceipt(client, {\n * hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea',\n * })\n *\n * const logs = parseEventLogs({ logs: receipt.logs })\n * // [{ args: { ... }, eventName: 'TransactionDeposited', ... }, ...]\n */\nexport function parseEventLogs<\n abi extends Abi | readonly unknown[],\n strict extends boolean | undefined = true,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = undefined,\n>(\n parameters: ParseEventLogsParameters,\n): ParseEventLogsReturnType {\n const { abi, args, logs, strict = true } = parameters\n\n const eventName = (() => {\n if (!parameters.eventName) return undefined\n if (Array.isArray(parameters.eventName)) return parameters.eventName\n return [parameters.eventName as string]\n })()\n\n const abiTopics = (abi as Abi)\n .filter((abiItem) => abiItem.type === 'event')\n .map((abiItem) => ({\n abi: abiItem,\n selector: toEventSelector(abiItem),\n }))\n\n return logs\n .map((log) => {\n // Normalize RpcLog (hex-encoded quantities) to Log (bigint/number).\n // When logs come directly from an RPC response (e.g. eth_getLogs),\n // fields like blockNumber are hex strings instead of bigints.\n const formattedLog =\n typeof log.blockNumber === 'string' ? formatLog(log as RpcLog) : log\n\n // Find all matching ABI items with the same selector.\n // Multiple events can share the same selector but differ in indexed parameters\n // (e.g., ERC20 vs ERC721 Transfer events).\n const abiItems = abiTopics.filter(\n (abiTopic) => formattedLog.topics[0] === abiTopic.selector,\n )\n if (abiItems.length === 0) return null\n\n // Try each matching ABI item until one successfully decodes.\n let event: { eventName: string; args: unknown } | undefined\n let abiItem: { abi: AbiEvent; selector: Address } | undefined\n\n for (const item of abiItems) {\n try {\n event = decodeEventLog({\n ...formattedLog,\n abi: [item.abi],\n strict: true,\n })\n abiItem = item\n break\n } catch {\n // Try next ABI item\n }\n }\n\n // If strict decoding failed for all, and we're in non-strict mode,\n // fall back to the first matching ABI item.\n if (!event && !strict) {\n abiItem = abiItems[0]\n try {\n event = decodeEventLog({\n data: formattedLog.data,\n topics: formattedLog.topics,\n abi: [abiItem.abi],\n strict: false,\n })\n } catch {\n // If decoding still fails, return partial log in non-strict mode.\n const isUnnamed = abiItem.abi.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n return {\n ...formattedLog,\n args: isUnnamed ? [] : {},\n eventName: abiItem.abi.name,\n }\n }\n }\n\n // If no event was found, return null.\n if (!event || !abiItem) return null\n\n // Check that the decoded event name matches the provided event name.\n if (eventName && !eventName.includes(event.eventName)) return null\n\n // Check that the decoded event args match the provided args.\n if (\n !includesArgs({\n args: event.args,\n inputs: abiItem.abi.inputs,\n matchArgs: args,\n })\n )\n return null\n\n return { ...event, ...formattedLog }\n })\n .filter(Boolean) as unknown as ParseEventLogsReturnType<\n abi,\n eventName,\n strict\n >\n}\n\nfunction includesArgs(parameters: {\n args: unknown\n inputs: AbiEvent['inputs']\n matchArgs: unknown\n}) {\n const { args, inputs, matchArgs } = parameters\n\n if (!matchArgs) return true\n if (!args) return false\n\n function isEqual(input: AbiEventParameter, value: unknown, arg: unknown) {\n try {\n if (input.type === 'address')\n return isAddressEqual(value as Address, arg as Address)\n if (input.type === 'string' || input.type === 'bytes')\n return keccak256(toBytes(value as string)) === arg\n return value === arg\n } catch {\n return false\n }\n }\n\n if (Array.isArray(args) && Array.isArray(matchArgs)) {\n return matchArgs.every((value, index) => {\n if (value === null || value === undefined) return true\n const input = inputs[index]\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) => isEqual(input, value, args[index]))\n })\n }\n\n if (\n typeof args === 'object' &&\n !Array.isArray(args) &&\n typeof matchArgs === 'object' &&\n !Array.isArray(matchArgs)\n )\n return Object.entries(matchArgs).every(([key, value]) => {\n if (value === null || value === undefined) return true\n const input = inputs.find((input) => input.name === key)\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) =>\n isEqual(input, value, (args as Record)[key]),\n )\n })\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n blockTimestamp: log.blockTimestamp\n ? BigInt(log.blockTimestamp)\n : log.blockTimestamp === null\n ? null\n : undefined,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n } as Log\n}\n","import type { Abi, AbiParameter } from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgsFromTopics,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n Prettify,\n UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n> = {\n abi: abi\n data?: data | undefined\n eventName?: eventName | ContractEventName | undefined\n strict?: strict | boolean | undefined\n topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n ///\n allEventNames extends\n ContractEventName = eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n> = IsNarrowable extends true\n ? {\n [name in allEventNames]: Prettify<\n {\n eventName: name\n } & UnionEvaluate<\n ContractEventArgsFromTopics extends infer allArgs\n ? topics extends readonly []\n ? data extends undefined\n ? { args?: undefined }\n : { args?: allArgs | undefined }\n : { args: allArgs }\n : never\n >\n >\n }[allEventNames]\n : {\n eventName: eventName\n args: readonly unknown[] | undefined\n }\n\nexport type DecodeEventLogErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiEventSignatureEmptyTopicsErrorType\n | AbiEventSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | DecodeLogTopicsMismatchErrorType\n | DecodeLogDataMismatchErrorType\n | FormatAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n>(\n parameters: DecodeEventLogParameters,\n): DecodeEventLogReturnType {\n const {\n abi,\n data,\n strict: strict_,\n topics,\n } = parameters as DecodeEventLogParameters\n\n const strict = strict_ ?? true\n const [signature, ...argTopics] = topics\n if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n const abiItem = abi.find(\n (x) =>\n x.type === 'event' &&\n signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n )\n\n if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n const { name, inputs } = abiItem\n const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n const args: any = isUnnamed ? [] : {}\n\n // Decode topics (indexed args).\n const indexedInputs = inputs\n .map((x, i) => [x, i] as const)\n .filter(([x]) => 'indexed' in x && x.indexed)\n\n const missingIndexedInputs: [AbiParameter, number][] = []\n\n for (let i = 0; i < indexedInputs.length; i++) {\n const [param, argIndex] = indexedInputs[i]\n const topic = argTopics[i]\n if (!topic) {\n if (strict)\n throw new DecodeLogTopicsMismatch({\n abiItem,\n param: param as AbiParameter & { indexed: boolean },\n })\n // Track missing indexed inputs to decode from data when strict is false\n missingIndexedInputs.push([param, argIndex])\n continue\n }\n args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({\n param,\n value: topic,\n })\n }\n\n // Decode data (non-indexed args + missing indexed args when strict is false).\n const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n\n // When strict is false, missing indexed inputs should be decoded from data\n const inputsToDecode = strict\n ? nonIndexedInputs\n : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]\n\n if (inputsToDecode.length > 0) {\n if (data && data !== '0x') {\n try {\n const decodedData = decodeAbiParameters(\n inputsToDecode,\n data,\n ) as unknown[]\n if (decodedData) {\n let dataIndex = 0\n // First, assign missing indexed parameters (when strict is false)\n if (!strict) {\n for (const [param, argIndex] of missingIndexedInputs) {\n args[isUnnamed ? argIndex : param.name || argIndex] =\n decodedData[dataIndex++]\n }\n }\n // Then, assign non-indexed parameters\n if (isUnnamed) {\n for (let i = 0; i < inputs.length; i++)\n if (args[i] === undefined && dataIndex < decodedData.length)\n args[i] = decodedData[dataIndex++]\n } else\n for (let i = 0; i < nonIndexedInputs.length; i++)\n args[nonIndexedInputs[i].name!] = decodedData[dataIndex++]\n }\n } catch (err) {\n if (strict) {\n if (\n err instanceof AbiDecodingDataSizeTooSmallError ||\n err instanceof PositionOutOfBoundsError\n )\n throw new DecodeLogDataMismatch({\n abiItem,\n data: data,\n params: inputsToDecode,\n size: size(data),\n })\n throw err\n }\n }\n } else if (strict) {\n throw new DecodeLogDataMismatch({\n abiItem,\n data: '0x',\n params: inputsToDecode,\n size: 0,\n })\n }\n }\n\n return {\n eventName: name,\n args: Object.values(args).length > 0 ? args : undefined,\n } as unknown as DecodeEventLogReturnType\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n if (\n param.type === 'string' ||\n param.type === 'bytes' ||\n param.type === 'tuple' ||\n param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n )\n return value\n const decodedArg = decodeAbiParameters([param], value) || []\n return decodedArg[0]\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** Address or list of addresses from which logs originated */\n address?: Address | Address[] | undefined\n} & (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events: abiEvents\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n) &\n (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n )\n\nexport type GetLogsReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetLogsErrorType =\n | DecodeEventLogErrorType\n | EncodeEventTopicsErrorType\n | FormatLogErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n {\n address,\n blockHash,\n fromBlock,\n toBlock,\n event,\n events: events_,\n args,\n strict: strict_,\n }: GetLogsParameters = {},\n): Promise> {\n const strict = strict_ ?? false\n const events = events_ ?? (event ? [event] : undefined)\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args: events_ ? undefined : args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n let logs: RpcLog[]\n if (blockHash) {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [{ address, topics, blockHash }],\n })\n } else {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [\n {\n address,\n topics,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n },\n ],\n })\n }\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!events)\n return formattedLogs as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: events,\n args: args as any,\n logs: formattedLogs,\n strict,\n }) as unknown as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = ContractFunctionReturnType\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n>(\n client: Client,\n parameters: ReadContractParameters,\n): Promise> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { Abi, AbiFunction, AbiStateMutability, Address } from 'abitype'\n\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 type { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, ParseAccount } from '../../types/account.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n ExtractAbiFunctionForArgs,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type {\n IsNarrowable,\n NoInfer,\n Prettify,\n UnionEvaluate,\n UnionOmit,\n} from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { WriteContractParameters } from '../wallet/writeContract.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type GetMutabilityAwareValue<\n abi extends Abi | readonly unknown[],\n mutability extends AbiStateMutability = AbiStateMutability,\n functionName extends ContractFunctionName<\n abi,\n mutability\n > = ContractFunctionName,\n valueType = TransactionRequest['value'],\n args extends ContractFunctionArgs<\n abi,\n mutability,\n functionName\n > = ContractFunctionArgs,\n abiFunction extends AbiFunction = abi extends Abi\n ? ExtractAbiFunctionForArgs\n : AbiFunction,\n _Narrowable extends boolean = IsNarrowable,\n> = _Narrowable extends true\n ? abiFunction['stateMutability'] extends 'payable'\n ? { value?: NoInfer | undefined }\n : abiFunction['payable'] extends true\n ? { value?: NoInfer | undefined }\n : { value?: undefined }\n : { value?: NoInfer | undefined }\n\nexport type SimulateContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n ///\n derivedChain extends Chain | undefined = DeriveChain,\n callParameters extends\n CallParameters = CallParameters,\n> = {\n account?: accountOverride | null | undefined\n chain?: chainOverride | undefined\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n} & ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit<\n callParameters,\n | 'account'\n | 'batch'\n | 'code'\n | 'to'\n | 'data'\n | 'factory'\n | 'factoryData'\n | 'value'\n > &\n GetMutabilityAwareValue<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n callParameters['value'],\n args\n >\n\nexport type SimulateContractReturnType<\n out abi extends Abi | readonly unknown[] = Abi,\n in out functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n in out args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n /** @ts-expect-error cast variance */\n out chain extends Chain | undefined = Chain | undefined,\n out account extends Account | undefined = Account | undefined,\n out chainOverride extends Chain | undefined = Chain | undefined,\n out accountOverride extends Account | Address | null | undefined =\n | Account\n | Address\n | null\n | undefined,\n ///\n in out minimizedAbi extends Abi = readonly [\n ExtractAbiFunctionForArgs<\n abi extends Abi ? abi : Abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >,\n ],\n out resolvedAccount extends\n | Account\n | null\n | undefined = accountOverride extends Account | Address | null\n ? ParseAccount\n : account,\n> = {\n result: ContractFunctionReturnType<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >\n request: Prettify<\n UnionEvaluate<\n UnionOmit<\n WriteContractParameters<\n minimizedAbi,\n functionName,\n args,\n chain,\n undefined,\n chainOverride\n >,\n 'account' | 'abi' | 'args' | 'chain' | 'functionName'\n >\n > &\n ContractFunctionParameters<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n > & {\n chain: DeriveChain\n } & (resolvedAccount extends Account | null\n ? { account: resolvedAccount }\n : { account?: undefined })\n >\n}\n\nexport type SimulateContractErrorType =\n | ParseAccountErrorType\n | EncodeFunctionDataErrorType\n | GetContractErrorReturnType\n | ErrorType\n\n/**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await simulateContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function simulateContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n): Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n> {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...callRequest\n } = parameters as SimulateContractParameters\n\n const account = callRequest.account\n ? parseAccount(callRequest.account)\n : client.account\n const calldata = encodeFunctionData({ abi, args, functionName })\n\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n batch: false,\n data: `${calldata}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...callRequest,\n account,\n })\n const result = decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n })\n const minimizedAbi = abi.filter(\n (abiItem) =>\n 'name' in abiItem && abiItem.name === parameters.functionName,\n )\n return {\n result,\n request: {\n abi: minimizedAbi,\n address,\n args,\n dataSuffix,\n functionName,\n ...callRequest,\n account,\n },\n } as unknown as SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/simulateContract',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport { createContractEventFilter } from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n type GetContractEventsParameters,\n getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchContractEventOnLogsParameter<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = abi extends Abi\n ? Abi extends abi\n ? Log[]\n : Log, strict>[]\n : Log[]\n\nexport type WatchContractEventOnLogsFn<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter) => void\n\nexport type WatchContractEventParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchContractEventOnLogsFn<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n strict\n >\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & GetPollOptions\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n>(\n client: Client,\n parameters: WatchContractEventParameters,\n): WatchContractEventReturnType {\n const {\n abi,\n address,\n args,\n batch = true,\n eventName,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n } = parameters\n\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n const pollContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abi, eventName> | undefined\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createContractEventFilter,\n 'createContractEventFilter',\n )({\n abi,\n address,\n args: args as any,\n eventName: eventName as any,\n strict: strict as any,\n fromBlock,\n })) as Filter<'event', abi, eventName>\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber < blockNumber) {\n logs = await getAction(\n client,\n getContractEvents,\n 'getContractEvents',\n )({\n abi,\n address,\n args,\n eventName,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n strict,\n } as {} as GetContractEventsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n ])\n\n let active = true\n let unsubscribe = () => (active = false)\n return observe(observerId, { onLogs, onError }, (emit) => {\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const topics: LogTopic[] = eventName\n ? encodeEventTopics({\n abi: abi,\n eventName: eventName,\n args,\n } as EncodeEventTopicsParameters)\n : []\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: abi,\n data: log.data,\n topics: log.topics as any,\n strict: strict_,\n })\n const formatted = formatLog(log, {\n args,\n eventName: eventName as string,\n })\n emit.onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n emit.onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollContractEvent() : subscribeContractEvent()\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record\n\nexport type ObserveErrorType = ErrorType\n\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map<\n string,\n () => void | Promise\n>()\n\ntype EmitFunction = (\n emit: callbacks,\n) => MaybePromise void) | (() => Promise)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction,\n) {\n const callbackId = ++callbackCount\n\n const getListeners = () => listenersCache.get(observerId) || []\n\n const unsubscribe = () => {\n const listeners = getListeners()\n listenersCache.set(\n observerId,\n listeners.filter((cb: any) => cb.id !== callbackId),\n )\n }\n\n const unwatch = () => {\n const listeners = getListeners()\n if (!listeners.some((cb: any) => cb.id === callbackId)) return\n const cleanup = cleanupCache.get(observerId)\n if (listeners.length === 1 && cleanup) {\n const p = cleanup()\n if (p instanceof Promise) p.catch(() => {})\n }\n unsubscribe()\n }\n\n const listeners = getListeners()\n listenersCache.set(observerId, [\n ...listeners,\n { id: callbackId, fns: callbacks },\n ])\n\n if (listeners && listeners.length > 0) return unwatch\n\n const emit: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract]\n }\n\n const cleanup = fn(emit)\n if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n return unwatch\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise) | undefined\n // The interval (in ms).\n interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise,\n { emitOnBegin, initialWaitTime, interval }: PollOptions,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | undefined | void\n if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n const initialWait = (await initialWaitTime?.(data)) ?? interval\n await wait(initialWait)\n\n const poll = async () => {\n if (!active) return\n await fn({ unpoll: unwatch })\n await wait(interval)\n poll()\n }\n\n poll()\n }\n watch()\n\n return unwatch\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache(cacheKey: string) {\n const buildCache = (cacheKey: string, cache: Map) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype WithCacheParameters = {\n /** The key to cache the data against. */\n cacheKey: string\n /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n cacheTime?: number | undefined\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache(\n fn: () => Promise,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache(cacheKey)\n\n // If a response exists in the cache, and it's not expired, return it\n // and do not invoke the promise.\n // If the max age is 0, the cache is disabled.\n const response = cache.response.get()\n if (response && cacheTime > 0) {\n const age = Date.now() - response.created.getTime()\n if (age < cacheTime) return response.data\n }\n\n let promise = cache.promise.get()\n if (!promise) {\n promise = fn()\n\n // Store the promise in the cache so that subsequent invocations\n // will wait for the same promise to resolve (deduping).\n cache.promise.set(promise)\n }\n\n try {\n const data = await promise\n\n // Store the response in the cache so that subsequent invocations\n // will return the same response.\n cache.response.set({ created: new Date(), data })\n\n return data\n } finally {\n // Clear the promise cache so that subsequent invocations will\n // invoke the promise again.\n cache.promise.clear()\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\nexport function getBlockNumberCache(id: string) {\n return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber(\n client: Client,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcLog } from '../../index.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter\n}\n\nexport type GetFilterChangesReturnType<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = filterType extends 'event'\n ? Log[]\n : Hash[]\n\nexport type GetFilterChangesErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n transport extends Transport,\n chain extends Chain | undefined,\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const strict = 'strict' in filter && filter.strict\n\n const logs = await filter.request({\n method: 'eth_getFilterChanges',\n params: [filter.id],\n })\n\n if (typeof logs[0] === 'string')\n return logs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n\n const formattedLogs = logs.map((log) => formatLog(log as RpcLog))\n if (!('abi' in filter) || !filter.abi)\n return formattedLogs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n filter: Filter\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n _client: Client,\n { filter }: UninstallFilterParameters,\n): Promise {\n return filter.request({\n method: 'eth_uninstallFilter',\n params: [filter.id],\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction(\n client: Client,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry(\n fn: () => Promise,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial,\n _?: string | undefined,\n) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[\n transactionReceipt.type as keyof typeof transactionType\n ] || transactionReceipt.type\n : null,\n } as TransactionReceipt\n\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { DataSuffix } from '../types/dataSuffix.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify | undefined\n }\n | undefined\n /**\n * Default block tag to use for RPC requests.\n *\n * If the chain supports a pre-confirmation mechanism\n * (set via `chain.experimental_preconfirmationTime`), defaults to `'pending'`.\n *\n * @default 'latest'\n */\n experimental_blockTag?: BlockTag | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default chain.blockTime / 3\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default chain.blockTime / 3\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial>,\n >(\n fn: (\n client: Client,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** Default block tag to use for RPC requests. */\n experimental_blockTag?: BlockTag | undefined\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType['config'] & ReturnType['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n chain,\n ccipRead,\n dataSuffix,\n key = 'base',\n name = 'Base Client',\n type = 'base',\n } = parameters\n\n const experimental_blockTag =\n parameters.experimental_blockTag ??\n (typeof chain?.experimental_preconfirmationTime === 'number'\n ? 'pending'\n : undefined)\n const blockTime = chain?.blockTime ?? 12_000\n\n const defaultPollingInterval = Math.min(\n Math.max(Math.floor(blockTime / 2), 500),\n 4_000,\n )\n const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval\n const cacheTime = parameters.cacheTime ?? pollingInterval\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n account,\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n dataSuffix,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n ...(experimental_blockTag ? { experimental_blockTag } : {}),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema(): rpcSchema {\n return null as any\n}\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n addressResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n Pick & {\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS address for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Name to get the address for.\n */\n name: string\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n | GetChainContractAddressErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | DecodeFunctionResultErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress(\n client: Client,\n parameters: GetEnsAddressParameters,\n): Promise {\n const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } =\n parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n const args = (() => {\n if (coinType != null) return [namehash(name), BigInt(coinType)] as const\n return [namehash(name)] as const\n })()\n\n try {\n const functionData = encodeFunctionData({\n abi: addressResolverAbi,\n functionName: 'addr',\n args,\n })\n\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolveWithGateways',\n args: [\n toHex(packetToBytes(name)),\n functionData,\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const address = decodeFunctionResult({\n abi: addressResolverAbi,\n args,\n functionName: 'addr',\n data: res[0],\n })\n\n if (address === '0x') return null\n if (trim(address) === '0x00') return null\n return address\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(err: unknown): boolean {\n if (!(err instanceof BaseError)) return false\n const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (!(cause instanceof ContractFunctionRevertedError)) return false\n\n if (cause.data?.errorName === 'HttpError') return true\n if (cause.data?.errorName === 'ResolverError') return true\n if (cause.data?.errorName === 'ResolverNotContract') return true\n if (cause.data?.errorName === 'ResolverNotFound') return true\n if (cause.data?.errorName === 'ReverseAddressMismatch') return true\n if (cause.data?.errorName === 'UnsupportedResolverProfile') return true\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n type ToBytesErrorType,\n toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | ToBytesErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ConcatErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0x08c85f2f4059e930c45a6aeff9dcd3bd95dc3c5c1cddef6a0626b31152248560'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n let result = new Uint8Array(32).fill(0) as ByteArray\n if (!name) return bytesToHex(result)\n\n const labels = name.split('.')\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n const hashed = hashFromEncodedLabel\n ? toBytes(hashFromEncodedLabel)\n : keccak256(stringToBytes(labels[i]), 'bytes')\n result = keccak256(concat([result, hashed]), 'bytes')\n }\n\n return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n if (label.length !== 66) return null\n if (label.indexOf('[') !== 0) return null\n if (label.indexOf(']') !== 65) return null\n const hash = `0x${label.slice(1, 65)}`\n if (!isHex(hash)) return null\n return hash\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n type EncodeLabelhashErrorType,\n encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n | EncodeLabelhashErrorType\n | LabelhashErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n *\n * @example\n * packetToBytes('awkweb.eth')\n * '0x0661776b7765620365746800'\n *\n * @see https://docs.ens.domains/resolution/names#dns\n *\n */\nexport function packetToBytes(packet: string): ByteArray {\n // strip leading and trailing `.`\n const value = packet.replace(/^\\.|\\.$/gm, '')\n if (value.length === 0) return new Uint8Array(1)\n\n const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n let offset = 0\n const list = value.split('.')\n for (let i = 0; i < list.length; i++) {\n let encoded = stringToBytes(list[i])\n // if the length is > 255, make the encoded label value a labelhash\n // this is compatible with the universal resolver\n if (encoded.byteLength > 255)\n encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n bytes[offset] = encoded.length\n bytes.set(encoded, offset + 1)\n offset += encoded.length + 1\n }\n\n if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n return bytes\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n const result = new Uint8Array(32).fill(0)\n if (!label) return bytesToHex(result)\n return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","import { BaseError } from './base.js'\n\nexport type EnsAvatarInvalidMetadataErrorType =\n EnsAvatarInvalidMetadataError & {\n name: 'EnsAvatarInvalidMetadataError'\n }\nexport class EnsAvatarInvalidMetadataError extends BaseError {\n constructor({ data }: { data: any }) {\n super(\n 'Unable to extract image from metadata. The metadata may be malformed or invalid.',\n {\n metaMessages: [\n '- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.',\n '',\n `Provided data: ${JSON.stringify(data)}`,\n ],\n name: 'EnsAvatarInvalidMetadataError',\n },\n )\n }\n}\n\nexport type EnsAvatarInvalidNftUriErrorType = EnsAvatarInvalidNftUriError & {\n name: 'EnsAvatarInvalidNftUriError'\n}\nexport class EnsAvatarInvalidNftUriError extends BaseError {\n constructor({ reason }: { reason: string }) {\n super(`ENS NFT avatar URI is invalid. ${reason}`, {\n name: 'EnsAvatarInvalidNftUriError',\n })\n }\n}\n\nexport type EnsAvatarUriResolutionErrorType = EnsAvatarUriResolutionError & {\n name: 'EnsAvatarUriResolutionError'\n}\nexport class EnsAvatarUriResolutionError extends BaseError {\n constructor({ uri }: { uri: string }) {\n super(\n `Unable to resolve ENS avatar URI \"${uri}\". The URI may be malformed, invalid, or does not respond with a valid image.`,\n { name: 'EnsAvatarUriResolutionError' },\n )\n }\n}\n\nexport type EnsAvatarUnsupportedNamespaceErrorType =\n EnsAvatarUnsupportedNamespaceError & {\n name: 'EnsAvatarUnsupportedNamespaceError'\n }\nexport class EnsAvatarUnsupportedNamespaceError extends BaseError {\n constructor({ namespace }: { namespace: string }) {\n super(\n `ENS NFT avatar namespace \"${namespace}\" is not supported. Must be \"erc721\" or \"erc1155\".`,\n { name: 'EnsAvatarUnsupportedNamespaceError' },\n )\n }\n}\n\nexport type EnsInvalidChainIdErrorType = EnsInvalidChainIdError & {\n name: 'EnsInvalidChainIdError'\n}\nexport class EnsInvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId: number }) {\n super(\n `Invalid ENSIP-11 chainId: ${chainId}. Must be between 0 and 0x7fffffff, or 1.`,\n {\n name: 'EnsInvalidChainIdError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n type ReadContractErrorType,\n readContract,\n} from '../../../actions/public/readContract.js'\nimport type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport {\n EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n} from '../../../errors/ens.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\ntype UriItem = {\n uri: string\n isOnChain: boolean\n isEncoded: boolean\n}\n\nconst networkRegex =\n /(?https?:\\/\\/[^/]*|ipfs:\\/|ipns:\\/|ar:\\/)?(?\\/)?(?ipfs\\/|ipns\\/)?(?[\\w\\-.]+)(?\\/.*)?/\nconst ipfsHashRegex =\n /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\\/(?[\\w\\-.]+))?(?\\/.*)?$/\nconst base64Regex = /^data:([a-zA-Z\\-/+]*);base64,([^\"].*)/\nconst dataURIRegex = /^data:([a-zA-Z\\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/\n\ntype IsImageUriErrorType = ErrorType\n\n/** @internal */\nexport async function isImageUri(uri: string) {\n try {\n const res = await fetch(uri, { method: 'HEAD' })\n // retrieve content type header to check if content is image\n if (res.status === 200) {\n const contentType = res.headers.get('content-type')\n return contentType?.startsWith('image/')\n }\n return false\n } catch (error: any) {\n // if error is not cors related then fail\n if (typeof error === 'object' && typeof error.response !== 'undefined') {\n return false\n }\n // fail in NodeJS, since the error is not cors but any other network issue\n if (!Object.hasOwn(globalThis, 'Image')) return false\n // in case of cors, use image api to validate if given url is an actual image\n return new Promise((resolve) => {\n const img = new Image()\n img.onload = () => {\n resolve(true)\n }\n img.onerror = () => {\n resolve(false)\n }\n img.src = uri\n })\n }\n}\n\ntype GetGatewayErrorType = ErrorType\n\n/** @internal */\nexport function getGateway(custom: string | undefined, defaultGateway: string) {\n if (!custom) return defaultGateway\n if (custom.endsWith('/')) return custom.slice(0, -1)\n return custom\n}\n\nexport type ResolveAvatarUriErrorType =\n | GetGatewayErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport function resolveAvatarUri({\n uri,\n gatewayUrls,\n}: {\n uri: string\n gatewayUrls?: AssetGatewayUrls | undefined\n}): UriItem {\n const isEncoded = base64Regex.test(uri)\n if (isEncoded) return { uri, isOnChain: true, isEncoded }\n\n const ipfsGateway = getGateway(gatewayUrls?.ipfs, 'https://ipfs.io')\n const arweaveGateway = getGateway(gatewayUrls?.arweave, 'https://arweave.net')\n\n const networkRegexMatch = uri.match(networkRegex)\n const {\n protocol,\n subpath,\n target,\n subtarget = '',\n } = networkRegexMatch?.groups || {}\n\n const isIPNS = protocol === 'ipns:/' || subpath === 'ipns/'\n const isIPFS =\n protocol === 'ipfs:/' || subpath === 'ipfs/' || ipfsHashRegex.test(uri)\n\n if (uri.startsWith('http') && !isIPNS && !isIPFS) {\n let replacedUri = uri\n if (gatewayUrls?.arweave)\n replacedUri = uri.replace(/https:\\/\\/arweave.net/g, gatewayUrls?.arweave)\n return { uri: replacedUri, isOnChain: false, isEncoded: false }\n }\n\n if ((isIPNS || isIPFS) && target) {\n return {\n uri: `${ipfsGateway}/${isIPNS ? 'ipns' : 'ipfs'}/${target}${subtarget}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n if (protocol === 'ar:/' && target) {\n return {\n uri: `${arweaveGateway}/${target}${subtarget || ''}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n let parsedUri = uri.replace(dataURIRegex, '')\n if (parsedUri.startsWith(' {\n try {\n const res = await fetch(uri).then((res) => res.json())\n const image = await parseAvatarUri({\n gatewayUrls,\n uri: getJsonImage(res),\n })\n return image\n } catch {\n throw new EnsAvatarUriResolutionError({ uri })\n }\n}\n\nexport type ParseAvatarUriErrorType =\n | ResolveAvatarUriErrorType\n | IsImageUriErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport async function parseAvatarUri({\n gatewayUrls,\n uri,\n}: {\n gatewayUrls?: AssetGatewayUrls | undefined\n uri: string\n}): Promise {\n const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls })\n if (isOnChain) return resolvedURI\n\n // check if resolvedURI is an image, if it is return the url\n const isImage = await isImageUri(resolvedURI)\n if (isImage) return resolvedURI\n\n throw new EnsAvatarUriResolutionError({ uri })\n}\n\ntype ParsedNft = {\n chainID: number\n namespace: string\n contractAddress: Address\n tokenID: string\n}\n\nexport type ParseNftUriErrorType = EnsAvatarInvalidNftUriErrorType | ErrorType\n\nexport function parseNftUri(uri_: string): ParsedNft {\n let uri = uri_\n // parse valid nft spec (CAIP-22/CAIP-29)\n // @see: https://github.com/ChainAgnostic/CAIPs/tree/master/CAIPs\n if (uri.startsWith('did:nft:')) {\n // convert DID to CAIP\n uri = uri.replace('did:nft:', '').replace(/_/g, '/')\n }\n\n const [reference, asset_namespace, tokenID] = uri.split('/')\n const [eip_namespace, chainID] = reference.split(':')\n const [erc_namespace, contractAddress] = asset_namespace.split(':')\n\n if (!eip_namespace || eip_namespace.toLowerCase() !== 'eip155')\n throw new EnsAvatarInvalidNftUriError({ reason: 'Only EIP-155 supported' })\n if (!chainID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Chain ID not found' })\n if (!contractAddress)\n throw new EnsAvatarInvalidNftUriError({\n reason: 'Contract address not found',\n })\n if (!tokenID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Token ID not found' })\n if (!erc_namespace)\n throw new EnsAvatarInvalidNftUriError({ reason: 'ERC namespace not found' })\n\n return {\n chainID: Number.parseInt(chainID, 10),\n namespace: erc_namespace.toLowerCase(),\n contractAddress: contractAddress as Address,\n tokenID,\n }\n}\n\nexport type GetNftTokenUriErrorType =\n | ReadContractErrorType\n | EnsAvatarUnsupportedNamespaceErrorType\n | ErrorType\n\nexport async function getNftTokenUri(\n client: Client,\n { nft }: { nft: ParsedNft },\n) {\n if (nft.namespace === 'erc721') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'tokenURI',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'tokenURI',\n args: [BigInt(nft.tokenID)],\n })\n }\n if (nft.namespace === 'erc1155') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'uri',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: '_id', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'uri',\n args: [BigInt(nft.tokenID)],\n })\n }\n throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace })\n}\n","import type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\nimport {\n type GetJsonImageErrorType,\n type GetMetadataAvatarUriErrorType,\n type GetNftTokenUriErrorType,\n getJsonImage,\n getMetadataAvatarUri,\n getNftTokenUri,\n type ParseAvatarUriErrorType,\n type ParseNftUriErrorType,\n parseAvatarUri,\n parseNftUri,\n type ResolveAvatarUriErrorType,\n resolveAvatarUri,\n} from './utils.js'\n\nexport type ParseAvatarRecordErrorType =\n | ParseNftAvatarUriErrorType\n | ParseAvatarUriErrorType\n | ErrorType\n\n/*\n * @description Parses an ENS avatar record.\n *\n * @example\n * parseAvatarRecord('eip155:1/erc1155:0xb32979486938aa9694bfc898f35dbed459f44424/10063')\n * 'https://ipfs.io/ipfs/QmSP4nq9fnN9dAiCj42ug9Wa79rqmQerZXZch82VqpiH7U/image.gif'\n *\n * @see https://docs.ens.domains/web/avatars\n *\n */\nexport async function parseAvatarRecord(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n if (/eip155:/i.test(record))\n return parseNftAvatarUri(client, { gatewayUrls, record })\n return parseAvatarUri({ uri: record, gatewayUrls })\n}\n\ntype ParseNftAvatarUriErrorType =\n | ParseNftUriErrorType\n | GetNftTokenUriErrorType\n | ResolveAvatarUriErrorType\n | ParseAvatarUriErrorType\n | GetJsonImageErrorType\n | GetMetadataAvatarUriErrorType\n | ErrorType\n\nasync function parseNftAvatarUri(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n // parse NFT URI into properties\n const nft = parseNftUri(record)\n // fetch tokenURI from the NFT contract\n const nftUri = await getNftTokenUri(client, { nft })\n // resolve the URI from the fetched tokenURI\n const {\n uri: resolvedNftUri,\n isOnChain,\n isEncoded,\n } = resolveAvatarUri({ uri: nftUri, gatewayUrls })\n\n // if the resolved URI is on chain, return the data\n if (\n isOnChain &&\n (resolvedNftUri.includes('data:application/json;base64,') ||\n resolvedNftUri.startsWith('{'))\n ) {\n const encodedJson = isEncoded\n ? // if it is encoded, decode it\n atob(resolvedNftUri.replace('data:application/json;base64,', ''))\n : // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)\n resolvedNftUri\n\n const decoded = JSON.parse(encodedJson)\n return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls })\n }\n\n let uriTokenId = nft.tokenID\n if (nft.namespace === 'erc1155')\n uriTokenId = uriTokenId.replace('0x', '').padStart(64, '0')\n\n return getMetadataAvatarUri({\n gatewayUrls,\n uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId),\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n textResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsTextParameters = Prettify<\n Pick & {\n /** ENS name to get Text for. */\n name: string\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Text record to retrieve. */\n key: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsTextReturnType = string | null\n\nexport type GetEnsTextErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | DecodeFunctionResultErrorType\n\n/**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsText, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await getEnsText(client, {\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\nexport async function getEnsText(\n client: Client,\n parameters: GetEnsTextParameters,\n): Promise {\n const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n args: [\n toHex(packetToBytes(name)),\n encodeFunctionData({\n abi: textResolverAbi,\n functionName: 'text',\n args: [namehash(name), key],\n }),\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n functionName: 'resolveWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const record = decodeFunctionResult({\n abi: textResolverAbi,\n functionName: 'text',\n data: res[0],\n })\n\n return record === '' ? null : record\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../types/ens.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type ParseAvatarRecordErrorType,\n parseAvatarRecord,\n} from '../../utils/ens/avatar/parseAvatarRecord.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetEnsTextErrorType,\n type GetEnsTextParameters,\n getEnsText,\n} from './getEnsText.js'\n\nexport type GetEnsAvatarParameters = Prettify<\n Omit & {\n /** Gateway urls to resolve IPFS and/or Arweave assets. */\n assetGatewayUrls?: AssetGatewayUrls | undefined\n }\n>\n\nexport type GetEnsAvatarReturnType = string | null\n\nexport type GetEnsAvatarErrorType =\n | GetEnsTextErrorType\n | ParseAvatarRecordErrorType\n | ErrorType\n\n/**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAvatar, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await getEnsAvatar(client, {\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\nexport async function getEnsAvatar(\n client: Client,\n {\n blockNumber,\n blockTag,\n assetGatewayUrls,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress,\n }: GetEnsAvatarParameters,\n): Promise {\n const record = await getAction(\n client,\n getEnsText,\n 'getEnsText',\n )({\n blockNumber,\n blockTag,\n key: 'avatar',\n name,\n universalResolverAddress,\n gatewayUrls,\n strict,\n })\n if (!record) return null\n try {\n return await parseAvatarRecord(client, {\n record,\n gatewayUrls: assetGatewayUrls,\n })\n } catch {\n return null\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalResolverReverseAbi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport type { PacketToBytesErrorType } from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsNameParameters = Prettify<\n Pick & {\n /**\n * Address to get ENS name for.\n */\n address: Address\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS name for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsNameReturnType = string | null\n\nexport type GetEnsNameErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName(\n client: Client,\n parameters: GetEnsNameParameters,\n): Promise {\n const {\n address,\n blockNumber,\n blockTag,\n coinType = 60n,\n gatewayUrls,\n strict,\n } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverReverseAbi,\n args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]],\n functionName: 'reverseWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const [name] = await readContractAction(readContractParameters)\n\n return name || null\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsResolverParameters = Prettify<\n Pick & {\n /** Name to get the address for. */\n name: string\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsResolverReturnType = Address\n\nexport type GetEnsResolverErrorType =\n | GetChainContractAddressErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsResolver, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await getEnsResolver(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\nexport async function getEnsResolver(\n client: Client,\n parameters: GetEnsResolverParameters,\n): Promise {\n const { blockNumber, blockTag, name } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld)))\n throw new Error(\n `${name} is not a valid ENS TLD (${tlds?.join(', ')}) for chain \"${chain.name}\" (id: ${chain.id}).`,\n )\n\n const [resolverAddress] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address: universalResolverAddress,\n abi: [\n {\n inputs: [{ type: 'bytes' }],\n name: 'findResolver',\n outputs: [\n { type: 'address' },\n { type: 'bytes32' },\n { type: 'uint256' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ],\n functionName: 'findResolver',\n args: [toHex(packetToBytes(name))],\n blockNumber,\n blockTag,\n })\n return resolverAddress\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport {\n type GetEnsAddressParameters,\n type GetEnsAddressReturnType,\n getEnsAddress,\n} from '../../actions/ens/getEnsAddress.js'\nimport {\n type GetEnsAvatarParameters,\n type GetEnsAvatarReturnType,\n getEnsAvatar,\n} from '../../actions/ens/getEnsAvatar.js'\nimport {\n type GetEnsNameParameters,\n type GetEnsNameReturnType,\n getEnsName,\n} from '../../actions/ens/getEnsName.js'\nimport {\n type GetEnsResolverParameters,\n type GetEnsResolverReturnType,\n getEnsResolver,\n} from '../../actions/ens/getEnsResolver.js'\nimport {\n type GetEnsTextParameters,\n type GetEnsTextReturnType,\n getEnsText,\n} from '../../actions/ens/getEnsText.js'\nimport {\n type CallParameters,\n type CallReturnType,\n call,\n} from '../../actions/public/call.js'\nimport {\n type CreateAccessListParameters,\n type CreateAccessListReturnType,\n createAccessList,\n} from '../../actions/public/createAccessList.js'\nimport {\n type CreateBlockFilterReturnType,\n createBlockFilter,\n} from '../../actions/public/createBlockFilter.js'\nimport {\n type CreateContractEventFilterParameters,\n type CreateContractEventFilterReturnType,\n createContractEventFilter,\n} from '../../actions/public/createContractEventFilter.js'\nimport {\n type CreateEventFilterParameters,\n type CreateEventFilterReturnType,\n createEventFilter,\n} from '../../actions/public/createEventFilter.js'\nimport {\n type CreatePendingTransactionFilterReturnType,\n createPendingTransactionFilter,\n} from '../../actions/public/createPendingTransactionFilter.js'\nimport {\n type EstimateContractGasParameters,\n type EstimateContractGasReturnType,\n estimateContractGas,\n} from '../../actions/public/estimateContractGas.js'\nimport {\n type EstimateFeesPerGasParameters,\n type EstimateFeesPerGasReturnType,\n estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasParameters,\n type EstimateGasReturnType,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type EstimateMaxPriorityFeePerGasParameters,\n type EstimateMaxPriorityFeePerGasReturnType,\n estimateMaxPriorityFeePerGas,\n} from '../../actions/public/estimateMaxPriorityFeePerGas.js'\nimport {\n type FillTransactionParameters,\n type FillTransactionReturnType,\n fillTransaction,\n} from '../../actions/public/fillTransaction.js'\nimport {\n type GetBalanceParameters,\n type GetBalanceReturnType,\n getBalance,\n} from '../../actions/public/getBalance.js'\nimport {\n type GetBlobBaseFeeReturnType,\n getBlobBaseFee,\n} from '../../actions/public/getBlobBaseFee.js'\nimport {\n type GetBlockParameters,\n type GetBlockReturnType,\n getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetBlockNumberParameters,\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from '../../actions/public/getBlockNumber.js'\nimport {\n type GetBlockTransactionCountParameters,\n type GetBlockTransactionCountReturnType,\n getBlockTransactionCount,\n} from '../../actions/public/getBlockTransactionCount.js'\nimport {\n type GetChainIdReturnType,\n getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n type GetCodeParameters,\n type GetCodeReturnType,\n getCode,\n} from '../../actions/public/getCode.js'\nimport {\n type GetContractEventsParameters,\n type GetContractEventsReturnType,\n getContractEvents,\n} from '../../actions/public/getContractEvents.js'\nimport {\n type GetDelegationParameters,\n type GetDelegationReturnType,\n getDelegation,\n} from '../../actions/public/getDelegation.js'\nimport {\n type GetEip712DomainParameters,\n type GetEip712DomainReturnType,\n getEip712Domain,\n} from '../../actions/public/getEip712Domain.js'\nimport {\n type GetFeeHistoryParameters,\n type GetFeeHistoryReturnType,\n getFeeHistory,\n} from '../../actions/public/getFeeHistory.js'\nimport {\n type GetFilterChangesParameters,\n type GetFilterChangesReturnType,\n getFilterChanges,\n} from '../../actions/public/getFilterChanges.js'\nimport {\n type GetFilterLogsParameters,\n type GetFilterLogsReturnType,\n getFilterLogs,\n} from '../../actions/public/getFilterLogs.js'\nimport {\n type GetGasPriceReturnType,\n getGasPrice,\n} from '../../actions/public/getGasPrice.js'\nimport {\n type GetLogsParameters,\n type GetLogsReturnType,\n getLogs,\n} from '../../actions/public/getLogs.js'\nimport {\n type GetProofParameters,\n type GetProofReturnType,\n getProof,\n} from '../../actions/public/getProof.js'\nimport {\n type GetStorageAtParameters,\n type GetStorageAtReturnType,\n getStorageAt,\n} from '../../actions/public/getStorageAt.js'\nimport {\n type GetTransactionParameters,\n type GetTransactionReturnType,\n getTransaction,\n} from '../../actions/public/getTransaction.js'\nimport {\n type GetTransactionConfirmationsParameters,\n type GetTransactionConfirmationsReturnType,\n getTransactionConfirmations,\n} from '../../actions/public/getTransactionConfirmations.js'\nimport {\n type GetTransactionCountParameters,\n type GetTransactionCountReturnType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport {\n type GetTransactionReceiptParameters,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from '../../actions/public/getTransactionReceipt.js'\nimport {\n type MulticallParameters,\n type MulticallReturnType,\n multicall,\n} from '../../actions/public/multicall.js'\nimport {\n type ReadContractParameters,\n type ReadContractReturnType,\n readContract,\n} from '../../actions/public/readContract.js'\nimport {\n type SimulateBlocksParameters,\n type SimulateBlocksReturnType,\n simulateBlocks,\n} from '../../actions/public/simulateBlocks.js'\nimport {\n type SimulateCallsParameters,\n type SimulateCallsReturnType,\n simulateCalls,\n} from '../../actions/public/simulateCalls.js'\nimport {\n type SimulateContractParameters,\n type SimulateContractReturnType,\n simulateContract,\n} from '../../actions/public/simulateContract.js'\nimport {\n type UninstallFilterParameters,\n type UninstallFilterReturnType,\n uninstallFilter,\n} from '../../actions/public/uninstallFilter.js'\nimport {\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from '../../actions/public/verifyHash.js'\nimport {\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from '../../actions/public/verifyMessage.js'\nimport {\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from '../../actions/public/verifyTypedData.js'\nimport {\n type WaitForTransactionReceiptParameters,\n type WaitForTransactionReceiptReturnType,\n waitForTransactionReceipt,\n} from '../../actions/public/waitForTransactionReceipt.js'\nimport {\n type WatchBlockNumberParameters,\n type WatchBlockNumberReturnType,\n watchBlockNumber,\n} from '../../actions/public/watchBlockNumber.js'\nimport {\n type WatchBlocksParameters,\n type WatchBlocksReturnType,\n watchBlocks,\n} from '../../actions/public/watchBlocks.js'\nimport {\n type WatchContractEventParameters,\n type WatchContractEventReturnType,\n watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n type WatchEventParameters,\n type WatchEventReturnType,\n watchEvent,\n} from '../../actions/public/watchEvent.js'\nimport {\n type WatchPendingTransactionsParameters,\n type WatchPendingTransactionsReturnType,\n watchPendingTransactions,\n} from '../../actions/public/watchPendingTransactions.js'\nimport {\n type VerifySiweMessageParameters,\n type VerifySiweMessageReturnType,\n verifySiweMessage,\n} from '../../actions/siwe/verifySiweMessage.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\n type PrepareTransactionRequestReturnType,\n prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n type SendRawTransactionSyncParameters,\n type SendRawTransactionSyncReturnType,\n sendRawTransactionSync,\n} from '../../actions/wallet/sendRawTransactionSync.js'\nimport type { Account } from '../../types/account.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { FeeValuesType } from '../../types/fee.js'\nimport type { FilterType } from '../../types/filter.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type PublicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\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 args - {@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 *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await client.call({\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n call: (parameters: CallParameters) => Promise\n /**\n * Creates an EIP-2930 access list that you can include in a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param args - {@link CreateAccessListParameters}\n * @returns The call data. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const data = await client.createAccessList({\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n createAccessList: (\n parameters: CreateAccessListParameters,\n ) => Promise\n /**\n * Creates a Filter to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @returns Filter. {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, createBlockFilter, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\n createBlockFilter: () => Promise\n /**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param args - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\n createContractEventFilter: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param args - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\n createEventFilter: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _EventName extends string | undefined = MaybeAbiEventName,\n _Args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n >(\n args?:\n | CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n | undefined,\n ) => Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n >\n /**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\n createPendingTransactionFilter: () => Promise\n /**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * @remarks\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await client.estimateContractGas({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\n estimateContractGas: <\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n >(\n args: EstimateContractGasParameters,\n ) => Promise\n /**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param args - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await client.estimateGas({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n estimateGas: (\n args: EstimateGasParameters,\n ) => Promise\n /**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.fillTransaction({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n fillTransaction: <\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n ) => Promise>\n /**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * @remarks\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param args - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await client.getBalance({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\n getBalance: (args: GetBalanceParameters) => Promise\n /**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await client.getBlobBaseFee()\n */\n getBlobBaseFee: () => Promise\n /**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getBlock()\n */\n getBlock: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args?: GetBlockParameters | undefined,\n ) => Promise>\n /**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param args - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await client.getBlockNumber()\n * // 69420n\n */\n getBlockNumber: (\n args?: GetBlockNumberParameters | undefined,\n ) => Promise\n /**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await client.getBlockTransactionCount()\n */\n getBlockTransactionCount: (\n args?: GetBlockTransactionCountParameters | undefined,\n ) => Promise\n /** @deprecated Use `getCode` instead. */\n getBytecode: (args: GetCodeParameters) => Promise\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await client.getChainId()\n * // 1\n */\n getChainId: () => Promise\n /**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param args - {@link GetBytecodeParameters}\n * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getCode({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\n getCode: (args: GetCodeParameters) => Promise\n /**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/actions/public/getContractEvents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { wagmiAbi } from './abi'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\n getContractEvents: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetContractEventsReturnType\n >\n /**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param args - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await client.getDelegation({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getDelegation: (\n args: GetDelegationParameters,\n ) => Promise\n /**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await client.getEip712Domain({\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\n getEip712Domain: (\n args: GetEip712DomainParameters,\n ) => Promise\n /**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await client.getEnsAddress({\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\n getEnsAddress: (\n args: GetEnsAddressParameters,\n ) => Promise\n /**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await client.getEnsAvatar({\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\n getEnsAvatar: (\n args: GetEnsAvatarParameters,\n ) => Promise\n /**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param args - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await client.getEnsName({\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\n getEnsName: (args: GetEnsNameParameters) => Promise\n /**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await client.getEnsResolver({\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\n getEnsResolver: (\n args: GetEnsResolverParameters,\n ) => Promise\n /**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await client.getEnsText({\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\n getEnsText: (args: GetEnsTextParameters) => Promise\n /**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param args - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await client.getFeeHistory({\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\n getFeeHistory: (\n args: GetFeeHistoryParameters,\n ) => Promise\n /**\n * Returns an estimate for the fees per gas for a transaction to be included\n * in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateFeesPerGas()\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\n estimateFeesPerGas: <\n chainOverride extends Chain | undefined = undefined,\n type extends FeeValuesType = 'eip1559',\n >(\n args?: EstimateFeesPerGasParameters | undefined,\n ) => Promise>\n /**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * @remarks\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param args - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createBlockFilter()\n * const hashes = await client.getFilterChanges({ filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * const hashes = await client.getFilterChanges({ filter })\n */\n getFilterChanges: <\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * @remarks\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param args - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterLogs({ filter })\n */\n getFilterLogs: <\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterLogsParameters,\n ) => Promise<\n GetFilterLogsReturnType\n >\n /**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await client.getGasPrice()\n */\n getGasPrice: () => Promise\n /**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param args - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getLogs()\n */\n getLogs: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args?:\n | GetLogsParameters\n | undefined,\n ) => Promise<\n GetLogsReturnType\n >\n /**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getProof({\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\n getProof: (args: GetProofParameters) => Promise\n /**\n * Returns an estimate for the max priority fee per gas (in wei) for a transaction\n * to be included in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()\n * // 10000000n\n */\n estimateMaxPriorityFeePerGas: <\n chainOverride extends Chain | undefined = undefined,\n >(\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n ) => Promise\n /**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param args - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getStorageAt({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\n getStorageAt: (\n args: GetStorageAtParameters,\n ) => Promise\n /**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param args - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await client.getTransaction({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransaction: (\n args: GetTransactionParameters,\n ) => Promise>\n /**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param args - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await client.getTransactionConfirmations({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionConfirmations: (\n args: GetTransactionConfirmationsParameters,\n ) => Promise\n /**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has broadcast / sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param args - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await client.getTransactionCount({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getTransactionCount: (\n args: GetTransactionCountParameters,\n ) => Promise\n /**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt)\n *\n * @param args - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.getTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionReceipt: (\n args: GetTransactionReceiptParameters,\n ) => Promise>\n /**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param args - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const result = await client.multicall({\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\n multicall: <\n const contracts extends readonly unknown[],\n allowFailure extends boolean = true,\n >(\n args: MulticallParameters,\n ) => Promise>\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\n prepareTransactionRequest: <\n const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * @remarks\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.readContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\n readContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n >(\n args: ReadContractParameters,\n ) => Promise>\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await client.sendRawTransaction({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransaction: (\n args: SendRawTransactionParameters,\n ) => Promise\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionSyncParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await client.sendRawTransactionSync({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransactionSync: (\n args: SendRawTransactionSyncParameters,\n ) => Promise>\n /**\n * @deprecated Use `simulateBlocks` instead.\n */\n simulate: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateBlocks({\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateParameters}\n * @returns Simulated blocks. {@link SimulateReturnType}\n */\n simulateBlocks: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateCalls({\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n */\n simulateCalls: (\n args: SimulateCallsParameters,\n ) => Promise>\n /**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * @remarks\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.simulateContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n simulateContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n ) => Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n >\n /**\n * Verify that a hash was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyHash}\n *\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\n verifyHash: (args: VerifyHashParameters) => Promise\n /**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\n verifyMessage: (\n args: VerifyMessageParameters,\n ) => Promise\n /**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\n verifySiweMessage: (\n args: VerifySiweMessageParameters,\n ) => Promise\n /**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\n verifyTypedData: (\n args: VerifyTypedDataParameters,\n ) => Promise\n /**\n * Destroys a Filter that was created from one of the following Actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * @param args - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await client.createPendingTransactionFilter()\n * const uninstalled = await client.uninstallFilter({ filter })\n * // true\n */\n uninstallFilter: (\n args: UninstallFilterParameters,\n ) => Promise\n /**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * @remarks\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param args - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.waitForTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n waitForTransactionReceipt: (\n args: WaitForTransactionReceiptParameters,\n ) => Promise>\n /**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlockNumber({\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\n watchBlockNumber: (\n args: WatchBlockNumberParameters,\n ) => WatchBlockNumberReturnType\n /**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlocks({\n * onBlock: (block) => console.log(block),\n * })\n */\n watchBlocks: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args: WatchBlocksParameters<\n transport,\n chain,\n includeTransactions,\n blockTag\n >,\n ) => WatchBlocksReturnType\n /**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * @remarks\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchContractEvent({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchContractEvent: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchContractEventParameters,\n ) => WatchContractEventReturnType\n /**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * @remarks\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchEvent({\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchEvent: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchEventParameters,\n ) => WatchEventReturnType\n /**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * @remarks\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param args - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchPendingTransactions({\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\n watchPendingTransactions: (\n args: WatchPendingTransactionsParameters,\n ) => WatchPendingTransactionsReturnType\n}\n\nexport function publicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(\n client: Client,\n): PublicActions {\n return {\n call: (args) => call(client, args),\n createAccessList: (args) => createAccessList(client, args),\n createBlockFilter: () => createBlockFilter(client),\n createContractEventFilter: (args) =>\n createContractEventFilter(client, args),\n createEventFilter: (args) => createEventFilter(client, args),\n createPendingTransactionFilter: () =>\n createPendingTransactionFilter(client),\n estimateContractGas: (args) => estimateContractGas(client, args as any),\n estimateGas: (args) => estimateGas(client, args),\n getBalance: (args) => getBalance(client, args),\n getBlobBaseFee: () => getBlobBaseFee(client),\n getBlock: (args) => getBlock(client, args),\n getBlockNumber: (args) => getBlockNumber(client, args),\n getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),\n getBytecode: (args) => getCode(client, args),\n getChainId: () => getChainId(client),\n getCode: (args) => getCode(client, args),\n getContractEvents: (args) => getContractEvents(client, args),\n getDelegation: (args) => getDelegation(client, args),\n getEip712Domain: (args) => getEip712Domain(client, args),\n getEnsAddress: (args) => getEnsAddress(client, args),\n getEnsAvatar: (args) => getEnsAvatar(client, args),\n getEnsName: (args) => getEnsName(client, args),\n getEnsResolver: (args) => getEnsResolver(client, args),\n getEnsText: (args) => getEnsText(client, args),\n getFeeHistory: (args) => getFeeHistory(client, args),\n estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),\n getFilterChanges: (args) => getFilterChanges(client, args),\n getFilterLogs: (args) => getFilterLogs(client, args),\n getGasPrice: () => getGasPrice(client),\n getLogs: (args) => getLogs(client, args as any),\n getProof: (args) => getProof(client, args),\n estimateMaxPriorityFeePerGas: (args) =>\n estimateMaxPriorityFeePerGas(client, args),\n fillTransaction: (args) => fillTransaction(client, args),\n getStorageAt: (args) => getStorageAt(client, args),\n getTransaction: (args) => getTransaction(client, args),\n getTransactionConfirmations: (args) =>\n getTransactionConfirmations(client, args),\n getTransactionCount: (args) => getTransactionCount(client, args),\n getTransactionReceipt: (args) => getTransactionReceipt(client, args),\n multicall: (args) => multicall(client, args),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n readContract: (args) => readContract(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n sendRawTransactionSync: (args) => sendRawTransactionSync(client, args),\n simulate: (args) => simulateBlocks(client, args),\n simulateBlocks: (args) => simulateBlocks(client, args),\n simulateCalls: (args) => simulateCalls(client, args),\n simulateContract: (args) => simulateContract(client, args),\n verifyHash: (args) => verifyHash(client, args),\n verifyMessage: (args) => verifyMessage(client, args),\n verifySiweMessage: (args) => verifySiweMessage(client, args),\n verifyTypedData: (args) => verifyTypedData(client, args),\n uninstallFilter: (args) => uninstallFilter(client, args),\n waitForTransactionReceipt: (args) =>\n waitForTransactionReceipt(client, args),\n watchBlocks: (args) => watchBlocks(client, args),\n watchBlockNumber: (args) => watchBlockNumber(client, args),\n watchContractEvent: (args) => watchContractEvent(client, args),\n watchEvent: (args) => watchEvent(client, args),\n watchPendingTransactions: (args) => watchPendingTransactions(client, args),\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { AccessList, TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, Prettify, UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\n\nexport type CreateAccessListParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n FormattedTransactionRequest,\n 'from' | 'nonce' | 'accessList'\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | 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 )\n\nexport type CreateAccessListReturnType = Prettify<{\n accessList: AccessList\n gasUsed: bigint\n}>\n\nexport type CreateAccessListErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | RequestErrorType\n>\n\n/**\n * Creates an EIP-2930 access list.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param client - Client to use\n * @param parameters - {@link CreateAccessListParameters}\n * @returns The access list. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createAccessList } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await createAccessList(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function createAccessList(\n client: Client,\n args: CreateAccessListParameters,\n): Promise {\n const {\n account: account_ = client.account,\n blockNumber,\n blockTag = 'latest',\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n } as TransactionRequest,\n 'createAccessList',\n ) as TransactionRequest\n\n const response = await client.request({\n method: 'eth_createAccessList',\n params: [request as ExactPartial, block],\n })\n return {\n accessList: response.accessList,\n gasUsed: BigInt(response.gasUsed),\n }\n } catch (err) {\n throw getCallError(err as ErrorType, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateBlockFilterReturnType = Filter<'block'>\n\nexport type CreateBlockFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\nexport async function createBlockFilter(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newBlockFilter',\n })\n const id = await client.request({\n method: 'eth_newBlockFilter',\n })\n return { id, request: getRequest(id), type: 'block' }\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex, LogTopic } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateEventFilterParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (MaybeExtractEventArgsFromAbi<\n abiEvents,\n _eventName\n> extends infer eventFilterArgs\n ?\n | {\n args:\n | eventFilterArgs\n | (_args extends eventFilterArgs ? _args : never)\n event: abiEvent\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: abiEvent | undefined\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events: abiEvents | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n }\n : {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n })\n\nexport type CreateEventFilterReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = Prettify<\n Filter<'event', abiEvents, _eventName, _args, strict, fromBlock, toBlock>\n>\n\nexport type CreateEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param client - Client to use\n * @param parameters - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\nexport async function createEventFilter<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n event,\n events: events_,\n fromBlock,\n strict,\n toBlock,\n }: CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n > = {} as any,\n): Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n> {\n const events = events_ ?? (event ? [event] : undefined)\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n ...(topics.length ? { topics } : {}),\n },\n ],\n })\n\n return {\n abi: events,\n args,\n eventName: event ? (event as AbiEvent).name : undefined,\n fromBlock,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n toBlock,\n type: 'event',\n } as unknown as CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreatePendingTransactionFilterReturnType = Filter<'transaction'>\n\nexport type CreatePendingTransactionFilterErrorType =\n | RequestErrorType\n | ErrorType\n\n/**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\nexport async function createPendingTransactionFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newPendingTransactionFilter',\n })\n const id = await client.request({\n method: 'eth_newPendingTransactionFilter',\n })\n return { id, request: getRequest(id), type: 'transaction' }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport { decodeFunctionResult } from '../../utils/abi/decodeFunctionResult.js'\nimport { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type CallParameters, call } from './call.js'\n\nexport type GetBalanceParameters = {\n /** The address of the account. */\n address: Address\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 /** The balance of the account at a block tag. */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance(\n client: Client,\n {\n address,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n }: GetBalanceParameters,\n): Promise {\n if (client.batch?.multicall && client.chain?.contracts?.multicall3) {\n const multicall3Address = client.chain.contracts.multicall3.address\n\n const calldata = encodeFunctionData({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n })\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n to: multicall3Address,\n data: calldata,\n blockNumber,\n blockTag,\n } as unknown as CallParameters)\n\n return decodeFunctionResult({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n data: data || '0x',\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n\n const balance = await client.request({\n method: 'eth_getBalance',\n params: [address, blockNumberHex || blockTag],\n })\n return BigInt(balance)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetBlobBaseFeeReturnType = bigint\n\nexport type GetBlobBaseFeeErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await getBlobBaseFee(client)\n */\nexport async function getBlobBaseFee<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n): Promise {\n const baseFee = await client.request({\n method: 'eth_blobBaseFee',\n })\n return BigInt(baseFee)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Quantity } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBlockTransactionCountParameters =\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n\nexport type GetBlockTransactionCountReturnType = number\n\nexport type GetBlockTransactionCountErrorType =\n | NumberToHexErrorType\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await getBlockTransactionCount(client)\n */\nexport async function getBlockTransactionCount(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = 'latest',\n }: GetBlockTransactionCountParameters = {},\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let count: Quantity\n if (blockHash) {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByHash',\n params: [blockHash],\n },\n { dedupe: true },\n )\n } else {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByNumber',\n params: [blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n return hexToNumber(count)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetCodeParameters = {\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetCodeReturnType = Hex | undefined\n\nexport type GetCodeErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetCodeParameters}\n * @returns The contract's bytecode. {@link GetCodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCode } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getCode(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getCode(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetCodeParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const hex = await client.request(\n {\n method: 'eth_getCode',\n params: [address, blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n if (hex === '0x') return undefined\n return hex\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport { type SizeErrorType, size } from '../../utils/data/size.js'\nimport { type SliceErrorType, slice } from '../../utils/data/slice.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\n\nexport type GetDelegationParameters = {\n /** The address to check for delegation. */\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetDelegationReturnType = Address | undefined\n\nexport type GetDelegationErrorType =\n | GetAddressErrorType\n | GetCodeErrorType\n | SliceErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param client - Client to use\n * @param parameters - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getDelegation } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await getDelegation(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getDelegation(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetDelegationParameters,\n): Promise {\n const code = await getCode(client, {\n address,\n ...(blockNumber !== undefined ? { blockNumber } : { blockTag }),\n } as GetDelegationParameters)\n\n if (!code) return undefined\n\n // EIP-7702 delegation designator: 0xef0100 prefix (3 bytes) + address (20 bytes) = 23 bytes\n if (size(code) !== 23) return undefined\n\n // Check for EIP-7702 delegation designator prefix\n if (!code.startsWith('0xef0100')) return undefined\n\n // Extract the delegated address (bytes 3-23) and checksum it\n return getAddress(slice(code, 3, 23))\n}\n","import type { Address } from 'abitype'\nimport { BaseError } from './base.js'\n\nexport type Eip712DomainNotFoundErrorType = Eip712DomainNotFoundError & {\n name: 'Eip712DomainNotFoundError'\n}\nexport class Eip712DomainNotFoundError extends BaseError {\n constructor({ address }: { address: Address }) {\n super(`No EIP-712 domain found on contract \"${address}\".`, {\n metaMessages: [\n 'Ensure that:',\n `- The contract is deployed at the address \"${address}\".`,\n '- `eip712Domain()` function exists on the contract.',\n '- `eip712Domain()` function matches signature to ERC-5267 specification.',\n ],\n name: 'Eip712DomainNotFoundError',\n })\n }\n}\n","import type { Address, TypedDataDomain } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip712DomainNotFoundError,\n type Eip712DomainNotFoundErrorType,\n} from '../../errors/eip712.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequiredBy } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from './readContract.js'\n\nexport type GetEip712DomainParameters = {\n address: Address\n} & Pick\n\nexport type GetEip712DomainReturnType = {\n domain: RequiredBy<\n TypedDataDomain,\n 'chainId' | 'name' | 'verifyingContract' | 'salt' | 'version'\n >\n fields: Hex\n extensions: readonly bigint[]\n}\n\nexport type GetEip712DomainErrorType =\n | Eip712DomainNotFoundErrorType\n | ReadContractErrorType\n | ErrorType\n\n/**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, getEip712Domain } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await getEip712Domain(client, {\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\nexport async function getEip712Domain(\n client: Client,\n parameters: GetEip712DomainParameters,\n): Promise {\n const { address, factory, factoryData } = parameters\n\n try {\n const [\n fields,\n name,\n version,\n chainId,\n verifyingContract,\n salt,\n extensions,\n ] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi,\n address,\n functionName: 'eip712Domain',\n factory,\n factoryData,\n })\n\n return {\n domain: {\n name,\n version,\n chainId: Number(chainId),\n verifyingContract,\n salt,\n },\n extensions,\n fields,\n }\n } catch (e) {\n const error = e as ReadContractErrorType\n if (\n error.name === 'ContractFunctionExecutionError' &&\n error.cause.name === 'ContractFunctionZeroDataError'\n ) {\n throw new Eip712DomainNotFoundError({ address })\n }\n throw error\n }\n}\n\nconst abi = [\n {\n inputs: [],\n name: 'eip712Domain',\n outputs: [\n { name: 'fields', type: 'bytes1' },\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n { name: 'extensions', type: 'uint256[]' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatFeeHistoryErrorType,\n formatFeeHistory,\n} from '../../utils/formatters/feeHistory.js'\n\nexport type GetFeeHistoryParameters = {\n /**\n * Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.\n */\n blockCount: number\n /**\n * A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used.\n */\n rewardPercentiles: number[]\n} & (\n | {\n blockNumber?: undefined\n /**\n * Highest number block of the requested range.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n | {\n /** Highest number block of the requested range. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\nexport type GetFeeHistoryReturnType = FeeHistory\n\nexport type GetFeeHistoryErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | FormatFeeHistoryErrorType\n\n/**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param client - Client to use\n * @param parameters - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getFeeHistory } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await getFeeHistory(client, {\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\nexport async function getFeeHistory(\n client: Client,\n {\n blockCount,\n blockNumber,\n blockTag = 'latest',\n rewardPercentiles,\n }: GetFeeHistoryParameters,\n): Promise {\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const feeHistory = await client.request(\n {\n method: 'eth_feeHistory',\n params: [\n numberToHex(blockCount),\n blockNumberHex || blockTag,\n rewardPercentiles,\n ],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n return formatFeeHistory(feeHistory)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RpcFeeHistory } from '../../types/rpc.js'\n\nexport type FormatFeeHistoryErrorType = ErrorType\n\nexport function formatFeeHistory(feeHistory: RpcFeeHistory): FeeHistory {\n return {\n baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),\n gasUsedRatio: feeHistory.gasUsedRatio,\n oldestBlock: BigInt(feeHistory.oldestBlock),\n reward: feeHistory.reward?.map((reward) =>\n reward.map((value) => BigInt(value)),\n ),\n }\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterLogsParameters<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<'event', abi, eventName, any, strict, fromBlock, toBlock>\n}\nexport type GetFilterLogsReturnType<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetFilterLogsErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterLogs(client, { filter })\n */\nexport async function getFilterLogs<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterLogsParameters,\n): Promise<\n GetFilterLogsReturnType\n> {\n const strict = filter.strict ?? false\n\n const logs = await filter.request({\n method: 'eth_getFilterLogs',\n params: [filter.id],\n })\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!filter.abi)\n return formattedLogs as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Address } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatProofErrorType,\n formatProof,\n} from '../../utils/formatters/proof.js'\n\nexport type GetProofParameters = {\n /** Account address. */\n address: Address\n /** Array of storage-keys that should be proofed and included. */\n storageKeys: Hash[]\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetProofReturnType = Proof\n\nexport type GetProofErrorType =\n | NumberToHexErrorType\n | FormatProofErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getProof } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getProof(client, {\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\nexport async function getProof(\n client: Client,\n {\n address,\n blockNumber,\n blockTag: blockTag_,\n storageKeys,\n }: GetProofParameters,\n): Promise {\n const blockTag = blockTag_ ?? 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n const proof = await client.request({\n method: 'eth_getProof',\n params: [address, storageKeys, blockNumberHex || blockTag],\n })\n\n return formatProof(proof)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../../types/authorization.js'\nimport { toHex } from '../encoding/toHex.js'\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.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 { chainId, nonce, ...signature } = authorization\n const contractAddress = authorization.address\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 {\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 { MaybePromise, OneOf } from '../../types/utils.js'\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../authorization/serializeAuthorizationList.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 {\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\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> = (\n transaction: OneOf,\n signature?: Signature | undefined,\n) => MaybePromise<\n SerializedTransactionReturnType<\n OneOf,\n _transactionType\n >\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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(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 ? numberToHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return numberToHex(1)\n\n return v === 27n ? '0x' : numberToHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\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 { chainId } = authorization\n const address = authorization.address\n if (!isAddress(address)) throw new InvalidAddressError({ address })\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 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 type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type GetAddressErrorType, getAddress } from '../address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../address/isAddressEqual.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n recoverAuthorizationAddress,\n} from './recoverAuthorizationAddress.js'\n\nexport type VerifyAuthorizationParameters =\n RecoverAuthorizationAddressParameters & {\n /** The address that signed the Authorization object. */\n address: Address\n }\n\nexport type VerifyAuthorizationReturnType = boolean\n\nexport type VerifyAuthorizationErrorType =\n | IsAddressEqualErrorType\n | GetAddressErrorType\n | RecoverAuthorizationAddressErrorType\n | ErrorType\n\n/**\n * Verify that an Authorization object was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/utilities/verifyAuthorization}\n *\n * @param parameters - {@link VerifyAuthorizationParameters}\n * @returns Whether or not the signature is valid. {@link VerifyAuthorizationReturnType}\n */\nexport async function verifyAuthorization({\n address,\n authorization,\n signature,\n}: VerifyAuthorizationParameters): Promise {\n return isAddressEqual(\n getAddress(address),\n await recoverAuthorizationAddress({\n authorization,\n signature,\n }),\n )\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n WalletConnectSessionSettlementError,\n type WalletConnectSessionSettlementErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | AtomicityNotSupportedErrorType\n | AtomicReadyWalletRejectedUpgradeErrorType\n | BundleTooLargeErrorType\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | DuplicateIdErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownBundleIdErrorType\n | UnknownRpcErrorType\n | UnsupportedChainIdErrorType\n | UnsupportedNonOptionalCapabilityErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WalletConnectSessionSettlementErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest Promise>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n methods,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n\n const { method } = args\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n\n const requestId = dedupe\n ? stringToHex(`${uid}.${stringify(args)}`)\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n\n // 5700\n case UnsupportedNonOptionalCapabilityError.code:\n throw new UnsupportedNonOptionalCapabilityError(err)\n // 5710\n case UnsupportedChainIdError.code:\n throw new UnsupportedChainIdError(err)\n // 5720\n case DuplicateIdError.code:\n throw new DuplicateIdError(err)\n // 5730\n case UnknownBundleIdError.code:\n throw new UnknownBundleIdError(err)\n // 5740\n case BundleTooLargeError.code:\n throw new BundleTooLargeError(err)\n // 5750\n case AtomicReadyWalletRejectedUpgradeError.code:\n throw new AtomicReadyWalletRejectedUpgradeError(err)\n // 5760\n case AtomicityNotSupportedError.code:\n throw new AtomicityNotSupportedError(err)\n\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n\n // WalletConnect: Session Settlement Failed\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n case WalletConnectSessionSettlementError.code:\n throw new WalletConnectSessionSettlementError(err)\n\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter, 10) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe(\n fn: () => Promise,\n { enabled = true, id }: WithDedupeOptions,\n): Promise {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport type DefineChainReturnType = Prettify<\n chain &\n (chain['extendSchema'] extends Record\n ? {\n extend: (\n extended: extended,\n ) => Assign\n }\n : {})\n>\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain,\n>(chain: chain): DefineChainReturnType, chain>> {\n const chainInstance = {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign, chain>\n\n function extend(base: typeof chainInstance) {\n type ExtendFn = (base: typeof chainInstance) => unknown\n return (fnOrExtended: ExtendFn | Record) => {\n const properties = (\n typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended\n ) as (typeof chainInstance)['extendSchema']\n const combined = { ...base, ...properties }\n return Object.assign(combined, { extend: extend(combined) })\n }\n }\n\n return Object.assign(chainInstance, {\n extend: extend(chainInstance),\n }) as never\n}\n\nexport function extendSchema>(): schema {\n return {} as schema\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n} from 'abitype'\nexport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nexport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from '../accounts/utils/publicKeyToAddress.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './abi/decodeAbiParameters.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n encodeDeployData,\n} from './abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n encodeErrorResult,\n} from './abi/encodeErrorResult.js'\nexport {\n type EncodeArgErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from './abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n encodeFunctionResult,\n} from './abi/encodeFunctionResult.js'\nexport { type EncodePackedErrorType, encodePacked } from './abi/encodePacked.js'\nexport {\n type FormatAbiItemErrorType,\n type FormatAbiParamErrorType,\n type FormatAbiParamsErrorType,\n formatAbiItem,\n formatAbiParams,\n} from './abi/formatAbiItem.js'\nexport {\n type FormatAbiItemWithArgsErrorType,\n formatAbiItemWithArgs,\n} from './abi/formatAbiItemWithArgs.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './abi/parseEventLogs.js'\nexport {\n type ChecksumAddressErrorType,\n getAddress,\n} from './address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './address/getContractAddress.js'\nexport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from './address/isAddressEqual.js'\nexport {\n type HashAuthorizationErrorType,\n type HashAuthorizationParameters,\n type HashAuthorizationReturnType,\n hashAuthorization,\n} from './authorization/hashAuthorization.js'\nexport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n type RecoverAuthorizationAddressReturnType,\n recoverAuthorizationAddress,\n} from './authorization/recoverAuthorizationAddress.js'\nexport {\n type SerializeAuthorizationListErrorType,\n type SerializeAuthorizationListReturnType,\n serializeAuthorizationList,\n} from './authorization/serializeAuthorizationList.js'\nexport {\n type VerifyAuthorizationErrorType,\n type VerifyAuthorizationParameters,\n type VerifyAuthorizationReturnType,\n verifyAuthorization,\n} from './authorization/verifyAuthorization.js'\nexport {\n buildRequest,\n type RequestErrorType,\n} from './buildRequest.js'\nexport {\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './chain/assertCurrentChain.js'\nexport { defineChain } from './chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n concat,\n concatBytes,\n concatHex,\n} from './data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n pad,\n padBytes,\n padHex,\n} from './data/pad.js'\nexport { type SizeErrorType, size } from './data/size.js'\nexport {\n type AssertEndOffsetErrorType,\n type AssertStartOffsetErrorType,\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n type SliceReturnType,\n slice,\n sliceBytes,\n sliceHex,\n} from './data/slice.js'\nexport { type TrimErrorType, type TrimReturnType, trim } from './data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBigInt as bytesToBigint,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n type FromBytesReturnType,\n fromBytes,\n} from './encoding/fromBytes.js'\nexport {\n type AssertSizeErrorType,\n type FromHexErrorType,\n type FromHexParameters,\n type FromHexReturnType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBigIntOpts,\n type HexToBoolErrorType,\n type HexToBoolOpts,\n type HexToNumberErrorType,\n type HexToNumberOpts,\n type HexToStringErrorType,\n type HexToStringOpts,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n fromRlp,\n} from './encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n type HexToRlpErrorType,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './encoding/toRlp.js'\nexport {\n type GetCallErrorReturnType,\n getCallError,\n} from './errors/getCallError.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './errors/getContractError.js'\nexport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from './errors/getEstimateGasError.js'\nexport {\n containsNodeError,\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './errors/getNodeError.js'\nexport {\n type GetTransactionErrorParameters,\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from './errors/getTransactionError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './formatters/block.js'\nexport { type ExtractErrorType, extract } from './formatters/extract.js'\nexport {\n type DefineFormatterErrorType,\n defineFormatter,\n} from './formatters/formatter.js'\nexport { type FormatLogErrorType, formatLog } from './formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n} from './formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from './formatters/transactionRequest.js'\nexport { getAction } from './getAction.js'\nexport { type IsHashErrorType, isHash } from './hash/isHash.js'\nexport { type Keccak256ErrorType, keccak256 } from './hash/keccak256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './hash/ripemd160.js'\nexport { type Sha256ErrorType, sha256 } from './hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './hash/toFunctionSignature.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './nonceManager.js'\nexport { arrayRegex, bytesRegex, integerRegex } from './regex.js'\nexport {\n getSocket,\n rpc,\n type WebSocketAsyncErrorType,\n type WebSocketAsyncOptions,\n type WebSocketAsyncReturnType,\n type WebSocketErrorType,\n type WebSocketOptions,\n type WebSocketReturnType,\n} from './rpc/compat.js'\nexport {\n getHttpRpcClient,\n type HttpRequestErrorType,\n type HttpRequestParameters,\n type HttpRequestReturnType,\n type HttpRpcClient,\n type HttpRpcClientOptions,\n} from './rpc/http.js'\nexport {\n type GetSocketParameters,\n type GetSocketRpcClientErrorType,\n type GetSocketRpcClientParameters,\n getSocketRpcClient,\n type Socket,\n type SocketRpcClient,\n socketClientCache,\n} from './rpc/socket.js'\nexport { getWebSocketRpcClient } from './rpc/webSocket.js'\nexport {\n type HashMessageErrorType,\n type HashMessageReturnType,\n hashMessage,\n} from './signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashStruct,\n hashTypedData,\n} from './signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './signature/isErc8010Signature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './signature/parseErc8010Signature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './signature/recoverPublicKey.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './signature/recoverTypedDataAddress.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './signature/serializeErc8010Signature.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n parseTransaction,\n} from './transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './transaction/serializeAccessList.js'\nexport {\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './typedData.js'\nexport { type FormatEtherErrorType, formatEther } from './unit/formatEther.js'\nexport { type FormatGweiErrorType, formatGwei } from './unit/formatGwei.js'\nexport { type FormatUnitsErrorType, formatUnits } from './unit/formatUnits.js'\nexport { type ParseEtherErrorType, parseEther } from './unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './unit/parseGwei.js'\nexport { type ParseUnitsErrorType, parseUnits } from './unit/parseUnits.js'\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport type { MaybePromise } from '../../types/utils.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Override for the fetch function used to make requests. */\n fetchFn?:\n | ((input: string | URL | Request, init?: RequestInit) => Promise)\n | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit | undefined\n /** A callback to handle the request. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Override for the fetch function used to make requests. */\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request(\n params: HttpRequestParameters,\n ): Promise>\n}\n\nexport function getHttpRpcClient(\n url_: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n const { url, headers: headers_url } = parseUrl(url_)\n\n return {\n async request(params) {\n const {\n body,\n fetchFn = options.fetchFn ?? fetch,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n ...headers_url,\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n const args = (await onRequest?.(request, init)) ?? { ...init, url }\n const response = await fetchFn(args.url ?? url, args)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n\n/** @internal */\nexport function parseUrl(url_: string) {\n try {\n const url = new URL(url_)\n\n const result = (() => {\n // Handle Basic authentication credentials\n if (url.username) {\n const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`\n url.username = ''\n url.password = ''\n\n return {\n url: url.toString(),\n headers: { Authorization: `Basic ${btoa(credentials)}` },\n }\n }\n\n return\n })()\n\n return { url: url.toString(), ...result }\n } catch {\n return { url: url_ }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout(\n fn: ({\n signal,\n }: {\n signal: AbortController['signal'] | null\n }) => Promise,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\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","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 bytesToHex,\n type StringToHexErrorType,\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","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from '../../types/typedData.js'\nimport type { UnionOmit } from '../../types/utils.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 getTypesForEIP712Domain,\n type ValidateTypedDataErrorType,\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 const typedData extends TypedData | Record = TypedData,\n>({\n domain,\n types,\n}: UnionOmit, 'primaryType'>) {\n return hashStruct({\n data: domain as Record,\n primaryType: 'EIP712Domain',\n types: types as Record,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>({\n data,\n primaryType,\n types,\n}: MessageDefinition) {\n const encoded = encodeData({\n data: data as Record,\n primaryType,\n types: types as Record,\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') return [{ type: 'bytes32' }, keccak256(value)]\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, 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_, 10) / 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_, 10))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_, 10),\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}: {\n domain?: TypedDataDomain | undefined\n}): 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 typeof domain?.chainId === 'bigint') && {\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: domain as never,\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","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 * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Authorization from '../core/Authorization.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport * as Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-8010 signature. */\nexport type Unwrapped = {\n /** Authorization signed by the delegatee. */\n authorization: Authorization.Authorization\n /** Data to initialize the delegation. */\n data?: Hex.Hex | undefined\n /** The original signature. */\n signature: Hex.Hex\n /** Address of the initializer. */\n to?: Address.Address | undefined\n}\n\n/** Wrapped ERC-8010 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-8010 wrapped signatures.\n */\nexport const magicBytes =\n '0x8010801080108010801080108010801080108010801080108010801080108010' as const\n\n/** Suffix ABI parameters for the ERC-8010 wrapped signature. */\nexport const suffixParameters = AbiParameters.from(\n '(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data',\n)\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * SignatureErc8010.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-8010 wrapped signature.\n * ```\n *\n * @param value - The value to assert.\n */\nexport function assert(value: Unwrapped | Wrapped) {\n if (typeof value === 'string') {\n if (Hex.slice(value, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(value)\n } else Signature.assert(value.authorization)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc8010.from('0x...') // [!code focus]\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc8010.from({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * })\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } }\n * ```\n *\n * @param value - Value to parse.\n * @returns Parsed value.\n */\nexport function from(value: Unwrapped | Wrapped): Unwrapped {\n if (typeof value === 'string') return unwrap(value)\n return value\n}\n\nexport declare namespace from {\n type ErrorType = unwrap.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Unwraps an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const { authorization, data, signature } = SignatureErc8010.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to unwrap.\n * @returns Unwrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const suffixLength = Hex.toNumber(Hex.slice(wrapped, -64, -32))\n const suffix = Hex.slice(wrapped, -suffixLength - 64, -64)\n const signature = Hex.slice(wrapped, 0, -suffixLength - 64)\n\n const [auth, to, data] = AbiParameters.decode(suffixParameters, suffix)\n\n const authorization = Authorization.from({\n address: auth.delegation,\n chainId: Number(auth.chainId),\n nonce: auth.nonce,\n yParity: auth.yParity,\n r: auth.r,\n s: auth.s,\n })\n\n return {\n authorization,\n signature,\n ...(data && data !== '0x' ? { data, to } : {}),\n }\n}\n\nexport declare namespace unwrap {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Wraps a signature into [ERC-8010 format](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md).\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc8010.wrap({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Values to wrap.\n * @returns Wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature } = value\n\n assert(value)\n\n const self = Secp256k1.recoverAddress({\n payload: Authorization.getSignPayload(value.authorization),\n signature: Signature.from(value.authorization),\n })\n\n const suffix = AbiParameters.encode(suffixParameters, [\n {\n ...value.authorization,\n delegation: value.authorization.address,\n chainId: BigInt(value.authorization.chainId),\n },\n value.to ?? self,\n data ?? '0x',\n ])\n const suffixLength = Hex.fromNumber(Hex.size(suffix), { size: 32 })\n return Hex.concat(signature, suffix, suffixLength, magicBytes)\n}\n\nexport declare namespace wrap {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const valid = SignatureErc8010.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param value - The value to validate.\n * @returns `true` if the value is valid, `false` otherwise.\n */\nexport function validate(value: Unwrapped | Wrapped): boolean {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-8010 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc8010.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-8010 wrapped signature.`)\n }\n}\n","import * as abitype from 'abitype'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiParameters.js'\nimport * as Cursor from './internal/cursor.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for ABI parameters. */\nexport type AbiParameters = readonly abitype.AbiParameter[]\n\n/** A parameter on an {@link ox#AbiParameters.AbiParameters}. */\nexport type Parameter = abitype.AbiParameter\n\n/** A packed ABI type. */\nexport type PackedAbiType =\n | abitype.SolidityAddress\n | abitype.SolidityBool\n | abitype.SolidityBytes\n | abitype.SolidityInt\n | abitype.SolidityString\n | abitype.SolidityArrayWithoutTuple\n\n/**\n * Decodes ABI-encoded data into its respective primitive values based on ABI Parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * You can pass **JSON ABI** Parameters:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' },\n * ],\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @param parameters - The set of ABI parameters to decode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param data - ABI encoded data.\n * @param options - Decoding options.\n * @returns Array of decoded values.\n */\nexport function decode<\n const parameters extends AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n>(\n parameters: parameters,\n data: Bytes.Bytes | Hex.Hex,\n options?: decode.Options,\n): decode.ReturnType\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n parameters: AbiParameters,\n data: Bytes.Bytes | Hex.Hex,\n options: {\n as?: 'Array' | 'Object' | undefined\n checksumAddress?: boolean | undefined\n } = {},\n): readonly unknown[] | Record {\n const { as = 'Array', checksumAddress = false } = options\n\n const bytes = typeof data === 'string' ? Bytes.fromHex(data) : data\n const cursor = Cursor.create(bytes)\n\n if (Bytes.size(bytes) === 0 && parameters.length > 0)\n throw new ZeroDataError()\n if (Bytes.size(bytes) && Bytes.size(bytes) < 32)\n throw new DataSizeTooSmallError({\n data: typeof data === 'string' ? data : Hex.fromBytes(data),\n parameters: parameters as readonly Parameter[],\n size: Bytes.size(bytes),\n })\n\n let consumed = 0\n const values: any = as === 'Array' ? [] : {}\n for (let i = 0; i < parameters.length; ++i) {\n const param = parameters[i] as Parameter\n cursor.setPosition(consumed)\n const [data, consumed_] = internal.decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: 0,\n })\n consumed += consumed_\n if (as === 'Array') values.push(data)\n else values[param.name ?? i] = data\n }\n return values\n}\n\nexport declare namespace decode {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Object' | 'Array' | undefined\n /**\n * Whether decoded addresses should be checksummed.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n\n type ReturnType<\n parameters extends AbiParameters = AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n > = parameters extends readonly []\n ? as extends 'Object'\n ? {}\n : []\n : as extends 'Object'\n ? internal.ToObject\n : internal.ToPrimitiveTypes\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | internal.decodeParameter.ErrorType\n | ZeroDataError\n | DataSizeTooSmallError\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes primitive values into ABI encoded data as per the [Application Binary Interface (ABI) Specification](https://docs.soliditylang.org/en/latest/abi-spec).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * Specify **JSON ABI** Parameters as schema:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * [\n * { type: 'string', name: 'name' },\n * { type: 'uint', name: 'age' },\n * { type: 'bool', name: 'isOwner' },\n * ],\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @param parameters - The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param values - The set of primitive values that correspond to the ABI types defined in `parameters`.\n * @returns ABI encoded data.\n */\nexport function encode<\n const parameters extends AbiParameters | readonly unknown[],\n>(\n parameters: parameters,\n values: parameters extends AbiParameters\n ? internal.ToPrimitiveTypes\n : never,\n options?: encode.Options,\n): Hex.Hex {\n const { checksumAddress = false } = options ?? {}\n\n if (parameters.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: parameters.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParameters = internal.prepareParameters({\n checksumAddress,\n parameters: parameters as readonly Parameter[],\n values: values as any,\n })\n const data = internal.encode(preparedParameters)\n if (data.length === 0) return '0x'\n return data\n}\n\nexport declare namespace encode {\n type ErrorType =\n | LengthMismatchError\n | internal.encode.ErrorType\n | internal.prepareParameters.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /**\n * Whether addresses should be checked against their checksum.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n}\n\n/**\n * Encodes an array of primitive values to a [packed ABI encoding](https://docs.soliditylang.org/en/latest/abi-spec.html#non-standard-packed-mode).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const encoded = AbiParameters.encodePacked(\n * ['address', 'string'],\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 'hello world'],\n * )\n * // @log: '0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64'\n * ```\n *\n * @param types - Set of ABI types to pack encode.\n * @param values - The set of primitive values that correspond to the ABI types defined in `types`.\n * @returns The encoded packed data.\n */\nexport function encodePacked<\n const packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: packedAbiTypes, values: encodePacked.Values): Hex.Hex {\n if (types.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: types.length as number,\n givenLength: values.length as number,\n })\n\n const data: Hex.Hex[] = []\n for (let i = 0; i < (types as unknown[]).length; i++) {\n const type = types[i]\n const value = values[i]\n data.push(encodePacked.encode(type, value))\n }\n return Hex.concat(...data)\n}\n\nexport namespace encodePacked {\n export type ErrorType =\n | Hex.concat.ErrorType\n | LengthMismatchError\n | Errors.GlobalErrorType\n\n export type Values<\n packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n > = {\n [key in keyof packedAbiTypes]: packedAbiTypes[key] extends abitype.AbiType\n ? abitype.AbiParameterToPrimitiveType<{ type: packedAbiTypes[key] }>\n : unknown\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc\n export function encode(\n type: packedAbiType,\n value: Values<[packedAbiType]>[0],\n isArray = false,\n ): Hex.Hex {\n if (type === 'address') {\n const address = value as Address.Address\n Address.assert(address)\n return Hex.padLeft(\n address.toLowerCase() as Hex.Hex,\n isArray ? 32 : 0,\n ) as Address.Address\n }\n if (type === 'string') return Hex.fromString(value as string)\n if (type === 'bytes') return value as Hex.Hex\n if (type === 'bool')\n return Hex.padLeft(Hex.fromBoolean(value as boolean), isArray ? 32 : 1)\n\n const intMatch = (type as string).match(Solidity.integerRegex)\n if (intMatch) {\n const [_type, baseType, bits = '256'] = intMatch\n const size = Number.parseInt(bits, 10) / 8\n return Hex.fromNumber(value as number, {\n size: isArray ? 32 : size,\n signed: baseType === 'int',\n })\n }\n\n const bytesMatch = (type as string).match(Solidity.bytesRegex)\n if (bytesMatch) {\n const [_type, size] = bytesMatch\n if (Number.parseInt(size!, 10) !== ((value as Hex.Hex).length - 2) / 2)\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size!, 10),\n value: value as Hex.Hex,\n })\n return Hex.padRight(value as Hex.Hex, isArray ? 32 : 0) as Hex.Hex\n }\n\n const arrayMatch = (type as string).match(Solidity.arrayRegex)\n if (arrayMatch && Array.isArray(value)) {\n const [_type, childType] = arrayMatch\n const data: Hex.Hex[] = []\n for (let i = 0; i < value.length; i++) {\n data.push(encode(childType, value[i], true))\n }\n if (data.length === 0) return '0x'\n return Hex.concat(...data)\n }\n\n throw new InvalidTypeError(type as string)\n }\n}\n\n/**\n * Formats {@link ox#AbiParameters.AbiParameters} into **Human Readable ABI Parameters**.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const formatted = AbiParameters.format([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param parameters - The ABI Parameters to format.\n * @returns The formatted ABI Parameters .\n */\nexport function format<\n const parameters extends readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n>(\n parameters:\n | parameters\n | readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n): abitype.FormatAbiParameters {\n return abitype.formatAbiParameters(parameters)\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses arbitrary **JSON ABI Parameters** or **Human Readable ABI Parameters** into typed {@link ox#AbiParameters.AbiParameters}.\n *\n * @example\n * ### JSON Parameters\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable Parameters\n *\n * Human Readable ABI Parameters can be parsed into a typed {@link ox#AbiParameters.AbiParameters}:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from('address spender, uint256 amount')\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'Foo foo, address bar',\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param parameters - The ABI Parameters to parse.\n * @returns The typed ABI Parameters.\n */\nexport function from<\n const parameters extends AbiParameters | string | readonly string[],\n>(\n parameters: parameters | AbiParameters | string | readonly string[],\n): from.ReturnType {\n if (Array.isArray(parameters) && typeof parameters[0] === 'string')\n return abitype.parseAbiParameters(parameters) as never\n if (typeof parameters === 'string')\n return abitype.parseAbiParameters(parameters) as never\n return parameters as never\n}\n\nexport declare namespace from {\n type ReturnType<\n parameters extends AbiParameters | string | readonly string[],\n > = parameters extends string\n ? abitype.ParseAbiParameters\n : parameters extends readonly string[]\n ? abitype.ParseAbiParameters\n : parameters\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Throws when the data size is too small for the given parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x010f')\n * // ↑ ❌ 2 bytes\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass a valid data size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class DataSizeTooSmallError extends Errors.BaseError {\n override readonly name = 'AbiParameters.DataSizeTooSmallError'\n constructor({\n data,\n parameters,\n size,\n }: { data: Hex.Hex; parameters: readonly Parameter[]; size: number }) {\n super(`Data size of ${size} bytes is too small for given parameters.`, {\n metaMessages: [\n `Params: (${abitype.formatAbiParameters(parameters as readonly [Parameter])})`,\n `Data: ${data} (${size} bytes)`,\n ],\n })\n }\n}\n\n/**\n * Throws when zero data is provided, but data is expected.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x')\n * // ↑ ❌ zero data\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass valid data.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class ZeroDataError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\n/**\n * The length of the array value does not match the length specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('uint256[3]'), [[69n, 420n]])\n * // ↑ expected: 3 ↑ ❌ length: 2\n * // @error: AbiParameters.ArrayLengthMismatchError: ABI encoding array length mismatch\n * // @error: for type `uint256[3]`. Expected: `3`. Given: `2`.\n * ```\n *\n * ### Solution\n *\n * Pass an array of the correct length.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [[69n, 420n, 69n]])\n * // ↑ ✅ length: 3\n * ```\n */\nexport class ArrayLengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n `Array length mismatch for type \\`${type}\\`. Expected: \\`${expectedLength}\\`. Given: \\`${givenLength}\\`.`,\n )\n }\n}\n\n/**\n * The size of the bytes value does not match the size specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('bytes8'), [['0xdeadbeefdeadbeefdeadbeef']])\n * // ↑ expected: 8 bytes ↑ ❌ size: 12 bytes\n * // @error: BytesSizeMismatchError: Size of bytes \"0xdeadbeefdeadbeefdeadbeef\"\n * // @error: (bytes12) does not match expected size (bytes8).\n * ```\n *\n * ### Solution\n *\n * Pass a bytes value of the correct size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['bytes8']), ['0xdeadbeefdeadbeef'])\n * // ↑ ✅ size: 8 bytes\n * ```\n */\nexport class BytesSizeMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.BytesSizeMismatchError'\n constructor({\n expectedSize,\n value,\n }: { expectedSize: number; value: Hex.Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${Hex.size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\n/**\n * The length of the values to encode does not match the length of the ABI parameters.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['string', 'uint256']), ['hello'])\n * // @error: LengthMismatchError: ABI encoding params/values length mismatch.\n * // @error: Expected length (params): 2\n * // @error: Given length (values): 1\n * ```\n *\n * ### Solution\n *\n * Pass the correct number of values to encode.\n *\n * ### Solution\n *\n * Pass a [valid ABI type](https://docs.soliditylang.org/en/develop/abi-spec.html#types).\n */\nexport class LengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.LengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding parameters/values length mismatch.',\n `Expected length (parameters): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * The value provided is not a valid array as specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [69])\n * ```\n *\n * ### Solution\n *\n * Pass an array value.\n */\nexport class InvalidArrayError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidArrayError'\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is not a valid array.`)\n }\n}\n\n/**\n * Throws when the ABI parameter type is invalid.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'lol' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ❌ invalid type\n * // @error: AbiParameters.InvalidTypeError: Type `lol` is not a valid ABI Type.\n * ```\n */\nexport class InvalidTypeError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidTypeError'\n constructor(type: string) {\n super(`Type \\`${type}\\` is not a valid ABI Type.`)\n }\n}\n","import type { Address as abitype_Address } from 'abitype'\nimport * as Bytes from './Bytes.js'\nimport * as Caches from './Caches.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as PublicKey from './PublicKey.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** Root type for Address. */\nexport type Address = abitype_Address\n\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(\n value: string,\n options: assert.Options = {},\n): asserts value is Address {\n const { strict = true } = options\n\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n })\n\n if (strict) {\n if (value.toLowerCase() === value) return\n if (checksum(value as Address) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n })\n }\n}\n\nexport declare namespace assert {\n type Options = {\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\n type ErrorType = InvalidAddressError | Errors.GlobalErrorType\n}\n\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address: string): Address {\n if (Caches.checksum.has(address)) return Caches.checksum.get(address)!\n\n assert(address, { strict: false })\n\n const hexAddress = address.substring(2).toLowerCase()\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' })\n\n const characters = hexAddress.split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1]! >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i]!.toUpperCase()\n }\n if ((hash[i >> 1]! & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1]!.toUpperCase()\n }\n }\n\n const result = `0x${characters.join('')}` as const\n Caches.checksum.set(address, result)\n return result\n}\n\nexport declare namespace checksum {\n type ErrorType =\n | assert.ErrorType\n | Hash.keccak256.ErrorType\n | Bytes.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a stringified address to a typed (optionally checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: true\n * })\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address: string, options: from.Options = {}): Address {\n const { checksum: checksumVal = false } = options\n assert(address)\n if (checksumVal) return checksum(address)\n return address as Address\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | assert.ErrorType\n | checksum.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(\n publicKey: PublicKey.PublicKey,\n options: fromPublicKey.Options = {},\n): Address {\n const address = Hash.keccak256(\n `0x${PublicKey.toHex(publicKey).slice(4)}`,\n ).substring(26)\n return from(`0x${address}`, options)\n}\n\nexport declare namespace fromPublicKey {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA: Address, addressB: Address): boolean {\n assert(addressA, { strict: false })\n assert(addressB, { strict: false })\n return addressA.toLowerCase() === addressB.toLowerCase()\n}\n\nexport declare namespace isEqual {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(\n address: string,\n options: validate.Options = {},\n): address is Address {\n const { strict = true } = options ?? {}\n try {\n assert(address, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\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}\n\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError<\n cause extends InvalidInputError | InvalidChecksumError =\n | InvalidInputError\n | InvalidChecksumError,\n> extends Errors.BaseError {\n override readonly name = 'Address.InvalidAddressError'\n\n constructor({ address, cause }: { address: string; cause: cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n override readonly name = 'Address.InvalidInputError'\n\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.')\n }\n}\n\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n override readonly name = 'Address.InvalidChecksumError'\n\n constructor() {\n super('Address does not match its checksum counterpart.')\n }\n}\n","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see 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 * as Address from './Address.js'\nimport { LruMap } from './internal/lru.js'\n\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap(8192),\n}\n\nexport const checksum = caches.checksum\n\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches)) cache.clear()\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3'\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: keccak256.Options = {},\n): keccak256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_keccak256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace keccak256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [HMAC-SHA256](https://en.wikipedia.org/wiki/HMAC) of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `hmac` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef')\n * // @log: '0x...'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param key - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} key.\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns HMAC-SHA256 hash.\n */\nexport function hmac256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n key: Hex.Hex | Bytes.Bytes,\n value: value | Hex.Hex | Bytes.Bytes,\n options: hmac256.Options = {},\n): hmac256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = hmac(noble_sha256, Bytes.from(key), Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace hmac256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: ripemd160.Options = {},\n): ripemd160.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_ripemd160(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace ripemd160 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: sha256.Options = {},\n): sha256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_sha256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace sha256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value: string): value is Hex.Hex {\n return Hex.validate(value) && Hex.size(value) === 32\n}\n\nexport declare namespace validate {\n type ErrorType =\n | Hex.validate.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial } from './internal/types.js'\nimport * as Json from './Json.js'\n\n/** Root type for an ECDSA Public Key. */\nexport type PublicKey<\n compressed extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n compressed extends true\n ? {\n prefix: numberType\n x: bigintType\n y?: undefined\n }\n : {\n prefix: numberType\n x: bigintType\n y: bigintType\n }\n>\n\n/**\n * Asserts that a {@link ox#PublicKey.PublicKey} is valid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @error: PublicKey.InvalidError: Value \\`{\"y\":\"1\"}\\` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function assert(\n publicKey: ExactPartial,\n options: assert.Options = {},\n): asserts publicKey is PublicKey {\n const { compressed } = options\n const { prefix, x, y } = publicKey\n\n // Uncompressed\n if (\n compressed === false ||\n (typeof x === 'bigint' && typeof y === 'bigint')\n ) {\n if (prefix !== 4)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidUncompressedPrefixError(),\n })\n return\n }\n\n // Compressed\n if (\n compressed === true ||\n (typeof x === 'bigint' && typeof y === 'undefined')\n ) {\n if (prefix !== 3 && prefix !== 2)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidCompressedPrefixError(),\n })\n return\n }\n\n // Unknown/invalid\n throw new InvalidError({ publicKey })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = InvalidError | InvalidPrefixError | Errors.GlobalErrorType\n}\n\n/**\n * Compresses a {@link ox#PublicKey.PublicKey}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const compressed = PublicKey.compress(publicKey) // [!code focus]\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The public key to compress.\n * @returns The compressed public key.\n */\nexport function compress(publicKey: PublicKey): PublicKey {\n const { x, y } = publicKey\n return {\n prefix: y % 2n === 0n ? 2 : 3,\n x,\n }\n}\n\nexport declare namespace compress {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#PublicKey.PublicKey} object from a {@link ox#PublicKey.PublicKey}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from('0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param value - The public key value to instantiate.\n * @returns The instantiated {@link ox#PublicKey.PublicKey}.\n */\nexport function from<\n const publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes,\n>(value: from.Value): from.ReturnType {\n const publicKey = (() => {\n if (Hex.validate(value)) return fromHex(value)\n if (Bytes.validate(value)) return fromBytes(value)\n\n const { prefix, x, y } = value\n if (typeof x === 'bigint' && typeof y === 'bigint')\n return { prefix: prefix ?? 0x04, x, y }\n return { prefix, x }\n })()\n\n assert(publicKey)\n\n return publicKey as never\n}\n\n/** @internal */\ntype CompressedPublicKey = PublicKey\n\n/** @internal */\ntype UncompressedPublicKey = Omit, 'prefix'> & {\n prefix?: PublicKey['prefix'] | undefined\n}\n\nexport declare namespace from {\n type Value<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey | CompressedPublicKey | UncompressedPublicKey\n\n type ReturnType<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey extends CompressedPublicKey | UncompressedPublicKey\n ? publicKey extends UncompressedPublicKey\n ? Compute\n : publicKey\n : PublicKey\n\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromBytes(publicKey: Bytes.Bytes): PublicKey {\n return fromHex(Hex.fromBytes(publicKey))\n}\n\nexport declare namespace fromBytes {\n type ErrorType =\n | fromHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### Deserializing a Compressed Public Key\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75')\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromHex(publicKey: Hex.Hex): PublicKey {\n if (\n publicKey.length !== 132 &&\n publicKey.length !== 130 &&\n publicKey.length !== 68\n )\n throw new InvalidSerializedSizeError({ publicKey })\n\n if (publicKey.length === 130) {\n const x = BigInt(Hex.slice(publicKey, 0, 32))\n const y = BigInt(Hex.slice(publicKey, 32, 64))\n return {\n prefix: 4,\n x,\n y,\n } as never\n }\n\n if (publicKey.length === 132) {\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n const y = BigInt(Hex.slice(publicKey, 33, 65))\n return {\n prefix,\n x,\n y,\n } as never\n }\n\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n return {\n prefix,\n x,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType = Hex.slice.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const bytes = PublicKey.toBytes(publicKey) // [!code focus]\n * // @log: Uint8Array [128, 3, 131, ...]\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toBytes(\n publicKey: PublicKey,\n options: toBytes.Options = {},\n): Bytes.Bytes {\n return Bytes.fromHex(toHex(publicKey, options))\n}\n\nexport declare namespace toBytes {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const hex = PublicKey.toHex(publicKey) // [!code focus]\n * // @log: '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toHex(\n publicKey: PublicKey,\n options: toHex.Options = {},\n): Hex.Hex {\n assert(publicKey)\n\n const { prefix, x, y } = publicKey\n const { includePrefix = true } = options\n\n const publicKey_ = Hex.concat(\n includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x',\n Hex.fromNumber(x, { size: 32 }),\n // If the public key is not compressed, add the y coordinate.\n typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x',\n )\n\n return publicKey_\n}\n\nexport declare namespace toHex {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Validates a {@link ox#PublicKey.PublicKey}. Returns `true` if valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const valid = PublicKey.validate({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @log: false\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function validate(\n publicKey: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(publicKey, options)\n return true\n } catch (_error) {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a public key is invalid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({ y: 1n })\n * // @error: PublicKey.InvalidError: Value `{\"y\":1n}` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n */\nexport class InvalidError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidError'\n\n constructor({ publicKey }: { publicKey: unknown }) {\n super(`Value \\`${Json.stringify(publicKey)}\\` is not a valid public key.`, {\n metaMessages: [\n 'Public key must contain:',\n '- an `x` and `prefix` value (compressed)',\n '- an `x`, `y`, and `prefix` value (uncompressed)',\n ],\n })\n }\n}\n\n/** Thrown when a public key has an invalid prefix. */\nexport class InvalidPrefixError<\n cause extends InvalidCompressedPrefixError | InvalidUncompressedPrefixError =\n | InvalidCompressedPrefixError\n | InvalidUncompressedPrefixError,\n> extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidPrefixError'\n\n constructor({ prefix, cause }: { prefix: number | undefined; cause: cause }) {\n super(`Prefix \"${prefix}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when the public key has an invalid prefix for a compressed public key. */\nexport class InvalidCompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidCompressedPrefixError'\n\n constructor() {\n super('Prefix must be 2 or 3 for compressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid prefix for an uncompressed public key. */\nexport class InvalidUncompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidUncompressedPrefixError'\n\n constructor() {\n super('Prefix must be 4 for uncompressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid serialized size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidSerializedSizeError'\n\n constructor({ publicKey }: { publicKey: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${publicKey}\\` is an invalid public key size.`, {\n metaMessages: [\n 'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',\n `Received ${Hex.size(Hex.from(publicKey))} bytes.`,\n ],\n })\n }\n}\n","import type {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\n} from 'abitype'\nimport * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Bytes from '../Bytes.js'\nimport * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\nimport { integerRegex } from '../Solidity.js'\nimport type * as Cursor from './cursor.js'\nimport type { Compute, IsNarrowable, UnionToIntersection } from './types.js'\n\n/** @internal */\nexport type ParameterToPrimitiveType<\n abiParameter extends AbiParameter | { name: string; type: unknown },\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParameterToPrimitiveType\n\n/** @internal */\nexport type PreparedParameter = { dynamic: boolean; encoded: Hex.Hex }\n\n/** @internal */\nexport type ToObject<\n parameters extends readonly AbiParameter[],\n kind extends AbiParameterKind = AbiParameterKind,\n> = IsNarrowable extends true\n ? Compute<\n UnionToIntersection<\n {\n [index in keyof parameters]: parameters[index] extends {\n name: infer name extends string\n }\n ? {\n [key in name]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n : {\n [key in index]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n }[number]\n >\n >\n : unknown\n\n/** @internal */\nexport type ToPrimitiveTypes<\n abiParameters extends readonly AbiParameter[],\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParametersToPrimitiveTypes\n\n/** @internal */\nexport type Tuple = ParameterToPrimitiveType\n\n/** @internal */\nexport function decodeParameter(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(\n cursor,\n { ...param, type },\n { checksumAddress, length, staticPosition },\n )\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, {\n checksumAddress,\n staticPosition,\n })\n if (param.type === 'address')\n return decodeAddress(cursor, { checksum: checksumAddress })\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 AbiParameters.InvalidTypeError(param.type)\n}\n\nexport declare namespace decodeParameter {\n type ErrorType =\n | decodeArray.ErrorType\n | decodeTuple.ErrorType\n | decodeAddress.ErrorType\n | decodeBool.ErrorType\n | decodeBytes.ErrorType\n | decodeNumber.ErrorType\n | decodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\n/** @internal */\nexport function decodeAddress(\n cursor: Cursor.Cursor,\n options: { checksum?: boolean | undefined } = {},\n) {\n const { checksum = false } = options\n const value = cursor.readBytes(32)\n const wrap = (address: Hex.Hex) =>\n checksum ? Address.checksum(address) : address\n return [wrap(Hex.fromBytes(Bytes.slice(value, -20))), 32]\n}\n\nexport declare namespace decodeAddress {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeArray(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n staticPosition: number\n },\n) {\n const { checksumAddress, length, staticPosition } = options\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 = Bytes.toNumber(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 = Bytes.toNumber(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 checksumAddress,\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeArray {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBool(cursor: Cursor.Cursor) {\n return [Bytes.toBoolean(cursor.readBytes(32), { size: 32 }), 32]\n}\n\nexport declare namespace decodeBool {\n type ErrorType = Bytes.toBoolean.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBytes(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\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 = Bytes.toNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = Bytes.toNumber(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 [Hex.fromBytes(data), 32]\n }\n\n const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))\n return [value, 32]\n}\n\nexport declare namespace decodeBytes {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeNumber(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10)\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? Bytes.toBigInt(value, { signed })\n : Bytes.toNumber(value, { signed }),\n 32,\n ]\n}\n\nexport declare namespace decodeNumber {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport type TupleAbiParameter = AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n}\n\n/** @internal */\nexport function decodeTuple(\n cursor: Cursor.Cursor,\n param: TupleAbiParameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeTuple {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeString(\n cursor: Cursor.Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = Bytes.toNumber(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 = Bytes.toNumber(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 = Bytes.toString(Bytes.trimLeft(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\nexport declare namespace decodeString {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toString.ErrorType\n | Bytes.trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameters<\n const parameters extends AbiParameters.AbiParameters,\n>({\n checksumAddress,\n parameters,\n values,\n}: {\n checksumAddress?: boolean | undefined\n parameters: parameters\n values: parameters extends AbiParameters.AbiParameters\n ? ToPrimitiveTypes\n : never\n}) {\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameters.length; i++) {\n preparedParameters.push(\n prepareParameter({\n checksumAddress,\n parameter: parameters[i]!,\n value: values[i],\n }),\n )\n }\n return preparedParameters\n}\n\n/** @internal */\nexport declare namespace prepareParameters {\n type ErrorType = prepareParameter.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameter<\n const parameter extends AbiParameters.Parameter,\n>({\n checksumAddress = false,\n parameter: parameter_,\n value,\n}: {\n parameter: parameter\n value: parameter extends AbiParameters.Parameter\n ? ParameterToPrimitiveType\n : never\n checksumAddress?: boolean | undefined\n}): PreparedParameter {\n const parameter = parameter_ as AbiParameters.Parameter\n\n const arrayComponents = getArrayComponents(parameter.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, {\n checksumAddress,\n length,\n parameter: {\n ...parameter,\n type,\n },\n })\n }\n if (parameter.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n checksumAddress,\n parameter: parameter as TupleAbiParameter,\n })\n }\n if (parameter.type === 'address') {\n return encodeAddress(value as unknown as Hex.Hex, {\n checksum: checksumAddress,\n })\n }\n if (parameter.type === 'bool') {\n return encodeBoolean(value as unknown as boolean)\n }\n if (parameter.type.startsWith('uint') || parameter.type.startsWith('int')) {\n const signed = parameter.type.startsWith('int')\n const [, , size = '256'] = integerRegex.exec(parameter.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\n }\n if (parameter.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex.Hex, { type: parameter.type })\n }\n if (parameter.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new AbiParameters.InvalidTypeError(parameter.type)\n}\n\n/** @internal */\nexport declare namespace prepareParameter {\n type ErrorType =\n | encodeArray.ErrorType\n | encodeTuple.ErrorType\n | encodeAddress.ErrorType\n | encodeBoolean.ErrorType\n | encodeBytes.ErrorType\n | encodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encode(preparedParameters: PreparedParameter[]): Hex.Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) staticSize += 32\n else staticSize += Hex.size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParameters: Hex.Hex[] = []\n const dynamicParameters: Hex.Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) {\n staticParameters.push(\n Hex.fromNumber(staticSize + dynamicSize, { size: 32 }),\n )\n dynamicParameters.push(encoded)\n dynamicSize += Hex.size(encoded)\n } else {\n staticParameters.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return Hex.concat(...staticParameters, ...dynamicParameters)\n}\n\n/** @internal */\nexport declare namespace encode {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeAddress(\n value: Hex.Hex,\n options: { checksum: boolean },\n): PreparedParameter {\n const { checksum = false } = options\n Address.assert(value, { strict: checksum })\n return {\n dynamic: false,\n encoded: Hex.padLeft(value.toLowerCase() as Hex.Hex),\n }\n}\n\n/** @internal */\nexport declare namespace encodeAddress {\n type ErrorType =\n | Address.assert.ErrorType\n | Hex.padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeArray(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, length, parameter } = options\n\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new AbiParameters.InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiParameters.ArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${parameter.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter,\n value: value[i],\n })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParameters.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encode(preparedParameters)\n if (dynamic) {\n const length = Hex.fromNumber(preparedParameters.length, { size: 32 })\n return {\n dynamic: true,\n encoded:\n preparedParameters.length > 0 ? Hex.concat(length, data) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeArray {\n type ErrorType =\n | AbiParameters.InvalidArrayError\n | AbiParameters.ArrayLengthMismatchError\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBytes(\n value: Hex.Hex,\n { type }: { type: string },\n): PreparedParameter {\n const [, parametersize] = type.split('bytes')\n const bytesSize = Hex.size(value)\n if (!parametersize) {\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_ = Hex.padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32)\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padLeft(Hex.fromNumber(bytesSize, { size: 32 })),\n value_,\n ),\n }\n }\n if (bytesSize !== Number.parseInt(parametersize, 10))\n throw new AbiParameters.BytesSizeMismatchError({\n expectedSize: Number.parseInt(parametersize, 10),\n value,\n })\n return { dynamic: false, encoded: Hex.padRight(value) }\n}\n\n/** @internal */\nexport declare namespace encodeBytes {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.padRight.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBoolean(value: boolean): PreparedParameter {\n if (typeof value !== 'boolean')\n throw new Errors.BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: Hex.padLeft(Hex.fromBoolean(value)) }\n}\n\n/** @internal */\nexport declare namespace encodeBoolean {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.fromBoolean.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeNumber(\n value: number,\n { signed, size }: { signed: boolean; size: number },\n): PreparedParameter {\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 Hex.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: Hex.fromNumber(value, {\n size: 32,\n signed,\n }),\n }\n}\n\n/** @internal */\nexport declare namespace encodeNumber {\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeString(value: string): PreparedParameter {\n const hexValue = Hex.fromString(value)\n const partsLength = Math.ceil(Hex.size(hexValue) / 32)\n const parts: Hex.Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(Hex.padRight(Hex.slice(hexValue, i * 32, (i + 1) * 32)))\n }\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padRight(Hex.fromNumber(Hex.size(hexValue), { size: 32 })),\n ...parts,\n ),\n }\n}\n\n/** @internal */\nexport declare namespace encodeString {\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Hex.padRight.ErrorType\n | Hex.slice.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeTuple<\n const parameter extends AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n },\n>(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, parameter } = options\n\n let dynamic = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameter.components.length; i++) {\n const param_ = parameter.components[i]!\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParameters.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encode(preparedParameters)\n : Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeTuple {\n type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\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\n/** @internal */\nexport function hasDynamicChild(param: AbiParameters.Parameter) {\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({\n ...param,\n type: arrayComponents[1],\n } as AbiParameters.Parameter)\n )\n return true\n\n return false\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\nexport 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 type { Bytes } from '../Bytes.js'\nimport * as Errors from '../Errors.js'\n\n/** @internal */\nexport type Cursor = {\n bytes: Bytes\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): Bytes[number]\n inspectBytes(length: number, position?: number): Bytes\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: Bytes[number]): void\n pushBytes(bytes: Bytes): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): Bytes[number]\n readBytes(length: number, size?: number): Bytes\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\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: Bytes[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: Bytes) {\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\n/** @internal */\nexport function create(\n bytes: Bytes,\n { recursiveReadLimit = 8_192 }: create.Config = {},\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\n/** @internal */\nexport declare namespace create {\n type Config = { recursiveReadLimit?: number | undefined }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport class NegativeOffsetError extends Errors.BaseError {\n override readonly name = 'Cursor.NegativeOffsetError'\n\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`)\n }\n}\n\n/** @internal */\nexport class PositionOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Cursor.PositionOutOfBoundsError'\n\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n )\n }\n}\n\n/** @internal */\nexport class RecursiveReadLimitExceededError extends Errors.BaseError {\n override readonly name = 'Cursor.RecursiveReadLimitExceededError'\n\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n )\n }\n}\n","import type * as Address from './Address.js'\nimport type * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, Mutable, Undefined } from './internal/types.js'\nimport * as Rlp from './Rlp.js'\nimport * as Signature from './Signature.js'\n\n/** Root type for an EIP-7702 Authorization. */\nexport type Authorization<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** Address of the contract to set as code for the Authority. */\n address: Address.Address\n /** Chain ID to authorize. */\n chainId: numberType\n /** Nonce of the Authority to authorize. */\n nonce: bigintType\n } & (signed extends true\n ? Signature.Signature\n : Undefined)\n>\n\n/** RPC representation of an {@link ox#Authorization.Authorization}. */\nexport type Rpc = Authorization\n\n/** List of {@link ox#Authorization.Authorization}. */\nexport type List<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute[]>\n\n/** RPC representation of an {@link ox#Authorization.List}. */\nexport type ListRpc = List\n\n/** Signed representation of a list of {@link ox#Authorization.Authorization}. */\nexport type ListSigned = List<\n true,\n bigintType,\n numberType\n>\n\n/** Signed representation of an {@link ox#Authorization.Authorization}. */\nexport type Signed = Authorization<\n true,\n bigintType,\n numberType\n>\n\n/** Tuple representation of an {@link ox#Authorization.Authorization}. */\nexport type Tuple = signed extends true\n ? readonly [\n chainId: Hex.Hex,\n address: Hex.Hex,\n nonce: Hex.Hex,\n yParity: Hex.Hex,\n r: Hex.Hex,\n s: Hex.Hex,\n ]\n : readonly [chainId: Hex.Hex, address: Hex.Hex, nonce: Hex.Hex]\n\n/** Tuple representation of a signed {@link ox#Authorization.Authorization}. */\nexport type TupleSigned = Tuple\n\n/** Tuple representation of a list of {@link ox#Authorization.Authorization}. */\nexport type TupleList =\n readonly Tuple[]\n\n/** Tuple representation of a list of signed {@link ox#Authorization.Authorization}. */\nexport type TupleListSigned = TupleList\n\n/**\n * Converts an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization object into a typed {@link ox#Authorization.Authorization}.\n *\n * @example\n * An Authorization can be instantiated from an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * A {@link ox#Signature.Signature} can be attached with the `signature` option. The example below demonstrates signing\n * an Authorization with {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: Authorization.getSignPayload(authorization),\n * privateKey: '0x...',\n * })\n *\n * const authorization_signed = Authorization.from(authorization, { signature }) // [!code focus]\n * ```\n *\n * @param authorization - An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n * @param options - Authorization options.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function from<\n const authorization extends Authorization | Rpc,\n const signature extends Signature.Signature | undefined = undefined,\n>(\n authorization: authorization | Authorization,\n options: from.Options = {},\n): from.ReturnType {\n if (typeof authorization.chainId === 'string')\n return fromRpc(authorization) as never\n return { ...authorization, ...options.signature } as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = {\n /** The {@link ox#Signature.Signature} to attach to the Authorization. */\n signature?: signature | Signature.Signature | undefined\n }\n\n type ReturnType<\n authorization extends Authorization | Rpc = Authorization,\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends Signature.Signature ? Readonly : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Rpc} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param authorization - The RPC-formatted Authorization.\n * @returns A signed {@link ox#Authorization.Authorization}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)!\n\n return {\n address,\n chainId: Number(chainId),\n nonce: BigInt(nonce),\n ...signature,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.ListRpc} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * }])\n * ```\n *\n * @param authorizationList - The RPC-formatted Authorization list.\n * @returns A signed {@link ox#Authorization.List}.\n */\nexport function fromRpcList(authorizationList: ListRpc): ListSigned {\n return authorizationList.map(fromRpc)\n}\n\nexport declare namespace fromRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Tuple} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3'\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: }\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3',\n * '0x1',\n * '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90',\n * '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: }\n * ```\n *\n * @param tuple - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function fromTuple(\n tuple: tuple,\n): fromTuple.ReturnType {\n const [chainId, address, nonce, yParity, r, s] = tuple\n let args = {\n address,\n chainId: chainId === '0x' ? 0 : Number(chainId),\n nonce: nonce === '0x' ? 0n : BigInt(nonce),\n }\n if (yParity && r && s)\n args = { ...args, ...Signature.fromTuple([yParity, r, s]) }\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType = Compute<\n Authorization ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.TupleList} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param tupleList - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n * @returns An {@link ox#Authorization.List}.\n */\nexport function fromTupleList(\n tupleList: tupleList,\n): fromTupleList.ReturnType {\n const list: Mutable = []\n for (const tuple of tupleList) list.push(fromTuple(tuple))\n return list as never\n}\n\nexport declare namespace fromTupleList {\n type ReturnType = Compute<\n TupleList ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * The example below demonstrates computing the sign payload for an {@link ox#Authorization.Authorization}. This payload\n * can then be passed to signing functions like {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = Authorization.getSignPayload(authorization) // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload,\n * privateKey: '0x...',\n * })\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: Authorization): Hex.Hex {\n return hash(authorization, { presign: true })\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const hash = Authorization.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The hash.\n */\nexport function hash(\n authorization: Authorization,\n options: hash.Options = {},\n): Hex.Hex {\n const { presign } = options\n return Hash.keccak256(\n Hex.concat(\n '0x05',\n Rlp.fromHex(\n toTuple(\n presign\n ? {\n address: authorization.address,\n chainId: authorization.chainId,\n nonce: authorization.nonce,\n }\n : authorization,\n ),\n ),\n ),\n )\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /** Whether to hash this authorization for signing. @default false */\n presign?: boolean | undefined\n }\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * })\n * ```\n *\n * @param authorization - An Authorization.\n * @returns An RPC-formatted Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, nonce, ...signature } = authorization\n\n return {\n address,\n chainId: Hex.fromNumber(chainId),\n nonce: Hex.fromNumber(nonce),\n ...Signature.toRpc(signature),\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.ListRpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * }])\n * ```\n *\n * @param authorizationList - An Authorization List.\n * @returns An RPC-formatted Authorization List.\n */\nexport function toRpcList(authorizationList: ListSigned): ListRpc {\n return authorizationList.map(toRpc)\n}\n\nexport declare namespace toRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const tuple = Authorization.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n */\nexport function toTuple(\n authorization: authorization,\n): toTuple.ReturnType {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)\n return [\n chainId ? Hex.fromNumber(chainId) : '0x',\n address,\n nonce ? Hex.fromNumber(nonce) : '0x',\n ...(signature ? Signature.toTuple(signature) : []),\n ] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType =\n Compute>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.TupleList}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization_1 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * const authorization_2 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 3,\n * nonce: 20n,\n * })\n *\n * const tuple = Authorization.toTupleList([authorization_1, authorization_2]) // [!code focus]\n * // @log: [\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ],\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param list - An {@link ox#Authorization.List}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n */\nexport function toTupleList<\n const list extends\n | readonly Authorization[]\n | readonly Authorization[],\n>(list?: list | undefined): toTupleList.ReturnType {\n if (!list || list.length === 0) return []\n\n const tupleList: Mutable = []\n for (const authorization of list) tupleList.push(toTuple(authorization))\n\n return tupleList as never\n}\n\nexport declare namespace toTupleList {\n type ReturnType<\n list extends\n | readonly Authorization[]\n | readonly Authorization[],\n > = Compute<\n TupleList[] ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Cursor from './internal/cursor.js'\nimport type { ExactPartial, RecursiveArray } from './internal/types.js'\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toBytes('0x8b68656c6c6f20776f726c64')\n * // Uint8Array([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Bytes.Bytes} value.\n */\nexport function toBytes(\n value: Bytes.Bytes | Hex.Hex,\n): RecursiveArray {\n return to(value, 'Bytes')\n}\n\nexport declare namespace toBytes {\n type ErrorType = to.ErrorType\n}\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toHex('0x8b68656c6c6f20776f726c64')\n * // 0x68656c6c6f20776f726c64\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes.Bytes | Hex.Hex): RecursiveArray {\n return to(value, 'Hex')\n}\n\nexport declare namespace toHex {\n type ErrorType = to.ErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\n/////////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport function to<\n value extends Bytes.Bytes | Hex.Hex,\n to extends 'Hex' | 'Bytes',\n>(value: value, to: to | 'Hex' | 'Bytes'): to.ReturnType {\n const to_ = to ?? (typeof value === 'string' ? 'Hex' : 'Bytes')\n\n const bytes = (() => {\n if (typeof value === 'string') {\n if (value.length > 3 && value.length % 2 !== 0)\n throw new Hex.InvalidLengthError(value)\n return Bytes.fromHex(value)\n }\n return value as Bytes.Bytes\n })()\n\n const cursor = Cursor.create(bytes, {\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n })\n const result = decodeRlpCursor(cursor, to_)\n\n return result as to.ReturnType\n}\n\n/** @internal */\nexport declare namespace to {\n type ReturnType =\n | (to extends 'Bytes' ? RecursiveArray : never)\n | (to extends 'Hex' ? RecursiveArray : never)\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | decodeRlpCursor.ErrorType\n | Cursor.create.ErrorType\n | Hex.InvalidLengthError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\n\n/** @internal */\nexport function decodeRlpCursor(\n cursor: Cursor.Cursor,\n to: to | 'Hex' | 'Bytes' | undefined = 'Hex',\n): decodeRlpCursor.ReturnType {\n if (cursor.bytes.length === 0)\n return (\n to === 'Hex' ? Hex.fromBytes(cursor.bytes) : cursor.bytes\n ) as decodeRlpCursor.ReturnType\n\n const prefix = cursor.readByte()\n if (prefix < 0x80) cursor.decrementPosition(1)\n\n // bytes\n if (prefix < 0xc0) {\n const length = readLength(cursor, prefix, 0x80)\n const bytes = cursor.readBytes(length)\n return (\n to === 'Hex' ? Hex.fromBytes(bytes) : bytes\n ) as decodeRlpCursor.ReturnType\n }\n\n // list\n const length = readLength(cursor, prefix, 0xc0)\n return readList(cursor, length, to) as {} as decodeRlpCursor.ReturnType\n}\n\n/** @internal */\nexport declare namespace decodeRlpCursor {\n type ReturnType = to.ReturnType\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | readLength.ErrorType\n | readList.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readLength(\n cursor: Cursor.Cursor,\n prefix: number,\n offset: number,\n) {\n if (offset === 0x80 && prefix < 0x80) return 1\n if (prefix <= offset + 55) return prefix - offset\n if (prefix === offset + 55 + 1) return cursor.readUint8()\n if (prefix === offset + 55 + 2) return cursor.readUint16()\n if (prefix === offset + 55 + 3) return cursor.readUint24()\n if (prefix === offset + 55 + 4) return cursor.readUint32()\n throw new Errors.BaseError('Invalid RLP prefix')\n}\n\n/** @internal */\nexport declare namespace readLength {\n type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readList(\n cursor: Cursor.Cursor,\n length: number,\n to: to | 'Hex' | 'Bytes',\n) {\n const position = cursor.position\n const value: decodeRlpCursor.ReturnType[] = []\n while (cursor.position - position < length)\n value.push(decodeRlpCursor(cursor, to))\n return value\n}\n\n/** @internal */\nexport declare namespace readList {\n type ErrorType = Errors.GlobalErrorType\n}\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor.Cursor): void\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.from('0x68656c6c6f20776f726c64', { as: 'Hex' })\n * // @log: 0x8b68656c6c6f20776f726c64\n *\n * Rlp.from(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), { as: 'Bytes' })\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function from(\n value: RecursiveArray | RecursiveArray,\n options: from.Options,\n): from.ReturnType {\n const { as } = options\n\n const encodable = getEncodable(value)\n const cursor = Cursor.create(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (as === 'Hex') return Hex.fromBytes(cursor.bytes) as from.ReturnType\n return cursor.bytes as from.ReturnType\n}\n\nexport declare namespace from {\n type Options = {\n /** The type to convert the RLP value to. */\n as: as | 'Hex' | 'Bytes'\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Cursor.create.ErrorType\n | Hex.fromBytes.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.fromBytes(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]))\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromBytes(\n bytes: RecursiveArray,\n options: fromBytes.Options = {},\n): fromBytes.ReturnType {\n const { as = 'Bytes' } = options\n return from(bytes, { as }) as never\n}\n\nexport declare namespace fromBytes {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n *\n * Rlp.fromHex('0x68656c6c6f20776f726c64')\n * // @log: 0x8b68656c6c6f20776f726c64\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromHex(\n hex: RecursiveArray,\n options: fromHex.Options = {},\n): fromHex.ReturnType {\n const { as = 'Hex' } = options\n return from(hex, { as }) as never\n}\n\nexport declare namespace fromHex {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\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.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: Bytes.Bytes | Hex.Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? Bytes.fromHex(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.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 <= 0xff) return 1\n if (length <= 0xff_ff) return 2\n if (length <= 0xff_ff_ff) return 3\n if (length <= 0xff_ff_ff_ff) return 4\n throw new Errors.BaseError('Length is too large.')\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial, OneOf } from './internal/types.js'\nimport * as Json from './Json.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for an ECDSA signature. */\nexport type Signature<\n recovered extends boolean = true,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n recovered extends true\n ? {\n r: bigintType\n s: bigintType\n yParity: numberType\n }\n : {\n r: bigintType\n s: bigintType\n yParity?: numberType | undefined\n }\n>\n\n/** RPC-formatted ECDSA signature. */\nexport type Rpc = Signature<\n recovered,\n Hex.Hex,\n Hex.Hex\n>\n\n/** (Legacy) ECDSA signature. */\nexport type Legacy = {\n r: bigintType\n s: bigintType\n v: numberType\n}\n\n/** RPC-formatted (Legacy) ECDSA signature. */\nexport type LegacyRpc = Legacy\n\nexport type Tuple = readonly [yParity: Hex.Hex, r: Hex.Hex, s: Hex.Hex]\n\n/**\n * Asserts that a Signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.assert({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @error: InvalidSignatureRError:\n * // @error: Value `-549...n` is an invalid r value.\n * // @error: r must be a positive integer less than 2^256.\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function assert(\n signature: ExactPartial,\n options: assert.Options = {},\n): asserts signature is Signature {\n const { recovered } = options\n if (typeof signature.r === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (typeof signature.s === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (recovered && typeof signature.yParity === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (signature.r < 0n || signature.r > Solidity.maxUint256)\n throw new InvalidRError({ value: signature.r })\n if (signature.s < 0n || signature.s > Solidity.maxUint256)\n throw new InvalidSError({ value: signature.s })\n if (\n typeof signature.yParity === 'number' &&\n signature.yParity !== 0 &&\n signature.yParity !== 1\n )\n throw new InvalidYParityError({ value: signature.yParity })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType =\n | MissingPropertiesError\n | InvalidRError\n | InvalidSError\n | InvalidYParityError\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Bytes.Bytes} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param signature - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromBytes(signature: Bytes.Bytes): Signature {\n return fromHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Hex.Hex} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.fromHex('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c')\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param serialized - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromHex(signature: Hex.Hex): Signature {\n if (signature.length !== 130 && signature.length !== 132)\n throw new InvalidSerializedSizeError({ signature })\n\n const r = BigInt(Hex.slice(signature, 0, 32))\n const s = BigInt(Hex.slice(signature, 32, 64))\n\n const yParity = (() => {\n const yParity = Number(`0x${signature.slice(130)}`)\n if (Number.isNaN(yParity)) return undefined\n try {\n return vToYParity(yParity)\n } catch {\n throw new InvalidYParityError({ value: yParity })\n }\n })()\n\n if (typeof yParity === 'undefined')\n return {\n r,\n s,\n } as never\n return {\n r,\n s,\n yParity,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType =\n | Hex.from.ErrorType\n | InvalidSerializedSizeError\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts a {@link ox#Signature.Signature} from an arbitrary object that may include signature properties.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.extract({\n * baz: 'barry',\n * foo: 'bar',\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * zebra: 'stripes',\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @param value - The arbitrary object to extract the signature from.\n * @returns The extracted {@link ox#Signature.Signature}.\n */\nexport function extract(value: extract.Value): Signature | undefined {\n if (typeof value.r === 'undefined') return undefined\n if (typeof value.s === 'undefined') return undefined\n return from(value as any)\n}\n\nexport declare namespace extract {\n type Value = {\n r?: bigint | Hex.Hex | undefined\n s?: bigint | Hex.Hex | undefined\n yParity?: number | Hex.Hex | undefined\n v?: number | Hex.Hex | undefined\n }\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#Signature.Signature} object from a {@link ox#Signature.Signature}, {@link ox#Signature.Legacy}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db801')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @example\n * ### From Legacy\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * v: 27,\n * })\n * // @log: {\n * // @log: r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * // @log: s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * // @log: yParity: 0\n * // @log: }\n * ```\n *\n * @param signature - The signature value to instantiate.\n * @returns The instantiated {@link ox#Signature.Signature}.\n */\nexport function from<\n const signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n>(\n signature:\n | signature\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n): from.ReturnType {\n const signature_ = (() => {\n if (typeof signature === 'string') return fromHex(signature)\n if (signature instanceof Uint8Array) return fromBytes(signature)\n if (typeof signature.r === 'string') return fromRpc(signature)\n if (signature.v) return fromLegacy(signature)\n return {\n r: signature.r,\n s: signature.s,\n ...(typeof signature.yParity !== 'undefined'\n ? { yParity: signature.yParity }\n : {}),\n }\n })()\n assert(signature_)\n return signature_ as never\n}\n\nexport declare namespace from {\n type ReturnType<\n signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n > = signature extends Signature & { v?: undefined }\n ? signature\n : Signature\n\n type ErrorType =\n | assert.ErrorType\n | fromBytes.ErrorType\n | fromHex.ErrorType\n | vToYParity.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerBytes(new Uint8Array([132, 51, 23, ...]))\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerBytes(signature: Bytes.Bytes): Signature {\n return fromDerHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerHex('0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerHex(signature: Hex.Hex): Signature {\n const { r, s } = secp256k1.Signature.fromDER(Hex.from(signature).slice(2))\n return { r, s }\n}\n\nexport declare namespace fromDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Legacy} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.fromLegacy({ r: 1n, s: 2n, v: 28 })\n * // @log: { r: 1n, s: 2n, yParity: 1 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Legacy} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromLegacy(signature: Legacy): Signature {\n return {\n r: signature.r,\n s: signature.s,\n yParity: vToYParity(signature.v),\n }\n}\n\nexport declare namespace fromLegacy {\n type ErrorType = vToYParity.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Rpc} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromRpc({\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Rpc} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromRpc(signature: {\n r: Hex.Hex\n s: Hex.Hex\n yParity?: Hex.Hex | undefined\n v?: Hex.Hex | undefined\n}): Signature {\n const yParity = (() => {\n const v = signature.v ? Number(signature.v) : undefined\n let yParity = signature.yParity ? Number(signature.yParity) : undefined\n if (typeof v === 'number' && typeof yParity !== 'number')\n yParity = vToYParity(v)\n if (typeof yParity !== 'number')\n throw new InvalidYParityError({ value: signature.yParity })\n return yParity\n })()\n\n return {\n r: BigInt(signature.r),\n s: BigInt(signature.s),\n yParity,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Tuple} to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromTuple(['0x01', '0x7b', '0x1c8'])\n * // @log: {\n * // @log: r: 123n,\n * // @log: s: 456n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @param tuple - The {@link ox#Signature.Tuple} to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromTuple(tuple: Tuple): Signature {\n const [yParity, r, s] = tuple\n return from({\n r: r === '0x' ? 0n : BigInt(r),\n s: s === '0x' ? 0n : BigInt(s),\n yParity: yParity === '0x' ? 0 : Number(yParity),\n })\n}\n\nexport declare namespace fromTuple {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toBytes({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: Uint8Array [102, 16, 10, ...]\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toBytes(signature: Signature): Bytes.Bytes {\n return Bytes.fromHex(toHex(signature))\n}\n\nexport declare namespace toBytes {\n type ErrorType =\n | toHex.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toHex({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c'\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toHex(signature: Signature): Hex.Hex {\n assert(signature)\n\n const r = signature.r\n const s = signature.s\n\n const signature_ = Hex.concat(\n Hex.fromNumber(r, { size: 32 }),\n Hex.fromNumber(s, { size: 32 }),\n // If the signature is recovered, add the recovery byte to the signature.\n typeof signature.yParity === 'number'\n ? Hex.fromNumber(yParityToV(signature.yParity), { size: 1 })\n : '0x',\n )\n\n return signature_\n}\n\nexport declare namespace toHex {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerBytes(signature)\n * // @log: Uint8Array [132, 51, 23, ...]\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerBytes(signature: Signature): Bytes.Bytes {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return sig.toDERRawBytes()\n}\n\nexport declare namespace toDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerHex(signature)\n * // @log: '0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8'\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerHex(signature: Signature): Hex.Hex {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return `0x${sig.toDERHex()}`\n}\n\nexport declare namespace toDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Legacy}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.toLegacy({ r: 1n, s: 2n, yParity: 1 })\n * // @log: { r: 1n, s: 2n, v: 28 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Legacy}.\n */\nexport function toLegacy(signature: Signature): Legacy {\n return {\n r: signature.r,\n s: signature.s,\n v: yParityToV(signature.yParity),\n }\n}\n\nexport declare namespace toLegacy {\n type ErrorType = yParityToV.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toRpc({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Rpc}.\n */\nexport function toRpc(signature: Signature): Rpc {\n const { r, s, yParity } = signature\n return {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity: yParity === 0 ? '0x0' : '0x1',\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to a serialized {@link ox#Signature.Tuple} to be used for signatures in Transaction Envelopes, EIP-7702 Authorization Lists, etc.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signatureTuple = Signature.toTuple({\n * r: 123n,\n * s: 456n,\n * yParity: 1,\n * })\n * // @log: [yParity: '0x01', r: '0x7b', s: '0x1c8']\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The {@link ox#Signature.Tuple}.\n */\nexport function toTuple(signature: Signature): Tuple {\n const { r, s, yParity } = signature\n\n return [\n yParity ? '0x01' : '0x',\n r === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(r!)),\n s === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(s!)),\n ] as const\n}\n\nexport declare namespace toTuple {\n type ErrorType =\n | Hex.trimLeft.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a Signature. Returns `true` if the signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const valid = Signature.validate({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: false\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function validate(\n signature: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(signature, options)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const yParity = Signature.vToYParity(28)\n * // @log: 1\n * ```\n *\n * @param v - The ECDSA `v` value to convert.\n * @returns The `yParity` value.\n */\nexport function vToYParity(v: number): Signature['yParity'] {\n if (v === 0 || v === 27) return 0\n if (v === 1 || v === 28) return 1\n if (v >= 35) return v % 2 === 0 ? 1 : 0\n throw new InvalidVError({ value: v })\n}\n\nexport declare namespace vToYParity {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const v = Signature.yParityToV(1)\n * // @log: 28\n * ```\n *\n * @param yParity - The ECDSA `yParity` value to convert.\n * @returns The `v` value.\n */\nexport function yParityToV(yParity: number): number {\n if (yParity === 0) return 27\n if (yParity === 1) return 28\n throw new InvalidYParityError({ value: yParity })\n}\n\nexport declare namespace yParityToV {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/** Thrown when the serialized signature is of an invalid size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSerializedSizeError'\n\n constructor({ signature }: { signature: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${signature}\\` is an invalid signature size.`, {\n metaMessages: [\n 'Expected: 64 bytes or 65 bytes.',\n `Received ${Hex.size(Hex.from(signature))} bytes.`,\n ],\n })\n }\n}\n\n/** Thrown when the signature is missing either an `r`, `s`, or `yParity` property. */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'Signature.MissingPropertiesError'\n\n constructor({ signature }: { signature: unknown }) {\n super(\n `Signature \\`${Json.stringify(signature)}\\` is missing either an \\`r\\`, \\`s\\`, or \\`yParity\\` property.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `r` value. */\nexport class InvalidRError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidRError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid r value. r must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `s` value. */\nexport class InvalidSError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid s value. s must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `yParity` value. */\nexport class InvalidYParityError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidYParityError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid y-parity value. Y-parity must be 0 or 1.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `v` value. */\nexport class InvalidVError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidVError'\n\n constructor({ value }: { value: number }) {\n super(`Value \\`${value}\\` is an invalid v value. v must be 27, 28 or >=35.`)\n }\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Entropy from './internal/entropy.js'\nimport type { OneOf } from './internal/types.js'\nimport * as PublicKey from './PublicKey.js'\nimport type * as Signature from './Signature.js'\n\n/** Re-export of noble/curves secp256k1 utilities. */\nexport const noble = secp256k1\n\n/**\n * Creates a new secp256k1 ECDSA key pair consisting of a private key and its corresponding public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey, publicKey } = Secp256k1.createKeyPair()\n * ```\n *\n * @param options - The options to generate the key pair.\n * @returns The generated key pair containing both private and public keys.\n */\nexport function createKeyPair(\n options: createKeyPair.Options = {},\n): createKeyPair.ReturnType {\n const { as = 'Hex' } = options\n const privateKey = randomPrivateKey({ as })\n const publicKey = getPublicKey({ privateKey })\n\n return {\n privateKey: privateKey as never,\n publicKey,\n }\n}\n\nexport declare namespace createKeyPair {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType = {\n privateKey:\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n publicKey: PublicKey.PublicKey\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the secp256k1 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const publicKey = Secp256k1.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(\n options: getPublicKey.Options,\n): PublicKey.PublicKey {\n const { privateKey } = options\n const point = secp256k1.ProjectivePoint.fromPrivateKey(\n Hex.from(privateKey).slice(2),\n )\n return PublicKey.from(point)\n}\n\nexport declare namespace getPublicKey {\n type Options = {\n /**\n * Private key to compute the public key from.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes a shared secret using ECDH (Elliptic Curve Diffie-Hellman) between a private key and a public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey: privateKeyA } = Secp256k1.createKeyPair()\n * const { publicKey: publicKeyB } = Secp256k1.createKeyPair()\n *\n * const sharedSecret = Secp256k1.getSharedSecret({\n * privateKey: privateKeyA,\n * publicKey: publicKeyB\n * })\n * ```\n *\n * @param options - The options to compute the shared secret.\n * @returns The computed shared secret.\n */\nexport function getSharedSecret(\n options: getSharedSecret.Options,\n): getSharedSecret.ReturnType {\n const { as = 'Hex', privateKey, publicKey } = options\n const point = secp256k1.ProjectivePoint.fromHex(\n PublicKey.toHex(publicKey).slice(2),\n )\n const sharedPoint = point.multiply(\n secp256k1.utils.normPrivateKeyToScalar(Hex.from(privateKey).slice(2)),\n )\n const sharedSecret = sharedPoint.toRawBytes(true) // compressed format\n if (as === 'Hex') return Hex.fromBytes(sharedSecret) as never\n return sharedSecret as never\n}\n\nexport declare namespace getSharedSecret {\n type Options = {\n /**\n * Format of the returned shared secret.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n /**\n * Private key to use for the shared secret computation.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n /**\n * Public key to use for the shared secret computation.\n */\n publicKey: PublicKey.PublicKey\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.toHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random ECDSA private key on the secp256k1 curve.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey(\n options: randomPrivateKey.Options = {},\n): randomPrivateKey.ReturnType {\n const { as = 'Hex' } = options\n const bytes = secp256k1.utils.randomPrivateKey()\n if (as === 'Hex') return Hex.fromBytes(bytes) as never\n return bytes as never\n}\n\nexport declare namespace randomPrivateKey {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing address from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const address = Secp256k1.recoverAddress({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered address.\n */\nexport function recoverAddress(\n options: recoverAddress.Options,\n): recoverAddress.ReturnType {\n return Address.fromPublicKey(recoverPublicKey(options))\n}\n\nexport declare namespace recoverAddress {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = Secp256k1.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(\n options: recoverPublicKey.Options,\n): PublicKey.PublicKey {\n const { payload, signature } = options\n const { r, s, yParity } = signature\n const signature_ = new secp256k1.Signature(\n BigInt(r),\n BigInt(s),\n ).addRecoveryBit(yParity)\n const point = signature_.recoverPublicKey(Hex.from(payload).substring(2))\n return PublicKey.from(point)\n}\n\nexport declare namespace recoverPublicKey {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ErrorType =\n | PublicKey.from.ErrorType\n | Hex.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs the payload with the provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options: sign.Options): Signature.Signature {\n const {\n extraEntropy = Entropy.extraEntropy,\n hash,\n payload,\n privateKey,\n } = options\n const { r, s, recovery } = secp256k1.sign(\n Bytes.from(payload),\n Bytes.from(privateKey),\n {\n extraEntropy:\n typeof extraEntropy === 'boolean'\n ? extraEntropy\n : Hex.from(extraEntropy).slice(2),\n lowS: true,\n ...(hash ? { prehash: true } : {}),\n },\n )\n return {\n r,\n s,\n yParity: recovery,\n }\n}\n\nexport declare namespace sign {\n type Options = {\n /**\n * Extra entropy to add to the signing process. Setting to `false` will disable it.\n * @default true\n */\n extraEntropy?: boolean | Hex.Hex | Bytes.Bytes | undefined\n /**\n * If set to `true`, the payload will be hashed (sha256) before being signed.\n */\n hash?: boolean | undefined\n /**\n * Payload to sign.\n */\n payload: Hex.Hex | Bytes.Bytes\n /**\n * ECDSA private key.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Bytes.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Verifies a payload was signed by the provided address.\n *\n * @example\n * ### Verify with Ethereum Address\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Verify with Public Key\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = '0x...'\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided address.\n */\nexport function verify(options: verify.Options): boolean {\n const { address, hash, payload, publicKey, signature } = options\n if (address)\n return Address.isEqual(address, recoverAddress({ payload, signature }))\n return secp256k1.verify(\n signature,\n Bytes.from(payload),\n PublicKey.toBytes(publicKey),\n ...(hash ? [{ prehash: true, lowS: true }] : []),\n )\n}\n\nexport declare namespace verify {\n type Options = {\n /** If set to `true`, the payload will be hashed (sha256) before being verified. */\n hash?: boolean | undefined\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Address that signed the payload. */\n address: Address.Address\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RpcProof } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../index.js'\n\nexport type FormatProofErrorType = ErrorType\n\nfunction formatStorageProof(storageProof: RpcProof['storageProof']) {\n return storageProof.map((proof) => ({\n ...proof,\n value: BigInt(proof.value),\n }))\n}\n\nexport function formatProof(proof: ExactPartial) {\n return {\n ...proof,\n balance: proof.balance ? BigInt(proof.balance) : undefined,\n nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined,\n storageProof: proof.storageProof\n ? formatStorageProof(proof.storageProof)\n : undefined,\n } as Proof\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetStorageAtParameters = {\n address: Address\n slot: Hex\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetStorageAtReturnType = Hex | undefined\n\nexport type GetStorageAtErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param client - Client to use\n * @param parameters - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getStorageAt(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\nexport async function getStorageAt(\n client: Client,\n { address, blockNumber, blockTag = 'latest', slot }: GetStorageAtParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const data = await client.request({\n method: 'eth_getStorageAt',\n params: [address, slot, blockNumberHex || blockTag],\n })\n return data\n}\n","import type { Address } from '../../accounts/index.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { OneOf, Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters =\n OneOf<\n // eth_getTransactionByBlockHashAndIndex\n | {\n /** The block hash */\n blockHash: Hash\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block number */\n blockNumber: bigint\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block tag. */\n blockTag: blockTag | BlockTag\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByHash\n | {\n /** The hash of the transaction. */\n hash: Hash\n }\n // eth_getTransactionBySenderAndNonce\n | {\n /** The sender of the transaction. */\n sender: Address\n /** The nonce of the transaction on the sender. */\n nonce: number\n }\n >\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetTransactionErrorType =\n | TransactionNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n sender,\n nonce,\n }: GetTransactionParameters,\n): Promise> {\n const blockTag = blockTag_ || 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let transaction: RpcTransaction | null = null\n if (hash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if ((blockNumberHex || blockTag) && typeof index === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n } else if (sender && typeof nonce === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionBySenderAndNonce',\n params: [sender, numberToHex(nonce)],\n },\n { dedupe: true },\n )\n }\n\n if (!transaction)\n throw new TransactionNotFoundError({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n })\n\n const format =\n client.chain?.formatters?.transaction?.format || formatTransaction\n return format(transaction, 'getTransaction')\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { FormattedTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetBlockNumberErrorType,\n getBlockNumber,\n} from './getBlockNumber.js'\nimport {\n type GetTransactionErrorType,\n getTransaction,\n} from './getTransaction.js'\n\nexport type GetTransactionConfirmationsParameters<\n chain extends Chain | undefined = Chain,\n> =\n | {\n /** The transaction hash. */\n hash: Hash\n transactionReceipt?: undefined\n }\n | {\n hash?: undefined\n /** The transaction receipt. */\n transactionReceipt: FormattedTransactionReceipt\n }\n\nexport type GetTransactionConfirmationsReturnType = bigint\n\nexport type GetTransactionConfirmationsErrorType =\n | GetBlockNumberErrorType\n | GetTransactionErrorType\n | ErrorType\n\n/**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionConfirmations } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await getTransactionConfirmations(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionConfirmations<\n chain extends Chain | undefined,\n>(\n client: Client,\n { hash, transactionReceipt }: GetTransactionConfirmationsParameters,\n): Promise {\n const [blockNumber, transaction] = await Promise.all([\n getAction(client, getBlockNumber, 'getBlockNumber')({}),\n hash\n ? getAction(client, getTransaction, 'getTransaction')({ hash })\n : undefined,\n ])\n const transactionBlockNumber =\n transactionReceipt?.blockNumber || transaction?.blockNumber\n if (!transactionBlockNumber) return 0n\n return blockNumber - transactionBlockNumber! + 1n\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n /** The hash of the transaction. */\n hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt(\n client: Client,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(\n receipt,\n 'getTransactionReceipt',\n ) as GetTransactionReceiptReturnType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { multicall3Bytecode } from '../../constants/contracts.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record\n } = {},\n> = Pick<\n CallParameters,\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'stateOverride'\n> & {\n /** The account to use for the multicall. */\n account?: Address | undefined\n /** Whether to allow failures. */\n allowFailure?: allowFailure | boolean | undefined\n /** The size of each batch of calls. */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The contracts to call. */\n contracts: MulticallContracts<\n Narrow,\n { mutability: AbiStateMutability } & options\n >\n /** The address of the multicall3 contract to use. */\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client,\n parameters: MulticallParameters,\n): Promise> {\n const {\n account,\n authorizationList,\n allowFailure = true,\n blockNumber,\n blockOverrides,\n blockTag,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const {\n batchSize = parameters.batchSize ?? 1024,\n deployless = parameters.deployless ?? false,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n\n const multicallAddress = (() => {\n if (parameters.multicallAddress) return parameters.multicallAddress\n if (deployless) return null\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n })()\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n sender: account,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress === null\n ? { code: multicall3Bytecode }\n : { address: multicallAddress }),\n abi: multicall3Abi,\n account,\n args: [calls],\n authorizationList,\n blockNumber,\n blockOverrides,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType\n}\n","import type { Abi, AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\n\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 { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.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 EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { concat } from '../../utils/data/concat.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getContractError } from '../../utils/errors/getContractError.js'\nimport {\n type GetNodeErrorReturnType,\n getNodeError,\n} from '../../utils/errors/getNodeError.js'\nimport {\n type FormatBlockErrorType,\n formatBlock,\n} from '../../utils/formatters/block.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport {\n type FormatTransactionRequestErrorType,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\n\ntype CallExtraProperties = ExactPartial<\n UnionOmit<\n TransactionRequest,\n 'blobs' | 'data' | 'kzg' | 'to' | 'sidecars' | 'value'\n >\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Recipient. `null` if contract deployment. */\n to?: Address | null | undefined\n}\n\nexport type SimulateBlocksParameters<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Blocks to simulate. */\n blocks: readonly {\n /** Block overrides. */\n blockOverrides?: BlockOverrides.BlockOverrides | undefined\n /** Calls to execute. */\n calls: Calls, CallExtraProperties>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n }[]\n /** Whether to return the full transactions. */\n returnFullTransactions?: boolean | undefined\n /** Whether to trace transfers. */\n traceTransfers?: boolean | undefined\n /** Whether to enable validation mode. */\n validation?: boolean | 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)\n\nexport type SimulateBlocksReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = readonly (Block & {\n calls: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n})[]\n\nexport type SimulateBlocksErrorType =\n | AssertRequestErrorType\n | DecodeFunctionResultErrorType\n | EncodeFunctionDataErrorType\n | FormatBlockErrorType\n | FormatTransactionRequestErrorType\n | GetNodeErrorReturnType\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createClient, http, parseEther } from 'viem'\n * import { simulate } from 'viem/actions'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulate(client, {\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateBlocksParameters}\n * @returns Simulated blocks. {@link SimulateBlocksReturnType}\n */\nexport async function simulateBlocks<\n chain extends Chain | undefined,\n const calls extends readonly unknown[],\n>(\n client: Client,\n parameters: SimulateBlocksParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n blocks,\n returnFullTransactions,\n traceTransfers,\n validation,\n } = parameters\n\n try {\n const blockStateCalls = []\n for (const block of blocks) {\n const blockOverrides = block.blockOverrides\n ? BlockOverrides.toRpc(block.blockOverrides)\n : undefined\n const calls = block.calls.map((call_) => {\n const call = call_ as Call\n const account = call.account ? parseAccount(call.account) : undefined\n const data = call.abi ? encodeFunctionData(call) : call.data\n const request = {\n ...call,\n account,\n data: call.dataSuffix\n ? concat([data || '0x', call.dataSuffix])\n : data,\n from: call.from ?? account?.address,\n } as const\n assertRequest(request)\n return formatTransactionRequest(request)\n })\n const stateOverrides = block.stateOverrides\n ? serializeStateOverride(block.stateOverrides)\n : undefined\n\n blockStateCalls.push({\n blockOverrides,\n calls,\n stateOverrides,\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const result = await client.request({\n method: 'eth_simulateV1',\n params: [\n { blockStateCalls, returnFullTransactions, traceTransfers, validation },\n block,\n ],\n })\n\n return result.map((block, i) => ({\n ...formatBlock(block),\n calls: block.calls.map((call, j) => {\n const { abi, args, functionName, to } = blocks[i].calls[j] as Call<\n unknown,\n CallExtraProperties\n >\n\n const data = call.error?.data ?? call.returnData\n const gasUsed = BigInt(call.gasUsed)\n const logs = call.logs?.map((log) => formatLog(log))\n const status = call.status === '0x1' ? 'success' : 'failure'\n\n const result =\n abi && status === 'success' && data !== '0x'\n ? decodeFunctionResult({\n abi,\n data,\n functionName,\n })\n : null\n\n const error = (() => {\n if (status === 'success') return undefined\n\n let error: Error | undefined\n if (data === '0x') error = new AbiDecodingZeroDataError()\n else if (data) error = new RawContractError({ data })\n\n if (!error) return undefined\n return getContractError(error, {\n abi: (abi ?? []) as Abi,\n address: to ?? '0x',\n args,\n functionName: functionName ?? '',\n })\n })()\n\n return {\n data,\n gasUsed,\n logs,\n status,\n ...(status === 'success'\n ? {\n result,\n }\n : {\n error,\n }),\n }\n }),\n })) as unknown as SimulateBlocksReturnType\n } catch (e) {\n const cause = e as BaseError\n const error = getNodeError(cause, {})\n if (error instanceof UnknownNodeError) throw cause\n throw error\n }\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiItem.js'\nimport type { UnionCompute } from './internal/types.js'\n\n/** Root type for an item on an {@link ox#Abi.Abi}. */\nexport type AbiItem = Abi.Abi[number]\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type Foo = AbiItem.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = Extract\n\n/**\n * Extracts the names of all {@link ox#AbiItem.AbiItem} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type names = AbiItem.Name\n * // ^?\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames = Extract<\n abi[number],\n { name: string }\n>['name']\n\n/**\n * Formats an {@link ox#AbiItem.AbiItem} into a **Human Readable ABI Item**.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const formatted = AbiItem.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiItem - The ABI Item to format.\n * @returns The formatted ABI Item .\n */\nexport function format(\n abiItem: abiItem | AbiItem,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiItem) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Item** or **Human Readable ABI Item** into a typed {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from({\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: [{ type: 'bool' }],\n * })\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiItem - The ABI Item to parse.\n * @returns The typed ABI Item.\n */\nexport function from<\n const abiItem extends AbiItem | string | readonly string[],\n>(\n abiItem: (abiItem | AbiItem | string | readonly string[]) &\n (\n | (abiItem extends string ? internal.Signature : never)\n | (abiItem extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiItem\n ),\n options: from.Options = {},\n): from.ReturnType {\n const { prepare = true } = options\n const item = (() => {\n if (Array.isArray(abiItem)) return abitype.parseAbiItem(abiItem)\n if (typeof abiItem === 'string')\n return abitype.parseAbiItem(abiItem as never)\n return abiItem\n })() as AbiItem\n return {\n ...item,\n ...(prepare ? { hash: getSignatureHash(item) } : {}),\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType =\n abiItem extends string\n ? abitype.ParseAbiItem\n : abiItem extends readonly string[]\n ? abitype.ParseAbiItem\n : abiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ABI Items can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiItem.fromAbi(abi, 'Transfer') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Items can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiItem.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Item from an `eth_call` RPC response,\n * a Transaction `input`, or from Event Log `topics`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends internal.ExtractArgs | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: fromAbi.Options,\n): fromAbi.ReturnType {\n const { args = [], prepare = true } = (options ??\n {}) as unknown as fromAbi.Options\n\n const isSelector = Hex.validate(name, { strict: false })\n const abiItems = (abi as Abi.Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function' || abiItem.type === 'error')\n return getSelector(abiItem) === Hex.slice(name, 0, 4)\n if (abiItem.type === 'event') return getSignatureHash(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0) throw new NotFoundError({ name: name as string })\n if (abiItems.length === 1)\n return {\n ...abiItems[0],\n ...(prepare ? { hash: getSignatureHash(abiItems[0]!) } : {}),\n } as never\n\n let matchedAbiItem: AbiItem | 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 {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\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 internal.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 = internal.getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AmbiguityError(\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 const abiItem = (() => {\n if (matchedAbiItem) return matchedAbiItem\n const [abiItem, ...overloads] = abiItems\n return { ...abiItem!, overloads }\n })()\n\n if (!abiItem) throw new NotFoundError({ name: name as string })\n return {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\n}\n\nexport declare namespace fromAbi {\n type Options<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n ///\n allArgs = internal.ExtractArgs,\n > = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n } & UnionCompute<\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.Abi\n ? args extends allArgs\n ? internal.Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (internal.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\n type ReturnType<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n fallback = AbiItem,\n > = abi extends Abi.Abi\n ? Abi.Abi extends abi\n ? fallback\n : internal.ExtractForArgs<\n abi,\n name,\n args extends internal.ExtractArgs\n ? args\n : internal.ExtractArgs\n >\n : fallback\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const selector = AbiItem.getSelector(erc20Abi, 'ownerOf')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for. Can be a signature or an ABI item for an error, event, function, etc.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSelector(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSelector(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n return Hex.slice(getSignatureHash(abiItem), 0, 4)\n}\n\nexport declare namespace getSelector {\n type ErrorType =\n | getSignatureHash.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the stringified signature for a given {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature('function ownerOf(uint256 tokenId)')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const signature = AbiItem.getSignature(erc20Abi, 'ownerOf')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature for.\n * @returns The stringified signature of the ABI Item.\n */\nexport function getSignature<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): string\nexport function getSignature(abiItem: string | AbiItem): string\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignature(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): string {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n const signature = (() => {\n if (typeof abiItem === 'string') return abiItem\n return abitype.formatAbiItem(abiItem)\n })()\n return internal.normalizeSignature(signature)\n}\n\nexport declare namespace getSignature {\n type ErrorType =\n | internal.normalizeSignature.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the signature hash for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing Event Topic values.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash('event Transfer(address indexed from, address indexed to, uint256 amount)')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const hash = AbiItem.getSignatureHash(erc20Abi, 'Transfer')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash({\n * name: 'Transfer',\n * type: 'event',\n * inputs: [\n * { name: 'from', type: 'address', indexed: true },\n * { name: 'to', type: 'address', indexed: true },\n * { name: 'amount', type: 'uint256', indexed: false },\n * ],\n * })\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature hash for.\n * @returns The {@link ox#Hash.(keccak256:function)} hash of the ABI item's signature.\n */\nexport function getSignatureHash<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSignatureHash(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignatureHash(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n if (typeof abiItem !== 'string' && 'hash' in abiItem && abiItem.hash)\n return abiItem.hash as Hex.Hex\n return Hash.keccak256(Hex.fromString(getSignature(abiItem)))\n}\n\nexport declare namespace getSignatureHash {\n type ErrorType =\n | getSignature.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Throws when ambiguous types are found on overloaded ABI items.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from(['function foo(address)', 'function foo(bytes20)'])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n *\n * ### Solution\n *\n * Remove one of the ambiguous types from the ABI.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function foo(bytes20)' // [!code --]\n * ])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n */\nexport class AmbiguityError extends Errors.BaseError {\n override readonly name = 'AbiItem.AmbiguityError'\n constructor(\n x: { abiItem: Abi.Abi[number]; type: string },\n y: { abiItem: Abi.Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI Items.', {\n metaMessages: [\n // TODO: abitype to add support for signature-formatted ABI items.\n `\\`${x.type}\\` in \\`${internal.normalizeSignature(abitype.formatAbiItem(x.abiItem))}\\`, and`,\n `\\`${y.type}\\` in \\`${internal.normalizeSignature(abitype.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 })\n }\n}\n\n/**\n * Throws when an ABI item is not found in the ABI.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * // @error: AbiItem.NotFoundError: ABI function with name \"baz\" not found.\n * ```\n *\n * ### Solution\n *\n * Ensure the ABI item exists on the ABI.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)',\n * 'function baz(bool)' // [!code ++]\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * ```\n */\nexport class NotFoundError extends Errors.BaseError {\n override readonly name = 'AbiItem.NotFoundError'\n constructor({\n name,\n data,\n type = 'item',\n }: {\n name?: string | undefined\n data?: Hex.Hex | undefined\n type?: string | undefined\n }) {\n const selector = (() => {\n if (name) return ` with name \"${name}\"`\n if (data) return ` with data \"${data}\"`\n return ''\n })()\n super(`ABI ${type}${selector} not found.`)\n }\n}\n\n/**\n * Throws when the selector size is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0xaaa')\n * // @error: AbiItem.InvalidSelectorSizeError: Selector size is invalid. Expected 4 bytes. Received 2 bytes (\"0xaaa\").\n * ```\n *\n * ### Solution\n *\n * Ensure the selector size is 4 bytes.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0x7af82b1a')\n * ```\n */\nexport class InvalidSelectorSizeError extends Errors.BaseError {\n override readonly name = 'AbiItem.InvalidSelectorSizeError'\n constructor({ data }: { data: Hex.Hex }) {\n super(\n `Selector size is invalid. Expected 4 bytes. Received ${Hex.size(data)} bytes (\"${data}\").`,\n )\n }\n}\n","import type * as abitype from 'abitype'\nimport type * as Abi from '../Abi.js'\nimport type * as AbiItem from '../AbiItem.js'\nimport type * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Errors from '../Errors.js'\nimport type {\n Compute,\n IsNever,\n IsUnion,\n TypeErrorMessage,\n UnionToTuple,\n} from './types.js'\n\n/** @internal */\nexport type ExtractArgs<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends AbiItem.Name = AbiItem.Name,\n> = abitype.AbiParametersToPrimitiveTypes<\n AbiItem.FromAbi['inputs'],\n 'inputs'\n> extends infer args\n ? [args] extends [never]\n ? readonly unknown[]\n : args\n : readonly unknown[]\n\n/** @internal */\nexport type ExtractForArgs<\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = IsUnion extends true\n ? {\n [key in keyof abi]: abi[key] extends { name: name } ? abi[key] : never\n }[number]\n : AbiItem.FromAbi extends infer abiItem extends AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n }\n ? IsUnion extends true // narrow overloads using `args` by converting to tuple and filtering out overloads that don't match\n ? UnionToTuple extends infer abiItems extends\n readonly (AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n })[]\n ? IsNever> extends true\n ? Compute<\n abiItems[0] & {\n readonly overloads: UnionToTuple<\n Exclude\n >\n }\n >\n : TupleToUnion // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)\n : never\n : abiItem\n : never\n\n/** @internal */\nexport type TupleToUnion<\n abiItems extends readonly {\n inputs: readonly abitype.AbiParameter[]\n }[],\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = {\n [k in keyof abiItems]: (\n readonly [] extends args\n ? readonly [] // fallback to `readonly []` if `args` has no value (e.g. `args` property not provided)\n : args\n ) extends abitype.AbiParametersToPrimitiveTypes<\n abiItems[k]['inputs'],\n 'inputs'\n >\n ? abiItems[k]\n : never\n}[number]\n\n/** @internal */\nexport type ErrorSignature<\n name extends string = string,\n parameters extends string = string,\n> = `error ${name}(${parameters})`\n\n/** @internal */\nexport type IsErrorSignature =\n signature extends ErrorSignature ? IsName : false\n\n/** @internal */\nexport type EventSignature<\n name extends string = string,\n parameters extends string = string,\n> = `event ${name}(${parameters})`\n\n/** @internal */\nexport type IsEventSignature =\n signature extends EventSignature ? IsName : false\n\n/** @internal */\nexport type FunctionSignature<\n name extends string = string,\n tail extends string = string,\n> = `function ${name}(${tail}`\nexport type IsFunctionSignature =\n signature extends FunctionSignature\n ? IsName extends true\n ? signature extends ValidFunctionSignatures\n ? true\n : // Check that `Parameters` is not absorbing other types (e.g. `returns`)\n signature extends `function ${string}(${infer parameters})`\n ? parameters extends InvalidFunctionParameters\n ? false\n : true\n : false\n : false\n : false\n/** @internal */\nexport type Scope = 'public' | 'external' // `internal` or `private` functions wouldn't make it to ABI so can ignore\n\n/** @internal */\nexport type Returns = `returns (${string})` | `returns(${string})`\n\n// Almost all valid function signatures, except `function ${string}(${infer parameters})` since `parameters` can absorb returns\n/** @internal */\nexport type ValidFunctionSignatures =\n | `function ${string}()`\n // basic\n | `function ${string}() ${Returns}`\n | `function ${string}() ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope}`\n // combinations\n | `function ${string}() ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}() ${Scope} ${Returns}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n // Parameters\n | `function ${string}(${string}) ${Returns}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n\n/** @internal */\nexport type StructSignature<\n name extends string = string,\n properties extends string = string,\n> = `struct ${name} {${properties}}`\n\n/** @internal */\nexport type IsStructSignature =\n signature extends StructSignature ? IsName : false\n\n/** @internal */\nexport type ConstructorSignature =\n `constructor(${tail}`\n\n/** @internal */\nexport type IsConstructorSignature =\n signature extends ConstructorSignature\n ? signature extends ValidConstructorSignatures\n ? true\n : false\n : false\n\n/** @internal */\nexport type ValidConstructorSignatures =\n | `constructor(${string})`\n | `constructor(${string}) payable`\n\n/** @internal */\nexport type FallbackSignature =\n `fallback() external${abiStateMutability}`\n\n/** @internal */\nexport type ReceiveSignature = 'receive() external payable'\n\n// TODO: Maybe use this for signature validation one day\n// https://twitter.com/devanshj__/status/1610423724708343808\n/** @internal */\nexport type IsSignature =\n | (IsErrorSignature extends true ? true : never)\n | (IsEventSignature extends true ? true : never)\n | (IsFunctionSignature extends true ? true : never)\n | (IsStructSignature extends true ? true : never)\n | (IsConstructorSignature extends true ? true : never)\n | (type extends FallbackSignature ? true : never)\n | (type extends ReceiveSignature ? true : never) extends infer condition\n ? [condition] extends [never]\n ? false\n : true\n : false\n\n/** @internal */\nexport type Signature<\n string1 extends string,\n string2 extends string | unknown = unknown,\n> = IsSignature extends true\n ? string1\n : string extends string1 // if exactly `string` (not narrowed), then pass through as valid\n ? string1\n : TypeErrorMessage<`Signature \"${string1}\" is invalid${string2 extends string\n ? ` at position ${string2}`\n : ''}.`>\n\n/** @internal */\nexport type Signatures = {\n [key in keyof signatures]: Signature\n}\n\n/** @internal */\nexport type IsName = name extends ''\n ? false\n : ValidateName extends name\n ? true\n : false\n\n/** @internal */\nexport type ValidateName<\n name extends string,\n checkCharacters extends boolean = false,\n> = name extends `${string}${' '}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot contain whitespace.`>\n : IsSolidityKeyword extends true\n ? TypeErrorMessage<`\"${name}\" is a protected Solidity keyword.`>\n : name extends `${number}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot be a number string.`>\n : name extends `${number}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot start with a number.`>\n : checkCharacters extends true\n ? IsValidCharacter extends true\n ? name\n : TypeErrorMessage<`\"${name}\" contains invalid character.`>\n : name\n\n/** @internal */\nexport type IsSolidityKeyword =\n type extends SolidityKeywords ? true : false\n\n/** @internal */\nexport type SolidityKeywords =\n | 'after'\n | 'alias'\n | 'anonymous'\n | 'apply'\n | 'auto'\n | 'byte'\n | 'calldata'\n | 'case'\n | 'catch'\n | 'constant'\n | 'copyof'\n | 'default'\n | 'defined'\n | 'error'\n | 'event'\n | 'external'\n | 'false'\n | 'final'\n | 'function'\n | 'immutable'\n | 'implements'\n | 'in'\n | 'indexed'\n | 'inline'\n | 'internal'\n | 'let'\n | 'mapping'\n | 'match'\n | 'memory'\n | 'mutable'\n | 'null'\n | 'of'\n | 'override'\n | 'partial'\n | 'private'\n | 'promise'\n | 'public'\n | 'pure'\n | 'reference'\n | 'relocatable'\n | 'return'\n | 'returns'\n | 'sizeof'\n | 'static'\n | 'storage'\n | 'struct'\n | 'super'\n | 'supports'\n | 'switch'\n | 'this'\n | 'true'\n | 'try'\n | 'typedef'\n | 'typeof'\n | 'var'\n | 'view'\n | 'virtual'\n | `address${`[${string}]` | ''}`\n | `bool${`[${string}]` | ''}`\n | `string${`[${string}]` | ''}`\n | `tuple${`[${string}]` | ''}`\n | `bytes${number | ''}${`[${string}]` | ''}`\n | `${'u' | ''}int${number | ''}${`[${string}]` | ''}`\n\n/** @internal */\nexport type IsValidCharacter =\n character extends `${ValidCharacters}${infer tail}`\n ? tail extends ''\n ? true\n : IsValidCharacter\n : false\n\n// biome-ignore format: no formatting\n/** @internal */\nexport type ValidCharacters =\n // uppercase letters\n | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'\n // lowercase letters\n | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'\n // numbers\n | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n // special characters\n | '_' | '$'\n\n// Template string inference can absorb `returns`:\n// type Result = `function foo(string) return s (uint256)` extends `function ${string}(${infer Parameters})` ? Parameters : never\n// // ^? type Result = \"string ) return s (uint256\"\n// So we need to validate against `returns` keyword with all combinations of whitespace\n/** @internal */\nexport type InvalidFunctionParameters =\n | `${string}${MangledReturns} (${string}`\n | `${string}) ${MangledReturns}${string}`\n | `${string})${string}${MangledReturns}${string}(${string}`\n\n// r_e_t_u_r_n_s\n/** @internal */\nexport type MangledReturns =\n // Single\n | `r${string}eturns`\n | `re${string}turns`\n | `ret${string}urns`\n | `retu${string}rns`\n | `retur${string}ns`\n | `return${string}s`\n // Double\n // `r_e*`\n | `r${string}e${string}turns`\n | `r${string}et${string}urns`\n | `r${string}etu${string}rns`\n | `r${string}etur${string}ns`\n | `r${string}eturn${string}s`\n // `re_t*`\n | `re${string}t${string}urns`\n | `re${string}tu${string}rns`\n | `re${string}tur${string}ns`\n | `re${string}turn${string}s`\n // `ret_u*`\n | `ret${string}u${string}rns`\n | `ret${string}ur${string}ns`\n | `ret${string}urn${string}s`\n // `retu_r*`\n | `retu${string}r${string}ns`\n | `retu${string}rn${string}s`\n // `retur_n*`\n | `retur${string}n${string}s`\n // Triple\n // `r_e_t*`\n | `r${string}e${string}t${string}urns`\n | `r${string}e${string}tu${string}rns`\n | `r${string}e${string}tur${string}ns`\n | `r${string}e${string}turn${string}s`\n // `re_t_u*`\n | `re${string}t${string}u${string}rns`\n | `re${string}t${string}ur${string}ns`\n | `re${string}t${string}urn${string}s`\n // `ret_u_r*`\n | `ret${string}u${string}r${string}ns`\n | `ret${string}u${string}rn${string}s`\n // `retu_r_n*`\n | `retu${string}r${string}n${string}s`\n // Quadruple\n // `r_e_t_u*`\n | `r${string}e${string}t${string}u${string}rns`\n | `r${string}e${string}t${string}ur${string}ns`\n | `r${string}e${string}t${string}urn${string}s`\n // `re_t_u_r*`\n | `re${string}t${string}u${string}r${string}ns`\n | `re${string}t${string}u${string}rn${string}s`\n // `ret_u_r_n*`\n | `ret${string}u${string}r${string}n${string}s`\n // Quintuple\n // `r_e_t_u_r*`\n | `r${string}e${string}t${string}u${string}r${string}ns`\n | `r${string}e${string}t${string}u${string}rn${string}s`\n // `re_t_u_r_n*`\n | `re${string}t${string}u${string}r${string}n${string}s`\n // Sextuple\n // `r_e_t_u_r_n_s`\n | `r${string}e${string}t${string}u${string}r${string}n${string}s`\n\n/** @internal */\nexport type Widen =\n | ([unknown] extends [type] ? unknown : never)\n | (type extends Function ? type : never)\n | (type extends abitype.ResolvedRegister['bigIntType'] ? bigint : never)\n | (type extends boolean ? boolean : never)\n | (type extends abitype.ResolvedRegister['intType'] ? number : never)\n | (type extends string\n ? type extends abitype.ResolvedRegister['addressType']\n ? abitype.ResolvedRegister['addressType']\n : type extends abitype.ResolvedRegister['bytesType']['inputs']\n ? abitype.ResolvedRegister['bytesType']\n : string\n : never)\n | (type extends readonly [] ? readonly [] : never)\n | (type extends Record\n ? { [K in keyof type]: Widen }\n : never)\n | (type extends { length: number }\n ? {\n [K in keyof type]: Widen\n } extends infer Val extends readonly unknown[]\n ? readonly [...Val]\n : never\n : never)\n\n/** @internal */\nexport function normalizeSignature(signature: string): string {\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', 'error', ''].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 Errors.BaseError('Unable to normalize signature.')\n\n return result\n}\n\n/** @internal */\nexport declare namespace normalizeSignature {\n export type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function isArgOfType(\n arg: unknown,\n abiParameter: AbiParameters.Parameter,\n): boolean {\n const argType = typeof arg\n const abiParameterType = abiParameter.type\n switch (abiParameterType) {\n case 'address':\n return Address.validate(arg as Address.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 AbiParameters.Parameter,\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 AbiParameters.Parameter),\n )\n )\n }\n\n return false\n }\n }\n}\n\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameters.Parameter[],\n targetParameters: readonly AbiParameters.Parameter[],\n args: ExtractArgs,\n): AbiParameters.Parameter['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 Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n if (types.includes('address') && types.includes('bytes'))\n return Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiConstructor.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `constructor` type. */\nexport type AbiConstructor = abitype.AbiConstructor\n\n/**\n * ABI-decodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const bytecode = '0x...'\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode,\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(constructor, { // [!code focus]\n * bytecode, // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.decode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param abiConstructor - The ABI Constructor to decode.\n * @param options - Decoding options.\n * @returns The decoded constructor inputs.\n */\nexport function decode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: decode.Options,\n): decode.ReturnType\nexport function decode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: decode.Options,\n): decode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: decode.Options]\n | [abiConstructor: AbiConstructor, options: decode.Options]\n): decode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n decode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, decode.Options]\n }\n return parameters as [AbiConstructor, decode.Options]\n })()\n\n const { bytecode } = options\n if (abiConstructor.inputs?.length === 0) return undefined\n const data = options.data.replace(bytecode, '0x') as Hex.Hex\n return AbiParameters.decode(abiConstructor.inputs, data)\n}\n\nexport declare namespace decode {\n interface Options {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The encoded constructor. */\n data: Hex.Hex\n }\n\n type ReturnType =\n | (abiConstructor['inputs']['length'] extends 0\n ? undefined\n : abitype.AbiParametersToPrimitiveTypes)\n | (IsNarrowable extends true\n ? never\n : undefined)\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.encode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n], // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiConstructor.encode` to encode the constructor of a contract and deploy it.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { AbiConstructor, Hex } from 'ox'\n *\n * // 1. Instantiate the ABI Constructor.\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner, uint256 amount)',\n * )\n *\n * // 2. Encode the ABI Constructor.\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * // 3. Deploy the contract.\n * const hash = await window.ethereum!.request({\n * method: 'eth_sendTransaction',\n * params: [{ data }],\n * })\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiConstructor - The ABI Constructor to encode.\n * @param options - Encoding options.\n * @returns The encoded constructor.\n */\nexport function encode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: encode.Options,\n): encode.ReturnType\nexport function encode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: encode.Options,\n): encode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: encode.Options]\n | [abiConstructor: AbiConstructor, options: encode.Options]\n): encode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n encode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, encode.Options]\n }\n\n return parameters as [AbiConstructor, encode.Options]\n })()\n\n const { bytecode, args } = options\n return Hex.concat(\n bytecode,\n abiConstructor.inputs?.length && args?.length\n ? AbiParameters.encode(abiConstructor.inputs, args as readonly unknown[])\n : '0x',\n )\n}\n\nexport declare namespace encode {\n type Options<\n abiConstructor extends AbiConstructor = AbiConstructor,\n ///\n args extends abitype.AbiParametersToPrimitiveTypes<\n abiConstructor['inputs']\n > = abitype.AbiParametersToPrimitiveTypes,\n > = {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The constructor arguments to encode. */\n args?: args | undefined\n } & (readonly [] extends args\n ? {}\n : {\n /** The constructor arguments to encode. */\n args: args\n })\n\n type ReturnType = Hex.Hex\n\n type ErrorType =\n | Hex.concat.ErrorType\n | AbiParameters.encode.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function format(\n abiConstructor: abiConstructor,\n): format.ReturnType\n/**\n * Formats an {@link ox#AbiConstructor.AbiConstructor} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const formatted = AbiConstructor.format({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiConstructor - The ABI Constructor to format.\n * @returns The formatted ABI Constructor.\n */\nexport function format(abiConstructor: AbiConstructor): string\n/** @internal */\nexport function format(abiConstructor: AbiConstructor): format.ReturnType {\n return abitype.formatAbiItem(abiConstructor)\n}\n\nexport declare namespace format {\n type ReturnType =\n abitype.FormatAbiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function from<\n const abiConstructor extends AbiConstructor | string | readonly string[],\n>(\n abiConstructor: (abiConstructor | string | readonly string[]) &\n (\n | (abiConstructor extends string\n ? internal.Signature\n : never)\n | (abiConstructor extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiConstructor\n ),\n): from.ReturnType\n/**\n * Parses an arbitrary **JSON ABI Constructor** or **Human Readable ABI Constructor** into a typed {@link ox#AbiConstructor.AbiConstructor}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner)' // [!code hl]\n * )\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from([\n * 'struct Foo { address owner; uint256 amount; }', // [!code hl]\n * 'constructor(Foo foo)',\n * ])\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiConstructor - The ABI Constructor to parse.\n * @returns Typed ABI Constructor.\n */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): AbiConstructor\n/** @internal */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): from.ReturnType {\n return AbiItem.from(abiConstructor as AbiConstructor)\n}\n\nexport declare namespace from {\n type ReturnType<\n abiConstructor extends\n | AbiConstructor\n | string\n | readonly string[] = AbiConstructor,\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function fromAbi(\n abi: abi | Abi.Abi | readonly unknown[],\n): fromAbi.ReturnType\n/**\n * Extracts an {@link ox#AbiConstructor.AbiConstructor} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Events can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([\n * 'constructor(address owner)',\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiConstructor.fromAbi(abi) // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @returns The ABI constructor.\n */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): AbiConstructor\n/** @internal */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): fromAbi.ReturnType {\n const item = (abi as Abi.Abi).find((item) => item.type === 'constructor')\n if (!item) throw new AbiItem.NotFoundError({ name: 'constructor' })\n return item\n}\n\nexport declare namespace fromAbi {\n type ReturnType = Extract<\n abi[number],\n { type: 'constructor' }\n >\n\n type ErrorType = AbiItem.NotFoundError | Errors.GlobalErrorType\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiFunction.js'\nimport type * as AbiItem_internal from './internal/abiItem.js'\nimport type * as AbiParameters_internal from './internal/abiParameters.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `function` type. */\nexport type AbiFunction = abitype.AbiFunction & {\n hash?: Hex.Hex | undefined\n overloads?: readonly AbiFunction[] | undefined\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type Foo = AbiFunction.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = abitype.ExtractAbiFunction\n\n/**\n * Extracts the names of all {@link ox#AbiFunction.AbiFunction} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type names = AbiFunction.Name\n * // ^?\n *\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames<\n abi extends Abi.Abi,\n abiStateMutability extends\n abitype.AbiStateMutability = abitype.AbiStateMutability,\n> = abitype.ExtractAbiFunctionNames\n\n/**\n * ABI-decodes function arguments according to the ABI Item's input types (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n *\n * const input = AbiFunction.decodeData(approve, data) // [!code focus]\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n * const data = '0x...\n *\n * const input = AbiFunction.decodeData(\n * abi, // [!code focus]\n * 'approve', // [!code focus]\n * data\n * )\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @param abiFunction - The ABI Item to decode.\n * @param data - The data to decode.\n */\nexport function decodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n): decodeData.ReturnType\nexport function decodeData(\n abiFunction: abiItem | AbiFunction,\n data: Hex.Hex,\n): decodeData.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeData(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: Hex.Hex | string, data: Hex.Hex]\n | [abiFunction: AbiFunction, data: Hex.Hex]\n) {\n const [abiFunction, data] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n ]\n return [fromAbi(abi, name), data]\n }\n return parameters as [AbiFunction, Hex.Hex]\n })()\n\n const { overloads } = abiFunction\n\n if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })\n if (abiFunction.inputs?.length === 0) return undefined\n\n const item = overloads\n ? fromAbi([abiFunction, ...overloads], data as never)\n : abiFunction\n\n if (Hex.size(data) <= 4) return undefined\n return AbiParameters.decode(item.inputs, Hex.slice(data, 4))\n}\n\nexport declare namespace decodeData {\n type ReturnType = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ? abiFunction['inputs'] extends readonly []\n ? undefined\n :\n | AbiParameters_internal.ToPrimitiveTypes\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? AbiParameters_internal.ToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >\n : never)\n : unknown\n\n type ErrorType =\n | fromAbi.ErrorType\n | AbiParameters.decode.ErrorType\n | Hex.size.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * ABI-decodes a function's result according to the ABI Item's output types (`outputs`).\n *\n * :::tip\n *\n * This function is typically used to decode contract function return values (e.g. the response of an `eth_call` or the `input` property of a Transaction).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply') // [!code hl]\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const output = AbiFunction.decodeResult(\n * erc20Abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * data\n * )\n * // @log: 42n\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.decodeResult` to decode the result of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input.\n * const data = AbiFunction.encodeData(\n * balanceOf,\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B']\n * )\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output. // [!code focus]\n * const balance = AbiFunction.decodeResult(balanceOf, response) // [!code focus]\n * // @log: 42n\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to decode\n * @param data - ABI-encoded function output\n * @param options - Decoding options\n * @returns Decoded function output\n */\nexport function decodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\nexport function decodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, data, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), data, options]\n }\n return parameters as [\n AbiFunction,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n })()\n\n const values = AbiParameters.decode(abiFunction.outputs, data, options)\n if (values && Object.keys(values).length === 0) return undefined\n if (values && Object.keys(values).length === 1) {\n if (Array.isArray(values)) return values[0]\n return Object.values(values)[0]\n }\n return values\n}\n\nexport declare namespace decodeResult {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Array' | 'Object' | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = IsNarrowable extends true\n ? abiFunction['outputs'] extends readonly []\n ? undefined\n : abiFunction['outputs'] extends readonly [\n infer type extends abitype.AbiParameter,\n ]\n ? abitype.AbiParameterToPrimitiveType\n : AbiParameters.decode.ReturnType<\n abiFunction['outputs'],\n as\n > extends infer types\n ? types extends readonly []\n ? undefined\n : types extends readonly [infer type]\n ? type\n : types\n : never\n : unknown\n\n type ErrorType = AbiParameters.decode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes function arguments (`inputs`), prefixed with the 4 byte function selector.\n *\n * :::tip\n *\n * This function is typically used to encode a contract function and its arguments for contract calls (e.g. `data` parameter of an `eth_call` or `eth_sendTransaction`).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData( // [!code focus]\n * approve, // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] // [!code focus]\n * ) // [!code focus]\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const approve = AbiFunction.fromAbi(erc20Abi, 'approve') // [!code hl]\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeData(\n * erc20Abi, // [!code focus]\n * 'approve', // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.encodeData` to encode the input of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input. // [!code focus]\n * const data = AbiFunction.encodeData( // [!code focus]\n * balanceOf, // [!code focus]\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] // [!code focus]\n * ) // [!code focus]\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output.\n * const balance = AbiFunction.decodeResult(balanceOf, response)\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to encode\n * @param args - Function arguments\n * @returns ABI-encoded function name and arguments\n */\nexport function encodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n ...args: encodeData.Args\n): Hex.Hex\nexport function encodeData(\n abiFunction: abiFunction | AbiFunction,\n ...args: encodeData.Args\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeData(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n ...args: readonly unknown[],\n ]\n | [abiFunction: AbiFunction, ...args: readonly unknown[]]\n) {\n const [abiFunction, args = []] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, args] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n readonly unknown[],\n ]\n return [fromAbi(abi, name, { args }), args]\n }\n const [abiFunction, args] = parameters as [AbiFunction, readonly unknown[]]\n return [abiFunction, args]\n })()\n\n const { overloads } = abiFunction\n\n const item = overloads\n ? (fromAbi([abiFunction as AbiFunction, ...overloads], abiFunction.name, {\n args,\n }) as AbiFunction)\n : abiFunction\n\n const selector = getSelector(item)\n\n const data =\n args.length > 0 ? AbiParameters.encode(item.inputs, args) : undefined\n\n return data ? Hex.concat(selector, data) : selector\n}\n\nexport declare namespace encodeData {\n type Args = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ?\n | (abitype.AbiParametersToPrimitiveTypes<\n abiFunction['inputs']\n > extends readonly []\n ? []\n : [abitype.AbiParametersToPrimitiveTypes])\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? [\n abitype.AbiParametersToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >,\n ]\n : [])\n : readonly unknown[]\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes a function's result (`outputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n * const output = AbiFunction.decodeResult(totalSupply, '0x000000000000000000000000000000000000000000000000000000000000002a')\n * // 42n\n *\n * const data = AbiFunction.encodeResult(totalSupply, 42n) // [!code focus]\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeResult(\n * abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * 42n\n * )\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @param abiFunction - The ABI item to encode the function output for.\n * @param output - The function output to encode.\n * @param options - Encoding options.\n * @returns The encoded function output.\n */\nexport function encodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n as extends 'Object' | 'Array' = 'Array',\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\nexport function encodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, output, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, output, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n any,\n encodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), output, options]\n }\n return parameters as [\n AbiFunction,\n any,\n encodeResult.Options | undefined,\n ]\n })()\n\n const { as = 'Array' } = options\n\n const values = (() => {\n if (abiFunction.outputs.length === 1) return [output]\n if (Array.isArray(output)) return output\n if (as === 'Object') return Object.values(output as any)\n return [output]\n })()\n\n return AbiParameters.encode(abiFunction.outputs, values)\n}\n\nexport declare namespace encodeResult {\n type Output<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = abiFunction['outputs'] extends readonly []\n ? never\n : abiFunction['outputs']['length'] extends 1\n ? AbiParameters_internal.ToPrimitiveTypes[0]\n : as extends 'Object'\n ? AbiParameters_internal.ToObject\n : AbiParameters_internal.ToPrimitiveTypes\n\n type Options = {\n as?: as | 'Object' | 'Array' | undefined\n }\n\n type ErrorType = AbiParameters.encode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Formats an {@link ox#AbiFunction.AbiFunction} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const formatted = AbiFunction.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiFunction - The ABI Function to format.\n * @returns The formatted ABI Function.\n */\nexport function format(\n abiFunction: abiFunction | AbiFunction,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiFunction) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Function** or **Human Readable ABI Function** into a typed {@link ox#AbiFunction.AbiFunction}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from({\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: [{ type: 'bool' }],\n * })\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiFunction - The ABI Function to parse.\n * @returns Typed ABI Function.\n */\nexport function from<\n const abiFunction extends AbiFunction | string | readonly string[],\n>(\n abiFunction: (abiFunction | AbiFunction | string | readonly string[]) &\n (\n | (abiFunction extends string ? internal.Signature : never)\n | (abiFunction extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiFunction\n ),\n options: from.Options = {},\n): from.ReturnType {\n return AbiItem.from(abiFunction as AbiFunction, options) as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted function (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction | string | readonly string[],\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Functions can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiFunction.fromAbi(abi, 'foo') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Functions can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiFunction.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Function from an `eth_call` RPC response or\n * from a Transaction `input`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: AbiItem.fromAbi.Options<\n abi,\n name,\n args,\n AbiItem_internal.ExtractArgs\n >,\n): AbiItem.fromAbi.ReturnType {\n const item = AbiItem.fromAbi(abi, name, options as any)\n if (item.type !== 'function')\n throw new AbiItem.NotFoundError({ name, type: 'function' })\n return item as never\n}\n\nexport declare namespace fromAbi {\n type ErrorType = AbiItem.fromAbi.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiFunction.AbiFunction}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector(abiItem: string | AbiFunction): Hex.Hex {\n return AbiItem.getSelector(abiItem)\n}\n\nexport declare namespace getSelector {\n type ErrorType = AbiItem.getSelector.ErrorType | Errors.GlobalErrorType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as AbiConstructor from 'ox/AbiConstructor'\nimport * as AbiFunction from 'ox/AbiFunction'\n\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { ethAddress, zeroAddress } from '../../constants/address.js'\nimport { deploylessCallViaBytecodeBytecode } from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { Mutable } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { hexToBigInt } from '../../utils/index.js'\nimport {\n type CreateAccessListErrorType,\n createAccessList,\n} from './createAccessList.js'\nimport {\n type SimulateBlocksErrorType,\n type SimulateBlocksParameters,\n simulateBlocks,\n} from './simulateBlocks.js'\n\nconst getBalanceCode =\n '0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033'\n\nexport type SimulateCallsParameters<\n calls extends readonly unknown[] = readonly unknown[],\n account extends Account | Address | undefined = Account | Address | undefined,\n> = Omit & {\n /** Account attached to the calls (msg.sender). */\n account?: account | undefined\n /** Calls to simulate. */\n calls: Calls>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n /** Whether to trace asset changes. */\n traceAssetChanges?: boolean | undefined\n}\n\nexport type SimulateCallsReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Asset changes. */\n assetChanges: readonly {\n token: {\n address: Address\n decimals?: number | undefined\n symbol?: string | undefined\n }\n value: { pre: bigint; post: bigint; diff: bigint }\n }[]\n /** Block results. */\n block: Block\n /** Call results. */\n results: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n}\n\nexport type SimulateCallsErrorType =\n | AbiFunction.encodeData.ErrorType\n | AbiFunction.from.ErrorType\n | CreateAccessListErrorType\n | EncodeFunctionDataErrorType\n | SimulateBlocksErrorType\n | ErrorType\n\n/**\n * Simulates execution of a batch of calls.\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateCalls } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulateCalls(client, {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n */\nexport async function simulateCalls<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateCallsParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag,\n calls,\n stateOverrides,\n traceAssetChanges,\n traceTransfers,\n validation,\n } = parameters\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n\n if (traceAssetChanges && !account)\n throw new BaseError(\n '`account` is required when `traceAssetChanges` is true',\n )\n\n // Derive bytecode to extract ETH balance via a contract call.\n const getBalanceData = account\n ? AbiConstructor.encode(AbiConstructor.from('constructor(bytes, bytes)'), {\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [\n getBalanceCode,\n AbiFunction.encodeData(\n AbiFunction.from('function getBalance(address)'),\n [account.address],\n ),\n ],\n })\n : undefined\n\n // Fetch ERC20/721 addresses that were \"touched\" from the calls.\n const assetAddresses = traceAssetChanges\n ? await Promise.all(\n parameters.calls.map(async (call: any) => {\n if (!call.data && !call.abi) return\n const { accessList } = await createAccessList(client, {\n account: account!.address,\n ...call,\n data: call.abi ? encodeFunctionData(call) : call.data,\n })\n return accessList.map(({ address, storageKeys }) =>\n storageKeys.length > 0 ? address : null,\n )\n }),\n ).then((x) => x.flat().filter(Boolean))\n : []\n\n const blocks = await simulateBlocks(client, {\n blockNumber,\n blockTag: blockTag as undefined,\n blocks: [\n ...(traceAssetChanges\n ? [\n // ETH pre balances\n {\n calls: [{ data: getBalanceData }],\n stateOverrides,\n },\n\n // Asset pre balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n\n {\n calls: [...calls, {}].map((call) => ({\n ...(call as Call),\n from: account?.address,\n })) as any,\n stateOverrides,\n },\n\n ...(traceAssetChanges\n ? [\n // ETH post balances\n {\n calls: [{ data: getBalanceData }],\n },\n\n // Asset post balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Decimals\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from('function decimals() returns (uint256)'),\n ],\n functionName: 'decimals',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Token URI\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from(\n 'function tokenURI(uint256) returns (string)',\n ),\n ],\n functionName: 'tokenURI',\n args: [0n],\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Symbols\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [AbiFunction.from('function symbol() returns (string)')],\n functionName: 'symbol',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n ],\n traceTransfers,\n validation,\n })\n\n const block_results = traceAssetChanges ? blocks[2] : blocks[0]\n const [\n block_ethPre,\n block_assetsPre,\n ,\n block_ethPost,\n block_assetsPost,\n block_decimals,\n block_tokenURI,\n block_symbols,\n ] = traceAssetChanges ? blocks : []\n\n // Extract call results from the simulation.\n const { calls: block_calls, ...block } = block_results\n const results = block_calls.slice(0, -1) ?? []\n\n // Extract pre-execution ETH and asset balances.\n const ethPre = block_ethPre?.calls ?? []\n const assetsPre = block_assetsPre?.calls ?? []\n const balancesPre = [...ethPre, ...assetsPre].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract post-execution ETH and asset balances.\n const ethPost = block_ethPost?.calls ?? []\n const assetsPost = block_assetsPost?.calls ?? []\n const balancesPost = [...ethPost, ...assetsPost].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract asset symbols & decimals.\n const decimals = (block_decimals?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (number | null)[]\n const symbols = (block_symbols?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n const tokenURI = (block_tokenURI?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n\n const changes: Mutable['assetChanges']> = []\n for (const [i, balancePost] of balancesPost.entries()) {\n const balancePre = balancesPre[i]\n\n if (typeof balancePost !== 'bigint') continue\n if (typeof balancePre !== 'bigint') continue\n\n const decimals_ = decimals[i - 1]\n const symbol_ = symbols[i - 1]\n const tokenURI_ = tokenURI[i - 1]\n\n const token = (() => {\n if (i === 0)\n return {\n address: ethAddress,\n decimals: 18,\n symbol: 'ETH',\n }\n\n return {\n address: assetAddresses[i - 1]! as Address,\n decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined,\n symbol: symbol_ ?? undefined,\n }\n })()\n\n if (changes.some((change) => change.token.address === token.address))\n continue\n\n changes.push({\n token,\n value: {\n pre: balancePre,\n post: balancePost,\n diff: balancePost - balancePre,\n },\n })\n }\n\n return {\n assetChanges: changes,\n block,\n results,\n } as unknown as SimulateCallsReturnType\n}\n","export const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const\n\nexport const zeroAddress = '0x0000000000000000000000000000000000000000' as const\n","import type * as Abi from '../core/Abi.js'\nimport * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-6492 signature. */\nexport type Unwrapped = {\n /** Calldata to pass to the target address for counterfactual verification. */\n data: Hex.Hex\n /** The original signature. */\n signature: Hex.Hex\n /** The target address to use for counterfactual verification. */\n to: Address.Address\n}\n\n/** Wrapped ERC-6492 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-6492 wrapped signatures.\n */\nexport const magicBytes =\n '0x6492649264926492649264926492649264926492649264926492649264926492' as const\n\n/**\n * Deployless ERC-6492 signature verification bytecode.\n */\nexport const universalSignatureValidatorBytecode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\n/**\n * ABI for the ERC-6492 universal deployless signature validator contract.\n *\n * Constructor return value is `0x1` (valid) or `0x0` (invalid).\n */\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 satisfies Abi.Abi\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * SignatureErc6492.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-6492 wrapped signature.\n * ```\n *\n * @param wrapped - The wrapped signature to assert.\n */\nexport function assert(wrapped: Wrapped) {\n if (Hex.slice(wrapped, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(wrapped)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc6492.from('0x...') // [!code focus]\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc6492.from({ // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * to: '0x...', // [!code focus]\n * })\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', }\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function from(wrapped: Unwrapped | Wrapped): Unwrapped {\n if (typeof wrapped === 'string') return unwrap(wrapped)\n return wrapped\n}\n\nexport declare namespace from {\n type ReturnType = Unwrapped\n\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const { data, signature, to } = SignatureErc6492.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const [to, data, signature] = AbiParameters.decode(\n AbiParameters.from('address, bytes, bytes'),\n wrapped,\n )\n\n return { data, signature, to }\n}\n\nexport declare namespace unwrap {\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc6492.wrap({ // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * to: '0x00000000219ab540356cBB839Cbe05303d7705Fa', // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Wrapped signature to serialize.\n * @returns Serialized wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature, to } = value\n\n return Hex.concat(\n AbiParameters.encode(AbiParameters.from('address, bytes, bytes'), [\n to,\n data,\n signature,\n ]),\n magicBytes,\n )\n}\n\nexport declare namespace wrap {\n type ErrorType =\n | AbiParameters.encode.ErrorType\n | Hex.concat.ErrorType\n | Signature.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const valid = SignatureErc6492.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param wrapped - The wrapped signature to validate.\n * @returns `true` if the wrapped signature is valid, `false` otherwise.\n */\nexport function validate(wrapped: Wrapped): boolean {\n try {\n assert(wrapped)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-6492 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc6492.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-6492 wrapped signature.`)\n }\n}\n","import type { Address } from 'abitype'\nimport { SignatureErc6492 } from 'ox/erc6492'\nimport { SignatureErc8010 } from 'ox/erc8010'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n erc1271Abi,\n erc6492SignatureValidatorAbi,\n multicall3Abi,\n} from '../../constants/abis.js'\nimport {\n erc6492SignatureValidatorByteCode,\n multicall3Bytecode,\n} from '../../constants/contracts.js'\nimport {\n CallExecutionError,\n ContractFunctionExecutionError,\n} from '../../errors/contract.js'\nimport type { InvalidHexBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.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 {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../../utils/address/isAddressEqual.js'\nimport { verifyAuthorization } from '../../utils/authorization/verifyAuthorization.js'\nimport { type ConcatHexErrorType, concatHex } from '../../utils/data/concat.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { hexToBool } from '../../utils/encoding/fromHex.js'\nimport {\n type BytesToHexErrorType,\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../utils/signature/recoverAddress.js'\nimport {\n type SerializeSignatureErrorType,\n serializeSignature,\n} from '../../utils/signature/serializeSignature.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type VerifyHashParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n /** The address that signed the original message. */\n address: Address\n /** The chain to use. */\n chain?: Chain | null | undefined\n /** The address of the ERC-6492 signature verifier contract. */\n erc6492VerifierAddress?: Address | undefined\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n /** @deprecated use `erc6492VerifierAddress` instead. */\n universalSignatureVerifierAddress?: Address | undefined\n} & OneOf<{ factory: Address; factoryData: Hex } | {}>\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n | BytesToHexErrorType\n | CallErrorType\n | ConcatHexErrorType\n | EncodeDeployDataErrorType\n | EncodeFunctionDataErrorType\n | ErrorType\n | GetAddressErrorType\n | GetCodeErrorType\n | InvalidHexBooleanError\n | IsAddressEqualErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ReadContractErrorType\n | RecoverAddressErrorType\n | SerializeSignatureErrorType\n\n/**\n * Verifies a message hash onchain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash(\n client: Client,\n parameters: VerifyHashParameters,\n): Promise {\n const {\n address,\n chain = client.chain,\n hash,\n erc6492VerifierAddress:\n verifierAddress = parameters.universalSignatureVerifierAddress ??\n chain?.contracts?.erc6492Verifier?.address,\n multicallAddress = parameters.multicallAddress ??\n chain?.contracts?.multicall3?.address,\n } = parameters\n\n if (chain?.verifyHash) return await chain.verifyHash(client, parameters)\n\n const signature = (() => {\n const signature = parameters.signature\n if (isHex(signature)) return signature\n if (typeof signature === 'object' && 'r' in signature && 's' in signature)\n return serializeSignature(signature)\n return bytesToHex(signature)\n })()\n\n try {\n if (SignatureErc8010.validate(signature))\n return await verifyErc8010(client, {\n ...parameters,\n multicallAddress,\n signature,\n })\n return await verifyErc6492(client, {\n ...parameters,\n verifierAddress,\n signature,\n })\n } catch (error) {\n // Fallback attempt to verify the signature via ECDSA recovery.\n try {\n const verified = isAddressEqual(\n getAddress(address),\n await recoverAddress({ hash, signature }),\n )\n if (verified) return true\n } catch {}\n\n if (error instanceof VerificationError) {\n // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n // this can happen for many reasons, for example if signer can not be recovered from the signature\n // or if the signature has no valid format\n return false\n }\n\n throw error\n }\n}\n\n/** @internal */\nexport async function verifyErc8010(\n client: Client,\n parameters: verifyErc8010.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, multicallAddress } = parameters\n\n const {\n authorization: authorization_ox,\n data: initData,\n signature,\n to,\n } = SignatureErc8010.unwrap(parameters.signature)\n\n // Check if already delegated\n const code = await getCode(client, {\n address,\n blockNumber,\n blockTag,\n } as never)\n\n // If already delegated, perform standard ERC-1271 verification.\n if (code === concatHex(['0xef0100', authorization_ox.address]))\n return await verifyErc1271(client, {\n address,\n blockNumber,\n blockTag,\n hash,\n signature,\n })\n\n const authorization = {\n address: authorization_ox.address,\n chainId: Number(authorization_ox.chainId),\n nonce: Number(authorization_ox.nonce),\n r: numberToHex(authorization_ox.r, { size: 32 }),\n s: numberToHex(authorization_ox.s, { size: 32 }),\n yParity: authorization_ox.yParity,\n } as const\n\n const valid = await verifyAuthorization({\n address,\n authorization,\n })\n if (!valid) throw new VerificationError()\n\n // Deployless verification.\n const results = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress\n ? { address: multicallAddress }\n : { code: multicall3Bytecode }),\n authorizationList: [authorization],\n abi: multicall3Abi,\n blockNumber,\n blockTag: 'pending',\n functionName: 'aggregate3',\n args: [\n [\n ...(initData\n ? ([\n {\n allowFailure: true,\n target: to ?? address,\n callData: initData,\n },\n ] as const)\n : []),\n {\n allowFailure: true,\n target: address,\n callData: encodeFunctionData({\n abi: erc1271Abi,\n functionName: 'isValidSignature',\n args: [hash, signature],\n }),\n },\n ],\n ],\n })\n\n const data = results[results.length - 1]?.returnData\n\n if (data?.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc8010 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nasync function verifyErc6492(\n client: Client,\n parameters: verifyErc6492.Parameters,\n) {\n const {\n address,\n factory,\n factoryData,\n hash,\n signature,\n verifierAddress,\n ...rest\n } = parameters\n\n const wrappedSignature = await (async () => {\n // If no `factory` or `factoryData` is provided, it is assumed that the\n // address is not a Smart Account, or the Smart Account is already deployed.\n if (!factory && !factoryData) return signature\n\n // If the signature is already wrapped, return the signature.\n if (SignatureErc6492.validate(signature)) return signature\n\n // If the Smart Account is not deployed, wrap the signature with a 6492 wrapper\n // to perform counterfactual validation.\n return SignatureErc6492.wrap({\n data: factoryData!,\n signature,\n to: factory!,\n })\n })()\n\n const args = verifierAddress\n ? ({\n to: verifierAddress,\n data: encodeFunctionData({\n abi: erc6492SignatureValidatorAbi,\n functionName: 'isValidSig',\n args: [address, hash, wrappedSignature],\n }),\n ...rest,\n } as unknown as CallParameters)\n : ({\n data: encodeDeployData({\n abi: erc6492SignatureValidatorAbi,\n args: [address, hash, wrappedSignature],\n bytecode: erc6492SignatureValidatorByteCode,\n }),\n ...rest,\n } as unknown as CallParameters)\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )(args).catch((error) => {\n if (error instanceof CallExecutionError) throw new VerificationError()\n throw error\n })\n\n if (hexToBool(data ?? '0x0')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc6492 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n /** The address of the ERC-6492 signature verifier contract. */\n verifierAddress?: Address | undefined\n } & OneOf<{ factory: Address; factoryData: Hex } | {}>\n}\n\n/** @internal */\nexport async function verifyErc1271(\n client: Client,\n parameters: verifyErc1271.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, signature } = parameters\n\n const result = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address,\n abi: erc1271Abi,\n args: [hash, signature],\n blockNumber,\n blockTag,\n functionName: 'isValidSignature',\n }).catch((error) => {\n if (error instanceof ContractFunctionExecutionError)\n throw new VerificationError()\n throw error\n })\n\n if (result.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc1271 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\nclass VerificationError extends Error {}\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","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ByteArray,\n Hex,\n SignableMessage,\n Signature,\n} from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyMessageParameters = Prettify<\n Omit & {\n /** The address that signed the original message. */\n address: Address\n /** The message to be verified. */\n message: SignableMessage\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n }\n>\n\nexport type VerifyMessageReturnType = boolean\n\nexport type VerifyMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\nexport async function verifyMessage(\n client: Client,\n {\n address,\n message,\n factory,\n factoryData,\n signature,\n ...callRequest\n }: VerifyMessageParameters,\n): Promise {\n const hash = hashMessage(message)\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address, TypedData } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = Omit &\n TypedDataDefinition & {\n /** The address to verify the typed data for. */\n address: Address\n /** The signature to verify */\n signature: Hex | ByteArray | Signature\n }\n\nexport type VerifyTypedDataReturnType = boolean\n\nexport type VerifyTypedDataErrorType =\n | HashTypedDataErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\nexport async function verifyTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: VerifyTypedDataParameters,\n): Promise {\n const {\n address,\n factory,\n factoryData,\n signature,\n message,\n primaryType,\n types,\n domain,\n ...callRequest\n } = parameters as VerifyTypedDataParameters\n const hash = hashTypedData({ message, primaryType, types, domain })\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n TransactionNotFoundError,\n TransactionReceiptNotFoundError,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n type GetTransactionErrorType,\n type GetTransactionReturnType,\n getTransaction,\n} from './getTransaction.js'\nimport {\n type GetTransactionReceiptErrorType,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n type WatchBlockNumberErrorType,\n watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * Whether to check for transaction replacements.\n * @default true\n */\n checkReplacement?: boolean | undefined\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | WaitForTransactionReceiptTimeoutErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: WaitForTransactionReceiptParameters,\n): Promise> {\n const {\n checkReplacement = true,\n confirmations = 1,\n hash,\n onReplaced,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n } = parameters\n\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n const pollingInterval = (() => {\n if (parameters.pollingInterval) return parameters.pollingInterval\n if (client.chain?.experimental_preconfirmationTime)\n return client.chain.experimental_preconfirmationTime\n return client.pollingInterval\n })()\n\n let transaction: GetTransactionReturnType | undefined\n let replacedTransaction: GetTransactionReturnType | undefined\n let receipt: GetTransactionReceiptReturnType | undefined\n let retrying = false\n\n let _unobserve: () => void\n let _unwatch: () => void\n\n const { promise, resolve, reject } =\n withResolvers>()\n\n const timer = timeout\n ? setTimeout(() => {\n _unwatch?.()\n _unobserve?.()\n reject(new WaitForTransactionReceiptTimeoutError({ hash }))\n }, timeout)\n : undefined\n\n _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n async (emit) => {\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash }).catch(() => undefined)\n\n if (receipt && confirmations <= 1) {\n clearTimeout(timer)\n emit.resolve(receipt)\n _unobserve?.()\n return\n }\n\n _unwatch = getAction(\n client,\n watchBlockNumber,\n 'watchBlockNumber',\n )({\n emitMissed: true,\n emitOnBegin: true,\n poll: true,\n pollingInterval,\n async onBlockNumber(blockNumber_) {\n const done = (fn: () => void) => {\n clearTimeout(timer)\n _unwatch?.()\n fn()\n _unobserve?.()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\n\n try {\n // If we already have a valid receipt, let's check if we have enough\n // confirmations. If we do, then we can resolve.\n if (receipt) {\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n return\n }\n\n // Get the transaction to check if it's been replaced.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined transactions.\n if (checkReplacement && !transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\n },\n )\n retrying = false\n }\n\n // Get the receipt to check if it's been processed.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n } catch (err) {\n // If the receipt is not found, the transaction will be pending.\n // We need to check if it has potentially been replaced.\n if (\n err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\n\n try {\n replacedTransaction = transaction\n\n // Let's retrieve the transactions from the current block.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined blocks.\n retrying = true\n const block = await withRetry(\n () =>\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber,\n includeTransactions: true,\n }),\n {\n delay: retryDelay,\n retryCount,\n shouldRetry: ({ error }) =>\n error instanceof BlockNotFoundError,\n },\n )\n retrying = false\n\n const replacementTransaction = (\n block.transactions as {} as Transaction[]\n ).find(\n ({ from, nonce }) =>\n from === replacedTransaction!.from &&\n nonce === replacedTransaction!.nonce,\n )\n\n // If we couldn't find a replacement transaction, continue polling.\n if (!replacementTransaction) return\n\n // If we found a replacement transaction, return it's receipt.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({\n hash: replacementTransaction.hash,\n })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n let reason: ReplacementReason = 'replaced'\n if (\n replacementTransaction.to === replacedTransaction.to &&\n replacementTransaction.value === replacedTransaction.value &&\n replacementTransaction.input === replacedTransaction.input\n ) {\n reason = 'repriced'\n } else if (\n replacementTransaction.from === replacementTransaction.to &&\n replacementTransaction.value === 0n\n ) {\n reason = 'cancelled'\n }\n\n done(() => {\n emit.onReplaced?.({\n reason,\n replacedTransaction: replacedTransaction! as any,\n transaction: replacementTransaction,\n transactionReceipt: receipt!,\n })\n emit.resolve(receipt!)\n })\n } catch (err_) {\n done(() => emit.reject(err_))\n }\n } else {\n done(() => emit.reject(err))\n }\n }\n },\n })\n },\n )\n\n return promise\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n blockNumber: OnBlockNumberParameter,\n prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type WatchBlockNumberParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when a new block number is received. */\n onBlockNumber: OnBlockNumberFn\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n const pollBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) =>\n poll(\n async () => {\n try {\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({ cacheTime: 0 })\n\n if (prevBlockNumber !== undefined) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (blockNumber === prevBlockNumber) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n emit.onBlockNumber(i, prevBlockNumber)\n prevBlockNumber = i\n }\n }\n }\n\n // If the next block number is greater than the previous,\n // it is not in the past, and we can emit the new block number.\n if (\n prevBlockNumber === undefined ||\n blockNumber > prevBlockNumber\n ) {\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockReturnType, getBlock } from './getBlock.js'\n\nexport type OnBlockParameter<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = GetBlockReturnType\n\nexport type OnBlock<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = (\n block: OnBlockParameter,\n prevBlock: OnBlockParameter | undefined,\n) => void\n\nexport type WatchBlocksParameters<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** The callback to call when a new block is received. */\n onBlock: OnBlock\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n blockTag?: undefined\n emitMissed?: undefined\n emitOnBegin?: undefined\n includeTransactions?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** The block tag. Defaults to \"latest\". */\n blockTag?: blockTag | BlockTag | undefined\n /** Whether or not to emit the missed blocks to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the block to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to the client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlocksReturnType = () => void\n\nexport type WatchBlocksErrorType =\n | StringifyErrorType\n | PollErrorType\n | ErrorType\n\n/**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, watchBlocks, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlocks(client, {\n * onBlock: (block) => console.log(block),\n * })\n */\nexport function watchBlocks<\n transport extends Transport,\n chain extends Chain | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockTag = client.experimental_blockTag ?? 'latest',\n emitMissed = false,\n emitOnBegin = false,\n onBlock,\n onError,\n includeTransactions: includeTransactions_,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlocksParameters,\n): WatchBlocksReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const includeTransactions = includeTransactions_ ?? false\n\n let prevBlock:\n | GetBlockReturnType\n | undefined\n\n const pollBlocks = () => {\n const observerId = stringify([\n 'watchBlocks',\n client.uid,\n blockTag,\n emitMissed,\n emitOnBegin,\n includeTransactions,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlock, onError }, (emit) =>\n poll(\n async () => {\n try {\n const block = await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n if (block.number !== null && prevBlock?.number != null) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (block.number === prevBlock.number) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (block.number - prevBlock.number > 1 && emitMissed) {\n for (let i = prevBlock?.number + 1n; i < block.number; i++) {\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: i,\n includeTransactions,\n })) as GetBlockReturnType\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block\n }\n }\n }\n\n if (\n // If no previous block exists, emit.\n prevBlock?.number == null ||\n // If the block tag is \"pending\" with no block number, emit.\n (blockTag === 'pending' && block?.number == null) ||\n // If the next block number is greater than the previous block number, emit.\n // We don't want to emit blocks in the past.\n (block.number !== null && block.number > prevBlock.number)\n ) {\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block as any\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlocks = () => {\n let active = true\n let emitFetched = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n if (emitOnBegin) {\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n .then((block) => {\n if (!active) return\n if (!emitFetched) return\n onBlock(block as any, undefined)\n emitFetched = false\n })\n .catch(onError)\n }\n\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n async onData(data: any) {\n if (!active) return\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: data.result?.number,\n includeTransactions,\n }).catch(() => {})) as GetBlockReturnType\n if (!active) return\n onBlock(block as any, prevBlock as any)\n emitFetched = false\n prevBlock = block\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollBlocks() : subscribeBlocks()\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport {\n type CreateEventFilterParameters,\n createEventFilter,\n} from './createEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { type GetLogsParameters, getLogs } from './getLogs.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchEventOnLogsParameter<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n eventName extends string | undefined = MaybeAbiEventName,\n> = Log[]\nexport type WatchEventOnLogsFn<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = (\n logs: WatchEventOnLogsParameter,\n) => void\n\nexport type WatchEventParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchEventOnLogsFn\n} & GetPollOptions &\n (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: abiEvents | undefined\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n )\n\nexport type WatchEventReturnType = () => void\n\nexport type WatchEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchEvent } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchEvent(client, {\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchEvent<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n _eventName extends string | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n batch = true,\n event,\n events,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n }: WatchEventParameters,\n): WatchEventReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const strict = strict_ ?? false\n\n const pollEvent = () => {\n const observerId = stringify([\n 'watchEvent',\n address,\n args,\n batch,\n client.uid,\n event,\n pollingInterval,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abiEvents, _eventName, any>\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createEventFilter as any,\n 'createEventFilter',\n )({\n address,\n args,\n event: event!,\n events,\n strict,\n fromBlock,\n } as unknown as CreateEventFilterParameters)) as unknown as Filter<\n 'event',\n abiEvents,\n _eventName\n >\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n logs = await getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n event: event!,\n events,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n } as unknown as GetLogsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeEvent = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const events_ = events ?? (event ? [event] : undefined)\n let topics: LogTopic[] = []\n if (events_) {\n const encoded = (events_ as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: events_ ?? [],\n data: log.data,\n topics: log.topics,\n strict,\n })\n const formatted = formatLog(log, { args, eventName })\n onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollEvent() : subscribeEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { createPendingTransactionFilter } from './createPendingTransactionFilter.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type OnTransactionsParameter = Hash[]\nexport type OnTransactionsFn = (transactions: OnTransactionsParameter) => void\n\nexport type WatchPendingTransactionsParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new transactions are received. */\n onTransactions: OnTransactionsFn\n} & GetPollOptions\n\nexport type WatchPendingTransactionsReturnType = () => void\n\nexport type WatchPendingTransactionsErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param client - Client to use\n * @param parameters - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchPendingTransactions } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await watchPendingTransactions(client, {\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\nexport function watchPendingTransactions<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n {\n batch = true,\n onError,\n onTransactions,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchPendingTransactionsParameters,\n) {\n const enablePolling =\n typeof poll_ !== 'undefined'\n ? poll_\n : client.transport.type !== 'webSocket' && client.transport.type !== 'ipc'\n\n const pollPendingTransactions = () => {\n const observerId = stringify([\n 'watchPendingTransactions',\n client.uid,\n batch,\n pollingInterval,\n ])\n return observe(observerId, { onTransactions, onError }, (emit) => {\n let filter: Filter<'transaction'>\n\n const unwatch = poll(\n async () => {\n try {\n if (!filter) {\n try {\n filter = await getAction(\n client,\n createPendingTransactionFilter,\n 'createPendingTransactionFilter',\n )({})\n return\n } catch (err) {\n unwatch()\n throw err\n }\n }\n\n const hashes = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n if (hashes.length === 0) return\n if (batch) emit.onTransactions(hashes)\n else for (const hash of hashes) emit.onTransactions([hash])\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribePendingTransactions = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n params: ['newPendingTransactions'],\n onData(data: any) {\n if (!active) return\n const transaction = data.result\n onTransactions([transaction])\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling\n ? pollPendingTransactions()\n : subscribePendingTransactions()\n}\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\nimport type { SiweMessage } from './types.js'\n\n/**\n * @description Parses EIP-4361 formatted message into message fields object.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n *\n * @returns EIP-4361 fields object\n */\nexport function parseSiweMessage(\n message: string,\n): Prettify> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: Address\n domain: string\n scheme?: string\n statement?: string\n }\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string\n expirationTime?: string\n issuedAt?: string\n nonce: string\n notBefore?: string\n requestId?: string\n uri: string\n version: '1'\n }\n const resources = message.split('Resources:')[1]?.split('\\n- ').slice(1)\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n }\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\\n)(?
0x[a-fA-F0-9]{40})\\n\\n(?:(?.*)\\n\\n)?/\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?.+))\\n(?:Version: (?.+))\\n(?:Chain ID: (?\\d+))\\n(?:Nonce: (?[a-zA-Z0-9]+))\\n(?:Issued At: (?.+))(?:\\nExpiration Time: (?.+))?(?:\\nNot Before: (?.+))?(?:\\nRequest ID: (?.+))?/\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport type { SiweMessage } from './types.js'\n\nexport type ValidateSiweMessageParameters = {\n /**\n * Ethereum address to check against.\n */\n address?: Address | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined\n /**\n * EIP-4361 message fields.\n */\n message: ExactPartial\n /**\n * Random string to check against.\n */\n nonce?: string | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined\n}\n\nexport type ValidateSiweMessageReturnType = boolean\n\n/**\n * @description Validates EIP-4361 message.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n */\nexport function validateSiweMessage(\n parameters: ValidateSiweMessageParameters,\n): ValidateSiweMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters\n\n if (domain && message.domain !== domain) return false\n if (nonce && message.nonce !== nonce) return false\n if (scheme && message.scheme !== scheme) return false\n\n if (message.expirationTime && time >= message.expirationTime) return false\n if (message.notBefore && time < message.notBefore) return false\n\n try {\n if (!message.address) return false\n if (!isAddress(message.address, { strict: false })) return false\n if (address && !isAddressEqual(message.address, address)) return false\n } catch {\n return false\n }\n\n return true\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport { parseSiweMessage } from '../../utils/siwe/parseSiweMessage.js'\nimport {\n type ValidateSiweMessageParameters,\n validateSiweMessage,\n} from '../../utils/siwe/validateSiweMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from '../public/verifyHash.js'\n\nexport type VerifySiweMessageParameters = Prettify<\n Pick &\n Pick<\n ValidateSiweMessageParameters,\n 'address' | 'domain' | 'nonce' | 'scheme' | 'time'\n > & {\n /**\n * EIP-4361 formatted message.\n */\n message: string\n /**\n * Signature to check against.\n */\n signature: Hex\n }\n>\n\nexport type VerifySiweMessageReturnType = boolean\n\nexport type VerifySiweMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\nexport async function verifySiweMessage(\n client: Client,\n parameters: VerifySiweMessageParameters,\n): Promise {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n ...callRequest\n } = parameters\n\n const parsed = parseSiweMessage(message)\n if (!parsed.address) return false\n\n const isValid = validateSiweMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n })\n if (!isValid) return false\n\n const hash = hashMessage(message)\n return verifyHash(client, {\n address: parsed.address,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionReceiptRevertedError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { formatTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport type { FormattedTransactionReceipt } from '../../utils/index.js'\n\nexport type SendRawTransactionSyncParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n /** Whether to throw an error if the transaction was detected as reverted. @default true */\n throwOnReceiptRevert?: boolean | undefined\n /** The timeout for the transaction. */\n timeout?: number | undefined\n}\n\nexport type SendRawTransactionSyncReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type SendRawTransactionSyncErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network synchronously,\n * and waits for the transaction to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await sendRawTransactionSync(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransactionSync(\n client: Client,\n {\n serializedTransaction,\n throwOnReceiptRevert,\n timeout,\n }: SendRawTransactionSyncParameters,\n): Promise> {\n const receipt = await client.request(\n {\n method: 'eth_sendRawTransactionSync',\n params: timeout\n ? [serializedTransaction, timeout]\n : [serializedTransaction],\n },\n { retryCount: 0 },\n )\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n\n const formatted = format(receipt) as SendRawTransactionSyncReturnType\n if (formatted.status === 'reverted' && throwOnReceiptRevert)\n throw new TransactionReceiptRevertedError({ receipt: formatted })\n return formatted\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account, ParseAccount } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { PublicRpcSchema, RpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n} from './createClient.js'\nimport { type PublicActions, publicActions } from './decorators/public.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type PublicClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Pick<\n ClientConfig,\n | 'batch'\n | 'cacheTime'\n | 'ccipRead'\n | 'chain'\n | 'experimental_blockTag'\n | 'key'\n | 'name'\n | 'pollingInterval'\n | 'rpcSchema'\n | 'transport'\n >\n>\n\nexport type PublicClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Client<\n transport,\n chain,\n accountOrAddress,\n rpcSchema extends RpcSchema\n ? [...PublicRpcSchema, ...rpcSchema]\n : PublicRpcSchema,\n PublicActions\n >\n>\n\nexport type CreatePublicClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://viem.sh/docs/clients/public\n *\n * A Public Client is an interface to \"public\" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param config - {@link PublicClientConfig}\n * @returns A Public Client. {@link PublicClient}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: PublicClientConfig,\n): PublicClient, rpcSchema> {\n const { key = 'public', name = 'Public Client' } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n type: 'publicClient',\n })\n return client.extend(publicActions) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { OneOf } from '../../types/utils.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** Methods to include or exclude from executing RPC requests. */\n methods?:\n | OneOf<\n | {\n include?: string[] | undefined\n }\n | {\n exclude?: string[] | undefined\n }\n >\n | undefined\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = ({\n chain,\n}: {\n account?: Account | undefined\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record,\n>(\n {\n key,\n methods,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig,\n value?: rpcAttributes | undefined,\n): ReturnType> {\n const uid = uid_()\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\n value,\n }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { EIP1193RequestFn, RpcSchema } from '../../types/eip1193.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n getHttpRpcClient,\n type HttpRpcClientOptions,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './createTransport.js'\n\nexport type HttpTransportConfig<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** Methods to include or exclude from executing RPC requests. */\n methods?: TransportConfig['methods'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** Whether to return JSON RPC errors as responses instead of throwing. */\n raw?: raw | boolean | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** Typed JSON-RPC schema for the transport. */\n rpcSchema?: rpcSchema | RpcSchema | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n },\n EIP1193RequestFn\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n>(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig = {},\n): HttpTransport {\n const {\n batch,\n fetchFn,\n fetchOptions,\n key = 'http',\n methods,\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n raw,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchFn,\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n methods,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n\n if (raw) return { error, result }\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type AbiParameter,\n type AbiParameterKind,\n type AbiParameterToPrimitiveType,\n type AbiStateMutability,\n type Address,\n CircularReferenceError,\n InvalidAbiItemError,\n InvalidAbiParameterError,\n InvalidAbiParametersError,\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n InvalidParenthesisError,\n InvalidSignatureError,\n InvalidStructSignatureError,\n type Narrow,\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n SolidityProtectedKeywordError,\n type TypedData,\n type TypedDataDomain,\n type TypedDataParameter,\n UnknownSignatureError,\n UnknownTypeError,\n} from 'abitype'\nexport type {\n BlockOverrides,\n Rpc as RpcBlockOverrides,\n} from 'ox/BlockOverrides'\nexport type { EntryPointVersion } from './account-abstraction/types/entryPointVersion.js'\nexport type {\n RpcEstimateUserOperationGasReturnType,\n RpcGetUserOperationByHashReturnType,\n RpcUserOperation,\n RpcUserOperationReceipt,\n RpcUserOperationRequest,\n} from './account-abstraction/types/rpc.js'\nexport type {\n EstimateUserOperationGasReturnType,\n GetUserOperationByHashReturnType,\n PackedUserOperation,\n UserOperation,\n UserOperationReceipt,\n UserOperationRequest,\n} from './account-abstraction/types/userOperation.js'\nexport type {\n Account,\n AccountSource,\n CustomSource,\n HDAccount,\n HDOptions,\n JsonRpcAccount,\n LocalAccount,\n PrivateKeyAccount,\n} from './accounts/types.js'\nexport type {\n GetEnsAddressErrorType,\n GetEnsAddressParameters,\n GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n GetEnsAvatarErrorType,\n GetEnsAvatarParameters,\n GetEnsAvatarReturnType,\n} from './actions/ens/getEnsAvatar.js'\nexport type {\n GetEnsNameErrorType,\n GetEnsNameParameters,\n GetEnsNameReturnType,\n} from './actions/ens/getEnsName.js'\nexport type {\n GetEnsResolverErrorType,\n GetEnsResolverParameters,\n GetEnsResolverReturnType,\n} from './actions/ens/getEnsResolver.js'\nexport type {\n GetEnsTextErrorType,\n GetEnsTextParameters,\n GetEnsTextReturnType,\n} from './actions/ens/getEnsText.js'\nexport {\n type GetContractErrorType,\n type GetContractParameters,\n type GetContractReturnType,\n getContract,\n} from './actions/getContract.js'\nexport type {\n CallErrorType,\n CallParameters,\n CallReturnType,\n} from './actions/public/call.js'\nexport type {\n CreateAccessListErrorType,\n CreateAccessListParameters,\n CreateAccessListReturnType,\n} from './actions/public/createAccessList.js'\nexport type {\n CreateBlockFilterErrorType,\n CreateBlockFilterReturnType,\n} from './actions/public/createBlockFilter.js'\nexport type {\n CreateContractEventFilterErrorType,\n CreateContractEventFilterParameters,\n CreateContractEventFilterReturnType,\n} from './actions/public/createContractEventFilter.js'\nexport type {\n CreateEventFilterErrorType,\n CreateEventFilterParameters,\n CreateEventFilterReturnType,\n} from './actions/public/createEventFilter.js'\nexport type {\n CreatePendingTransactionFilterErrorType,\n CreatePendingTransactionFilterReturnType,\n} from './actions/public/createPendingTransactionFilter.js'\nexport type {\n EstimateContractGasErrorType,\n EstimateContractGasParameters,\n EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n EstimateFeesPerGasErrorType,\n EstimateFeesPerGasParameters,\n EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n EstimateGasErrorType,\n EstimateGasParameters,\n EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n EstimateMaxPriorityFeePerGasErrorType,\n EstimateMaxPriorityFeePerGasParameters,\n EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n FillTransactionErrorType,\n FillTransactionParameters,\n FillTransactionReturnType,\n} from './actions/public/fillTransaction.js'\nexport type {\n GetBalanceErrorType,\n GetBalanceParameters,\n GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n GetBlobBaseFeeErrorType,\n GetBlobBaseFeeReturnType,\n} from './actions/public/getBlobBaseFee.js'\nexport type {\n GetBlockErrorType,\n GetBlockParameters,\n GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n GetBlockNumberErrorType,\n GetBlockNumberParameters,\n GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n GetBlockTransactionCountErrorType,\n GetBlockTransactionCountParameters,\n GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n GetChainIdErrorType,\n GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n /** @deprecated Use `GetCodeErrorType` instead */\n GetCodeErrorType as GetBytecodeErrorType,\n GetCodeErrorType,\n /** @deprecated Use `GetCodeParameters` instead */\n GetCodeParameters as GetBytecodeParameters,\n GetCodeParameters,\n /** @deprecated Use `GetCodeReturnType` instead */\n GetCodeReturnType as GetBytecodeReturnType,\n GetCodeReturnType,\n} from './actions/public/getCode.js'\nexport type {\n GetContractEventsErrorType,\n GetContractEventsParameters,\n GetContractEventsReturnType,\n} from './actions/public/getContractEvents.js'\nexport type {\n GetDelegationErrorType,\n GetDelegationParameters,\n GetDelegationReturnType,\n} from './actions/public/getDelegation.js'\nexport type {\n GetEip712DomainErrorType,\n GetEip712DomainParameters,\n GetEip712DomainReturnType,\n} from './actions/public/getEip712Domain.js'\nexport type {\n GetFeeHistoryErrorType,\n GetFeeHistoryParameters,\n GetFeeHistoryReturnType,\n} from './actions/public/getFeeHistory.js'\nexport type {\n GetFilterChangesErrorType,\n GetFilterChangesParameters,\n GetFilterChangesReturnType,\n} from './actions/public/getFilterChanges.js'\nexport type {\n GetFilterLogsErrorType,\n GetFilterLogsParameters,\n GetFilterLogsReturnType,\n} from './actions/public/getFilterLogs.js'\nexport type {\n GetGasPriceErrorType,\n GetGasPriceReturnType,\n} from './actions/public/getGasPrice.js'\nexport type {\n GetLogsErrorType,\n GetLogsParameters,\n GetLogsReturnType,\n} from './actions/public/getLogs.js'\nexport type {\n GetProofErrorType,\n GetProofParameters,\n GetProofReturnType,\n} from './actions/public/getProof.js'\nexport type {\n GetStorageAtErrorType,\n GetStorageAtParameters,\n GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n GetTransactionErrorType,\n GetTransactionParameters,\n GetTransactionReturnType,\n} from './actions/public/getTransaction.js'\nexport type {\n GetTransactionConfirmationsErrorType,\n GetTransactionConfirmationsParameters,\n GetTransactionConfirmationsReturnType,\n} from './actions/public/getTransactionConfirmations.js'\nexport type {\n GetTransactionCountErrorType,\n GetTransactionCountParameters,\n GetTransactionCountReturnType,\n} from './actions/public/getTransactionCount.js'\nexport type {\n GetTransactionReceiptErrorType,\n GetTransactionReceiptParameters,\n GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n MulticallErrorType,\n MulticallParameters,\n MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n ReadContractErrorType,\n ReadContractParameters,\n ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n SimulateBlocksErrorType,\n SimulateBlocksParameters,\n SimulateBlocksReturnType,\n} from './actions/public/simulateBlocks.js'\nexport type {\n SimulateCallsErrorType,\n SimulateCallsParameters,\n SimulateCallsReturnType,\n} from './actions/public/simulateCalls.js'\nexport type {\n GetMutabilityAwareValue,\n SimulateContractErrorType,\n SimulateContractParameters,\n SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n UninstallFilterErrorType,\n UninstallFilterParameters,\n UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n VerifyHashErrorType as VerifyHashActionErrorType,\n VerifyHashParameters as VerifyHashActionParameters,\n VerifyHashReturnType as VerifyHashActionReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n VerifyMessageErrorType as VerifyMessageActionErrorType,\n VerifyMessageParameters as VerifyMessageActionParameters,\n VerifyMessageReturnType as VerifyMessageActionReturnType,\n} from './actions/public/verifyMessage.js'\nexport type {\n VerifyTypedDataErrorType as VerifyTypedDataActionErrorType,\n VerifyTypedDataParameters as VerifyTypedDataActionParameters,\n VerifyTypedDataReturnType as VerifyTypedDataActionReturnType,\n} from './actions/public/verifyTypedData.js'\nexport type {\n ReplacementReason,\n ReplacementReturnType,\n WaitForTransactionReceiptErrorType,\n WaitForTransactionReceiptParameters,\n WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n OnBlockNumberFn,\n OnBlockNumberParameter,\n WatchBlockNumberErrorType,\n WatchBlockNumberParameters,\n WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n OnBlock,\n OnBlockParameter,\n WatchBlocksErrorType,\n WatchBlocksParameters,\n WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n WatchContractEventErrorType,\n WatchContractEventOnLogsFn,\n WatchContractEventOnLogsParameter,\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n WatchEventErrorType,\n WatchEventOnLogsFn,\n WatchEventOnLogsParameter,\n WatchEventParameters,\n WatchEventReturnType,\n} from './actions/public/watchEvent.js'\nexport type {\n OnTransactionsFn,\n OnTransactionsParameter,\n WatchPendingTransactionsErrorType,\n WatchPendingTransactionsParameters,\n WatchPendingTransactionsReturnType,\n} from './actions/public/watchPendingTransactions.js'\nexport type {\n DropTransactionErrorType,\n DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n DumpStateErrorType,\n DumpStateReturnType,\n} from './actions/test/dumpState.js'\nexport type {\n GetAutomineErrorType,\n GetAutomineReturnType,\n} from './actions/test/getAutomine.js'\nexport type {\n GetTxpoolContentErrorType,\n GetTxpoolContentReturnType,\n} from './actions/test/getTxpoolContent.js'\nexport type {\n GetTxpoolStatusErrorType,\n GetTxpoolStatusReturnType,\n} from './actions/test/getTxpoolStatus.js'\nexport type {\n ImpersonateAccountErrorType,\n ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n IncreaseTimeErrorType,\n IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type {\n InspectTxpoolErrorType,\n InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type {\n LoadStateErrorType,\n LoadStateParameters,\n LoadStateReturnType,\n} from './actions/test/loadState.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type { RemoveBlockTimestampIntervalErrorType } from './actions/test/removeBlockTimestampInterval.js'\nexport type { ResetErrorType, ResetParameters } from './actions/test/reset.js'\nexport type {\n RevertErrorType,\n RevertParameters,\n} from './actions/test/revert.js'\nexport type {\n SendUnsignedTransactionErrorType,\n SendUnsignedTransactionParameters,\n SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type { SetAutomineErrorType } from './actions/test/setAutomine.js'\nexport type {\n SetBalanceErrorType,\n SetBalanceParameters,\n} from './actions/test/setBalance.js'\nexport type {\n SetBlockGasLimitErrorType,\n SetBlockGasLimitParameters,\n} from './actions/test/setBlockGasLimit.js'\nexport type {\n SetBlockTimestampIntervalErrorType,\n SetBlockTimestampIntervalParameters,\n} from './actions/test/setBlockTimestampInterval.js'\nexport type {\n SetCodeErrorType,\n SetCodeParameters,\n} from './actions/test/setCode.js'\nexport type {\n SetCoinbaseErrorType,\n SetCoinbaseParameters,\n} from './actions/test/setCoinbase.js'\nexport type {\n SetIntervalMiningErrorType,\n SetIntervalMiningParameters,\n} from './actions/test/setIntervalMining.js'\nexport type { SetLoggingEnabledErrorType } from './actions/test/setLoggingEnabled.js'\nexport type {\n SetMinGasPriceErrorType,\n SetMinGasPriceParameters,\n} from './actions/test/setMinGasPrice.js'\nexport type {\n SetNextBlockBaseFeePerGasErrorType,\n SetNextBlockBaseFeePerGasParameters,\n} from './actions/test/setNextBlockBaseFeePerGas.js'\nexport type {\n SetNextBlockTimestampErrorType,\n SetNextBlockTimestampParameters,\n} from './actions/test/setNextBlockTimestamp.js'\nexport type {\n SetNonceErrorType,\n SetNonceParameters,\n} from './actions/test/setNonce.js'\nexport type { SetRpcUrlErrorType } from './actions/test/setRpcUrl.js'\nexport type {\n SetStorageAtErrorType,\n SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type { SnapshotErrorType } from './actions/test/snapshot.js'\nexport type {\n StopImpersonatingAccountErrorType,\n StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n AddChainErrorType,\n AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport type {\n DeployContractErrorType,\n DeployContractParameters,\n DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n GetAddressesErrorType,\n GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n GetCallsStatusErrorType,\n GetCallsStatusParameters,\n GetCallsStatusReturnType,\n} from './actions/wallet/getCallsStatus.js'\nexport type {\n GetCapabilitiesErrorType,\n GetCapabilitiesParameters,\n GetCapabilitiesReturnType,\n} from './actions/wallet/getCapabilities.js'\nexport type {\n GetPermissionsErrorType,\n GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n PrepareAuthorizationErrorType,\n PrepareAuthorizationParameters,\n PrepareAuthorizationReturnType,\n} from './actions/wallet/prepareAuthorization.js'\nexport type {\n PrepareTransactionRequestErrorType,\n PrepareTransactionRequestParameters,\n PrepareTransactionRequestParameterType,\n PrepareTransactionRequestRequest,\n PrepareTransactionRequestReturnType,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n RequestAddressesErrorType,\n RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n RequestPermissionsErrorType,\n RequestPermissionsParameters,\n RequestPermissionsReturnType,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n SendCallsErrorType,\n SendCallsParameters,\n SendCallsReturnType,\n} from './actions/wallet/sendCalls.js'\nexport type {\n SendCallsSyncErrorType,\n SendCallsSyncParameters,\n SendCallsSyncReturnType,\n} from './actions/wallet/sendCallsSync.js'\nexport type {\n SendRawTransactionErrorType,\n SendRawTransactionParameters,\n SendRawTransactionReturnType,\n} from './actions/wallet/sendRawTransaction.js'\nexport type {\n SendRawTransactionSyncErrorType,\n SendRawTransactionSyncParameters,\n SendRawTransactionSyncReturnType,\n} from './actions/wallet/sendRawTransactionSync.js'\nexport type {\n SendTransactionErrorType,\n SendTransactionParameters,\n SendTransactionRequest,\n SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n SendTransactionSyncErrorType,\n SendTransactionSyncParameters,\n SendTransactionSyncRequest,\n SendTransactionSyncReturnType,\n} from './actions/wallet/sendTransactionSync.js'\nexport type {\n ShowCallsStatusErrorType,\n ShowCallsStatusParameters,\n ShowCallsStatusReturnType,\n} from './actions/wallet/showCallsStatus.js'\nexport type {\n SignAuthorizationErrorType,\n SignAuthorizationParameters,\n SignAuthorizationReturnType,\n} from './actions/wallet/signAuthorization.js'\nexport type {\n SignMessageErrorType,\n SignMessageParameters,\n SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n SignTransactionErrorType,\n SignTransactionParameters,\n SignTransactionRequest,\n SignTransactionReturnType,\n} from './actions/wallet/signTransaction.js'\nexport type {\n SignTypedDataErrorType,\n SignTypedDataParameters,\n SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n SwitchChainErrorType,\n SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n WaitForCallsStatusErrorType,\n WaitForCallsStatusParameters,\n WaitForCallsStatusReturnType,\n WaitForCallsStatusTimeoutErrorType,\n} from './actions/wallet/waitForCallsStatus.js'\nexport { WaitForCallsStatusTimeoutError } from './actions/wallet/waitForCallsStatus.js'\nexport type {\n WatchAssetErrorType,\n WatchAssetParameters,\n WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n WriteContractErrorType,\n WriteContractParameters,\n WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n WriteContractSyncErrorType,\n WriteContractSyncParameters,\n WriteContractSyncReturnType,\n} from './actions/wallet/writeContractSync.js'\nexport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n type MulticallBatchOptions,\n rpcSchema,\n} from './clients/createClient.js'\nexport {\n type CreatePublicClientErrorType,\n createPublicClient,\n type PublicClient,\n type PublicClientConfig,\n} from './clients/createPublicClient.js'\nexport {\n type CreateTestClientErrorType,\n createTestClient,\n type TestClient,\n type TestClientConfig,\n} from './clients/createTestClient.js'\nexport {\n type CreateWalletClientErrorType,\n createWalletClient,\n type WalletClient,\n type WalletClientConfig,\n} from './clients/createWalletClient.js'\nexport {\n type PublicActions,\n publicActions,\n} from './clients/decorators/public.js'\nexport {\n type TestActions,\n testActions,\n} from './clients/decorators/test.js'\nexport {\n type WalletActions,\n walletActions,\n} from './clients/decorators/wallet.js'\nexport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './clients/transports/createTransport.js'\nexport {\n type CustomTransport,\n type CustomTransportConfig,\n type CustomTransportErrorType,\n custom,\n} from './clients/transports/custom.js'\nexport {\n type FallbackTransport,\n type FallbackTransportConfig,\n type FallbackTransportErrorType,\n fallback,\n shouldThrow,\n} from './clients/transports/fallback.js'\nexport {\n type HttpTransport,\n type HttpTransportConfig,\n type HttpTransportErrorType,\n http,\n} from './clients/transports/http.js'\nexport {\n type WebSocketTransport,\n type WebSocketTransportConfig,\n type WebSocketTransportErrorType,\n webSocket,\n} from './clients/transports/webSocket.js'\nexport {\n erc20Abi,\n erc20Abi_bytes32,\n erc721Abi,\n erc1155Abi,\n erc4626Abi,\n erc6492SignatureValidatorAbi,\n /** @deprecated use `erc6492SignatureValidatorAbi` instead. */\n erc6492SignatureValidatorAbi as universalSignatureValidatorAbi,\n multicall3Abi,\n} from './constants/abis.js'\nexport { ethAddress, zeroAddress } from './constants/address.js'\nexport { zeroHash } from './constants/bytes.js'\nexport {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n erc6492SignatureValidatorByteCode,\n /** @deprecated use `erc6492SignatureValidatorByteCode` instead. */\n erc6492SignatureValidatorByteCode as universalSignatureValidatorByteCode,\n} from './constants/contracts.js'\nexport {\n maxInt8,\n maxInt16,\n maxInt24,\n maxInt32,\n maxInt40,\n maxInt48,\n maxInt56,\n maxInt64,\n maxInt72,\n maxInt80,\n maxInt88,\n maxInt96,\n maxInt104,\n maxInt112,\n maxInt120,\n maxInt128,\n maxInt136,\n maxInt144,\n maxInt152,\n maxInt160,\n maxInt168,\n maxInt176,\n maxInt184,\n maxInt192,\n maxInt200,\n maxInt208,\n maxInt216,\n maxInt224,\n maxInt232,\n maxInt240,\n maxInt248,\n maxInt256,\n maxUint8,\n maxUint16,\n maxUint24,\n maxUint32,\n maxUint40,\n maxUint48,\n maxUint56,\n maxUint64,\n maxUint72,\n maxUint80,\n maxUint88,\n maxUint96,\n maxUint104,\n maxUint112,\n maxUint120,\n maxUint128,\n maxUint136,\n maxUint144,\n maxUint152,\n maxUint160,\n maxUint168,\n maxUint176,\n maxUint184,\n maxUint192,\n maxUint200,\n maxUint208,\n maxUint216,\n maxUint224,\n maxUint232,\n maxUint240,\n maxUint248,\n maxUint256,\n minInt8,\n minInt16,\n minInt24,\n minInt32,\n minInt40,\n minInt48,\n minInt56,\n minInt64,\n minInt72,\n minInt80,\n minInt88,\n minInt96,\n minInt104,\n minInt112,\n minInt120,\n minInt128,\n minInt136,\n minInt144,\n minInt152,\n minInt160,\n minInt168,\n minInt176,\n minInt184,\n minInt192,\n minInt200,\n minInt208,\n minInt216,\n minInt224,\n minInt232,\n minInt240,\n minInt248,\n minInt256,\n} from './constants/number.js'\nexport { presignMessagePrefix } from './constants/strings.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.js'\nexport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n type AbiConstructorParamsNotFoundErrorType,\n AbiDecodingDataSizeInvalidError,\n type AbiDecodingDataSizeInvalidErrorType,\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiDecodingZeroDataError,\n type AbiDecodingZeroDataErrorType,\n AbiEncodingArrayLengthMismatchError,\n type AbiEncodingArrayLengthMismatchErrorType,\n AbiEncodingBytesSizeMismatchError,\n type AbiEncodingBytesSizeMismatchErrorType,\n AbiEncodingLengthMismatchError,\n type AbiEncodingLengthMismatchErrorType,\n AbiErrorInputsNotFoundError,\n type AbiErrorInputsNotFoundErrorType,\n AbiErrorNotFoundError,\n type AbiErrorNotFoundErrorType,\n AbiErrorSignatureNotFoundError,\n type AbiErrorSignatureNotFoundErrorType,\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n AbiFunctionSignatureNotFoundError,\n type AbiFunctionSignatureNotFoundErrorType,\n BytesSizeMismatchError,\n type BytesSizeMismatchErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n InvalidAbiEncodingTypeError,\n type InvalidAbiEncodingTypeErrorType,\n InvalidArrayError,\n type InvalidArrayErrorType,\n InvalidDefinitionTypeError,\n type InvalidDefinitionTypeErrorType,\n UnsupportedPackedAbiType,\n type UnsupportedPackedAbiTypeErrorType,\n} from './errors/abi.js'\nexport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from './errors/address.js'\nexport { BaseError, type BaseErrorType, setErrorConfig } from './errors/base.js'\nexport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n BundleFailedError,\n type BundleFailedErrorType,\n} from './errors/calls.js'\nexport {\n ChainDoesNotSupportContract,\n type ChainDoesNotSupportContractErrorType,\n ChainMismatchError,\n type ChainMismatchErrorType,\n ChainNotFoundError,\n type ChainNotFoundErrorType,\n ClientChainNotConfiguredError,\n type ClientChainNotConfiguredErrorType,\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from './errors/chain.js'\nexport {\n CallExecutionError,\n type CallExecutionErrorType,\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n CounterfactualDeploymentFailedError,\n type CounterfactualDeploymentFailedErrorType,\n RawContractError,\n type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n SliceOffsetOutOfBoundsError,\n type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n InvalidBytesBooleanError,\n type InvalidBytesBooleanErrorType,\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n InvalidHexValueError,\n type InvalidHexValueErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n type EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n EnsInvalidChainIdError,\n type EnsInvalidChainIdErrorType,\n} from './errors/ens.js'\nexport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n MaxFeePerGasTooLowError,\n type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from './errors/log.js'\nexport {\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'\nexport {\n HttpRequestError,\n type HttpRequestErrorType,\n RpcRequestError,\n type RpcRequestErrorType,\n SocketClosedError,\n type SocketClosedErrorType,\n TimeoutError,\n type TimeoutErrorType,\n WebSocketRequestError,\n type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n ProviderRpcError,\n type ProviderRpcErrorCode,\n type ProviderRpcErrorType,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from './errors/stateOverride.js'\nexport {\n FeeConflictError,\n type FeeConflictErrorType,\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n InvalidSerializedTransactionError,\n type InvalidSerializedTransactionErrorType,\n InvalidSerializedTransactionTypeError,\n type InvalidSerializedTransactionTypeErrorType,\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from './errors/transaction.js'\nexport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport {\n InvalidDomainError,\n type InvalidDomainErrorType,\n InvalidPrimaryTypeError,\n type InvalidPrimaryTypeErrorType,\n InvalidStructTypeError,\n type InvalidStructTypeErrorType,\n} from './errors/typedData.js'\nexport {\n InvalidDecimalNumberError,\n type InvalidDecimalNumberErrorType,\n} from './errors/unit.js'\nexport type {\n DeriveAccount,\n HDKey,\n ParseAccount,\n} from './types/account.js'\nexport type {\n Authorization,\n AuthorizationList,\n AuthorizationRequest,\n SerializedAuthorization,\n SerializedAuthorizationList,\n SignedAuthorization,\n SignedAuthorizationList,\n} from './types/authorization.js'\nexport type {\n Block,\n BlockIdentifier,\n BlockNumber,\n BlockTag,\n Uncle,\n} from './types/block.js'\nexport type { Call, Calls } from './types/calls.js'\nexport type {\n Capabilities,\n /** @deprecated Use `Capabilities` instead. */\n Capabilities as WalletCapabilities,\n CapabilitiesSchema,\n /** @deprecated Use `ChainIdToCapabilities` instead. */\n ChainIdToCapabilities as WalletCapabilitiesRecord,\n ChainIdToCapabilities,\n ExtractCapabilities,\n} from './types/capabilities.js'\nexport type {\n Chain,\n ChainConfig,\n ChainContract,\n ChainEstimateFeesPerGasFn,\n ChainEstimateFeesPerGasFnParameters,\n ChainFees,\n ChainFeesFnParameters,\n ChainFormatter,\n ChainFormatters,\n ChainMaxPriorityFeePerGasFn,\n ChainSerializers,\n DeriveChain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterParameters,\n ExtractChainFormatterReturnType,\n GetChainParameter,\n} from './types/chain.js'\nexport type {\n AbiEventParametersToPrimitiveTypes,\n AbiEventParameterToPrimitiveType,\n AbiEventTopicToPrimitiveType,\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ContractConstructorArgs,\n ContractErrorArgs,\n ContractErrorName,\n ContractEventArgs,\n ContractEventArgsFromTopics,\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n EventDefinition,\n ExtractAbiFunctionForArgs,\n ExtractAbiItem,\n ExtractAbiItemForArgs,\n ExtractAbiItemNames,\n GetEventArgs,\n GetValue,\n LogTopicType,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n UnionWiden,\n Widen,\n} from './types/contract.js'\nexport type { DataSuffix } from './types/dataSuffix.js'\nexport type {\n AddEthereumChainParameter,\n BundlerRpcSchema,\n DebugBundlerRpcSchema,\n EIP1193EventMap,\n EIP1193Events,\n EIP1193Parameters,\n EIP1193Provider,\n EIP1193RequestFn,\n EIP1474Methods,\n NetworkSync,\n PaymasterRpcSchema,\n ProviderConnectInfo,\n ProviderMessage,\n ProviderRpcErrorType as EIP1193ProviderRpcErrorType,\n PublicRpcSchema,\n RpcSchema,\n RpcSchemaOverride,\n TestRpcSchema,\n WalletCallReceipt,\n WalletGetAssetsParameters,\n WalletGetAssetsReturnType,\n WalletGetCallsStatusReturnType,\n WalletGrantPermissionsParameters,\n WalletGrantPermissionsReturnType,\n WalletPermission,\n WalletPermissionCaveat,\n WalletRpcSchema,\n WalletSendCallsParameters,\n WalletSendCallsReturnType,\n WatchAssetParams,\n} from './types/eip1193.js'\nexport { ProviderRpcError as EIP1193ProviderRpcError } from './types/eip1193.js'\nexport type { BlobSidecar, BlobSidecars } from './types/eip4844.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n FeeHistory,\n FeeValues,\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n FeeValuesType,\n} from './types/fee.js'\nexport type { Filter, FilterType } from './types/filter.js'\nexport type { GetTransactionRequestKzgParameter, Kzg } from './types/kzg.js'\nexport type { Log } from './types/log.js'\nexport type {\n ByteArray,\n CompactSignature,\n Hash,\n Hex,\n LogTopic,\n SignableMessage,\n Signature,\n} from './types/misc.js'\nexport type {\n MulticallContracts,\n MulticallResponse,\n MulticallResults,\n} from './types/multicall.js'\nexport type { Register, ResolvedRegister } from './types/register.js'\nexport type {\n Index,\n Quantity,\n RpcAccountStateOverride,\n RpcAuthorization,\n RpcAuthorizationList,\n RpcBlock,\n RpcBlockIdentifier,\n RpcBlockNumber,\n RpcFeeHistory,\n RpcFeeValues,\n RpcLog,\n RpcProof,\n RpcStateMapping,\n RpcStateOverride,\n RpcTransaction,\n RpcTransactionReceipt,\n RpcTransactionRequest,\n RpcUncle,\n Status,\n} from './types/rpc.js'\nexport type {\n StateMapping,\n StateOverride,\n} from './types/stateOverride.js'\nexport type {\n AccessList,\n Transaction,\n TransactionBase,\n TransactionEIP1559,\n TransactionEIP2930,\n TransactionEIP4844,\n TransactionEIP7702,\n TransactionLegacy,\n TransactionReceipt,\n TransactionRequest,\n TransactionRequestBase,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestGeneric,\n TransactionRequestLegacy,\n TransactionSerializable,\n TransactionSerializableBase,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionSerializedLegacy,\n TransactionType,\n} from './types/transaction.js'\nexport type { GetPollOptions, GetTransportConfig } from './types/transport.js'\nexport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from './types/typedData.js'\nexport type {\n Assign,\n Branded,\n Evaluate,\n ExactPartial,\n ExactRequired,\n IsNarrowable,\n IsNever,\n IsUndefined,\n IsUnion,\n LooseOmit,\n MaybePartial,\n MaybePromise,\n MaybeRequired,\n Mutable,\n NoInfer,\n NoUndefined,\n Omit,\n OneOf,\n Or,\n PartialBy,\n Prettify,\n RequiredBy,\n Some,\n UnionEvaluate,\n UnionLooseOmit,\n UnionOmit,\n UnionPartialBy,\n UnionPick,\n UnionRequiredBy,\n UnionToTuple,\n ValueOf,\n} from './types/utils.js'\nexport type { Withdrawal } from './types/withdrawal.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './utils/abi/decodeAbiParameters.js'\nexport {\n type DecodeDeployDataErrorType,\n type DecodeDeployDataParameters,\n type DecodeDeployDataReturnType,\n decodeDeployData,\n} from './utils/abi/decodeDeployData.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './utils/abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './utils/abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './utils/abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './utils/abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './utils/abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n type EncodeDeployDataReturnType,\n encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n type EncodeErrorResultReturnType,\n encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n type EncodeFunctionDataReturnType,\n encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n type EncodeFunctionResultReturnType,\n encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n type EncodePackedErrorType,\n encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n type GetAbiItemReturnType,\n getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './utils/abi/parseEventLogs.js'\nexport {\n type PrepareEncodeFunctionDataErrorType,\n type PrepareEncodeFunctionDataParameters,\n type PrepareEncodeFunctionDataReturnType,\n prepareEncodeFunctionData,\n} from './utils/abi/prepareEncodeFunctionData.js'\nexport {\n type ChecksumAddressErrorType,\n checksumAddress,\n type GetAddressErrorType,\n getAddress,\n} from './utils/address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n type IsAddressErrorType,\n type IsAddressOptions,\n isAddress,\n} from './utils/address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n type IsAddressEqualReturnType,\n isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport {\n type BlobsToCommitmentsErrorType,\n type BlobsToCommitmentsParameters,\n type BlobsToCommitmentsReturnType,\n blobsToCommitments,\n} from './utils/blob/blobsToCommitments.js'\nexport {\n blobsToProofs,\n type blobsToProofsErrorType,\n type blobsToProofsParameters,\n type blobsToProofsReturnType,\n} from './utils/blob/blobsToProofs.js'\nexport {\n type CommitmentsToVersionedHashesErrorType,\n type CommitmentsToVersionedHashesParameters,\n type CommitmentsToVersionedHashesReturnType,\n commitmentsToVersionedHashes,\n} from './utils/blob/commitmentsToVersionedHashes.js'\nexport {\n type CommitmentToVersionedHashErrorType,\n type CommitmentToVersionedHashParameters,\n type CommitmentToVersionedHashReturnType,\n commitmentToVersionedHash,\n} from './utils/blob/commitmentToVersionedHash.js'\nexport {\n type FromBlobsErrorType,\n type FromBlobsParameters,\n type FromBlobsReturnType,\n fromBlobs,\n} from './utils/blob/fromBlobs.js'\nexport {\n type SidecarsToVersionedHashesErrorType,\n type SidecarsToVersionedHashesParameters,\n type SidecarsToVersionedHashesReturnType,\n sidecarsToVersionedHashes,\n} from './utils/blob/sidecarsToVersionedHashes.js'\nexport {\n type ToBlobSidecarsErrorType,\n type ToBlobSidecarsParameters,\n type ToBlobSidecarsReturnType,\n toBlobSidecars,\n} from './utils/blob/toBlobSidecars.js'\nexport {\n type ToBlobsErrorType,\n type ToBlobsParameters,\n type ToBlobsReturnType,\n toBlobs,\n} from './utils/blob/toBlobs.js'\nexport {\n type CcipRequestErrorType,\n type CcipRequestParameters,\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport {\n type DefineChainReturnType,\n defineChain,\n extendSchema,\n} from './utils/chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './utils/chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './utils/chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n type ConcatReturnType,\n concat,\n concatBytes,\n concatHex,\n} from './utils/data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n type PadReturnType,\n pad,\n padBytes,\n padHex,\n} from './utils/data/pad.js'\nexport { type SizeErrorType, size } from './utils/data/size.js'\nexport {\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n slice,\n sliceBytes,\n sliceHex,\n} from './utils/data/slice.js'\nexport {\n type TrimErrorType,\n type TrimReturnType,\n trim,\n} from './utils/data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n type FromHexErrorType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBoolErrorType,\n type HexToNumberErrorType,\n type HexToStringErrorType,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './utils/encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n type FromRlpReturnType,\n fromRlp,\n} from './utils/encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './utils/encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './utils/encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n bytesToRlp,\n type HexToRlpErrorType,\n hexToRlp,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './utils/encoding/toRlp.js'\nexport { type LabelhashErrorType, labelhash } from './utils/ens/labelhash.js'\nexport { type NamehashErrorType, namehash } from './utils/ens/namehash.js'\nexport {\n type ToCoinTypeError,\n toCoinType,\n} from './utils/ens/toCoinType.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './utils/formatters/block.js'\nexport { type FormatLogErrorType, formatLog } from './utils/formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport {\n type Keccak256ErrorType,\n type Keccak256Hash,\n keccak256,\n} from './utils/hash/keccak256.js'\nexport {\n type Ripemd160ErrorType,\n type Ripemd160Hash,\n ripemd160,\n} from './utils/hash/ripemd160.js'\nexport {\n type Sha256ErrorType,\n type Sha256Hash,\n sha256,\n} from './utils/hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './utils/hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './utils/hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './utils/hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './utils/hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './utils/hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './utils/hash/toFunctionSignature.js'\nexport {\n type DefineKzgErrorType,\n type DefineKzgParameters,\n type DefineKzgReturnType,\n defineKzg,\n} from './utils/kzg/defineKzg.js'\nexport {\n type SetupKzgErrorType,\n type SetupKzgParameters,\n type SetupKzgReturnType,\n setupKzg,\n} from './utils/kzg/setupKzg.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './utils/nonceManager.js'\nexport { withCache } from './utils/promise/withCache.js'\nexport {\n type WithRetryErrorType,\n withRetry,\n} from './utils/promise/withRetry.js'\nexport {\n type WithTimeoutErrorType,\n withTimeout,\n} from './utils/promise/withTimeout.js'\nexport {\n type CompactSignatureToSignatureErrorType,\n compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n type HashMessageErrorType,\n hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashDomain,\n hashStruct,\n hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './utils/signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './utils/signature/isErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseCompactSignatureErrorType`. */\n type ParseCompactSignatureErrorType as HexToCompactSignatureErrorType,\n type ParseCompactSignatureErrorType,\n /** @deprecated Use `parseCompactSignature`. */\n parseCompactSignature as hexToCompactSignature,\n parseCompactSignature,\n} from './utils/signature/parseCompactSignature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './utils/signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './utils/signature/parseErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseSignatureErrorType`. */\n type ParseSignatureErrorType as HexToSignatureErrorType,\n type ParseSignatureErrorType,\n /** @deprecated Use `parseSignature`. */\n parseSignature as hexToSignature,\n parseSignature,\n} from './utils/signature/parseSignature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './utils/signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './utils/signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './utils/signature/recoverPublicKey.js'\nexport {\n type RecoverTransactionAddressErrorType,\n type RecoverTransactionAddressParameters,\n type RecoverTransactionAddressReturnType,\n recoverTransactionAddress,\n} from './utils/signature/recoverTransactionAddress.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeCompactSignatureErrorType as CompactSignatureToHexErrorType,\n type SerializeCompactSignatureErrorType,\n /** @deprecated Use `serializeCompactSignature` instead. */\n serializeCompactSignature as compactSignatureToHex,\n serializeCompactSignature,\n} from './utils/signature/serializeCompactSignature.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './utils/signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './utils/signature/serializeErc8010Signature.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n type SerializeSignatureParameters,\n type SerializeSignatureReturnType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from './utils/signature/serializeSignature.js'\nexport {\n type SignatureToCompactSignatureErrorType,\n signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n type ToPrefixedMessageErrorType,\n toPrefixedMessage,\n} from './utils/signature/toPrefixedMessage.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './utils/signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './utils/signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './utils/signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n type ParseTransactionReturnType,\n parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n type SerializedTransactionReturnType,\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './utils/transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n domainSeparator,\n type GetTypesForEIP712DomainErrorType,\n getTypesForEIP712Domain,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './utils/typedData.js'\nexport {\n type FormatEtherErrorType,\n formatEther,\n} from './utils/unit/formatEther.js'\nexport {\n type FormatGweiErrorType,\n formatGwei,\n} from './utils/unit/formatGwei.js'\nexport {\n type FormatUnitsErrorType,\n formatUnits,\n} from './utils/unit/formatUnits.js'\nexport {\n type ParseEtherErrorType,\n parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n type ParseUnitsErrorType,\n parseUnits,\n} from './utils/unit/parseUnits.js'\n","import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: Hash,\n PRFSalt: Hash,\n DK: Uint8Array,\n prfW: Hash,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/**\n * Audited & minimal JS implementation of\n * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).\n * @module\n * @example\n```js\nimport * as bip39 from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nconst mn = bip39.generateMnemonic(wordlist);\nconsole.log(mn);\nconst ent = bip39.mnemonicToEntropy(mn, wordlist)\nbip39.entropyToMnemonic(ent, wordlist);\nbip39.validateMnemonic(mn, wordlist);\nawait bip39.mnemonicToSeed(mn, 'password');\nbip39.mnemonicToSeedSync(mn, 'password');\n\n// Wordlists\nimport { wordlist as czech } from '@scure/bip39/wordlists/czech';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { wordlist as french } from '@scure/bip39/wordlists/french';\nimport { wordlist as italian } from '@scure/bip39/wordlists/italian';\nimport { wordlist as japanese } from '@scure/bip39/wordlists/japanese';\nimport { wordlist as korean } from '@scure/bip39/wordlists/korean';\nimport { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';\nimport { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';\nimport { wordlist as spanish } from '@scure/bip39/wordlists/spanish';\nimport { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';\n```\n */\n/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n abytes(ent, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.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 { 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 signAuthorization(authorization) {\n return 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","// 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 type { ErrorType } from '../errors/utils.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.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 signAuthorization: source.signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\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 { type IsHexErrorType, isHex } from '../../utils/data/isHex.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 { 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 =\n | HexToBytesErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | 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 {\n lowS: true,\n extraEntropy: isHex(extraEntropy, { strict: false })\n ? hexToBytes(extraEntropy)\n : extraEntropy,\n },\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 type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../utils/authorization/hashAuthorization.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 AuthorizationRequest & {\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 signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const { chainId, nonce, privateKey, to = 'object' } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n address,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\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 { 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(await serializer(signableTransaction)),\n privateKey,\n })\n return (await serializer(\n transaction,\n signature,\n )) as SignTransactionReturnType\n}\n","import type { TypedData } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\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'\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 [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):\n * `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(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","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","export const x402Version = 2;\n","import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData {\n facilitator: T;\n networks: Set;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = (\n map: Map>,\n network: Network,\n): Map | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = (\n map: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = (\n schemeMap: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record = {};\n Object.keys(obj as Record)\n .sort()\n .forEach(key => {\n const value = (obj as Record)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n","import { x402ResourceServer } from \"../server\";\nimport {\n decodePaymentSignatureHeader,\n encodePaymentRequiredHeader,\n encodePaymentResponseHeader,\n} from \".\";\nimport {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n SettleError,\n Price,\n Network,\n PaymentRequirements,\n} from \"../types\";\nimport { x402Version } from \"..\";\n\n/**\n * Framework-agnostic HTTP adapter interface\n * Implementations provide framework-specific HTTP operations\n */\nexport interface HTTPAdapter {\n getHeader(name: string): string | undefined;\n getMethod(): string;\n getPath(): string;\n getUrl(): string;\n getAcceptHeader(): string;\n getUserAgent(): string;\n\n /**\n * Get query parameters from the request URL\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams?(): Record;\n\n /**\n * Get a specific query parameter by name\n *\n * @param name - The query parameter name\n * @returns The query parameter value(s) or undefined\n */\n getQueryParam?(name: string): string | string[] | undefined;\n\n /**\n * Get the parsed request body\n * Framework adapters should parse JSON/form data appropriately\n *\n * @returns The parsed request body\n */\n getBody?(): unknown;\n}\n\n/**\n * Paywall configuration for HTML responses\n */\nexport interface PaywallConfig {\n appName?: string;\n appLogo?: string;\n sessionTokenEndpoint?: string;\n currentUrl?: string;\n testnet?: boolean;\n}\n\n/**\n * Paywall provider interface for generating HTML\n */\nexport interface PaywallProvider {\n generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;\n}\n\n/**\n * Dynamic payTo function that receives HTTP request context\n */\nexport type DynamicPayTo = (context: HTTPRequestContext) => string | Promise;\n\n/**\n * Dynamic price function that receives HTTP request context\n */\nexport type DynamicPrice = (context: HTTPRequestContext) => Price | Promise;\n\n/**\n * Result of response body callbacks containing content type and body.\n */\nexport interface HTTPResponseBody {\n /**\n * The content type for the response (e.g., 'application/json', 'text/plain').\n */\n contentType: string;\n\n /**\n * The response body to include in the 402 response.\n */\n body: unknown;\n}\n\n/**\n * Dynamic function to generate a custom response for unpaid requests.\n * Receives the HTTP request context and returns the content type and body to include in the 402 response.\n */\nexport type UnpaidResponseBody = (\n context: HTTPRequestContext,\n) => HTTPResponseBody | Promise;\n\n/**\n * Dynamic function to generate a custom response for settlement failures.\n * Receives the HTTP request context and settle failure result, returns the content type and body.\n */\nexport type SettlementFailedResponseBody = (\n context: HTTPRequestContext,\n settleResult: Omit,\n) => HTTPResponseBody | Promise;\n\n/**\n * A single payment option for a route\n * Represents one way a client can pay for access to the resource\n */\nexport interface PaymentOption {\n scheme: string;\n payTo: string | DynamicPayTo;\n price: Price | DynamicPrice;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record;\n}\n\n/**\n * Route configuration for HTTP endpoints\n *\n * The 'accepts' field defines payment options for the route.\n * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.\n */\nexport interface RouteConfig {\n // Payment option(s): single or array\n accepts: PaymentOption | PaymentOption[];\n\n // HTTP-specific metadata\n resource?: string;\n description?: string;\n mimeType?: string;\n customPaywallHtml?: string;\n\n /**\n * Optional callback to generate a custom response for unpaid API requests.\n * This allows servers to return preview data, error messages, or other content\n * when a request lacks payment.\n *\n * For browser requests (Accept: text/html), the paywall HTML takes precedence.\n * This callback is only used for API clients.\n *\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @returns An object containing both contentType and body for the 402 response\n */\n unpaidResponseBody?: UnpaidResponseBody;\n\n /**\n * Optional callback to generate a custom response for settlement failures.\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @param settleResult - The settlement failure result\n * @returns An object containing both contentType and body for the 402 response\n */\n settlementFailedResponseBody?: SettlementFailedResponseBody;\n\n // Extensions\n extensions?: Record;\n}\n\n/**\n * Routes configuration - maps path patterns to route configs\n */\nexport type RoutesConfig = Record | RouteConfig;\n\n/**\n * Hook that runs on every request to a protected route, before payment processing.\n * Can grant access without payment, deny the request, or continue to payment flow.\n *\n * @returns\n * - `void` - Continue to payment processing (default behavior)\n * - `{ grantAccess: true }` - Grant access without requiring payment\n * - `{ abort: true; reason: string }` - Deny the request (returns 403)\n */\nexport type ProtectedRequestHook = (\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n) => Promise;\n\n/**\n * Compiled route for efficient matching\n */\nexport interface CompiledRoute {\n verb: string;\n regex: RegExp;\n config: RouteConfig;\n}\n\n/**\n * HTTP request context that encapsulates all request data\n */\nexport interface HTTPRequestContext {\n adapter: HTTPAdapter;\n path: string;\n method: string;\n paymentHeader?: string;\n}\n\n/**\n * HTTP transport context contains both request context and optional response data.\n */\nexport interface HTTPTransportContext {\n /** The HTTP request context */\n request: HTTPRequestContext;\n /** The response body buffer */\n responseBody?: Buffer;\n}\n\n/**\n * HTTP response instructions for the framework middleware\n */\nexport interface HTTPResponseInstructions {\n status: number;\n headers: Record;\n body?: unknown; // e.g. Paywall for web browser requests, but could be any other type\n isHtml?: boolean; // e.g. if body is a paywall, then isHtml is true\n}\n\n/**\n * Result of processing an HTTP request for payment\n */\nexport type HTTPProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n declaredExtensions?: Record;\n }\n | { type: \"payment-error\"; response: HTTPResponseInstructions };\n\n/**\n * Result of processSettlement\n */\nexport type ProcessSettleSuccessResponse = SettleResponse & {\n success: true;\n headers: Record;\n requirements: PaymentRequirements;\n};\n\nexport type ProcessSettleFailureResponse = SettleResponse & {\n success: false;\n errorReason: string;\n errorMessage?: string;\n headers: Record;\n response: HTTPResponseInstructions;\n};\n\nexport type ProcessSettleResultResponse =\n | ProcessSettleSuccessResponse\n | ProcessSettleFailureResponse;\n\n/**\n * Represents a validation error for a specific route's payment configuration.\n */\nexport interface RouteValidationError {\n /** The route pattern (e.g., \"GET /api/weather\") */\n routePattern: string;\n /** The payment scheme that failed validation */\n scheme: string;\n /** The network that failed validation */\n network: Network;\n /** The type of validation failure */\n reason: \"missing_scheme\" | \"missing_facilitator\";\n /** Human-readable error message */\n message: string;\n}\n\n/**\n * Error thrown when route configuration validation fails.\n */\nexport class RouteConfigurationError extends Error {\n /** The validation errors that caused this exception */\n public readonly errors: RouteValidationError[];\n\n /**\n * Creates a new RouteConfigurationError with the given validation errors.\n *\n * @param errors - The validation errors that caused this exception.\n */\n constructor(errors: RouteValidationError[]) {\n const message = `x402 Route Configuration Errors:\\n${errors.map(e => ` - ${e.message}`).join(\"\\n\")}`;\n super(message);\n this.name = \"RouteConfigurationError\";\n this.errors = errors;\n }\n}\n\n/**\n * HTTP-enhanced x402 resource server\n * Provides framework-agnostic HTTP protocol handling\n */\nexport class x402HTTPResourceServer {\n private ResourceServer: x402ResourceServer;\n private compiledRoutes: CompiledRoute[] = [];\n private routesConfig: RoutesConfig;\n private paywallProvider?: PaywallProvider;\n private protectedRequestHooks: ProtectedRequestHook[] = [];\n\n /**\n * Creates a new x402HTTPResourceServer instance.\n *\n * @param ResourceServer - The core x402ResourceServer instance to use\n * @param routes - Route configuration for payment-protected endpoints\n */\n constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig) {\n this.ResourceServer = ResourceServer;\n this.routesConfig = routes;\n\n // Handle both single route and multiple routes\n const normalizedRoutes =\n typeof routes === \"object\" && !(\"accepts\" in routes)\n ? (routes as Record)\n : { \"*\": routes as RouteConfig };\n\n for (const [pattern, config] of Object.entries(normalizedRoutes)) {\n const parsed = this.parseRoutePattern(pattern);\n this.compiledRoutes.push({\n verb: parsed.verb,\n regex: parsed.regex,\n config,\n });\n }\n }\n\n /**\n * Get the underlying x402ResourceServer instance.\n *\n * @returns The underlying x402ResourceServer instance\n */\n get server(): x402ResourceServer {\n return this.ResourceServer;\n }\n\n /**\n * Get the routes configuration.\n *\n * @returns The routes configuration\n */\n get routes(): RoutesConfig {\n return this.routesConfig;\n }\n\n /**\n * Initialize the HTTP resource server.\n *\n * This method initializes the underlying resource server (fetching facilitator support)\n * and then validates that all route payment configurations have corresponding\n * registered schemes and facilitator support.\n *\n * @throws RouteConfigurationError if any route's payment options don't have\n * corresponding registered schemes or facilitator support\n *\n * @example\n * ```typescript\n * const httpServer = new x402HTTPResourceServer(server, routes);\n * await httpServer.initialize();\n * ```\n */\n async initialize(): Promise {\n // First, initialize the underlying resource server (fetches facilitator support)\n await this.ResourceServer.initialize();\n\n // Then validate route configuration\n const errors = this.validateRouteConfiguration();\n if (errors.length > 0) {\n throw new RouteConfigurationError(errors);\n }\n }\n\n /**\n * Register a custom paywall provider for generating HTML\n *\n * @param provider - PaywallProvider instance\n * @returns This service instance for chaining\n */\n registerPaywallProvider(provider: PaywallProvider): this {\n this.paywallProvider = provider;\n return this;\n }\n\n /**\n * Register a hook that runs on every request to a protected route, before payment processing.\n * Hooks are executed in order of registration. The first hook to return a non-void result wins.\n *\n * @param hook - The request hook function\n * @returns The x402HTTPResourceServer instance for chaining\n */\n onProtectedRequest(hook: ProtectedRequestHook): this {\n this.protectedRequestHooks.push(hook);\n return this;\n }\n\n /**\n * Process HTTP request and return response instructions\n * This is the main entry point for framework middleware\n *\n * @param context - HTTP request context\n * @param paywallConfig - Optional paywall configuration\n * @returns Process result indicating next action for middleware\n */\n async processHTTPRequest(\n context: HTTPRequestContext,\n paywallConfig?: PaywallConfig,\n ): Promise {\n const { adapter, path, method } = context;\n\n // Find matching route\n const routeConfig = this.getRouteConfig(path, method);\n if (!routeConfig) {\n return { type: \"no-payment-required\" }; // No payment required for this route\n }\n\n // Execute request hooks before any payment processing\n for (const hook of this.protectedRequestHooks) {\n const result = await hook(context, routeConfig);\n if (result && \"grantAccess\" in result) {\n return { type: \"no-payment-required\" };\n }\n if (result && \"abort\" in result) {\n return {\n type: \"payment-error\",\n response: {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: result.reason },\n },\n };\n }\n }\n\n // Normalize accepts field to array of payment options\n const paymentOptions = this.normalizePaymentOptions(routeConfig);\n\n // Check for payment header (v1 or v2)\n const paymentPayload = this.extractPayment(adapter);\n\n // Create resource info, using config override if provided\n const resourceInfo = {\n url: routeConfig.resource || context.adapter.getUrl(),\n description: routeConfig.description || \"\",\n mimeType: routeConfig.mimeType || \"\",\n };\n\n // Build requirements from all payment options\n // (this method handles resolving dynamic functions internally)\n let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(\n paymentOptions,\n context,\n );\n\n let extensions = routeConfig.extensions;\n if (extensions) {\n extensions = this.ResourceServer.enrichExtensions(extensions, context);\n }\n\n // createPaymentRequiredResponse already handles extension enrichment in the core layer\n const transportContext: HTTPTransportContext = { request: context };\n const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n !paymentPayload ? \"Payment required\" : undefined,\n extensions,\n transportContext,\n );\n\n // If no payment provided\n if (!paymentPayload) {\n // Resolve custom unpaid response body if provided\n const unpaidBody = routeConfig.unpaidResponseBody\n ? await routeConfig.unpaidResponseBody(context)\n : undefined;\n\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(\n paymentRequired,\n this.isWebBrowser(adapter),\n paywallConfig,\n routeConfig.customPaywallHtml,\n unpaidBody,\n ),\n };\n }\n\n // Verify payment\n try {\n const matchingRequirements = this.ResourceServer.findMatchingRequirements(\n paymentRequired.accepts,\n paymentPayload,\n );\n\n if (!matchingRequirements) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const verifyResult = await this.ResourceServer.verifyPayment(\n paymentPayload,\n matchingRequirements,\n );\n\n if (!verifyResult.isValid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n verifyResult.invalidReason,\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n // Payment is valid, return data needed for settlement\n return {\n type: \"payment-verified\",\n paymentPayload,\n paymentRequirements: matchingRequirements,\n declaredExtensions: routeConfig.extensions,\n };\n } catch (error) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n error instanceof Error ? error.message : \"Payment verification failed\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n }\n\n /**\n * Process settlement after successful response\n *\n * @param paymentPayload - The verified payment payload\n * @param requirements - The matching payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional HTTP transport context\n * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure\n */\n async processSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record,\n transportContext?: HTTPTransportContext,\n ): Promise {\n try {\n const settleResponse = await this.ResourceServer.settlePayment(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n );\n\n if (!settleResponse.success) {\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason: settleResponse.errorReason || \"Settlement failed\",\n errorMessage:\n settleResponse.errorMessage || settleResponse.errorReason || \"Settlement failed\",\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n\n return {\n ...settleResponse,\n success: true,\n headers: this.createSettlementHeaders(settleResponse),\n requirements,\n };\n } catch (error) {\n if (error instanceof SettleError) {\n const errorReason = error.errorReason || error.message;\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: error.errorMessage || errorReason,\n payer: error.payer,\n network: error.network,\n transaction: error.transaction,\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n const errorReason = error instanceof Error ? error.message : \"Settlement failed\";\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: errorReason,\n network: requirements.network as Network,\n transaction: \"\",\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n }\n\n /**\n * Check if a request requires payment based on route configuration\n *\n * @param context - HTTP request context\n * @returns True if the route requires payment, false otherwise\n */\n requiresPayment(context: HTTPRequestContext): boolean {\n const routeConfig = this.getRouteConfig(context.path, context.method);\n return routeConfig !== undefined;\n }\n\n /**\n * Build HTTPResponseInstructions for settlement failure.\n * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.\n *\n * @param failure - Settlement failure result with headers\n * @param transportContext - Optional HTTP transport context for the request\n * @returns HTTP response instructions for the 402 settlement failure response\n */\n private async buildSettlementFailureResponse(\n failure: Omit,\n transportContext?: HTTPTransportContext,\n ): Promise {\n const settlementHeaders = failure.headers;\n const routeConfig = transportContext\n ? this.getRouteConfig(transportContext.request.path, transportContext.request.method)\n : undefined;\n\n const customBody = routeConfig?.settlementFailedResponseBody\n ? await routeConfig.settlementFailedResponseBody(transportContext!.request, failure)\n : undefined;\n\n const contentType = customBody ? customBody.contentType : \"application/json\";\n const body = customBody ? customBody.body : {};\n\n return {\n status: 402,\n headers: {\n \"Content-Type\": contentType,\n ...settlementHeaders,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n };\n }\n\n /**\n * Normalizes a RouteConfig's accepts field into an array of PaymentOptions\n * Handles both single PaymentOption and array formats\n *\n * @param routeConfig - Route configuration\n * @returns Array of payment options\n */\n private normalizePaymentOptions(routeConfig: RouteConfig): PaymentOption[] {\n return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];\n }\n\n /**\n * Validates that all payment options in routes have corresponding registered schemes\n * and facilitator support.\n *\n * @returns Array of validation errors (empty if all routes are valid)\n */\n private validateRouteConfiguration(): RouteValidationError[] {\n const errors: RouteValidationError[] = [];\n\n // Normalize routes to array of [pattern, config] pairs\n const normalizedRoutes =\n typeof this.routesConfig === \"object\" && !(\"accepts\" in this.routesConfig)\n ? Object.entries(this.routesConfig as Record)\n : [[\"*\", this.routesConfig as RouteConfig] as [string, RouteConfig]];\n\n for (const [pattern, config] of normalizedRoutes) {\n const paymentOptions = this.normalizePaymentOptions(config);\n\n for (const option of paymentOptions) {\n // Check 1: Is scheme registered?\n if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_scheme\",\n message: `Route \"${pattern}\": No scheme implementation registered for \"${option.scheme}\" on network \"${option.network}\"`,\n });\n // Skip facilitator check if scheme isn't registered\n continue;\n }\n\n // Check 2: Does facilitator support this scheme/network combination?\n const supportedKind = this.ResourceServer.getSupportedKind(\n x402Version,\n option.network,\n option.scheme,\n );\n\n if (!supportedKind) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_facilitator\",\n message: `Route \"${pattern}\": Facilitator does not support scheme \"${option.scheme}\" on network \"${option.network}\"`,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get route configuration for a request\n *\n * @param path - Request path\n * @param method - HTTP method\n * @returns Route configuration or undefined if no match\n */\n private getRouteConfig(path: string, method: string): RouteConfig | undefined {\n const normalizedPath = this.normalizePath(path);\n const upperMethod = method.toUpperCase();\n\n const matchingRoute = this.compiledRoutes.find(\n route =>\n route.regex.test(normalizedPath) && (route.verb === \"*\" || route.verb === upperMethod),\n );\n\n return matchingRoute?.config;\n }\n\n /**\n * Extract payment from HTTP headers (handles v1 and v2)\n *\n * @param adapter - HTTP adapter\n * @returns Decoded payment payload or null\n */\n private extractPayment(adapter: HTTPAdapter): PaymentPayload | null {\n // Check v2 header first (PAYMENT-SIGNATURE)\n const header = adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"PAYMENT-SIGNATURE\");\n\n if (header) {\n try {\n return decodePaymentSignatureHeader(header);\n } catch (error) {\n console.warn(\"Failed to decode PAYMENT-SIGNATURE header:\", error);\n }\n }\n\n return null;\n }\n\n /**\n * Check if request is from a web browser\n *\n * @param adapter - HTTP adapter\n * @returns True if request appears to be from a browser\n */\n private isWebBrowser(adapter: HTTPAdapter): boolean {\n const accept = adapter.getAcceptHeader();\n const userAgent = adapter.getUserAgent();\n return accept.includes(\"text/html\") && userAgent.includes(\"Mozilla\");\n }\n\n /**\n * Create HTTP response instructions from payment required\n *\n * @param paymentRequired - Payment requirements\n * @param isWebBrowser - Whether request is from browser\n * @param paywallConfig - Paywall configuration\n * @param customHtml - Custom HTML template\n * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests\n * @returns Response instructions\n */\n private createHTTPResponse(\n paymentRequired: PaymentRequired,\n isWebBrowser: boolean,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n unpaidResponse?: HTTPResponseBody,\n ): HTTPResponseInstructions {\n // Use 412 Precondition Failed for permit2_allowance_required error\n // This signals client needs to approve Permit2 before retrying\n const status = paymentRequired.error === \"permit2_allowance_required\" ? 412 : 402;\n\n if (isWebBrowser) {\n const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);\n return {\n status,\n headers: { \"Content-Type\": \"text/html\" },\n body: html,\n isHtml: true,\n };\n }\n\n const response = this.createHTTPPaymentRequiredResponse(paymentRequired);\n\n // Use callback result if provided, otherwise default to JSON with empty object\n const contentType = unpaidResponse ? unpaidResponse.contentType : \"application/json\";\n const body = unpaidResponse ? unpaidResponse.body : {};\n\n return {\n status,\n headers: {\n \"Content-Type\": contentType,\n ...response.headers,\n },\n body,\n };\n }\n\n /**\n * Create HTTP payment required response (v1 puts in body, v2 puts in header)\n *\n * @param paymentRequired - Payment required object\n * @returns Headers and body for the HTTP response\n */\n private createHTTPPaymentRequiredResponse(paymentRequired: PaymentRequired): {\n headers: Record;\n } {\n return {\n headers: {\n \"PAYMENT-REQUIRED\": encodePaymentRequiredHeader(paymentRequired),\n },\n };\n }\n\n /**\n * Create settlement response headers\n *\n * @param settleResponse - Settlement response\n * @returns Headers to add to response\n */\n private createSettlementHeaders(settleResponse: SettleResponse): Record {\n const encoded = encodePaymentResponseHeader(settleResponse);\n return { \"PAYMENT-RESPONSE\": encoded };\n }\n\n /**\n * Parse route pattern into verb and regex\n *\n * @param pattern - Route pattern like \"GET /api/*\", \"/api/[id]\", or \"/api/:id\"\n * @returns Parsed pattern with verb and regex\n */\n private parseRoutePattern(pattern: string): { verb: string; regex: RegExp } {\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n\n const regex = new RegExp(\n `^${\n path\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\") // Escape regex special chars\n .replace(/\\*/g, \".*?\") // Wildcards\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Parameters (Next.js style [param])\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, \"[^/]+\") // Parameters (Express style :param)\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n );\n\n return { verb: verb.toUpperCase(), regex };\n }\n\n /**\n * Normalize path for matching\n *\n * @param path - Raw path from request\n * @returns Normalized path\n */\n private normalizePath(path: string): string {\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n let decodedOrRawPath: string;\n try {\n decodedOrRawPath = decodeURIComponent(pathWithoutQuery);\n } catch {\n decodedOrRawPath = pathWithoutQuery;\n }\n\n return decodedOrRawPath\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/(.+?)\\/+$/, \"$1\");\n }\n\n /**\n * Generate paywall HTML for browser requests\n *\n * @param paymentRequired - Payment required response\n * @param paywallConfig - Optional paywall configuration\n * @param customHtml - Optional custom HTML template\n * @returns HTML string\n */\n private generatePaywallHTML(\n paymentRequired: PaymentRequired,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n ): string {\n if (customHtml) {\n return customHtml;\n }\n\n // Use custom paywall provider if set\n if (this.paywallProvider) {\n return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);\n }\n\n // Try to use @x402/paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@x402/paywall\");\n const displayAmount = this.getDisplayAmount(paymentRequired);\n const resource = paymentRequired.resource;\n\n return paywall.getPaywallHtml({\n amount: displayAmount,\n paymentRequired,\n currentUrl: resource?.url || paywallConfig?.currentUrl || \"\",\n testnet: paywallConfig?.testnet ?? true,\n appName: paywallConfig?.appName,\n appLogo: paywallConfig?.appLogo,\n sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint,\n });\n } catch {\n // @x402/paywall not installed, fall back to basic HTML\n }\n\n // Fallback: Basic HTML paywall\n const resource = paymentRequired.resource;\n const displayAmount = this.getDisplayAmount(paymentRequired);\n\n return `\n \n \n \n Payment Required\n \n \n \n \n
\n ${paywallConfig?.appLogo ? `\"${paywallConfig.appName` : \"\"}\n

Payment Required

\n ${resource ? `

Resource: ${resource.description || resource.url}

` : \"\"}\n

Amount: $${displayAmount.toFixed(2)} USDC

\n
\n \n

\n Note: Install @x402/paywall for full wallet connection and payment UI.\n

\n
\n
\n \n \n `;\n }\n\n /**\n * Extract display amount from payment requirements.\n *\n * @param paymentRequired - The payment required object\n * @returns The display amount in decimal format\n */\n private getDisplayAmount(paymentRequired: PaymentRequired): number {\n const accepts = paymentRequired.accepts;\n if (accepts && accepts.length > 0) {\n const firstReq = accepts[0];\n if (\"amount\" in firstReq) {\n // V2 format\n return parseFloat(firstReq.amount) / 1000000; // Assuming USDC with 6 decimals\n }\n }\n return 0;\n }\n}\n","import { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport {\n VerifyResponse,\n SettleResponse,\n SupportedResponse,\n VerifyError,\n SettleError,\n} from \"../types/facilitator\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://x402.org/facilitator\";\n\nexport interface FacilitatorConfig {\n url?: string;\n createAuthHeaders?: () => Promise<{\n verify: Record;\n settle: Record;\n supported: Record;\n }>;\n}\n\n/**\n * Interface for facilitator clients\n * Can be implemented for HTTP-based or local facilitators\n */\nexport interface FacilitatorClient {\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Get supported payment kinds and extensions from the facilitator\n *\n * @returns Supported payment kinds and extensions\n */\n getSupported(): Promise;\n}\n\n/** Number of retries for getSupported() on 429 rate limit errors */\nconst GET_SUPPORTED_RETRIES = 3;\n/** Base delay in ms for exponential backoff on retries */\nconst GET_SUPPORTED_RETRY_DELAY_MS = 1000;\n\n/**\n * HTTP-based client for interacting with x402 facilitator services\n * Handles HTTP communication with facilitator endpoints\n */\nexport class HTTPFacilitatorClient implements FacilitatorClient {\n readonly url: string;\n private readonly _createAuthHeaders?: FacilitatorConfig[\"createAuthHeaders\"];\n\n /**\n * Creates a new HTTPFacilitatorClient instance.\n *\n * @param config - Configuration options for the facilitator client\n */\n constructor(config?: FacilitatorConfig) {\n this.url = config?.url || DEFAULT_FACILITATOR_URL;\n this._createAuthHeaders = config?.createAuthHeaders;\n }\n\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n async verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"verify\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/verify`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n const verifyResponse = data as VerifyResponse;\n if (!response.ok) {\n throw new VerifyError(response.status, verifyResponse);\n }\n return verifyResponse;\n }\n\n throw new Error(`Facilitator verify failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n async settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"settle\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/settle`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n const settleResponse = data as SettleResponse;\n if (!response.ok) {\n throw new SettleError(response.status, settleResponse);\n }\n return settleResponse;\n }\n\n throw new Error(`Facilitator settle failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Get supported payment kinds and extensions from the facilitator.\n * Retries with exponential backoff on 429 rate limit errors.\n *\n * @returns Supported payment kinds and extensions\n */\n async getSupported(): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"supported\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {\n const response = await fetch(`${this.url}/supported`, {\n method: \"GET\",\n headers,\n });\n\n if (response.ok) {\n return (await response.json()) as SupportedResponse;\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(`Facilitator getSupported failed (${response.status}): ${errorText}`);\n\n // Retry on 429 rate limit errors with exponential backoff\n if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {\n const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n throw lastError;\n }\n\n throw lastError ?? new Error(\"Facilitator getSupported failed after retries\");\n }\n\n /**\n * Creates authentication headers for a specific path.\n *\n * @param path - The path to create authentication headers for (e.g., \"verify\", \"settle\", \"supported\")\n * @returns An object containing the authentication headers for the specified path\n */\n async createAuthHeaders(path: string): Promise<{\n headers: Record;\n }> {\n if (this._createAuthHeaders) {\n const authHeaders = (await this._createAuthHeaders()) as Record<\n string,\n Record\n >;\n return {\n headers: authHeaders[path] ?? {},\n };\n }\n return {\n headers: {},\n };\n }\n\n /**\n * Helper to convert objects to JSON-safe format.\n * Handles BigInt and other non-JSON types.\n *\n * @param obj - The object to convert\n * @returns The JSON-safe representation of the object\n */\n private toJsonSafe(obj: unknown): unknown {\n return JSON.parse(\n JSON.stringify(obj, (_, value) => (typeof value === \"bigint\" ? value.toString() : value)),\n );\n }\n}\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client } from \"../client/x402Client\";\n\n/**\n * Context provided to onPaymentRequired hooks.\n */\nexport interface PaymentRequiredContext {\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return headers to try before payment, or void to proceed directly to payment.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<{ headers: Record } | void>;\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n private paymentRequiredHooks: PaymentRequiredHook[] = [];\n\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Register a hook to handle 402 responses before payment.\n * Hooks run in order; first to return headers wins.\n *\n * @param hook - The hook function to register\n * @returns This instance for chaining\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Run hooks and return headers if any hook provides them.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Headers to use for retry, or null to proceed to payment\n */\n async handlePaymentRequired(\n paymentRequired: PaymentRequired,\n ): Promise | null> {\n for (const hook of this.paymentRequiredHooks) {\n const result = await hook({ paymentRequired });\n if (result?.headers) {\n return result.headers;\n }\n }\n return null;\n }\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequired): Promise {\n return this.client.createPaymentPayload(paymentRequired);\n }\n}\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(paymentResponse: SettleResponse): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPTransportContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n HTTPResponseBody,\n SettlementFailedResponseBody,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n ProtectedRequestHook,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { x402HTTPClient, PaymentRequiredContext, PaymentRequiredHook } from \"./x402HTTPClient\";\n","import { x402Version } from \"..\";\nimport { SchemeNetworkClient } from \"../types/mechanisms\";\nimport { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport { Network, PaymentRequired } from \"../types\";\nimport { findByNetworkAndScheme, findSchemesByNetwork } from \"../utils\";\n\n/**\n * Client Hook Context Interfaces\n */\n\nexport interface PaymentCreationContext {\n paymentRequired: PaymentRequired;\n selectedRequirements: PaymentRequirements;\n}\n\nexport interface PaymentCreatedContext extends PaymentCreationContext {\n paymentPayload: PaymentPayload;\n}\n\nexport interface PaymentCreationFailureContext extends PaymentCreationContext {\n error: Error;\n}\n\n/**\n * Client Hook Type Definitions\n */\n\nexport type BeforePaymentCreationHook = (\n context: PaymentCreationContext,\n) => Promise;\n\nexport type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise;\n\nexport type OnPaymentCreationFailureHook = (\n context: PaymentCreationFailureContext,\n) => Promise;\n\nexport type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;\n\n/**\n * Extension that can enrich payment payloads on the client side.\n *\n * Client extensions are invoked after the scheme creates the base payment payload\n * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612\n * permit signing) to enrich the payload's extensions data.\n */\nexport interface ClientExtension {\n /**\n * Unique key identifying this extension (e.g., \"eip2612GasSponsoring\").\n * Must match the extension key used in PaymentRequired.extensions.\n */\n key: string;\n\n /**\n * Called after payload creation when the extension key is present in\n * paymentRequired.extensions. Allows the extension to enrich the payload\n * with extension-specific data (e.g., signing an EIP-2612 permit).\n *\n * @param paymentPayload - The payment payload to enrich\n * @param paymentRequired - The original PaymentRequired response\n * @returns The enriched payment payload\n */\n enrichPaymentPayload?: (\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ) => Promise;\n}\n\n/**\n * A policy function that filters or transforms payment requirements.\n * Policies are applied in order before the selector chooses the final option.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of payment requirements to filter/transform\n * @returns Filtered array of payment requirements\n */\nexport type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];\n\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme client implementation for this network\n */\n client: SchemeNetworkClient;\n\n /**\n * The x402 protocol version to use for this scheme\n *\n * @default 2\n */\n x402Version?: number;\n}\n\n/**\n * Configuration options for the fetch wrapper\n */\nexport interface x402ClientConfig {\n /**\n * Array of scheme registrations defining which payment methods are supported\n */\n schemes: SchemeRegistration[];\n\n /**\n * Policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Custom payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n}\n\n/**\n * Core client for managing x402 payment schemes and creating payment payloads.\n *\n * Handles registration of payment schemes, policy-based filtering of payment requirements,\n * and creation of payment payloads based on server requirements.\n */\nexport class x402Client {\n private readonly paymentRequirementsSelector: SelectPaymentRequirements;\n private readonly registeredClientSchemes: Map>> = new Map();\n private readonly policies: PaymentPolicy[] = [];\n private readonly registeredExtensions: Map = new Map();\n\n private beforePaymentCreationHooks: BeforePaymentCreationHook[] = [];\n private afterPaymentCreationHooks: AfterPaymentCreationHook[] = [];\n private onPaymentCreationFailureHooks: OnPaymentCreationFailureHook[] = [];\n\n /**\n * Creates a new x402Client instance.\n *\n * @param paymentRequirementsSelector - Function to select payment requirements from available options\n */\n constructor(paymentRequirementsSelector?: SelectPaymentRequirements) {\n this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version, accepts) => accepts[0]);\n }\n\n /**\n * Creates a new x402Client instance from a configuration object.\n *\n * @param config - The client configuration including schemes, policies, and payment requirements selector\n * @returns A configured x402Client instance\n */\n static fromConfig(config: x402ClientConfig): x402Client {\n const client = new x402Client(config.paymentRequirementsSelector);\n config.schemes.forEach(scheme => {\n if (scheme.x402Version === 1) {\n client.registerV1(scheme.network, scheme.client);\n } else {\n client.register(scheme.network, scheme.client);\n }\n });\n config.policies?.forEach(policy => {\n client.registerPolicy(policy);\n });\n return client;\n }\n\n /**\n * Registers a scheme client for the current x402 version.\n *\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n register(network: Network, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(x402Version, network, client);\n }\n\n /**\n * Registers a scheme client for x402 version 1.\n *\n * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n registerV1(network: string, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(1, network as Network, client);\n }\n\n /**\n * Registers a policy to filter or transform payment requirements.\n *\n * Policies are applied in order after filtering by registered schemes\n * and before the selector chooses the final payment requirement.\n *\n * @param policy - Function to filter/transform payment requirements\n * @returns The x402Client instance for chaining\n *\n * @example\n * ```typescript\n * // Prefer cheaper options\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))\n * );\n *\n * // Prefer specific networks\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => r.network.startsWith('eip155:'))\n * );\n * ```\n */\n registerPolicy(policy: PaymentPolicy): x402Client {\n this.policies.push(policy);\n return this;\n }\n\n /**\n * Registers a client extension that can enrich payment payloads.\n *\n * Extensions are invoked after the scheme creates the base payload and the\n * payload is wrapped with extensions/resource/accepted data. If the extension's\n * key is present in `paymentRequired.extensions`, the extension's\n * `enrichPaymentPayload` hook is called to modify the payload.\n *\n * @param extension - The client extension to register\n * @returns The x402Client instance for chaining\n */\n registerExtension(extension: ClientExtension): x402Client {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Register a hook to execute before payment payload creation.\n * Can abort creation by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client {\n this.beforePaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment payload creation.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client {\n this.afterPaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment payload creation fails.\n * Can recover from failure by returning { recovered: true, payload: PaymentPayload }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client {\n this.onPaymentCreationFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Creates a payment payload based on a PaymentRequired response.\n *\n * Automatically extracts x402Version, resource, and extensions from the PaymentRequired\n * response and constructs a complete PaymentPayload with the accepted requirements.\n *\n * @param paymentRequired - The PaymentRequired response from the server\n * @returns Promise resolving to the complete payment payload\n */\n async createPaymentPayload(\n paymentRequired: PaymentRequired,\n ): Promise {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);\n }\n\n const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);\n\n const context: PaymentCreationContext = {\n paymentRequired,\n selectedRequirements: requirements,\n };\n\n // Execute beforePaymentCreation hooks\n for (const hook of this.beforePaymentCreationHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Payment creation aborted: ${result.reason}`);\n }\n }\n\n try {\n const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);\n if (!schemeNetworkClient) {\n throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);\n }\n\n const partialPayload = await schemeNetworkClient.createPaymentPayload(\n paymentRequired.x402Version,\n requirements,\n { extensions: paymentRequired.extensions },\n );\n\n let paymentPayload: PaymentPayload;\n if (partialPayload.x402Version == 1) {\n paymentPayload = partialPayload as PaymentPayload;\n } else {\n // Merge server-declared extensions with any scheme-provided extensions.\n // Scheme extensions overlay on top (e.g., EIP-2612 info enriches server declaration).\n const mergedExtensions = this.mergeExtensions(\n paymentRequired.extensions,\n partialPayload.extensions,\n );\n\n paymentPayload = {\n x402Version: partialPayload.x402Version,\n payload: partialPayload.payload,\n extensions: mergedExtensions,\n resource: paymentRequired.resource,\n accepted: requirements,\n };\n }\n\n // Enrich payload via registered client extensions (for non-scheme extensions)\n paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);\n\n // Execute afterPaymentCreation hooks\n const createdContext: PaymentCreatedContext = {\n ...context,\n paymentPayload,\n };\n\n for (const hook of this.afterPaymentCreationHooks) {\n await hook(createdContext);\n }\n\n return paymentPayload;\n } catch (error) {\n const failureContext: PaymentCreationFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onPaymentCreationFailure hooks\n for (const hook of this.onPaymentCreationFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.payload;\n }\n }\n\n throw error;\n }\n }\n\n\n\n /**\n * Merges server-declared extensions with scheme-provided extensions.\n * Scheme extensions overlay on top of server extensions at each key,\n * preserving server-provided schema while overlaying scheme-provided info.\n *\n * @param serverExtensions - Extensions declared by the server in the 402 response\n * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)\n * @returns The merged extensions object, or undefined if both inputs are undefined\n */\n private mergeExtensions(\n serverExtensions?: Record,\n schemeExtensions?: Record,\n ): Record | undefined {\n if (!schemeExtensions) return serverExtensions;\n if (!serverExtensions) return schemeExtensions;\n\n const merged = { ...serverExtensions };\n for (const [key, schemeValue] of Object.entries(schemeExtensions)) {\n const serverValue = merged[key];\n if (\n serverValue &&\n typeof serverValue === \"object\" &&\n schemeValue &&\n typeof schemeValue === \"object\"\n ) {\n // Deep merge: scheme info overlays server info, schema preserved\n merged[key] = { ...serverValue as Record, ...schemeValue as Record };\n } else {\n merged[key] = schemeValue;\n }\n }\n return merged;\n }\n\n /**\n * Enriches a payment payload by calling registered extension hooks.\n * For each extension key present in the PaymentRequired response,\n * invokes the corresponding extension's enrichPaymentPayload callback.\n *\n * @param paymentPayload - The payment payload to enrich with extension data\n * @param paymentRequired - The PaymentRequired response containing extension declarations\n * @returns The enriched payment payload with extension data applied\n */\n private async enrichPaymentPayloadWithExtensions(\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ): Promise {\n if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {\n return paymentPayload;\n }\n\n let enriched = paymentPayload;\n for (const [key, extension] of this.registeredExtensions) {\n if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {\n enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);\n }\n }\n\n return enriched;\n }\n\n /**\n * Selects appropriate payment requirements based on registered clients and policies.\n *\n * Selection process:\n * 1. Filter by registered schemes (network + scheme support)\n * 2. Apply all registered policies in order\n * 3. Use selector to choose final requirement\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of available payment requirements\n * @returns The selected payment requirements\n */\n private selectPaymentRequirements(x402Version: number, paymentRequirements: PaymentRequirements[]): PaymentRequirements {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${x402Version}`);\n }\n\n // Step 1: Filter by registered schemes\n const supportedPaymentRequirements = paymentRequirements.filter(requirement => {\n let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);\n if (!clientSchemes) {\n return false;\n }\n\n return clientSchemes.has(requirement.scheme);\n })\n\n if (supportedPaymentRequirements.length === 0) {\n throw new Error(`No network/scheme registered for x402 version: ${x402Version} which comply with the payment requirements. ${JSON.stringify({\n x402Version,\n paymentRequirements,\n x402Versions: Array.from(this.registeredClientSchemes.keys()),\n networks: Array.from(clientSchemesByNetwork.keys()),\n schemes: Array.from(clientSchemesByNetwork.values()).map(schemes => Array.from(schemes.keys())).flat(),\n })}`);\n }\n\n // Step 2: Apply all policies in order\n let filteredRequirements = supportedPaymentRequirements;\n for (const policy of this.policies) {\n filteredRequirements = policy(x402Version, filteredRequirements);\n\n if (filteredRequirements.length === 0) {\n throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version}`);\n }\n }\n\n // Step 3: Use selector to choose final requirement\n return this.paymentRequirementsSelector(x402Version, filteredRequirements);\n }\n\n /**\n * Internal method to register a scheme client.\n *\n * @param x402Version - The x402 protocol version\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n private _registerScheme(x402Version: number, network: Network, client: SchemeNetworkClient): x402Client {\n if (!this.registeredClientSchemes.has(x402Version)) {\n this.registeredClientSchemes.set(x402Version, new Map());\n }\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version)!;\n if (!clientSchemesByNetwork.has(network)) {\n clientSchemesByNetwork.set(network, new Map());\n }\n\n const clientByScheme = clientSchemesByNetwork.get(network)!;\n if (!clientByScheme.has(client.scheme)) {\n clientByScheme.set(client.scheme, client);\n }\n\n return this;\n }\n}\n","import { x402Client, x402ClientConfig, x402HTTPClient } from \"@x402/core/client\";\nimport { type PaymentRequired } from \"@x402/core/types\";\n\n/**\n * Enables the payment of APIs using the x402 payment protocol v2.\n *\n * This function wraps the native fetch API to automatically handle 402 Payment Required responses\n * by creating and sending payment headers. It will:\n * 1. Make the initial request\n * 2. If a 402 response is received, parse the payment requirements\n * 3. Create a payment header using the configured x402HTTPClient\n * 4. Retry the request with the payment header\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param client - Configured x402Client or x402HTTPClient instance for handling payments\n * @returns A wrapped fetch function that handles 402 responses automatically\n *\n * @example\n * ```typescript\n * import { wrapFetchWithPayment, x402Client } from '@x402/fetch';\n * import { ExactEvmScheme } from '@x402/evm';\n * import { ExactSvmScheme } from '@x402/svm';\n *\n * const client = new x402Client()\n * .register('eip155:8453', new ExactEvmScheme(evmSigner))\n * .register('solana:mainnet', new ExactSvmScheme(svmSigner))\n * .register('eip155:1', new ExactEvmScheme(evmSigner), 1); // v1 protocol\n *\n * const fetchWithPay = wrapFetchWithPayment(fetch, client);\n *\n * // Make a request that may require payment\n * const response = await fetchWithPay('https://api.example.com/paid-endpoint');\n * ```\n *\n * @throws {Error} If no schemes are provided\n * @throws {Error} If the request configuration is missing\n * @throws {Error} If a payment has already been attempted for this request\n * @throws {Error} If there's an error creating the payment header\n */\nexport function wrapFetchWithPayment(\n fetch: typeof globalThis.fetch,\n client: x402Client | x402HTTPClient,\n) {\n const httpClient = client instanceof x402HTTPClient ? client : new x402HTTPClient(client);\n\n return async (input: RequestInfo | URL, init?: RequestInit) => {\n const request = new Request(input, init);\n const clonedRequest = request.clone();\n\n const response = await fetch(request);\n\n if (response.status !== 402) {\n return response;\n }\n\n // Parse payment requirements from response\n let paymentRequired: PaymentRequired;\n try {\n // Create getHeader function for case-insensitive header lookup\n const getHeader = (name: string) => response.headers.get(name);\n\n // Try to get from headers first (v2), then from body (v1)\n let body: PaymentRequired | undefined;\n try {\n const responseText = await response.text();\n if (responseText) {\n body = JSON.parse(responseText) as PaymentRequired;\n }\n } catch {\n // Ignore JSON parse errors - might be header-only response\n }\n\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n } catch (error) {\n throw new Error(\n `Failed to parse payment requirements: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Run payment required hooks\n const hookHeaders = await httpClient.handlePaymentRequired(paymentRequired);\n if (hookHeaders) {\n const hookRequest = clonedRequest.clone();\n for (const [key, value] of Object.entries(hookHeaders)) {\n hookRequest.headers.set(key, value);\n }\n const hookResponse = await fetch(hookRequest);\n if (hookResponse.status !== 402) {\n return hookResponse; // Hook succeeded\n }\n // Hook's retry got 402, fall through to payment\n }\n\n // Create payment payload (copy extensions from PaymentRequired)\n let paymentPayload;\n try {\n paymentPayload = await client.createPaymentPayload(paymentRequired);\n } catch (error) {\n throw new Error(\n `Failed to create payment payload: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Encode payment header\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);\n\n // Check if this is already a retry to prevent infinite loops\n if (clonedRequest.headers.has(\"PAYMENT-SIGNATURE\") || clonedRequest.headers.has(\"X-PAYMENT\")) {\n throw new Error(\"Payment already attempted\");\n }\n\n // Add payment headers to cloned request\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n clonedRequest.headers.set(\n \"Access-Control-Expose-Headers\",\n \"PAYMENT-RESPONSE,X-PAYMENT-RESPONSE\",\n );\n\n // Retry the request with payment\n const secondResponse = await fetch(clonedRequest);\n return secondResponse;\n };\n}\n\n/**\n * Creates a payment-enabled fetch function from a configuration object.\n *\n * @param fetch - The fetch function to wrap (typically globalThis.fetch)\n * @param config - Configuration options including scheme registrations and selectors\n * @returns A wrapped fetch function that handles 402 responses automatically\n */\nexport function wrapFetchWithPaymentFromConfig(\n fetch: typeof globalThis.fetch,\n config: x402ClientConfig,\n) {\n const client = x402Client.fromConfig(config);\n return wrapFetchWithPayment(fetch, client);\n}\n\n// Re-export types and utilities for convenience\nexport { x402Client, x402HTTPClient } from \"@x402/core/client\";\nexport type {\n PaymentPolicy,\n SchemeRegistration,\n SelectPaymentRequirements,\n x402ClientConfig,\n} from \"@x402/core/client\";\nexport { decodePaymentResponseHeader } from \"@x402/core/http\";\nexport type {\n Network,\n PaymentPayload,\n PaymentRequired,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\n","/**\n * Payment Pre-Auth Cache\n *\n * Wraps the @x402/fetch SDK with pre-authorization caching.\n * After the first 402 response, caches payment requirements per endpoint.\n * On subsequent requests, pre-signs payment and attaches it to the first\n * request, skipping the 402 round trip (~200ms savings per request).\n *\n * Falls back to normal 402 flow if pre-signed payment is rejected.\n */\n\nimport type { x402Client } from \"@x402/fetch\";\nimport { x402HTTPClient } from \"@x402/fetch\";\n\ntype PaymentRequired = Parameters[\"createPaymentPayload\"]>[0];\n\ninterface CachedEntry {\n paymentRequired: PaymentRequired;\n cachedAt: number;\n}\n\nconst DEFAULT_TTL_MS = 3_600_000; // 1 hour\n\ntype FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise;\n\nexport function createPayFetchWithPreAuth(\n baseFetch: FetchFn,\n client: x402Client,\n ttlMs = DEFAULT_TTL_MS,\n options?: { skipPreAuth?: boolean },\n): FetchFn {\n const httpClient = new x402HTTPClient(client);\n const cache = new Map();\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise => {\n const request = new Request(input, init);\n const urlPath = new URL(request.url).pathname;\n\n // Extract model from request body to create model-specific cache keys.\n // Without this, a cached payment from a paid model (e.g. sonnet) would be\n // incorrectly applied to a free model (nvidia/gpt-oss-120b), causing\n // payment errors even when the server wouldn't charge for the request.\n let requestModel = \"\";\n if (init?.body) {\n try {\n const bodyStr =\n init.body instanceof Uint8Array\n ? new TextDecoder().decode(init.body)\n : typeof init.body === \"string\"\n ? init.body\n : \"\";\n if (bodyStr) {\n const parsed = JSON.parse(bodyStr) as { model?: string };\n requestModel = parsed.model ?? \"\";\n }\n } catch {\n /* not JSON, use empty model */\n }\n }\n const cacheKey = `${urlPath}:${requestModel}`;\n\n // Try pre-auth if we have cached payment requirements\n // Skip for Solana: payments use per-tx blockhashes that expire ~60-90s,\n // making cached requirements useless and causing double charges.\n const cached = !options?.skipPreAuth ? cache.get(cacheKey) : undefined;\n if (cached && Date.now() - cached.cachedAt < ttlMs) {\n try {\n const payload = await client.createPaymentPayload(cached.paymentRequired);\n const headers = httpClient.encodePaymentSignatureHeader(payload);\n const preAuthRequest = request.clone();\n for (const [key, value] of Object.entries(headers)) {\n preAuthRequest.headers.set(key, value);\n }\n const response = await baseFetch(preAuthRequest);\n if (response.status !== 402) {\n return response; // Pre-auth worked — saved ~200ms\n }\n // Pre-auth rejected (params may have changed) — invalidate and fall through\n cache.delete(cacheKey);\n } catch {\n // Pre-auth signing failed — invalidate and fall through\n cache.delete(cacheKey);\n }\n }\n\n // Normal flow: make request, handle 402 if needed\n const clonedRequest = request.clone();\n const response = await baseFetch(request);\n if (response.status !== 402) {\n return response;\n }\n\n // Parse 402 response and cache for future pre-auth\n let paymentRequired: PaymentRequired;\n try {\n const getHeader = (name: string) => response.headers.get(name);\n let body: unknown;\n try {\n const responseText = await Promise.race([\n response.text(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Body read timeout\")), 30_000),\n ),\n ]);\n if (responseText) body = JSON.parse(responseText);\n } catch {\n /* empty body is fine */\n }\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n cache.set(cacheKey, { paymentRequired, cachedAt: Date.now() });\n } catch (error) {\n throw new Error(\n `Failed to parse payment requirements: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n { cause: error },\n );\n }\n\n // Sign payment and retry\n const payload = await client.createPaymentPayload(paymentRequired);\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(payload);\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n return baseFetch(clonedRequest);\n };\n}\n","import type { PaymentPayload } from \"@x402/core/types\";\nimport type { FacilitatorEvmSigner } from \"../signer\";\n\nexport const EIP2612_GAS_SPONSORING_KEY = \"eip2612GasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_KEY = \"erc20ApprovalGasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_VERSION = \"1\" as const;\n\nexport interface Eip2612GasSponsoringInfo {\n [key: string]: unknown;\n from: string;\n asset: string;\n spender: string;\n amount: string;\n nonce: string;\n deadline: string;\n signature: string;\n version: string;\n}\n\nexport interface Erc20ApprovalGasSponsoringInfo {\n [key: string]: unknown;\n from: `0x${string}`;\n asset: `0x${string}`;\n spender: `0x${string}`;\n amount: string;\n signedTransaction: `0x${string}`;\n version: string;\n}\n\n/**\n * A single transaction to be executed by the signer.\n * - `0x${string}`: a pre-signed serialized transaction (broadcast as-is via sendRawTransaction)\n * - `{ to, data, gas? }`: an unsigned call intent (signer signs and broadcasts)\n */\nexport type TransactionRequest =\n | `0x${string}`\n | { to: `0x${string}`; data: `0x${string}`; gas?: bigint };\n\nexport type Erc20ApprovalGasSponsoringSigner = FacilitatorEvmSigner & {\n sendTransactions(transactions: TransactionRequest[]): Promise<`0x${string}`[]>;\n simulateTransactions?(transactions: TransactionRequest[]): Promise;\n};\n\nexport interface Erc20ApprovalGasSponsoringFacilitatorExtension {\n key: typeof ERC20_APPROVAL_GAS_SPONSORING_KEY;\n signer?: Erc20ApprovalGasSponsoringSigner;\n signerForNetwork?: (network: string) => Erc20ApprovalGasSponsoringSigner | undefined;\n}\n\n/**\n * Extracts a typed `info` payload from an extension entry.\n *\n * @param payload - Payment payload containing optional extensions.\n * @param extensionKey - Extension key to extract.\n * @returns The extension `info` object when present; otherwise null.\n */\nfunction _extractInfo(\n payload: PaymentPayload,\n extensionKey: string,\n): Record | null {\n const extensions = payload.extensions;\n if (!extensions) return null;\n const extension = extensions[extensionKey] as { info?: Record } | undefined;\n if (!extension?.info) return null;\n return extension.info;\n}\n\n/**\n * Extracts and validates required EIP-2612 gas sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed EIP-2612 gas sponsoring info when available and complete.\n */\nexport function extractEip2612GasSponsoringInfo(\n payload: PaymentPayload,\n): Eip2612GasSponsoringInfo | null {\n const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.nonce ||\n !info.deadline ||\n !info.signature ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Eip2612GasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of EIP-2612 sponsoring info.\n *\n * @param info - EIP-2612 extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateEip2612GasSponsoringInfo(info: Eip2612GasSponsoringInfo): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n numericPattern.test(info.nonce) &&\n numericPattern.test(info.deadline) &&\n hexPattern.test(info.signature) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Extracts and validates required ERC-20 approval sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed ERC-20 approval sponsoring info when available and complete.\n */\nexport function extractErc20ApprovalGasSponsoringInfo(\n payload: PaymentPayload,\n): Erc20ApprovalGasSponsoringInfo | null {\n const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.signedTransaction ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Erc20ApprovalGasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of ERC-20 approval sponsoring info.\n *\n * @param info - ERC-20 approval extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateErc20ApprovalGasSponsoringInfo(\n info: Erc20ApprovalGasSponsoringInfo,\n): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n hexPattern.test(info.signedTransaction) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Resolves the ERC-20 approval extension signer for a specific network.\n *\n * @param extension - Optional facilitator extension config.\n * @param network - CAIP-2 network identifier.\n * @returns A network-specific signer when available, else the default signer.\n */\nexport function resolveErc20ApprovalExtensionSigner(\n extension: Erc20ApprovalGasSponsoringFacilitatorExtension | undefined,\n network: string,\n): Erc20ApprovalGasSponsoringSigner | undefined {\n if (!extension) return undefined;\n return extension.signerForNetwork?.(network) ?? extension.signer;\n}\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce } from \"../../../utils\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainIdV1(requirements.network as EvmNetworkV1);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Permit2 EIP-712 types for signing PermitWitnessTransferFrom.\n * Must match the exact format expected by the Permit2 contract.\n * Note: Types must be in ALPHABETICAL order after the primary type (TokenPermissions < Witness).\n */\nexport const permit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"Witness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n Witness: [\n { name: \"to\", type: \"address\" },\n { name: \"validAfter\", type: \"uint256\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"name\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"authorizer\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n name: \"authorizationState\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/**\n * EIP-2612 Permit EIP-712 types for signing token.permit().\n */\nexport const eip2612PermitTypes = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * EIP-2612 nonces ABI for querying current nonce.\n */\nexport const eip2612NoncesAbi = [\n {\n type: \"function\",\n name: \"nonces\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** ERC-20 approve(address,uint256) ABI for encoding/decoding approval calldata. */\nexport const erc20ApproveAbi = [\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n] as const;\n\n/** ERC-20 allowance(address,address) ABI for checking spender approval. */\nexport const erc20AllowanceAbi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** Gas limit for a standard ERC-20 approve() transaction. */\nexport const ERC20_APPROVE_GAS_LIMIT = 70_000n;\n\n/** Fallback max fee per gas (1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_FEE_PER_GAS = 1_000_000_000n;\n\n/** Fallback max priority fee per gas (0.1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100_000_000n;\n\n/**\n * Canonical Permit2 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/Uniswap/permit2\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\" as const;\n\n/**\n * x402ExactPermit2Proxy contract address.\n * Vanity address: 0x4020...0001 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0001\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402ExactPermit2ProxyAddress = \"0x402085c248EeA27D92E8b30b2C58ed07f9E20001\" as const;\n\n/**\n * x402UptoPermit2Proxy contract address.\n * Vanity address: 0x4020...0002 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0002\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402UptoPermit2ProxyAddress = \"0x402039b3d6E6BEC5A02c2C9fd937ac17A6940002\" as const;\n\n/**\n * Shared ABI components for the Permit2 witness tuple.\n * Used in both x402ExactPermit2ProxyABI and x402UptoPermit2ProxyABI to keep them in sync.\n * The upto contract's witness struct is identical to exact (both remove 'extra' post-audit).\n */\nconst permit2WitnessABIComponents = [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"validAfter\", type: \"uint256\", internalType: \"uint256\" },\n] as const;\n\n/**\n * x402UptoPermit2Proxy ABI - settle function for upto payment scheme (variable amounts).\n * Updated post-audit: 'extra' removed from witness struct, 'initialize()' removed (now\n * a constructor arg), and error names aligned with x402ExactPermit2Proxy.\n */\nexport const x402UptoPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n\n/**\n * x402ExactPermit2Proxy ABI - settle function for exact payment scheme.\n */\nexport const x402ExactPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n","import { toHex } from \"viem\";\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (network.startsWith(\"eip155:\")) {\n const idStr = network.split(\":\")[1];\n const chainId = parseInt(idStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n return chainId;\n }\n\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\nimport * as Errors from \"../../facilitator/errors\";\nimport {\n diagnoseEip3009SimulationFailure,\n executeTransferWithAuthorization,\n simulateEip3009Transfer,\n} from \"../../facilitator/eip3009-utils\";\n\nexport interface VerifyV1Options {\n /** Run onchain simulation. Defaults to true. */\n simulate?: boolean;\n}\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * If enabled, the facilitator will deploy ERC-4337 smart wallets\n * via EIP-6492 when encountering undeployed contract signatures.\n *\n * @default false\n */\n deployERC4337WithEIP6492?: boolean;\n /**\n * If enabled, simulates transaction before settling. Defaults to false, ie only simulate during verify.\n *\n * @default false\n */\n simulateInSettle?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n deployERC4337WithEIP6492: config?.deployERC4337WithEIP6492 ?? false,\n simulateInSettle: config?.simulateInSettle ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n return this._verify(payload, requirements);\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this._verify(payload, requirements, {\n simulate: this.config.simulateInSettle ?? false,\n });\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? Errors.ErrInvalidScheme,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable (for optional deployment)\n const { address: factoryAddress, data: factoryCalldata } = parseErc6492Signature(\n exactEvmPayload.signature!,\n );\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if configured and needed\n if (\n this.config.deployERC4337WithEIP6492 &&\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment transaction\n await this.signer.waitForTransactionReceipt({ hash: deployTx });\n }\n }\n\n const tx = await executeTransferWithAuthorization(\n this.signer,\n getAddress(requirements.asset),\n exactEvmPayload,\n );\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: Errors.ErrTransactionFailed,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n return {\n success: false,\n errorReason: error instanceof Error ? error.message : Errors.ErrTransactionFailed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n /**\n * Internal verify with optional simulation control.\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @param options - Verification options (e.g. simulate)\n * @returns Promise resolving to verification response\n */\n private async _verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n options?: VerifyV1Options,\n ): Promise {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n const payer = exactEvmPayload.authorization.from;\n let eip6492Deployment:\n | { factoryAddress: `0x${string}`; factoryCalldata: `0x${string}` }\n | undefined;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidScheme,\n payer,\n };\n }\n\n // Get chain configuration\n let chainId: number;\n try {\n chainId = getEvmChainIdV1(payloadV1.network as EvmNetworkV1);\n } catch {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: Errors.ErrMissingEip712Domain,\n payer,\n };\n }\n\n const { name, version } = requirements.extra;\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n // Verify signature (flatten EIP-6492 handling out of catch block)\n let isValid = false;\n try {\n isValid = await this.signer.verifyTypedData({\n address: payer,\n ...permitTypedData,\n signature: exactEvmPayload.signature!,\n });\n } catch {\n isValid = false;\n }\n\n const signature = exactEvmPayload.signature!;\n const sigLen = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n\n // Extract EIP-6492 deployment info (factory address + calldata) if present\n const erc6492Data = parseErc6492Signature(signature);\n const hasDeploymentInfo =\n erc6492Data.address &&\n erc6492Data.data &&\n !isAddressEqual(erc6492Data.address, \"0x0000000000000000000000000000000000000000\");\n\n if (hasDeploymentInfo) {\n eip6492Deployment = {\n factoryAddress: erc6492Data.address!,\n factoryCalldata: erc6492Data.data!,\n };\n }\n\n if (!isValid) {\n const isSmartWallet = sigLen > 130; // 65 bytes = 130 hex chars for EOA\n\n if (!isSmartWallet) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidSignature,\n payer,\n };\n }\n\n const bytecode = await this.signer.getCode({ address: payer });\n const isDeployed = bytecode && bytecode !== \"0x\";\n\n if (!isDeployed && !hasDeploymentInfo) {\n return {\n isValid: false,\n invalidReason: Errors.ErrUndeployedSmartWallet,\n payer,\n };\n }\n }\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrRecipientMismatch,\n payer,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidBeforeExpired,\n payer,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidAfterInFuture,\n payer,\n };\n }\n\n // Verify amount exactly matches requirements\n if (BigInt(exactEvmPayload.authorization.value) !== BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidAuthorizationValue,\n payer,\n };\n }\n\n // Transaction simulation\n if (options?.simulate !== false) {\n const simulationSucceeded = await simulateEip3009Transfer(\n this.signer,\n erc20Address,\n exactEvmPayload,\n eip6492Deployment,\n );\n if (!simulationSucceeded) {\n return diagnoseEip3009SimulationFailure(\n this.signer,\n erc20Address,\n exactEvmPayload,\n requirements,\n requirementsV1.maxAmountRequired,\n );\n }\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n }\n}\n","/**\n * Named error reason constants for the exact EVM facilitator.\n *\n * These strings must be character-for-character identical to the Go constants in\n * go/mechanisms/evm/exact/facilitator/errors.go to maintain cross-SDK parity.\n */\n\nexport const ErrInvalidScheme = \"invalid_exact_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_exact_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_exact_evm_missing_eip712_domain\";\nexport const ErrRecipientMismatch = \"invalid_exact_evm_recipient_mismatch\";\nexport const ErrInvalidSignature = \"invalid_exact_evm_signature\";\nexport const ErrValidBeforeExpired = \"invalid_exact_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture = \"invalid_exact_evm_payload_authorization_valid_after\";\nexport const ErrInvalidAuthorizationValue = \"invalid_exact_evm_authorization_value\";\nexport const ErrUndeployedSmartWallet = \"invalid_exact_evm_payload_undeployed_smart_wallet\";\nexport const ErrTransactionFailed = \"invalid_exact_evm_transaction_failed\";\n\n// EIP-3009 verify errors\nexport const ErrEip3009TokenNameMismatch = \"invalid_exact_evm_token_name_mismatch\";\nexport const ErrEip3009TokenVersionMismatch = \"invalid_exact_evm_token_version_mismatch\";\nexport const ErrEip3009NotSupported = \"invalid_exact_evm_eip3009_not_supported\";\nexport const ErrEip3009NonceAlreadyUsed = \"invalid_exact_evm_nonce_already_used\";\nexport const ErrEip3009InsufficientBalance = \"invalid_exact_evm_insufficient_balance\";\nexport const ErrEip3009SimulationFailed = \"invalid_exact_evm_transaction_simulation_failed\";\n\n// Permit2 verify errors\nexport const ErrPermit2InvalidSpender = \"invalid_permit2_spender\";\nexport const ErrPermit2RecipientMismatch = \"invalid_permit2_recipient_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"permit2_deadline_expired\";\nexport const ErrPermit2NotYetValid = \"permit2_not_yet_valid\";\nexport const ErrPermit2AmountMismatch = \"permit2_amount_mismatch\";\nexport const ErrPermit2TokenMismatch = \"permit2_token_mismatch\";\nexport const ErrPermit2InvalidSignature = \"invalid_permit2_signature\";\nexport const ErrPermit2AllowanceRequired = \"permit2_allowance_required\";\nexport const ErrPermit2SimulationFailed = \"permit2_simulation_failed\";\nexport const ErrPermit2InsufficientBalance = \"permit2_insufficient_balance\";\nexport const ErrPermit2ProxyNotDeployed = \"permit2_proxy_not_deployed\";\n\n// Permit2 settle errors (from contract reverts)\nexport const ErrPermit2InvalidAmount = \"permit2_invalid_amount\";\nexport const ErrPermit2InvalidDestination = \"permit2_invalid_destination\";\nexport const ErrPermit2InvalidOwner = \"permit2_invalid_owner\";\nexport const ErrPermit2PaymentTooEarly = \"permit2_payment_too_early\";\nexport const ErrPermit2InvalidNonce = \"permit2_invalid_nonce\";\nexport const ErrPermit2612AmountMismatch = \"permit2_2612_amount_mismatch\";\n\n// ERC-20 approval gas sponsoring verify errors\nexport const ErrErc20ApprovalInsufficientEthForGas = \"erc20_approval_insufficient_eth_for_gas\";\nexport const ErrErc20ApprovalInvalidFormat = \"invalid_erc20_approval_extension_format\";\nexport const ErrErc20ApprovalFromMismatch = \"erc20_approval_from_mismatch\";\nexport const ErrErc20ApprovalAssetMismatch = \"erc20_approval_asset_mismatch\";\nexport const ErrErc20ApprovalSpenderNotPermit2 = \"erc20_approval_spender_not_permit2\";\nexport const ErrErc20ApprovalTxWrongTarget = \"erc20_approval_tx_wrong_target\";\nexport const ErrErc20ApprovalTxWrongSelector = \"erc20_approval_tx_wrong_selector\";\nexport const ErrErc20ApprovalTxWrongSpender = \"erc20_approval_tx_wrong_spender\";\nexport const ErrErc20ApprovalTxInvalidCalldata = \"erc20_approval_tx_invalid_calldata\";\nexport const ErrErc20ApprovalTxSignerMismatch = \"erc20_approval_tx_signer_mismatch\";\nexport const ErrErc20ApprovalTxInvalidSignature = \"erc20_approval_tx_invalid_signature\";\nexport const ErrErc20ApprovalTxParseFailed = \"erc20_approval_tx_parse_failed\";\nexport const ErrErc20ApprovalTxFailed = \"erc20_approval_tx_failed\";\n\n// EIP-2612 gas sponsoring verify errors\nexport const ErrInvalidEip2612ExtensionFormat = \"invalid_eip2612_extension_format\";\nexport const ErrEip2612FromMismatch = \"eip2612_from_mismatch\";\nexport const ErrEip2612AssetMismatch = \"eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderNotPermit2 = \"eip2612_spender_not_permit2\";\nexport const ErrEip2612DeadlineExpired = \"eip2612_deadline_expired\";\n\n// Shared settle errors\nexport const ErrUnsupportedPayloadType = \"unsupported_payload_type\";\nexport const ErrInvalidTransactionState = \"invalid_transaction_state\";\n","import { PaymentRequirements, VerifyResponse } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress, Hex, parseErc6492Signature, parseSignature } from \"viem\";\nimport { eip3009ABI } from \"../../constants\";\nimport { multicall, ContractCall, RawContractCall } from \"../../multicall\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport * as Errors from \"./errors\";\n\nexport interface Eip6492Deployment {\n factoryAddress: `0x${string}`;\n factoryCalldata: `0x${string}`;\n}\n\n/**\n * Simulates transferWithAuthorization via eth_call.\n * Returns true if simulation succeeded, false if it failed.\n *\n * @param signer - EVM signer for contract reads\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param eip6492Deployment - Optional EIP-6492 factory info for undeployed smart wallets\n *\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulateEip3009Transfer(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n eip6492Deployment?: Eip6492Deployment,\n): Promise {\n const auth = payload.authorization;\n const transferArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (eip6492Deployment) {\n const { signature: innerSignature } = parseErc6492Signature(payload.signature!);\n const transferCalldata = encodeFunctionData({\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, innerSignature],\n });\n\n try {\n const results = await multicall(signer.readContract.bind(signer), [\n {\n address: getAddress(eip6492Deployment.factoryAddress),\n callData: eip6492Deployment.factoryCalldata,\n } satisfies RawContractCall,\n {\n address: erc20Address,\n callData: transferCalldata,\n } satisfies RawContractCall,\n ]);\n\n return results[1]?.status === \"success\";\n } catch {\n return false;\n }\n }\n\n const sig = payload.signature!;\n const sigLength = sig.startsWith(\"0x\") ? sig.length - 2 : sig.length;\n const isECDSA = sigLength === 130;\n\n try {\n if (isECDSA) {\n const parsedSig = parseSignature(sig);\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...transferArgs,\n (parsedSig.v as number | undefined) ?? parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, sig],\n });\n }\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * After simulation fails, runs a single diagnostic multicall to determine the most specific error reason.\n * Checks balanceOf, name, version and authorizationState in one RPC round-trip.\n *\n * @param signer - EVM signer used for the payment\n * @param erc20Address - Address of the ERC-20 token contract\n * @param payload - The EIP-3009 transfer authorization payload\n * @param requirements - Payment requirements to validate against\n * @param amountRequired - Required amount for the payment (balance check)\n *\n * @returns Promise resolving to the verification result with validity and optional invalid reason\n */\nexport async function diagnoseEip3009SimulationFailure(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n requirements: PaymentRequirements,\n amountRequired: string,\n): Promise {\n const payer = payload.authorization.from;\n\n const diagnosticCalls: ContractCall[] = [\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payload.authorization.from],\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"name\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"version\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"authorizationState\",\n args: [payload.authorization.from, payload.authorization.nonce],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [balanceResult, nameResult, versionResult, authStateResult] = results;\n\n if (authStateResult.status === \"failure\") {\n return { isValid: false, invalidReason: Errors.ErrEip3009NotSupported, payer };\n }\n\n if (authStateResult.status === \"success\" && authStateResult.result === true) {\n return { isValid: false, invalidReason: Errors.ErrEip3009NonceAlreadyUsed, payer };\n }\n\n if (\n nameResult.status === \"success\" &&\n requirements.extra?.name &&\n nameResult.result !== requirements.extra.name\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenNameMismatch, payer };\n }\n\n if (\n versionResult.status === \"success\" &&\n requirements.extra?.version &&\n versionResult.result !== requirements.extra.version\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenVersionMismatch, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrEip3009InsufficientBalance,\n payer,\n };\n }\n }\n } catch {\n // Diagnostic multicall failed — fall through to generic error\n }\n\n return { isValid: false, invalidReason: Errors.ErrEip3009SimulationFailed, payer };\n}\n\n/**\n * Executes transferWithAuthorization onchain.\n *\n * @param signer - EVM signer for contract writes\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n *\n * @returns Transaction hash\n */\nexport async function executeTransferWithAuthorization(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n): Promise {\n const { signature } = parseErc6492Signature(payload.signature!);\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n const auth = payload.authorization;\n const baseArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (isECDSA) {\n const parsedSig = parseSignature(signature);\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...baseArgs,\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n }\n\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...baseArgs, signature],\n });\n}\n","import { encodeFunctionData, decodeFunctionResult } from \"viem\";\n\n/**\n * Multicall3 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/mds1/multicall\n */\nexport const MULTICALL3_ADDRESS = \"0xcA11bde05977b3631167028862bE2a173976CA11\" as const;\n\n/** Multicall3 getEthBalance ABI for querying native token balance. */\nexport const multicall3GetEthBalanceAbi = [\n {\n name: \"getEthBalance\",\n inputs: [{ name: \"addr\", type: \"address\" }],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/** Multicall3 tryAggregate ABI for batching calls. */\nconst multicall3ABI = [\n {\n inputs: [\n { name: \"requireSuccess\", type: \"bool\" },\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n name: \"tryAggregate\",\n outputs: [\n {\n name: \"returnData\",\n type: \"tuple[]\",\n components: [\n { name: \"success\", type: \"bool\" },\n { name: \"returnData\", type: \"bytes\" },\n ],\n },\n ],\n stateMutability: \"payable\",\n type: \"function\",\n },\n] as const;\n\nexport type ContractCall = {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n};\n\nexport type RawContractCall = {\n address: `0x${string}`;\n callData: `0x${string}`;\n};\n\nexport type MulticallSuccess = { status: \"success\"; result: unknown };\nexport type MulticallFailure = { status: \"failure\"; error: Error };\nexport type MulticallResult = MulticallSuccess | MulticallFailure;\n\n/**\n * Batches contract calls via Multicall3 `tryAggregate(false, ...)`.\n *\n * Accepts a mix of typed ContractCall (ABI-encoded + decoded) and\n * RawContractCall (pre-encoded calldata, no decoding) entries.\n * Raw calls are useful for the EIP-6492 factory deployment case\n * where calldata is pre-encoded with no ABI available.\n */\ntype ReadContractFn = (args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n}) => Promise;\n\n/**\n * Executes multiple contract read calls in a single RPC round-trip using Multicall3.\n *\n * @param readContract - Function that performs a single contract read (e.g. viem readContract)\n * @param calls - Array of contract calls to batch (ContractCall or RawContractCall)\n * @returns A promise that resolves to an array of decoded results, one per call\n */\nexport async function multicall(\n readContract: ReadContractFn,\n calls: ReadonlyArray,\n): Promise {\n const aggregateCalls = calls.map(call => {\n if (\"callData\" in call) {\n return { target: call.address, callData: call.callData };\n }\n const callData = encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args as unknown[],\n });\n return { target: call.address, callData };\n });\n\n const rawResults = (await readContract({\n address: MULTICALL3_ADDRESS,\n abi: multicall3ABI,\n functionName: \"tryAggregate\",\n args: [false, aggregateCalls],\n })) as { success: boolean; returnData: `0x${string}` }[];\n\n return rawResults.map((raw, i) => {\n if (!raw.success) {\n return {\n status: \"failure\" as const,\n error: new Error(`multicall: call reverted (returnData: ${raw.returnData})`),\n };\n }\n\n const call = calls[i];\n if (\"callData\" in call) {\n return { status: \"success\" as const, result: undefined };\n }\n\n try {\n const decoded = decodeFunctionResult({\n abi: call.abi,\n functionName: call.functionName,\n data: raw.returnData,\n });\n return { status: \"success\" as const, result: decoded };\n } catch (err) {\n return {\n status: \"failure\" as const,\n error: err instanceof Error ? err : new Error(String(err)),\n };\n }\n });\n}\n","export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const EVM_NETWORK_CHAIN_ID_MAP = {\n ethereum: 1,\n sepolia: 11155111,\n abstract: 2741,\n \"abstract-testnet\": 11124,\n \"base-sepolia\": 84532,\n base: 8453,\n \"avalanche-fuji\": 43113,\n avalanche: 43114,\n iotex: 4689,\n sei: 1329,\n \"sei-testnet\": 1328,\n polygon: 137,\n \"polygon-amoy\": 80002,\n peaq: 3338,\n story: 1514,\n educhain: 41923,\n \"skale-base-sepolia\": 324705682,\n megaeth: 4326,\n monad: 143,\n} as const;\n\nexport type EvmNetworkV1 = keyof typeof EVM_NETWORK_CHAIN_ID_MAP;\n\nexport const NETWORKS: string[] = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);\n\n/**\n * Extract chain ID from a v1 legacy network name.\n *\n * @param network - The v1 network name (e.g., \"base-sepolia\", \"polygon\")\n * @returns The numeric chain ID\n * @throws Error if the network name is not a known v1 network\n */\nexport function getEvmChainIdV1(network: string): number {\n const chainId = EVM_NETWORK_CHAIN_ID_MAP[network as EvmNetworkV1];\n if (!chainId) {\n throw new Error(`Unsupported v1 network: ${network}`);\n }\n return chainId;\n}\n","import {\n SchemeNetworkClient,\n PaymentRequirements,\n PaymentPayloadResult,\n PaymentPayloadContext,\n} from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { AssetTransferMethod } from \"../../types\";\nimport { PERMIT2_ADDRESS, erc20AllowanceAbi } from \"../../constants\";\nimport { getAddress } from \"viem\";\nimport { getEvmChainId } from \"../../utils\";\nimport { EIP2612_GAS_SPONSORING_KEY, ERC20_APPROVAL_GAS_SPONSORING_KEY } from \"../extensions\";\nimport { createEIP3009Payload } from \"./eip3009\";\nimport { createPermit2Payload } from \"./permit2\";\nimport { signEip2612Permit } from \"./eip2612\";\nimport { signErc20ApprovalTransaction } from \"./erc20approval\";\nimport { ExactEvmSchemeOptions, resolveExtensionRpcCapabilities } from \"./rpc\";\n\n/**\n * EVM client implementation for the Exact payment scheme.\n * Supports both EIP-3009 (transferWithAuthorization) and Permit2 flows.\n *\n * Routes to the appropriate authorization method based on\n * `requirements.extra.assetTransferMethod`. Defaults to EIP-3009\n * for backward compatibility with older facilitators.\n *\n * When the server advertises `eip2612GasSponsoring` and the asset transfer\n * method is `permit2`, the scheme automatically signs an EIP-2612 permit\n * if the user lacks Permit2 approval. This requires `readContract` on the signer.\n */\nexport class ExactEvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClient instance.\n *\n * @param signer - The EVM signer for client operations.\n * Base flow only requires `address` + `signTypedData`.\n * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally\n * requires optional capabilities like `readContract` and tx signing helpers.\n * @param options - Optional RPC configuration used to backfill extension capabilities.\n */\n constructor(\n private readonly signer: ClientEvmSigner,\n private readonly options?: ExactEvmSchemeOptions,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.\n *\n * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the\n * signer supports `readContract`, automatically signs an EIP-2612 permit\n * when Permit2 allowance is insufficient.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @param context - Optional context with server-declared extensions\n * @returns Promise resolving to a payment payload result (with optional extensions)\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n context?: PaymentPayloadContext,\n ): Promise {\n const assetTransferMethod =\n (paymentRequirements.extra?.assetTransferMethod as AssetTransferMethod) ?? \"eip3009\";\n\n if (assetTransferMethod === \"permit2\") {\n const result = await createPermit2Payload(this.signer, x402Version, paymentRequirements);\n\n const eip2612Extensions = await this.trySignEip2612Permit(\n paymentRequirements,\n result,\n context,\n );\n\n if (eip2612Extensions) {\n return {\n ...result,\n extensions: eip2612Extensions,\n };\n }\n\n const erc20Extensions = await this.trySignErc20Approval(paymentRequirements, result, context);\n if (erc20Extensions) {\n return {\n ...result,\n extensions: erc20Extensions,\n };\n }\n\n return result;\n }\n\n return createEIP3009Payload(this.signer, x402Version, paymentRequirements);\n }\n\n /**\n * Attempts to sign an EIP-2612 permit for gasless Permit2 approval.\n *\n * Returns extension data if:\n * 1. Server advertises eip2612GasSponsoring\n * 2. Signer has readContract capability\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param result - The payment payload result from the scheme\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for EIP-2612 gas sponsoring, or undefined if not applicable\n */\n private async trySignEip2612Permit(\n requirements: PaymentRequirements,\n result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n const tokenName = requirements.extra?.name as string | undefined;\n const tokenVersion = requirements.extra?.version as string | undefined;\n if (!tokenName || !tokenVersion) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const permit2Auth = result.payload?.permit2Authorization as Record | undefined;\n const deadline =\n (permit2Auth?.deadline as string) ??\n Math.floor(Date.now() / 1000 + requirements.maxTimeoutSeconds).toString();\n\n const info = await signEip2612Permit(\n {\n address: this.signer.address,\n signTypedData: msg => this.signer.signTypedData(msg),\n readContract: capabilities.readContract,\n },\n tokenAddress,\n tokenName,\n tokenVersion,\n chainId,\n deadline,\n requirements.amount,\n );\n\n return {\n [EIP2612_GAS_SPONSORING_KEY]: { info },\n };\n }\n\n /**\n * Attempts to sign an ERC-20 approval transaction for gasless Permit2 approval.\n *\n * This is the fallback path when the token does not support EIP-2612. The client\n * signs (but does not broadcast) a raw `approve(Permit2, MaxUint256)` transaction.\n * The facilitator broadcasts it atomically before settling.\n *\n * Returns extension data if:\n * 1. Server advertises erc20ApprovalGasSponsoring\n * 2. Signer has signTransaction + getTransactionCount capabilities\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param _result - The payment payload result from the scheme (unused)\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for ERC-20 approval gas sponsoring, or undefined if not applicable\n */\n private async trySignErc20Approval(\n requirements: PaymentRequirements,\n _result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n if (!capabilities.signTransaction || !capabilities.getTransactionCount) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const info = await signErc20ApprovalTransaction(\n {\n address: this.signer.address,\n signTransaction: capabilities.signTransaction,\n getTransactionCount: capabilities.getTransactionCount,\n estimateFeesPerGas: capabilities.estimateFeesPerGas,\n },\n tokenAddress,\n chainId,\n );\n\n return {\n [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info },\n };\n }\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport { createNonce, getEvmChainId } from \"../../utils\";\n\n/**\n * Creates an EIP-3009 (transferWithAuthorization) payload.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createEIP3009Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEIP3009Payload[\"authorization\"] = {\n from: signer.address,\n to: getAddress(paymentRequirements.payTo),\n value: paymentRequirements.amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n const signature = await signEIP3009Authorization(signer, authorization, paymentRequirements);\n\n const payload: ExactEIP3009Payload = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the EIP-3009 authorization using EIP-712.\n *\n * @param signer - The EVM signer\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signEIP3009Authorization(\n signer: ClientEvmSigner,\n authorization: ExactEIP3009Payload[\"authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress } from \"viem\";\nimport {\n permit2WitnessTypes,\n PERMIT2_ADDRESS,\n x402ExactPermit2ProxyAddress,\n erc20ApproveAbi,\n erc20AllowanceAbi,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactPermit2Payload } from \"../../types\";\nimport { createPermit2Nonce, getEvmChainId } from \"../../utils\";\n\n/** Maximum uint256 value for unlimited approval. */\nconst MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\n/**\n * Creates a Permit2 payload using the x402Permit2Proxy witness pattern.\n * The spender is set to x402Permit2Proxy, which enforces that funds\n * can only be sent to the witness.to address.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createPermit2Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const now = Math.floor(Date.now() / 1000);\n const nonce = createPermit2Nonce();\n\n // Lower time bound - allow some clock skew\n const validAfter = (now - 600).toString();\n // Upper time bound is enforced by Permit2's deadline field\n const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();\n\n const permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"] = {\n from: signer.address,\n permitted: {\n token: getAddress(paymentRequirements.asset),\n amount: paymentRequirements.amount,\n },\n spender: x402ExactPermit2ProxyAddress,\n nonce,\n deadline,\n witness: {\n to: getAddress(paymentRequirements.payTo),\n validAfter,\n },\n };\n\n const signature = await signPermit2Authorization(\n signer,\n permit2Authorization,\n paymentRequirements,\n );\n\n const payload: ExactPermit2Payload = {\n signature,\n permit2Authorization,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the Permit2 authorization using EIP-712 with witness data.\n * The signature authorizes the x402Permit2Proxy to transfer tokens on behalf of the signer.\n *\n * @param signer - The EVM signer\n * @param permit2Authorization - The Permit2 authorization parameters\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signPermit2Authorization(\n signer: ClientEvmSigner,\n permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n const domain = {\n name: \"Permit2\",\n chainId,\n verifyingContract: PERMIT2_ADDRESS,\n };\n\n const message = {\n permitted: {\n token: getAddress(permit2Authorization.permitted.token),\n amount: BigInt(permit2Authorization.permitted.amount),\n },\n spender: getAddress(permit2Authorization.spender),\n nonce: BigInt(permit2Authorization.nonce),\n deadline: BigInt(permit2Authorization.deadline),\n witness: {\n to: getAddress(permit2Authorization.witness.to),\n validAfter: BigInt(permit2Authorization.witness.validAfter),\n },\n };\n\n return await signer.signTypedData({\n domain,\n types: permit2WitnessTypes,\n primaryType: \"PermitWitnessTransferFrom\",\n message,\n });\n}\n\n/**\n * Creates transaction data to approve Permit2 to spend tokens.\n * The user sends this transaction (paying gas) before using Permit2 flow.\n *\n * @param tokenAddress - The ERC20 token contract address\n * @returns Transaction data to send for approval\n *\n * @example\n * ```typescript\n * const tx = createPermit2ApprovalTx(\"0x...\");\n * await walletClient.sendTransaction({\n * to: tx.to,\n * data: tx.data,\n * });\n * ```\n */\nexport function createPermit2ApprovalTx(tokenAddress: `0x${string}`): {\n to: `0x${string}`;\n data: `0x${string}`;\n} {\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [PERMIT2_ADDRESS, MAX_UINT256],\n });\n\n return {\n to: getAddress(tokenAddress),\n data,\n };\n}\n\n/**\n * Parameters for checking Permit2 allowance.\n * Application provides these to check if approval is needed.\n */\nexport interface Permit2AllowanceParams {\n tokenAddress: `0x${string}`;\n ownerAddress: `0x${string}`;\n}\n\n/**\n * Returns contract read parameters for checking Permit2 allowance.\n * Use with a public client to check if the user has approved Permit2.\n *\n * @param params - The allowance check parameters\n * @returns Contract read parameters for checking allowance\n *\n * @example\n * ```typescript\n * const readParams = getPermit2AllowanceReadParams({\n * tokenAddress: \"0x...\",\n * ownerAddress: \"0x...\",\n * });\n *\n * const allowance = await publicClient.readContract(readParams);\n * const needsApproval = allowance < requiredAmount;\n * ```\n */\nexport function getPermit2AllowanceReadParams(params: Permit2AllowanceParams): {\n address: `0x${string}`;\n abi: typeof erc20AllowanceAbi;\n functionName: \"allowance\";\n args: [`0x${string}`, `0x${string}`];\n} {\n return {\n address: getAddress(params.tokenAddress),\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [getAddress(params.ownerAddress), PERMIT2_ADDRESS],\n };\n}\n","import { getAddress } from \"viem\";\nimport { eip2612PermitTypes, eip2612NoncesAbi, PERMIT2_ADDRESS } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport type { Eip2612GasSponsoringInfo } from \"../extensions\";\n\nexport type Eip2612PermitSigner = Pick & {\n readContract: NonNullable;\n};\n\n/**\n * Signs an EIP-2612 permit authorizing the Permit2 contract to spend tokens.\n *\n * This creates a gasless off-chain signature that the facilitator can submit\n * on-chain via `x402Permit2Proxy.settleWithPermit()`.\n *\n * The `permittedAmount` must match the Permit2 `permitted.amount` exactly, as the\n * proxy contract enforces `permit2612.value == permittedAmount`.\n *\n * @param signer - The client EVM signer (must support readContract for nonce query)\n * @param tokenAddress - The ERC-20 token contract address\n * @param tokenName - The token name (from paymentRequirements.extra.name)\n * @param tokenVersion - The token version (from paymentRequirements.extra.version)\n * @param chainId - The chain ID\n * @param deadline - The deadline for the permit (unix timestamp as string)\n * @param permittedAmount - The Permit2 permitted amount (must match exactly)\n * @returns The EIP-2612 gas sponsoring info object\n */\nexport async function signEip2612Permit(\n signer: Eip2612PermitSigner,\n tokenAddress: `0x${string}`,\n tokenName: string,\n tokenVersion: string,\n chainId: number,\n deadline: string,\n permittedAmount: string,\n): Promise {\n const owner = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Query the current EIP-2612 nonce from the token contract\n const nonce = (await signer.readContract({\n address: tokenAddress,\n abi: eip2612NoncesAbi,\n functionName: \"nonces\",\n args: [owner],\n })) as bigint;\n\n // Construct EIP-712 domain for the token's permit function\n const domain = {\n name: tokenName,\n version: tokenVersion,\n chainId,\n verifyingContract: tokenAddress,\n };\n\n const approvalAmount = BigInt(permittedAmount);\n\n const message = {\n owner,\n spender,\n value: approvalAmount,\n nonce,\n deadline: BigInt(deadline),\n };\n\n // Sign the EIP-2612 permit\n const signature = await signer.signTypedData({\n domain,\n types: eip2612PermitTypes,\n primaryType: \"Permit\",\n message,\n });\n\n return {\n from: owner,\n asset: tokenAddress,\n spender,\n amount: approvalAmount.toString(),\n nonce: nonce.toString(),\n deadline,\n signature,\n version: \"1\",\n };\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport {\n PERMIT2_ADDRESS,\n erc20ApproveAbi,\n ERC20_APPROVE_GAS_LIMIT,\n DEFAULT_MAX_FEE_PER_GAS,\n DEFAULT_MAX_PRIORITY_FEE_PER_GAS,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport {\n ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n type Erc20ApprovalGasSponsoringInfo,\n} from \"../extensions\";\n\nexport type Erc20ApprovalTxSigner = Pick & {\n signTransaction: NonNullable;\n getTransactionCount: NonNullable;\n estimateFeesPerGas?: NonNullable;\n};\n\n/**\n * Signs an EIP-1559 `approve(Permit2, MaxUint256)` transaction for the given token.\n *\n * The signed transaction is NOT broadcast here — the facilitator broadcasts it\n * atomically before settling the Permit2 payment. This enables Permit2 payments\n * for generic ERC-20 tokens that do NOT implement EIP-2612.\n *\n * Always approves MaxUint256 regardless of the payment amount.\n *\n * @param signer - The client EVM signer (must support signTransaction, getTransactionCount)\n * @param tokenAddress - The ERC-20 token contract address\n * @param chainId - The chain ID\n * @returns The ERC-20 approval gas sponsoring info object\n */\nexport async function signErc20ApprovalTransaction(\n signer: Erc20ApprovalTxSigner,\n tokenAddress: `0x${string}`,\n chainId: number,\n): Promise {\n const from = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Encode approve(PERMIT2_ADDRESS, MaxUint256) calldata\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [spender, maxUint256],\n });\n\n // Get current nonce for the sender\n const nonce = await signer.getTransactionCount({ address: from });\n\n // Get current fee estimates, with fallback values\n let maxFeePerGas: bigint;\n let maxPriorityFeePerGas: bigint;\n try {\n const fees = await signer.estimateFeesPerGas?.();\n if (!fees) {\n throw new Error(\"no fee estimates available\");\n }\n maxFeePerGas = fees.maxFeePerGas;\n maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n } catch {\n maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;\n maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;\n }\n\n // Sign the EIP-1559 transaction (not broadcast)\n const signedTransaction = await signer.signTransaction({\n to: tokenAddress,\n data,\n nonce,\n gas: ERC20_APPROVE_GAS_LIMIT,\n maxFeePerGas,\n maxPriorityFeePerGas,\n chainId,\n });\n\n return {\n from,\n asset: tokenAddress,\n spender,\n amount: maxUint256.toString(),\n signedTransaction,\n version: ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n };\n}\n","import { createPublicClient, http } from \"viem\";\nimport type { ClientEvmSigner } from \"../../signer\";\nimport { getEvmChainId } from \"../../utils\";\n\nexport type ExactEvmSchemeConfig = {\n rpcUrl?: string;\n};\n\nexport type ExactEvmSchemeConfigByChainId = Record;\n\nexport type ExactEvmSchemeOptions = ExactEvmSchemeConfig | ExactEvmSchemeConfigByChainId;\n\ntype ExtensionRpcCapabilities = Pick<\n ClientEvmSigner,\n \"readContract\" | \"signTransaction\" | \"getTransactionCount\" | \"estimateFeesPerGas\"\n>;\n\nconst rpcClientCache = new Map>();\n\n/**\n * Determines whether scheme options are keyed by numeric chain id.\n *\n * @param options - Exact EVM scheme options provided by the client.\n * @returns True when options are a chainId-to-config mapping.\n */\nfunction isConfigByChainId(\n options: ExactEvmSchemeOptions,\n): options is ExactEvmSchemeConfigByChainId {\n const keys = Object.keys(options);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n\n/**\n * Returns a cached viem public client for a specific RPC URL.\n *\n * @param rpcUrl - The RPC endpoint URL used to construct the client.\n * @returns A cached or newly created viem public client instance.\n */\nfunction getRpcClient(rpcUrl: string): ReturnType {\n const existing = rpcClientCache.get(rpcUrl);\n if (existing) {\n return existing;\n }\n\n const client = createPublicClient({\n transport: http(rpcUrl),\n });\n rpcClientCache.set(rpcUrl, client);\n return client;\n}\n\n/**\n * Resolves the RPC URL for a given CAIP-2 network from scheme options.\n *\n * @param network - CAIP-2 network identifier.\n * @param options - Optional scheme configuration (single config or chain map).\n * @returns The configured RPC URL for the network, if available.\n */\nexport function resolveRpcUrl(\n network: string,\n options?: ExactEvmSchemeOptions,\n): string | undefined {\n if (!options) {\n return undefined;\n }\n\n if (isConfigByChainId(options)) {\n const chainId = getEvmChainId(network);\n const optionsByChainId = options as ExactEvmSchemeConfigByChainId;\n return optionsByChainId[chainId]?.rpcUrl;\n }\n\n return (options as ExactEvmSchemeConfig).rpcUrl;\n}\n\n/**\n * Resolves extension RPC capabilities from signer methods and optional RPC backfill.\n *\n * @param network - CAIP-2 network identifier for chain resolution.\n * @param signer - Client signer with optional RPC-like methods.\n * @param options - Optional scheme configuration used for RPC backfill.\n * @returns The best available capability set for extension enrichment flows.\n */\nexport function resolveExtensionRpcCapabilities(\n network: string,\n signer: ClientEvmSigner,\n options?: ExactEvmSchemeOptions,\n): ExtensionRpcCapabilities {\n const capabilities: ExtensionRpcCapabilities = {\n signTransaction: signer.signTransaction,\n readContract: signer.readContract,\n getTransactionCount: signer.getTransactionCount,\n estimateFeesPerGas: signer.estimateFeesPerGas,\n };\n\n const needsRpcBackfill =\n !capabilities.readContract ||\n !capabilities.getTransactionCount ||\n !capabilities.estimateFeesPerGas;\n if (!needsRpcBackfill) {\n return capabilities;\n }\n\n const rpcUrl = resolveRpcUrl(network, options);\n if (!rpcUrl) {\n return capabilities;\n }\n const rpcClient = getRpcClient(rpcUrl);\n if (!capabilities.readContract) {\n capabilities.readContract = args => rpcClient.readContract(args as never) as Promise;\n }\n if (!capabilities.getTransactionCount) {\n capabilities.getTransactionCount = async args =>\n rpcClient.getTransactionCount({ address: args.address });\n }\n if (!capabilities.estimateFeesPerGas) {\n capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();\n }\n\n return capabilities;\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeOptions } from \"./rpc\";\nimport { ExactEvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Client\n */\nexport interface EvmClientConfig {\n /**\n * The EVM signer to use for creating payment payloads\n */\n signer: ClientEvmSigner;\n\n /**\n * Optional payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional Exact EVM client scheme options.\n * Supports either a single config ({ rpcUrl }) or per-chain configs\n * keyed by EVM chain ID ({ 8453: { rpcUrl: \"...\" } }).\n */\n schemeOptions?: ExactEvmSchemeOptions;\n\n /**\n * Optional specific networks to register.\n * If not provided, registers wildcard support (eip155:*).\n */\n networks?: Network[];\n}\n\n/**\n * Registers EVM exact payment schemes to an x402Client instance.\n *\n * This function registers:\n * - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for EVM client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@x402/evm/exact/client/register\";\n * import { x402Client } from \"@x402/core/client\";\n * import { privateKeyToAccount } from \"viem/accounts\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const client = new x402Client();\n * registerExactEvmScheme(client, { signer: account });\n * ```\n */\nexport function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client {\n const evmScheme = new ExactEvmScheme(config.signer, config.schemeOptions);\n\n // Register V2 scheme\n // EIP-2612 gas sponsoring is handled internally by the scheme when the\n // server advertises support - no separate extension registration needed.\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach(network => {\n client.register(network, evmScheme);\n });\n } else {\n // Register wildcard for all EVM chains\n client.register(\"eip155:*\", evmScheme);\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactEvmSchemeV1(config.signer));\n });\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * ClientEvmSigner - Used by x402 clients to sign payment authorizations.\n *\n * Typically a viem WalletClient extended with publicActions:\n * ```typescript\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * Or composed via `toClientEvmSigner(account, publicClient)`.\n */\nexport type ClientEvmSigner = {\n readonly address: `0x${string}`;\n signTypedData(message: {\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n }): Promise<`0x${string}`>;\n /**\n * Optional on-chain reads.\n * Required only for extension enrichment (EIP-2612 / ERC-20 approval).\n */\n readContract?(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n /**\n * Optional: Signs a raw EIP-1559 transaction without broadcasting.\n * Required for ERC-20 approval gas sponsoring when the token lacks EIP-2612.\n */\n signTransaction?(args: {\n to: `0x${string}`;\n data: `0x${string}`;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n chainId: number;\n }): Promise<`0x${string}`>;\n /**\n * Optional: Gets the current transaction count (nonce) for an address.\n * Required for ERC-20 approval gas sponsoring.\n */\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n /**\n * Optional: Estimates current gas fees per gas.\n * Required for ERC-20 approval gas sponsoring.\n */\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n};\n\n/**\n * FacilitatorEvmSigner - Used by x402 facilitators to verify and settle payments\n * This is typically a viem PublicClient + WalletClient combination that can\n * read contract state, verify signatures, write transactions, and wait for receipts\n *\n * Supports multiple addresses for load balancing, key rotation, and high availability\n */\nexport type FacilitatorEvmSigner = {\n /**\n * Get all addresses this facilitator can use for signing\n * Enables dynamic address selection for load balancing and key rotation\n */\n getAddresses(): readonly `0x${string}`[];\n\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n verifyTypedData(args: {\n address: `0x${string}`;\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n signature: `0x${string}`;\n }): Promise;\n writeContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n /** Optional gas limit. When provided, skips eth_estimateGas simulation. */\n gas?: bigint;\n }): Promise<`0x${string}`>;\n sendTransaction(args: { to: `0x${string}`; data: `0x${string}` }): Promise<`0x${string}`>;\n waitForTransactionReceipt(args: { hash: `0x${string}` }): Promise<{ status: string }>;\n getCode(args: { address: `0x${string}` }): Promise<`0x${string}` | undefined>;\n};\n\n/**\n * Composes a ClientEvmSigner from a local account and a public client.\n *\n * Use this when your signer (e.g., `privateKeyToAccount`) doesn't have\n * `readContract`. The `publicClient` provides the on-chain read capability.\n *\n * Alternatively, use a WalletClient extended with publicActions directly:\n * ```typescript\n * const signer = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * @param signer - A signer with `address` and `signTypedData` (and optionally `readContract`)\n * @param publicClient - A client with optional read/nonce/fee helpers\n * @param publicClient.readContract - The readContract method from the public client\n * @param publicClient.getTransactionCount - Optional getTransactionCount for ERC-20 approval\n * @param publicClient.estimateFeesPerGas - Optional estimateFeesPerGas for ERC-20 approval\n * @returns A ClientEvmSigner with any available optional capabilities\n *\n * @example\n * ```typescript\n * const account = privateKeyToAccount(\"0x...\");\n * const publicClient = createPublicClient({ chain: baseSepolia, transport: http() });\n * const signer = toClientEvmSigner(account, publicClient);\n * ```\n */\nexport function toClientEvmSigner(\n signer: Omit & {\n readContract?: ClientEvmSigner[\"readContract\"];\n },\n publicClient?: {\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n },\n): ClientEvmSigner {\n const readContract = signer.readContract ?? publicClient?.readContract.bind(publicClient);\n\n const result: ClientEvmSigner = {\n address: signer.address,\n signTypedData: msg => signer.signTypedData(msg),\n };\n\n if (readContract) {\n result.readContract = readContract;\n }\n\n // Forward optional capabilities from signer or publicClient\n const signTransaction = signer.signTransaction;\n if (signTransaction) {\n result.signTransaction = args => signTransaction(args);\n }\n\n const getTransactionCount =\n signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);\n if (getTransactionCount) {\n result.getTransactionCount = args => getTransactionCount(args);\n }\n\n const estimateFeesPerGas =\n signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);\n if (estimateFeesPerGas) {\n result.estimateFeesPerGas = () => estimateFeesPerGas();\n }\n\n return result;\n}\n\n/**\n * Converts a viem client with single address to a FacilitatorEvmSigner\n * Wraps the single address in a getAddresses() function for compatibility\n *\n * @param client - The client to convert (must have 'address' property)\n * @returns FacilitatorEvmSigner with getAddresses() support\n */\nexport function toFacilitatorEvmSigner(\n client: Omit & { address: `0x${string}` },\n): FacilitatorEvmSigner {\n return {\n ...client,\n getAddresses: () => [client.address],\n };\n}\n","/**\n * Rule-Based Classifier (v2 — Weighted Scoring)\n *\n * Scores a request across 14 weighted dimensions and maps the aggregate\n * score to a tier using configurable boundaries. Confidence is calibrated\n * via sigmoid — low confidence triggers the fallback classifier.\n *\n * Handles 70-80% of requests in < 1ms with zero cost.\n */\n\nimport type { Tier, ScoringResult, ScoringConfig } from \"./types.js\";\n\ntype DimensionScore = { name: string; score: number; signal: string | null };\n\n// ─── Dimension Scorers ───\n// Each returns a score in [-1, 1] and an optional signal string.\n\nfunction scoreTokenCount(\n estimatedTokens: number,\n thresholds: { simple: number; complex: number },\n): DimensionScore {\n if (estimatedTokens < thresholds.simple) {\n return { name: \"tokenCount\", score: -1.0, signal: `short (${estimatedTokens} tokens)` };\n }\n if (estimatedTokens > thresholds.complex) {\n return { name: \"tokenCount\", score: 1.0, signal: `long (${estimatedTokens} tokens)` };\n }\n return { name: \"tokenCount\", score: 0, signal: null };\n}\n\nfunction scoreKeywordMatch(\n text: string,\n keywords: string[],\n name: string,\n signalLabel: string,\n thresholds: { low: number; high: number },\n scores: { none: number; low: number; high: number },\n): DimensionScore {\n const matches = keywords.filter((kw) => text.includes(kw.toLowerCase()));\n if (matches.length >= thresholds.high) {\n return {\n name,\n score: scores.high,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n if (matches.length >= thresholds.low) {\n return {\n name,\n score: scores.low,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n return { name, score: scores.none, signal: null };\n}\n\nfunction scoreMultiStep(text: string): DimensionScore {\n const patterns = [/first.*then/i, /step \\d/i, /\\d\\.\\s/];\n const hits = patterns.filter((p) => p.test(text));\n if (hits.length > 0) {\n return { name: \"multiStepPatterns\", score: 0.5, signal: \"multi-step\" };\n }\n return { name: \"multiStepPatterns\", score: 0, signal: null };\n}\n\nfunction scoreQuestionComplexity(prompt: string): DimensionScore {\n const count = (prompt.match(/\\?/g) || []).length;\n if (count > 3) {\n return { name: \"questionComplexity\", score: 0.5, signal: `${count} questions` };\n }\n return { name: \"questionComplexity\", score: 0, signal: null };\n}\n\n/**\n * Score agentic task indicators.\n * Returns agenticScore (0-1) based on keyword matches:\n * - 4+ matches = 1.0 (high agentic)\n * - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)\n * - 1-2 matches = 0.2 (low agentic)\n *\n * Thresholds raised because common keywords were pruned from the list.\n */\nfunction scoreAgenticTask(\n text: string,\n keywords: string[],\n): { dimensionScore: DimensionScore; agenticScore: number } {\n let matchCount = 0;\n const signals: string[] = [];\n\n for (const keyword of keywords) {\n if (text.includes(keyword.toLowerCase())) {\n matchCount++;\n if (signals.length < 3) {\n signals.push(keyword);\n }\n }\n }\n\n // Threshold-based scoring (raised thresholds after keyword pruning)\n if (matchCount >= 4) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 1.0,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 1.0,\n };\n } else if (matchCount >= 3) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.6,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 0.6,\n };\n } else if (matchCount >= 1) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.2,\n signal: `agentic-light (${signals.join(\", \")})`,\n },\n agenticScore: 0.2,\n };\n }\n\n return {\n dimensionScore: { name: \"agenticTask\", score: 0, signal: null },\n agenticScore: 0,\n };\n}\n\n// ─── Main Classifier ───\n\nexport function classifyByRules(\n prompt: string,\n systemPrompt: string | undefined,\n estimatedTokens: number,\n config: ScoringConfig,\n): ScoringResult {\n // Score against user prompt only — system prompts contain boilerplate keywords\n // (tool definitions, skill descriptions, behavioral rules) that dominate scoring\n // and make every request score identically. See GitHub issue #50.\n const userText = prompt.toLowerCase();\n\n // Score all 14 dimensions against user text only\n const dimensions: DimensionScore[] = [\n // Token count uses total estimated tokens (system + user) — context size matters for model selection\n scoreTokenCount(estimatedTokens, config.tokenCountThresholds),\n scoreKeywordMatch(\n userText,\n config.codeKeywords,\n \"codePresence\",\n \"code\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.reasoningKeywords,\n \"reasoningMarkers\",\n \"reasoning\",\n { low: 1, high: 2 },\n { none: 0, low: 0.7, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.technicalKeywords,\n \"technicalTerms\",\n \"technical\",\n { low: 2, high: 4 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.creativeKeywords,\n \"creativeMarkers\",\n \"creative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.simpleKeywords,\n \"simpleIndicators\",\n \"simple\",\n { low: 1, high: 2 },\n { none: 0, low: -1.0, high: -1.0 },\n ),\n scoreMultiStep(userText),\n scoreQuestionComplexity(prompt),\n\n // 6 new dimensions\n scoreKeywordMatch(\n userText,\n config.imperativeVerbs,\n \"imperativeVerbs\",\n \"imperative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.constraintIndicators,\n \"constraintCount\",\n \"constraints\",\n { low: 1, high: 3 },\n { none: 0, low: 0.3, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.outputFormatKeywords,\n \"outputFormat\",\n \"format\",\n { low: 1, high: 2 },\n { none: 0, low: 0.4, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.referenceKeywords,\n \"referenceComplexity\",\n \"references\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.negationKeywords,\n \"negationComplexity\",\n \"negation\",\n { low: 2, high: 3 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.domainSpecificKeywords,\n \"domainSpecificity\",\n \"domain-specific\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.8 },\n ),\n ];\n\n // Score agentic task indicators — user prompt only\n // System prompt describes assistant behavior, not user's intent.\n // e.g. a coding assistant system prompt with \"edit files\" / \"fix bugs\" should NOT\n // force every request into agentic mode.\n const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);\n dimensions.push(agenticResult.dimensionScore);\n const agenticScore = agenticResult.agenticScore;\n\n // Collect signals\n const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);\n\n // Compute weighted score\n const weights = config.dimensionWeights;\n let weightedScore = 0;\n for (const d of dimensions) {\n const w = weights[d.name] ?? 0;\n weightedScore += d.score * w;\n }\n\n // Count reasoning markers for override — only check USER prompt, not system prompt\n // This prevents system prompts with \"step by step\" from triggering REASONING for simple queries\n const reasoningMatches = config.reasoningKeywords.filter((kw) =>\n userText.includes(kw.toLowerCase()),\n );\n\n // Direct reasoning override: 2+ reasoning markers = high confidence REASONING\n if (reasoningMatches.length >= 2) {\n const confidence = calibrateConfidence(\n Math.max(weightedScore, 0.3), // ensure positive for confidence calc\n config.confidenceSteepness,\n );\n return {\n score: weightedScore,\n tier: \"REASONING\",\n confidence: Math.max(confidence, 0.85),\n signals,\n agenticScore,\n dimensions,\n };\n }\n\n // Map weighted score to tier using boundaries\n const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;\n let tier: Tier;\n let distanceFromBoundary: number;\n\n if (weightedScore < simpleMedium) {\n tier = \"SIMPLE\";\n distanceFromBoundary = simpleMedium - weightedScore;\n } else if (weightedScore < mediumComplex) {\n tier = \"MEDIUM\";\n distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);\n } else if (weightedScore < complexReasoning) {\n tier = \"COMPLEX\";\n distanceFromBoundary = Math.min(\n weightedScore - mediumComplex,\n complexReasoning - weightedScore,\n );\n } else {\n tier = \"REASONING\";\n distanceFromBoundary = weightedScore - complexReasoning;\n }\n\n // Calibrate confidence via sigmoid of distance from nearest boundary\n const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);\n\n // If confidence is below threshold → ambiguous\n if (confidence < config.confidenceThreshold) {\n return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };\n }\n\n return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };\n}\n\n/**\n * Sigmoid confidence calibration.\n * Maps distance from tier boundary to [0.5, 1.0] confidence range.\n */\nfunction calibrateConfidence(distance: number, steepness: number): number {\n return 1 / (1 + Math.exp(-steepness * distance));\n}\n","/**\n * Tier → Model Selection\n *\n * Maps a classification tier to the cheapest capable model.\n * Builds RoutingDecision metadata with cost estimates and savings.\n */\n\nimport type { Tier, TierConfig, RoutingDecision } from \"./types.js\";\n\nexport type ModelPricing = {\n inputPrice: number; // per 1M tokens\n outputPrice: number; // per 1M tokens\n};\n\nconst BASELINE_MODEL_ID = \"anthropic/claude-opus-4.6\";\n\n// Hardcoded fallback: Claude Opus 4.6 pricing (per 1M tokens)\n// Used when baseline model not found in dynamic pricing map\nconst BASELINE_INPUT_PRICE = 5.0;\nconst BASELINE_OUTPUT_PRICE = 25.0;\n\n/**\n * Select the primary model for a tier and build the RoutingDecision.\n */\nexport function selectModel(\n tier: Tier,\n confidence: number,\n method: \"rules\" | \"llm\",\n reasoning: string,\n tierConfigs: Record,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n agenticScore?: number,\n): RoutingDecision {\n const tierConfig = tierConfigs[tier];\n const model = tierConfig.primary;\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n const costEstimate = inputCost + outputCost;\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return {\n model,\n tier,\n confidence,\n method,\n reasoning,\n costEstimate,\n baselineCost,\n savings,\n ...(agenticScore !== undefined && { agenticScore }),\n };\n}\n\n/**\n * Get the ordered fallback chain for a tier: [primary, ...fallbacks].\n */\nexport function getFallbackChain(tier: Tier, tierConfigs: Record): string[] {\n const config = tierConfigs[tier];\n return [config.primary, ...config.fallback];\n}\n\n/**\n * Calculate cost for a specific model (used when fallback model is used).\n * Returns updated cost fields for RoutingDecision.\n */\n// Server-side margin applied to all x402 payments (must match blockrun server's MARGIN_PERCENT)\nconst SERVER_MARGIN_PERCENT = 5;\n// Minimum payment enforced by CDP Facilitator (must match blockrun server's MIN_PAYMENT_USD)\nconst MIN_PAYMENT_USD = 0.001;\n\nexport function calculateModelCost(\n model: string,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n): { costEstimate: number; baselineCost: number; savings: number } {\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n // Include server margin + minimum payment to match actual x402 charge\n const costEstimate = Math.max(\n (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100),\n MIN_PAYMENT_USD,\n );\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return { costEstimate, baselineCost, savings };\n}\n\n/**\n * Filter a model list to only those that support tool calling.\n * When hasTools is false, returns the list unchanged.\n * When all models lack tool calling support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByToolCalling(\n models: string[],\n hasTools: boolean,\n supportsToolCalling: (modelId: string) => boolean,\n): string[] {\n if (!hasTools) return models;\n const filtered = models.filter(supportsToolCalling);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to only those that support vision (image inputs).\n * When hasVision is false, returns the list unchanged.\n * When all models lack vision support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByVision(\n models: string[],\n hasVision: boolean,\n supportsVision: (modelId: string) => boolean,\n): string[] {\n if (!hasVision) return models;\n const filtered = models.filter(supportsVision);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to remove user-excluded models.\n * When all models are excluded, returns the full list as a fallback\n * (same safety pattern as filterByToolCalling/filterByVision).\n */\nexport function filterByExcludeList(models: string[], excludeList: Set): string[] {\n if (excludeList.size === 0) return models;\n const filtered = models.filter((m) => !excludeList.has(m));\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Get the fallback chain filtered by context length.\n * Only returns models that can handle the estimated total context.\n *\n * @param tier - The tier to get fallback chain for\n * @param tierConfigs - Tier configurations\n * @param estimatedTotalTokens - Estimated total context (input + output)\n * @param getContextWindow - Function to get context window for a model ID\n * @returns Filtered list of models that can handle the context\n */\nexport function getFallbackChainFiltered(\n tier: Tier,\n tierConfigs: Record,\n estimatedTotalTokens: number,\n getContextWindow: (modelId: string) => number | undefined,\n): string[] {\n const fullChain = getFallbackChain(tier, tierConfigs);\n\n // Filter to models that can handle the context\n const filtered = fullChain.filter((modelId) => {\n const contextWindow = getContextWindow(modelId);\n if (contextWindow === undefined) {\n // Unknown model - include it (let API reject if needed)\n return true;\n }\n // Add 10% buffer for safety\n return contextWindow >= estimatedTotalTokens * 1.1;\n });\n\n // If all models filtered out, return the original chain\n // (let the API error out - better than no options)\n if (filtered.length === 0) {\n return fullChain;\n }\n\n return filtered;\n}\n","/**\n * Router Strategy Registry\n *\n * Pluggable strategy system for request routing.\n * Default: RulesStrategy — identical to the original inline route() logic, <1ms.\n */\n\nimport type { Tier, RoutingDecision, RouterStrategy, RouterOptions } from \"./types.js\";\nimport { classifyByRules } from \"./rules.js\";\nimport { selectModel } from \"./selector.js\";\n\n/**\n * Rules-based routing strategy.\n * Extracted from the original route() in index.ts — logic is identical.\n * Attaches tierConfigs and profile to the decision for downstream use.\n */\nexport class RulesStrategy implements RouterStrategy {\n readonly name = \"rules\";\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ): RoutingDecision {\n const { config, modelPricing } = options;\n\n // Estimate input tokens (~4 chars per token)\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // --- Rule-based classification (runs first to get agenticScore) ---\n const ruleResult = classifyByRules(prompt, systemPrompt, estimatedTokens, config.scoring);\n\n // --- Select tier configs based on routing profile ---\n const { routingProfile } = options;\n let tierConfigs: Record;\n let profileSuffix: string;\n let profile: RoutingDecision[\"profile\"];\n\n if (routingProfile === \"eco\" && config.ecoTiers) {\n tierConfigs = config.ecoTiers;\n profileSuffix = \" | eco\";\n profile = \"eco\";\n } else if (routingProfile === \"premium\" && config.premiumTiers) {\n tierConfigs = config.premiumTiers;\n profileSuffix = \" | premium\";\n profile = \"premium\";\n } else {\n // Auto profile (or undefined): intelligent routing with agentic detection\n const agenticScore = ruleResult.agenticScore ?? 0;\n const isAutoAgentic = agenticScore >= 0.5;\n const isExplicitAgentic = config.overrides.agenticMode ?? false;\n const hasToolsInRequest = options.hasTools ?? false;\n const useAgenticTiers =\n (hasToolsInRequest || isAutoAgentic || isExplicitAgentic) && config.agenticTiers != null;\n tierConfigs = useAgenticTiers ? config.agenticTiers! : config.tiers;\n profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? \" (tools)\" : \"\"}` : \"\";\n profile = useAgenticTiers ? \"agentic\" : \"auto\";\n }\n\n const agenticScoreValue = ruleResult.agenticScore;\n\n // --- Override: large context → force COMPLEX ---\n if (estimatedTokens > config.overrides.maxTokensForceComplex) {\n const decision = selectModel(\n \"COMPLEX\",\n 0.95,\n \"rules\",\n `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n\n // Structured output detection\n const hasStructuredOutput = systemPrompt ? /json|structured|schema/i.test(systemPrompt) : false;\n\n let tier: Tier;\n let confidence: number;\n const method: \"rules\" | \"llm\" = \"rules\";\n let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(\", \")}`;\n\n if (ruleResult.tier !== null) {\n tier = ruleResult.tier;\n confidence = ruleResult.confidence;\n } else {\n // Ambiguous — default to configurable tier (no external API call)\n tier = config.overrides.ambiguousDefaultTier;\n confidence = 0.5;\n reasoning += ` | ambiguous -> default: ${tier}`;\n }\n\n // Apply structured output minimum tier\n if (hasStructuredOutput) {\n const tierRank: Record = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };\n const minTier = config.overrides.structuredOutputMinTier;\n if (tierRank[tier] < tierRank[minTier]) {\n reasoning += ` | upgraded to ${minTier} (structured output)`;\n tier = minTier;\n }\n }\n\n // Add routing profile suffix to reasoning\n reasoning += profileSuffix;\n\n const decision = selectModel(\n tier,\n confidence,\n method,\n reasoning,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n}\n\n// --- Strategy Registry ---\n\nconst registry = new Map();\nregistry.set(\"rules\", new RulesStrategy());\n\nexport function getStrategy(name: string): RouterStrategy {\n const strategy = registry.get(name);\n if (!strategy) {\n throw new Error(`Unknown routing strategy: ${name}`);\n }\n return strategy;\n}\n\nexport function registerStrategy(strategy: RouterStrategy): void {\n registry.set(strategy.name, strategy);\n}\n","/**\n * Default Routing Config\n *\n * All routing parameters as a TypeScript constant.\n * Operators override via openclaw.yaml plugin config.\n *\n * Scoring uses 14 weighted dimensions with sigmoid confidence calibration.\n */\n\nimport type { RoutingConfig } from \"./types.js\";\n\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n version: \"2.0\",\n\n classifier: {\n llmModel: \"google/gemini-2.5-flash\",\n llmMaxTokens: 10,\n llmTemperature: 0,\n promptTruncationChars: 500,\n cacheTtlMs: 3_600_000, // 1 hour\n },\n\n scoring: {\n tokenCountThresholds: { simple: 50, complex: 500 },\n\n // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR\n codeKeywords: [\n // English\n \"function\",\n \"class\",\n \"import\",\n \"def\",\n \"SELECT\",\n \"async\",\n \"await\",\n \"const\",\n \"let\",\n \"var\",\n \"return\",\n \"```\",\n // Chinese\n \"函数\",\n \"类\",\n \"导入\",\n \"定义\",\n \"查询\",\n \"异步\",\n \"等待\",\n \"常量\",\n \"变量\",\n \"返回\",\n // Japanese\n \"関数\",\n \"クラス\",\n \"インポート\",\n \"非同期\",\n \"定数\",\n \"変数\",\n // Russian\n \"функция\",\n \"класс\",\n \"импорт\",\n \"определ\",\n \"запрос\",\n \"асинхронный\",\n \"ожидать\",\n \"константа\",\n \"переменная\",\n \"вернуть\",\n // German\n \"funktion\",\n \"klasse\",\n \"importieren\",\n \"definieren\",\n \"abfrage\",\n \"asynchron\",\n \"erwarten\",\n \"konstante\",\n \"variable\",\n \"zurückgeben\",\n // Spanish\n \"función\",\n \"clase\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"asíncrono\",\n \"esperar\",\n \"constante\",\n \"variable\",\n \"retornar\",\n // Portuguese\n \"função\",\n \"classe\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"assíncrono\",\n \"aguardar\",\n \"constante\",\n \"variável\",\n \"retornar\",\n // Korean\n \"함수\",\n \"클래스\",\n \"가져오기\",\n \"정의\",\n \"쿼리\",\n \"비동기\",\n \"대기\",\n \"상수\",\n \"변수\",\n \"반환\",\n // Arabic\n \"دالة\",\n \"فئة\",\n \"استيراد\",\n \"تعريف\",\n \"استعلام\",\n \"غير متزامن\",\n \"انتظار\",\n \"ثابت\",\n \"متغير\",\n \"إرجاع\",\n ],\n reasoningKeywords: [\n // English\n \"prove\",\n \"theorem\",\n \"derive\",\n \"step by step\",\n \"chain of thought\",\n \"formally\",\n \"mathematical\",\n \"proof\",\n \"logically\",\n // Chinese\n \"证明\",\n \"定理\",\n \"推导\",\n \"逐步\",\n \"思维链\",\n \"形式化\",\n \"数学\",\n \"逻辑\",\n // Japanese\n \"証明\",\n \"定理\",\n \"導出\",\n \"ステップバイステップ\",\n \"論理的\",\n // Russian\n \"доказать\",\n \"докажи\",\n \"доказательств\",\n \"теорема\",\n \"вывести\",\n \"шаг за шагом\",\n \"пошагово\",\n \"поэтапно\",\n \"цепочка рассуждений\",\n \"рассуждени\",\n \"формально\",\n \"математически\",\n \"логически\",\n // German\n \"beweisen\",\n \"beweis\",\n \"theorem\",\n \"ableiten\",\n \"schritt für schritt\",\n \"gedankenkette\",\n \"formal\",\n \"mathematisch\",\n \"logisch\",\n // Spanish\n \"demostrar\",\n \"teorema\",\n \"derivar\",\n \"paso a paso\",\n \"cadena de pensamiento\",\n \"formalmente\",\n \"matemático\",\n \"prueba\",\n \"lógicamente\",\n // Portuguese\n \"provar\",\n \"teorema\",\n \"derivar\",\n \"passo a passo\",\n \"cadeia de pensamento\",\n \"formalmente\",\n \"matemático\",\n \"prova\",\n \"logicamente\",\n // Korean\n \"증명\",\n \"정리\",\n \"도출\",\n \"단계별\",\n \"사고의 연쇄\",\n \"형식적\",\n \"수학적\",\n \"논리적\",\n // Arabic\n \"إثبات\",\n \"نظرية\",\n \"اشتقاق\",\n \"خطوة بخطوة\",\n \"سلسلة التفكير\",\n \"رسمياً\",\n \"رياضي\",\n \"برهان\",\n \"منطقياً\",\n ],\n simpleKeywords: [\n // English\n \"what is\",\n \"define\",\n \"translate\",\n \"hello\",\n \"yes or no\",\n \"capital of\",\n \"how old\",\n \"who is\",\n \"when was\",\n // Chinese\n \"什么是\",\n \"定义\",\n \"翻译\",\n \"你好\",\n \"是否\",\n \"首都\",\n \"多大\",\n \"谁是\",\n \"何时\",\n // Japanese\n \"とは\",\n \"定義\",\n \"翻訳\",\n \"こんにちは\",\n \"はいかいいえ\",\n \"首都\",\n \"誰\",\n // Russian\n \"что такое\",\n \"определение\",\n \"перевести\",\n \"переведи\",\n \"привет\",\n \"да или нет\",\n \"столица\",\n \"сколько лет\",\n \"кто такой\",\n \"когда\",\n \"объясни\",\n // German\n \"was ist\",\n \"definiere\",\n \"übersetze\",\n \"hallo\",\n \"ja oder nein\",\n \"hauptstadt\",\n \"wie alt\",\n \"wer ist\",\n \"wann\",\n \"erkläre\",\n // Spanish\n \"qué es\",\n \"definir\",\n \"traducir\",\n \"hola\",\n \"sí o no\",\n \"capital de\",\n \"cuántos años\",\n \"quién es\",\n \"cuándo\",\n // Portuguese\n \"o que é\",\n \"definir\",\n \"traduzir\",\n \"olá\",\n \"sim ou não\",\n \"capital de\",\n \"quantos anos\",\n \"quem é\",\n \"quando\",\n // Korean\n \"무엇\",\n \"정의\",\n \"번역\",\n \"안녕하세요\",\n \"예 또는 아니오\",\n \"수도\",\n \"누구\",\n \"언제\",\n // Arabic\n \"ما هو\",\n \"تعريف\",\n \"ترجم\",\n \"مرحبا\",\n \"نعم أو لا\",\n \"عاصمة\",\n \"من هو\",\n \"متى\",\n ],\n technicalKeywords: [\n // English\n \"algorithm\",\n \"optimize\",\n \"architecture\",\n \"distributed\",\n \"kubernetes\",\n \"microservice\",\n \"database\",\n \"infrastructure\",\n // Chinese\n \"算法\",\n \"优化\",\n \"架构\",\n \"分布式\",\n \"微服务\",\n \"数据库\",\n \"基础设施\",\n // Japanese\n \"アルゴリズム\",\n \"最適化\",\n \"アーキテクチャ\",\n \"分散\",\n \"マイクロサービス\",\n \"データベース\",\n // Russian\n \"алгоритм\",\n \"оптимизировать\",\n \"оптимизаци\",\n \"оптимизируй\",\n \"архитектура\",\n \"распределённый\",\n \"микросервис\",\n \"база данных\",\n \"инфраструктура\",\n // German\n \"algorithmus\",\n \"optimieren\",\n \"architektur\",\n \"verteilt\",\n \"kubernetes\",\n \"mikroservice\",\n \"datenbank\",\n \"infrastruktur\",\n // Spanish\n \"algoritmo\",\n \"optimizar\",\n \"arquitectura\",\n \"distribuido\",\n \"microservicio\",\n \"base de datos\",\n \"infraestructura\",\n // Portuguese\n \"algoritmo\",\n \"otimizar\",\n \"arquitetura\",\n \"distribuído\",\n \"microsserviço\",\n \"banco de dados\",\n \"infraestrutura\",\n // Korean\n \"알고리즘\",\n \"최적화\",\n \"아키텍처\",\n \"분산\",\n \"마이크로서비스\",\n \"데이터베이스\",\n \"인프라\",\n // Arabic\n \"خوارزمية\",\n \"تحسين\",\n \"بنية\",\n \"موزع\",\n \"خدمة مصغرة\",\n \"قاعدة بيانات\",\n \"بنية تحتية\",\n ],\n creativeKeywords: [\n // English\n \"story\",\n \"poem\",\n \"compose\",\n \"brainstorm\",\n \"creative\",\n \"imagine\",\n \"write a\",\n // Chinese\n \"故事\",\n \"诗\",\n \"创作\",\n \"头脑风暴\",\n \"创意\",\n \"想象\",\n \"写一个\",\n // Japanese\n \"物語\",\n \"詩\",\n \"作曲\",\n \"ブレインストーム\",\n \"創造的\",\n \"想像\",\n // Russian\n \"история\",\n \"рассказ\",\n \"стихотворение\",\n \"сочинить\",\n \"сочини\",\n \"мозговой штурм\",\n \"творческий\",\n \"представить\",\n \"придумай\",\n \"напиши\",\n // German\n \"geschichte\",\n \"gedicht\",\n \"komponieren\",\n \"brainstorming\",\n \"kreativ\",\n \"vorstellen\",\n \"schreibe\",\n \"erzählung\",\n // Spanish\n \"historia\",\n \"poema\",\n \"componer\",\n \"lluvia de ideas\",\n \"creativo\",\n \"imaginar\",\n \"escribe\",\n // Portuguese\n \"história\",\n \"poema\",\n \"compor\",\n \"criativo\",\n \"imaginar\",\n \"escreva\",\n // Korean\n \"이야기\",\n \"시\",\n \"작곡\",\n \"브레인스토밍\",\n \"창의적\",\n \"상상\",\n \"작성\",\n // Arabic\n \"قصة\",\n \"قصيدة\",\n \"تأليف\",\n \"عصف ذهني\",\n \"إبداعي\",\n \"تخيل\",\n \"اكتب\",\n ],\n\n // New dimension keyword lists (multilingual)\n imperativeVerbs: [\n // English\n \"build\",\n \"create\",\n \"implement\",\n \"design\",\n \"develop\",\n \"construct\",\n \"generate\",\n \"deploy\",\n \"configure\",\n \"set up\",\n // Chinese\n \"构建\",\n \"创建\",\n \"实现\",\n \"设计\",\n \"开发\",\n \"生成\",\n \"部署\",\n \"配置\",\n \"设置\",\n // Japanese\n \"構築\",\n \"作成\",\n \"実装\",\n \"設計\",\n \"開発\",\n \"生成\",\n \"デプロイ\",\n \"設定\",\n // Russian\n \"построить\",\n \"построй\",\n \"создать\",\n \"создай\",\n \"реализовать\",\n \"реализуй\",\n \"спроектировать\",\n \"разработать\",\n \"разработай\",\n \"сконструировать\",\n \"сгенерировать\",\n \"сгенерируй\",\n \"развернуть\",\n \"разверни\",\n \"настроить\",\n \"настрой\",\n // German\n \"erstellen\",\n \"bauen\",\n \"implementieren\",\n \"entwerfen\",\n \"entwickeln\",\n \"konstruieren\",\n \"generieren\",\n \"bereitstellen\",\n \"konfigurieren\",\n \"einrichten\",\n // Spanish\n \"construir\",\n \"crear\",\n \"implementar\",\n \"diseñar\",\n \"desarrollar\",\n \"generar\",\n \"desplegar\",\n \"configurar\",\n // Portuguese\n \"construir\",\n \"criar\",\n \"implementar\",\n \"projetar\",\n \"desenvolver\",\n \"gerar\",\n \"implantar\",\n \"configurar\",\n // Korean\n \"구축\",\n \"생성\",\n \"구현\",\n \"설계\",\n \"개발\",\n \"배포\",\n \"설정\",\n // Arabic\n \"بناء\",\n \"إنشاء\",\n \"تنفيذ\",\n \"تصميم\",\n \"تطوير\",\n \"توليد\",\n \"نشر\",\n \"إعداد\",\n ],\n constraintIndicators: [\n // English\n \"under\",\n \"at most\",\n \"at least\",\n \"within\",\n \"no more than\",\n \"o(\",\n \"maximum\",\n \"minimum\",\n \"limit\",\n \"budget\",\n // Chinese\n \"不超过\",\n \"至少\",\n \"最多\",\n \"在内\",\n \"最大\",\n \"最小\",\n \"限制\",\n \"预算\",\n // Japanese\n \"以下\",\n \"最大\",\n \"最小\",\n \"制限\",\n \"予算\",\n // Russian\n \"не более\",\n \"не менее\",\n \"как минимум\",\n \"в пределах\",\n \"максимум\",\n \"минимум\",\n \"ограничение\",\n \"бюджет\",\n // German\n \"höchstens\",\n \"mindestens\",\n \"innerhalb\",\n \"nicht mehr als\",\n \"maximal\",\n \"minimal\",\n \"grenze\",\n \"budget\",\n // Spanish\n \"como máximo\",\n \"al menos\",\n \"dentro de\",\n \"no más de\",\n \"máximo\",\n \"mínimo\",\n \"límite\",\n \"presupuesto\",\n // Portuguese\n \"no máximo\",\n \"pelo menos\",\n \"dentro de\",\n \"não mais que\",\n \"máximo\",\n \"mínimo\",\n \"limite\",\n \"orçamento\",\n // Korean\n \"이하\",\n \"이상\",\n \"최대\",\n \"최소\",\n \"제한\",\n \"예산\",\n // Arabic\n \"على الأكثر\",\n \"على الأقل\",\n \"ضمن\",\n \"لا يزيد عن\",\n \"أقصى\",\n \"أدنى\",\n \"حد\",\n \"ميزانية\",\n ],\n outputFormatKeywords: [\n // English\n \"json\",\n \"yaml\",\n \"xml\",\n \"table\",\n \"csv\",\n \"markdown\",\n \"schema\",\n \"format as\",\n \"structured\",\n // Chinese\n \"表格\",\n \"格式化为\",\n \"结构化\",\n // Japanese\n \"テーブル\",\n \"フォーマット\",\n \"構造化\",\n // Russian\n \"таблица\",\n \"форматировать как\",\n \"структурированный\",\n // German\n \"tabelle\",\n \"formatieren als\",\n \"strukturiert\",\n // Spanish\n \"tabla\",\n \"formatear como\",\n \"estructurado\",\n // Portuguese\n \"tabela\",\n \"formatar como\",\n \"estruturado\",\n // Korean\n \"테이블\",\n \"형식\",\n \"구조화\",\n // Arabic\n \"جدول\",\n \"تنسيق\",\n \"منظم\",\n ],\n referenceKeywords: [\n // English\n \"above\",\n \"below\",\n \"previous\",\n \"following\",\n \"the docs\",\n \"the api\",\n \"the code\",\n \"earlier\",\n \"attached\",\n // Chinese\n \"上面\",\n \"下面\",\n \"之前\",\n \"接下来\",\n \"文档\",\n \"代码\",\n \"附件\",\n // Japanese\n \"上記\",\n \"下記\",\n \"前の\",\n \"次の\",\n \"ドキュメント\",\n \"コード\",\n // Russian\n \"выше\",\n \"ниже\",\n \"предыдущий\",\n \"следующий\",\n \"документация\",\n \"код\",\n \"ранее\",\n \"вложение\",\n // German\n \"oben\",\n \"unten\",\n \"vorherige\",\n \"folgende\",\n \"dokumentation\",\n \"der code\",\n \"früher\",\n \"anhang\",\n // Spanish\n \"arriba\",\n \"abajo\",\n \"anterior\",\n \"siguiente\",\n \"documentación\",\n \"el código\",\n \"adjunto\",\n // Portuguese\n \"acima\",\n \"abaixo\",\n \"anterior\",\n \"seguinte\",\n \"documentação\",\n \"o código\",\n \"anexo\",\n // Korean\n \"위\",\n \"아래\",\n \"이전\",\n \"다음\",\n \"문서\",\n \"코드\",\n \"첨부\",\n // Arabic\n \"أعلاه\",\n \"أدناه\",\n \"السابق\",\n \"التالي\",\n \"الوثائق\",\n \"الكود\",\n \"مرفق\",\n ],\n negationKeywords: [\n // English\n \"don't\",\n \"do not\",\n \"avoid\",\n \"never\",\n \"without\",\n \"except\",\n \"exclude\",\n \"no longer\",\n // Chinese\n \"不要\",\n \"避免\",\n \"从不\",\n \"没有\",\n \"除了\",\n \"排除\",\n // Japanese\n \"しないで\",\n \"避ける\",\n \"決して\",\n \"なしで\",\n \"除く\",\n // Russian\n \"не делай\",\n \"не надо\",\n \"нельзя\",\n \"избегать\",\n \"никогда\",\n \"без\",\n \"кроме\",\n \"исключить\",\n \"больше не\",\n // German\n \"nicht\",\n \"vermeide\",\n \"niemals\",\n \"ohne\",\n \"außer\",\n \"ausschließen\",\n \"nicht mehr\",\n // Spanish\n \"no hagas\",\n \"evitar\",\n \"nunca\",\n \"sin\",\n \"excepto\",\n \"excluir\",\n // Portuguese\n \"não faça\",\n \"evitar\",\n \"nunca\",\n \"sem\",\n \"exceto\",\n \"excluir\",\n // Korean\n \"하지 마\",\n \"피하다\",\n \"절대\",\n \"없이\",\n \"제외\",\n // Arabic\n \"لا تفعل\",\n \"تجنب\",\n \"أبداً\",\n \"بدون\",\n \"باستثناء\",\n \"استبعاد\",\n ],\n domainSpecificKeywords: [\n // English\n \"quantum\",\n \"fpga\",\n \"vlsi\",\n \"risc-v\",\n \"asic\",\n \"photonics\",\n \"genomics\",\n \"proteomics\",\n \"topological\",\n \"homomorphic\",\n \"zero-knowledge\",\n \"lattice-based\",\n // Chinese\n \"量子\",\n \"光子学\",\n \"基因组学\",\n \"蛋白质组学\",\n \"拓扑\",\n \"同态\",\n \"零知识\",\n \"格密码\",\n // Japanese\n \"量子\",\n \"フォトニクス\",\n \"ゲノミクス\",\n \"トポロジカル\",\n // Russian\n \"квантовый\",\n \"фотоника\",\n \"геномика\",\n \"протеомика\",\n \"топологический\",\n \"гомоморфный\",\n \"с нулевым разглашением\",\n \"на основе решёток\",\n // German\n \"quanten\",\n \"photonik\",\n \"genomik\",\n \"proteomik\",\n \"topologisch\",\n \"homomorph\",\n \"zero-knowledge\",\n \"gitterbasiert\",\n // Spanish\n \"cuántico\",\n \"fotónica\",\n \"genómica\",\n \"proteómica\",\n \"topológico\",\n \"homomórfico\",\n // Portuguese\n \"quântico\",\n \"fotônica\",\n \"genômica\",\n \"proteômica\",\n \"topológico\",\n \"homomórfico\",\n // Korean\n \"양자\",\n \"포토닉스\",\n \"유전체학\",\n \"위상\",\n \"동형\",\n // Arabic\n \"كمي\",\n \"ضوئيات\",\n \"جينوميات\",\n \"طوبولوجي\",\n \"تماثلي\",\n ],\n\n // Agentic task keywords - file ops, execution, multi-step, iterative work\n // Pruned: removed overly common words like \"then\", \"first\", \"run\", \"test\", \"build\"\n agenticTaskKeywords: [\n // English - File operations (clearly agentic)\n \"read file\",\n \"read the file\",\n \"look at\",\n \"check the\",\n \"open the\",\n \"edit\",\n \"modify\",\n \"update the\",\n \"change the\",\n \"write to\",\n \"create file\",\n // English - Execution (specific commands only)\n \"execute\",\n \"deploy\",\n \"install\",\n \"npm\",\n \"pip\",\n \"compile\",\n // English - Multi-step patterns (specific only)\n \"after that\",\n \"and also\",\n \"once done\",\n \"step 1\",\n \"step 2\",\n // English - Iterative work\n \"fix\",\n \"debug\",\n \"until it works\",\n \"keep trying\",\n \"iterate\",\n \"make sure\",\n \"verify\",\n \"confirm\",\n // Chinese (keep specific ones)\n \"读取文件\",\n \"查看\",\n \"打开\",\n \"编辑\",\n \"修改\",\n \"更新\",\n \"创建\",\n \"执行\",\n \"部署\",\n \"安装\",\n \"第一步\",\n \"第二步\",\n \"修复\",\n \"调试\",\n \"直到\",\n \"确认\",\n \"验证\",\n // Spanish\n \"leer archivo\",\n \"editar\",\n \"modificar\",\n \"actualizar\",\n \"ejecutar\",\n \"desplegar\",\n \"instalar\",\n \"paso 1\",\n \"paso 2\",\n \"arreglar\",\n \"depurar\",\n \"verificar\",\n // Portuguese\n \"ler arquivo\",\n \"editar\",\n \"modificar\",\n \"atualizar\",\n \"executar\",\n \"implantar\",\n \"instalar\",\n \"passo 1\",\n \"passo 2\",\n \"corrigir\",\n \"depurar\",\n \"verificar\",\n // Korean\n \"파일 읽기\",\n \"편집\",\n \"수정\",\n \"업데이트\",\n \"실행\",\n \"배포\",\n \"설치\",\n \"단계 1\",\n \"단계 2\",\n \"디버그\",\n \"확인\",\n // Arabic\n \"قراءة ملف\",\n \"تحرير\",\n \"تعديل\",\n \"تحديث\",\n \"تنفيذ\",\n \"نشر\",\n \"تثبيت\",\n \"الخطوة 1\",\n \"الخطوة 2\",\n \"إصلاح\",\n \"تصحيح\",\n \"تحقق\",\n ],\n\n // Dimension weights (sum to 1.0)\n dimensionWeights: {\n tokenCount: 0.08,\n codePresence: 0.15,\n reasoningMarkers: 0.18,\n technicalTerms: 0.1,\n creativeMarkers: 0.05,\n simpleIndicators: 0.02, // Reduced from 0.12 to make room for agenticTask\n multiStepPatterns: 0.12,\n questionComplexity: 0.05,\n imperativeVerbs: 0.03,\n constraintCount: 0.04,\n outputFormat: 0.03,\n referenceComplexity: 0.02,\n negationComplexity: 0.01,\n domainSpecificity: 0.02,\n agenticTask: 0.04, // Reduced - agentic signals influence tier selection, not dominate it\n },\n\n // Tier boundaries on weighted score axis\n tierBoundaries: {\n simpleMedium: 0.0,\n mediumComplex: 0.3, // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier\n complexReasoning: 0.5, // Raised from 0.4 - reserve for true reasoning tasks\n },\n\n // Sigmoid steepness for confidence calibration\n confidenceSteepness: 12,\n // Below this confidence → ambiguous (null tier)\n confidenceThreshold: 0.7,\n },\n\n // Auto (balanced) tier configs - current default smart routing\n // Benchmark-tuned 2026-03-16: balancing quality (retention) + latency\n tiers: {\n SIMPLE: {\n primary: \"google/gemini-2.5-flash\", // 1,238ms, IQ 20, 60% retention (best) — fast AND quality\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — smarter fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, strong quality\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context — newest flash-lite\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"openai/gpt-5.4-nano\", // $0.20/$1.25, 1M context\n \"xai/grok-4-fast-non-reasoning\", // 1,143ms, $0.20/$0.50 — fast fallback\n \"free/gpt-oss-120b\", // 1,252ms, FREE fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, $0.60/$3.00 — strong tool use, quality output\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — nearly same IQ, faster + cheaper\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"google/gemini-2.5-flash\", // 1,238ms, 60% retention\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"xai/grok-3-mini\", // 1,202ms, $0.30/$0.50\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-pro\", // 1,609ms, IQ 57 — fast flagship quality\n fallback: [\n \"google/gemini-3-pro-preview\", // 1,352ms, IQ 48 — quality-first fallback\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — fast + smart\n \"xai/grok-4-0709\", // 1,348ms, IQ 41\n \"google/gemini-2.5-pro\", // 1,294ms\n \"anthropic/claude-sonnet-4.6\", // 2,110ms, IQ 52 — quality fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32\n \"google/gemini-2.5-flash\", // 1,238ms, IQ 20 — cheap last resort\n \"openai/gpt-5.4\", // 6,213ms, IQ 57 — slowest but highest quality\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // 1,454ms, $0.20/$0.50\n fallback: [\n \"xai/grok-4-fast-reasoning\", // 1,298ms, $0.20/$0.50\n \"deepseek/deepseek-reasoner\", // 1,454ms, cheap reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Eco tier configs - absolute cheapest (blockrun/eco)\n ecoTiers: {\n SIMPLE: {\n primary: \"free/gpt-oss-120b\", // FREE! $0.00/$0.00\n fallback: [\n \"free/gpt-oss-20b\", // FREE — smaller, faster\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n \"openai/gpt-5.4-nano\", // $0.20/$1.25 — fast nano\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\", // $0.20/$0.50\n ],\n },\n MEDIUM: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n fallback: [\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\",\n \"google/gemini-2.5-flash\",\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n fallback: [\n \"google/gemini-2.5-flash-lite\",\n \"xai/grok-4-0709\",\n \"google/gemini-2.5-flash\",\n \"deepseek/deepseek-chat\",\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // $0.20/$0.50\n fallback: [\"xai/grok-4-fast-reasoning\", \"deepseek/deepseek-reasoner\"],\n },\n },\n\n // Premium tier configs - best quality (blockrun/premium)\n // codex=complex coding, kimi=simple coding, sonnet=reasoning/instructions, opus=architecture/PM/audits\n premiumTiers: {\n SIMPLE: {\n primary: \"moonshot/kimi-k2.5\", // $0.60/$3.00 - good for simple coding\n fallback: [\n \"google/gemini-2.5-flash\", // 60% retention, fast growth\n \"anthropic/claude-haiku-4.5\",\n \"google/gemini-2.5-flash-lite\",\n \"deepseek/deepseek-chat\",\n ],\n },\n MEDIUM: {\n primary: \"openai/gpt-5.3-codex\", // $1.75/$14 - 400K context, 128K output, replaces 5.2\n fallback: [\n \"moonshot/kimi-k2.5\",\n \"google/gemini-2.5-flash\", // 60% retention, good coding capability\n \"google/gemini-2.5-pro\",\n \"xai/grok-4-0709\",\n \"anthropic/claude-sonnet-4.6\",\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-opus-4.6\", // Best quality for complex tasks\n fallback: [\n \"openai/gpt-5.4\", // Newest flagship\n \"openai/gpt-5.3-codex\",\n \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-sonnet-4.6\",\n \"google/gemini-3.1-pro\", // Newest Gemini\n \"google/gemini-3-pro-preview\",\n \"moonshot/kimi-k2.5\",\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms, $3/$15 - best for reasoning/instructions\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms, cheap fast reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Agentic tier configs - models that excel at multi-step autonomous tasks\n agenticTiers: {\n SIMPLE: {\n primary: \"openai/gpt-4o-mini\", // $0.15/$0.60 - best tool compliance at lowest cost\n fallback: [\n \"moonshot/kimi-k2.5\", // 1,646ms, strong tool use quality\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, $0.60/$3.00 - strong tool use, proper function calls\n fallback: [\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"openai/gpt-4o-mini\", // 2,764ms, reliable tool calling\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"deepseek/deepseek-chat\", // 1,431ms\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — best agentic quality\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms — top quality\n \"google/gemini-3.1-pro\", // 1,609ms\n \"xai/grok-4-0709\", // 1,348ms\n \"openai/gpt-5.4\", // 6,213ms — slow but highest quality fallback\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — strong tool use + reasoning\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms\n \"deepseek/deepseek-reasoner\", // 1,454ms\n ],\n },\n },\n\n overrides: {\n maxTokensForceComplex: 100_000,\n structuredOutputMinTier: \"MEDIUM\",\n ambiguousDefaultTier: \"MEDIUM\",\n agenticMode: false,\n },\n};\n","/**\n * Smart Router Entry Point\n *\n * Classifies requests and routes to the cheapest capable model.\n * Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).\n */\n\nimport type { RoutingDecision, RouterOptions } from \"./types.js\";\nimport { getStrategy } from \"./strategy.js\";\n\n/**\n * Route a request to the cheapest capable model.\n * Delegates to the registered \"rules\" strategy by default.\n */\nexport function route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n): RoutingDecision {\n const strategy = getStrategy(\"rules\");\n return strategy.route(prompt, systemPrompt, maxOutputTokens, options);\n}\n\nexport { getStrategy, registerStrategy } from \"./strategy.js\";\nexport {\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n} from \"./selector.js\";\nexport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nexport type {\n RoutingDecision,\n Tier,\n RoutingConfig,\n RouterOptions,\n RouterStrategy,\n} from \"./types.js\";\nexport type { ModelPricing } from \"./selector.js\";\n","/**\n * BlockRun Model Definitions for OpenClaw\n *\n * Maps BlockRun's 55+ AI models to OpenClaw's ModelDefinitionConfig format.\n * All models use the \"openai-completions\" API since BlockRun is OpenAI-compatible.\n *\n * Pricing is in USD per 1M tokens. Operators pay these rates via x402;\n * they set their own markup when reselling to end users (Phase 2).\n */\n\nimport type { ModelDefinitionConfig, ModelProviderConfig } from \"./types.js\";\n\n/**\n * Model aliases for convenient shorthand access.\n * Users can type `/model claude` instead of `/model blockrun/anthropic/claude-sonnet-4-6`.\n */\nexport const MODEL_ALIASES: Record = {\n // Claude - use newest versions (4.6)\n claude: \"anthropic/claude-sonnet-4.6\",\n sonnet: \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4.6\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n opus: \"anthropic/claude-opus-4.6\",\n \"opus-4\": \"anthropic/claude-opus-4.6\",\n \"opus-4.6\": \"anthropic/claude-opus-4.6\",\n \"opus-4-6\": \"anthropic/claude-opus-4.6\",\n haiku: \"anthropic/claude-haiku-4.5\",\n // Claude - provider/shortname patterns (common in agent frameworks)\n \"anthropic/sonnet\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/opus\": \"anthropic/claude-opus-4.6\",\n \"anthropic/haiku\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude\": \"anthropic/claude-sonnet-4.6\",\n // Backward compatibility - map all variants to 4.6\n \"anthropic/claude-sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-opus-4\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4-6\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4.5\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-haiku-4\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude-haiku-4-5\": \"anthropic/claude-haiku-4.5\",\n\n // OpenAI\n gpt: \"openai/gpt-4o\",\n gpt4: \"openai/gpt-4o\",\n gpt5: \"openai/gpt-5.4\",\n \"gpt-5.4\": \"openai/gpt-5.4\",\n \"gpt-5.4-pro\": \"openai/gpt-5.4-pro\",\n \"gpt-5.4-nano\": \"openai/gpt-5.4-nano\",\n nano: \"openai/gpt-5.4-nano\",\n \"gpt-5-nano\": \"openai/gpt-5.4-nano\",\n codex: \"openai/gpt-5.3-codex\",\n mini: \"openai/gpt-4o-mini\",\n o1: \"openai/o1\",\n o3: \"openai/o3\",\n\n // DeepSeek\n deepseek: \"deepseek/deepseek-chat\",\n \"deepseek-chat\": \"deepseek/deepseek-chat\",\n reasoner: \"deepseek/deepseek-reasoner\",\n\n // Kimi / Moonshot\n kimi: \"moonshot/kimi-k2.5\",\n moonshot: \"moonshot/kimi-k2.5\",\n \"kimi-k2.5\": \"moonshot/kimi-k2.5\",\n\n // Google\n gemini: \"google/gemini-2.5-pro\",\n flash: \"google/gemini-2.5-flash\",\n \"gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"google/gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"gemini-3.1-flash-lite\": \"google/gemini-3.1-flash-lite\",\n\n // xAI\n grok: \"xai/grok-3\",\n \"grok-fast\": \"xai/grok-4-fast-reasoning\",\n \"grok-code\": \"deepseek/deepseek-chat\", // was grok-code-fast-1, delisted due to poor retention\n // Delisted model redirects — full model IDs that were previously valid but removed\n \"grok-code-fast-1\": \"deepseek/deepseek-chat\", // bare alias\n \"xai/grok-code-fast-1\": \"deepseek/deepseek-chat\", // delisted 2026-03-12\n \"xai/grok-3-fast\": \"xai/grok-4-fast-reasoning\", // delisted (too expensive)\n\n // NVIDIA — backward compat aliases (nvidia/xxx → free/xxx)\n nvidia: \"free/gpt-oss-120b\",\n \"gpt-120b\": \"free/gpt-oss-120b\",\n \"gpt-20b\": \"free/gpt-oss-20b\",\n \"nvidia/gpt-oss-120b\": \"free/gpt-oss-120b\",\n \"nvidia/gpt-oss-20b\": \"free/gpt-oss-20b\",\n \"nvidia/nemotron-ultra-253b\": \"free/nemotron-ultra-253b\",\n \"nvidia/nemotron-3-super-120b\": \"free/nemotron-3-super-120b\",\n \"nvidia/nemotron-super-49b\": \"free/nemotron-super-49b\",\n \"nvidia/deepseek-v3.2\": \"free/deepseek-v3.2\",\n \"nvidia/mistral-large-3-675b\": \"free/mistral-large-3-675b\",\n \"nvidia/qwen3-coder-480b\": \"free/qwen3-coder-480b\",\n \"nvidia/devstral-2-123b\": \"free/devstral-2-123b\",\n \"nvidia/glm-4.7\": \"free/glm-4.7\",\n \"nvidia/llama-4-maverick\": \"free/llama-4-maverick\",\n // Free model shorthand aliases\n \"deepseek-free\": \"free/deepseek-v3.2\",\n \"mistral-free\": \"free/mistral-large-3-675b\",\n \"glm-free\": \"free/glm-4.7\",\n \"llama-free\": \"free/llama-4-maverick\",\n nemotron: \"free/nemotron-ultra-253b\",\n \"nemotron-ultra\": \"free/nemotron-ultra-253b\",\n \"nemotron-253b\": \"free/nemotron-ultra-253b\",\n \"nemotron-super\": \"free/nemotron-super-49b\",\n \"nemotron-49b\": \"free/nemotron-super-49b\",\n \"nemotron-120b\": \"free/nemotron-3-super-120b\",\n devstral: \"free/devstral-2-123b\",\n \"devstral-2\": \"free/devstral-2-123b\",\n \"qwen-coder\": \"free/qwen3-coder-480b\",\n \"qwen-coder-free\": \"free/qwen3-coder-480b\",\n maverick: \"free/llama-4-maverick\",\n free: \"free/nemotron-ultra-253b\",\n\n // MiniMax\n minimax: \"minimax/minimax-m2.7\",\n \"minimax-m2.7\": \"minimax/minimax-m2.7\",\n \"minimax-m2.5\": \"minimax/minimax-m2.5\",\n\n // Z.AI GLM-5\n glm: \"zai/glm-5\",\n \"glm-5\": \"zai/glm-5\",\n \"glm-5-turbo\": \"zai/glm-5-turbo\",\n\n // Routing profile aliases (common variations)\n \"auto-router\": \"auto\",\n router: \"auto\",\n\n // Note: auto, eco, premium are virtual routing profiles registered in BLOCKRUN_MODELS\n // They don't need aliases since they're already top-level model IDs\n};\n\n/**\n * Resolve a model alias to its full model ID.\n * Also strips \"blockrun/\" prefix for direct model paths.\n * Examples:\n * - \"claude\" -> \"anthropic/claude-sonnet-4-6\" (alias)\n * - \"blockrun/claude\" -> \"anthropic/claude-sonnet-4-6\" (alias with prefix)\n * - \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\" (prefix stripped)\n * - \"openai/gpt-4o\" -> \"openai/gpt-4o\" (unchanged)\n */\nexport function resolveModelAlias(model: string): string {\n const normalized = model.trim().toLowerCase();\n const resolved = MODEL_ALIASES[normalized];\n if (resolved) return resolved;\n\n // Check with \"blockrun/\" prefix stripped\n if (normalized.startsWith(\"blockrun/\")) {\n const withoutPrefix = normalized.slice(\"blockrun/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // Even if not an alias, strip the prefix for direct model paths\n // e.g., \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\"\n return withoutPrefix;\n }\n\n // Strip \"openai/\" prefix when it wraps a virtual routing profile or alias.\n // OpenClaw sends virtual models as \"openai/eco\", \"openai/auto\", etc. because\n // the provider uses the openai-completions API type.\n if (normalized.startsWith(\"openai/\")) {\n const withoutPrefix = normalized.slice(\"openai/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // If it's a known BlockRun virtual profile (eco, auto, premium), return bare id\n const isVirtualProfile = BLOCKRUN_MODELS.some((m) => m.id === withoutPrefix);\n if (isVirtualProfile) return withoutPrefix;\n }\n\n return model;\n}\n\ntype BlockRunModel = {\n id: string;\n name: string;\n /** Model version (e.g., \"4.6\", \"3.1\", \"5.2\") for tracking updates */\n version?: string;\n inputPrice: number;\n outputPrice: number;\n contextWindow: number;\n maxOutput: number;\n reasoning?: boolean;\n vision?: boolean;\n /** Models optimized for agentic workflows (multi-step autonomous tasks) */\n agentic?: boolean;\n /**\n * Model supports OpenAI-compatible structured function/tool calling.\n * Models without this flag output tool invocations as plain text JSON,\n * which leaks raw {\"command\":\"...\"} into visible chat messages.\n * Default: false (must opt-in to prevent silent regressions on new models).\n */\n toolCalling?: boolean;\n /** Model is deprecated — will be routed to fallbackModel if set */\n deprecated?: boolean;\n /** Model ID to route to when this model is deprecated */\n fallbackModel?: string;\n};\n\nexport const BLOCKRUN_MODELS: BlockRunModel[] = [\n // Smart routing meta-models — proxy replaces with actual model\n // NOTE: Model IDs are WITHOUT provider prefix (OpenClaw adds \"blockrun/\" automatically)\n {\n id: \"auto\",\n name: \"Auto (Smart Router - Balanced)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"free\",\n name: \"Free → Nemotron Ultra 253B\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131_072,\n maxOutput: 16_384,\n reasoning: true,\n },\n {\n id: \"eco\",\n name: \"Eco (Smart Router - Cost Optimized)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"premium\",\n name: \"Premium (Smart Router - Best Quality)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 2_000_000,\n maxOutput: 200_000,\n },\n\n // OpenAI GPT-5 Family\n {\n id: \"openai/gpt-5.2\",\n name: \"GPT-5.2\",\n version: \"5.2\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-mini\",\n name: \"GPT-5 Mini\",\n version: \"5.0\",\n inputPrice: 0.25,\n outputPrice: 2.0,\n contextWindow: 200000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-nano\",\n name: \"GPT-5 Nano\",\n version: \"5.0\",\n inputPrice: 0.05,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 32768,\n toolCalling: true,\n deprecated: true,\n fallbackModel: \"openai/gpt-5.4-nano\",\n },\n {\n id: \"openai/gpt-5.2-pro\",\n name: \"GPT-5.2 Pro\",\n version: \"5.2\",\n inputPrice: 21.0,\n outputPrice: 168.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n // GPT-5.4 — newest flagship, same input price as 4o but much more capable\n {\n id: \"openai/gpt-5.4\",\n name: \"GPT-5.4\",\n version: \"5.4\",\n inputPrice: 2.5,\n outputPrice: 15.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-pro\",\n name: \"GPT-5.4 Pro\",\n version: \"5.4\",\n inputPrice: 30.0,\n outputPrice: 180.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-nano\",\n name: \"GPT-5.4 Nano\",\n version: \"5.4\",\n inputPrice: 0.2,\n outputPrice: 1.25,\n contextWindow: 1050000,\n maxOutput: 32768,\n toolCalling: true,\n },\n\n // OpenAI GPT-5.3 Family\n {\n id: \"openai/gpt-5.3\",\n name: \"GPT-5.3\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 128000,\n maxOutput: 16000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI Codex Family\n {\n id: \"openai/gpt-5.3-codex\",\n name: \"GPT-5.3 Codex\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI GPT-4 Family\n {\n id: \"openai/gpt-4.1\",\n name: \"GPT-4.1\",\n version: \"4.1\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-mini\",\n name: \"GPT-4.1 Mini\",\n version: \"4.1\",\n inputPrice: 0.4,\n outputPrice: 1.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-nano\",\n name: \"GPT-4.1 Nano\",\n version: \"4.1\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o\",\n name: \"GPT-4o\",\n version: \"4o\",\n inputPrice: 2.5,\n outputPrice: 10.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o-mini\",\n name: \"GPT-4o Mini\",\n version: \"4o-mini\",\n inputPrice: 0.15,\n outputPrice: 0.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // OpenAI O-series (Reasoning)\n {\n id: \"openai/o1\",\n name: \"o1\",\n version: \"1\",\n inputPrice: 15.0,\n outputPrice: 60.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o1-mini\",\n name: \"o1-mini\",\n version: \"1-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3\",\n name: \"o3\",\n version: \"3\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3-mini\",\n name: \"o3-mini\",\n version: \"3-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o4-mini\",\n name: \"o4-mini\",\n version: \"4-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n\n // Anthropic - all Claude models excel at agentic workflows\n // Use newest versions (4.6) with full provider prefix\n {\n id: \"anthropic/claude-haiku-4.5\",\n name: \"Claude Haiku 4.5\",\n version: \"4.5\",\n inputPrice: 1.0,\n outputPrice: 5.0,\n contextWindow: 200000,\n maxOutput: 8192,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-sonnet-4.6\",\n name: \"Claude Sonnet 4.6\",\n version: \"4.6\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 200000,\n maxOutput: 64000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-opus-4.6\",\n name: \"Claude Opus 4.6\",\n version: \"4.6\",\n inputPrice: 5.0,\n outputPrice: 25.0,\n contextWindow: 200000,\n maxOutput: 32000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Google\n {\n id: \"google/gemini-3.1-pro\",\n name: \"Gemini 3.1 Pro\",\n version: \"3.1\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-pro-preview\",\n name: \"Gemini 3 Pro Preview\",\n version: \"3.0\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-flash-preview\",\n name: \"Gemini 3 Flash Preview\",\n version: \"3.0\",\n inputPrice: 0.5,\n outputPrice: 3.0,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n },\n {\n id: \"google/gemini-2.5-pro\",\n name: \"Gemini 2.5 Pro\",\n version: \"2.5\",\n inputPrice: 1.25,\n outputPrice: 10.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash\",\n name: \"Gemini 2.5 Flash\",\n version: \"2.5\",\n inputPrice: 0.3,\n outputPrice: 2.5,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash-lite\",\n name: \"Gemini 2.5 Flash Lite\",\n version: \"2.5\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 1000000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3.1-flash-lite\",\n name: \"Gemini 3.1 Flash Lite\",\n version: \"3.1\",\n inputPrice: 0.25,\n outputPrice: 1.5,\n contextWindow: 1000000,\n maxOutput: 8192,\n toolCalling: true,\n },\n\n // DeepSeek\n {\n id: \"deepseek/deepseek-chat\",\n name: \"DeepSeek V3.2 Chat\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n toolCalling: true,\n },\n {\n id: \"deepseek/deepseek-reasoner\",\n name: \"DeepSeek V3.2 Reasoner\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n reasoning: true,\n toolCalling: true,\n },\n\n // Moonshot / Kimi - optimized for agentic workflows\n {\n id: \"moonshot/kimi-k2.5\",\n name: \"Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 8192,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // xAI / Grok\n {\n id: \"xai/grok-3\",\n name: \"Grok 3\",\n version: \"3\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n // grok-3-fast removed - too expensive ($5/$25), use grok-4-fast instead\n {\n id: \"xai/grok-3-mini\",\n name: \"Grok 3 Mini\",\n version: \"3-mini\",\n inputPrice: 0.3,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // xAI Grok 4 Family - Ultra-cheap fast models\n {\n id: \"xai/grok-4-fast-reasoning\",\n name: \"Grok 4 Fast Reasoning\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-fast-non-reasoning\",\n name: \"Grok 4 Fast\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-reasoning\",\n name: \"Grok 4.1 Fast Reasoning\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-non-reasoning\",\n name: \"Grok 4.1 Fast\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n // xai/grok-code-fast-1 delisted 2026-03-12: poor retention (coding users churn),\n // no structured tool calling, alias \"grok-code\" redirected to deepseek-chat\n {\n id: \"xai/grok-4-0709\",\n name: \"Grok 4 (0709)\",\n version: \"4-0709\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-2-vision\",\n name: \"Grok 2 Vision\",\n version: \"2\",\n inputPrice: 2.0,\n outputPrice: 10.0,\n contextWindow: 131072,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n\n // MiniMax\n {\n id: \"minimax/minimax-m2.7\",\n name: \"MiniMax M2.7\",\n version: \"m2.7\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"minimax/minimax-m2.5\",\n name: \"MiniMax M2.5\",\n version: \"m2.5\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Free models (hosted by NVIDIA, billingMode: \"free\" on server)\n // IDs use \"free/\" prefix so users see them as free in the /model picker.\n // ClawRouter maps free/xxx → nvidia/xxx before sending to BlockRun upstream.\n // toolCalling intentionally omitted: structured function calling unverified.\n {\n id: \"free/gpt-oss-120b\",\n name: \"[Free] GPT-OSS 120B\",\n version: \"120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/gpt-oss-20b\",\n name: \"[Free] GPT-OSS 20B\",\n version: \"20b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/nemotron-ultra-253b\",\n name: \"[Free] Nemotron Ultra 253B\",\n version: \"253b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-3-super-120b\",\n name: \"[Free] Nemotron 3 Super 120B\",\n version: \"3-super-120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-super-49b\",\n name: \"[Free] Nemotron Super 49B\",\n version: \"super-49b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/deepseek-v3.2\",\n name: \"[Free] DeepSeek V3.2\",\n version: \"v3.2\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/mistral-large-3-675b\",\n name: \"[Free] Mistral Large 675B\",\n version: \"3-675b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/qwen3-coder-480b\",\n name: \"[Free] Qwen3 Coder 480B\",\n version: \"480b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/devstral-2-123b\",\n name: \"[Free] Devstral 2 123B\",\n version: \"2-123b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/glm-4.7\",\n name: \"[Free] GLM-4.7\",\n version: \"4.7\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/llama-4-maverick\",\n name: \"[Free] Llama 4 Maverick\",\n version: \"4-maverick\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n\n // NVIDIA - Paid models\n {\n id: \"nvidia/kimi-k2.5\",\n name: \"NVIDIA Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // Z.AI GLM-5 Models\n {\n id: \"zai/glm-5\",\n name: \"GLM-5\",\n version: \"5\",\n inputPrice: 1.0,\n outputPrice: 3.2,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n {\n id: \"zai/glm-5-turbo\",\n name: \"GLM-5 Turbo\",\n version: \"5-turbo\",\n inputPrice: 1.2,\n outputPrice: 4.0,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n];\n\n/**\n * Convert BlockRun model definitions to OpenClaw ModelDefinitionConfig format.\n */\nfunction toOpenClawModel(m: BlockRunModel): ModelDefinitionConfig {\n return {\n id: m.id,\n name: m.name,\n api: \"openai-completions\",\n reasoning: m.reasoning ?? false,\n input: m.vision ? [\"text\", \"image\"] : [\"text\"],\n cost: {\n input: m.inputPrice,\n output: m.outputPrice,\n cacheRead: 0,\n cacheWrite: 0,\n },\n contextWindow: m.contextWindow,\n maxTokens: m.maxOutput,\n };\n}\n\n/**\n * Alias models that map to real models.\n * These allow users to use friendly names like \"free\" or \"gpt-120b\".\n */\nconst ALIAS_MODELS: ModelDefinitionConfig[] = Object.entries(MODEL_ALIASES)\n .map(([alias, targetId]) => {\n const target = BLOCKRUN_MODELS.find((m) => m.id === targetId);\n if (!target) return null;\n return toOpenClawModel({ ...target, id: alias, name: `${alias} → ${target.name}` });\n })\n .filter((m): m is ModelDefinitionConfig => m !== null);\n\n/**\n * All BlockRun models in OpenClaw format (including aliases).\n */\nexport const OPENCLAW_MODELS: ModelDefinitionConfig[] = [\n ...BLOCKRUN_MODELS.map(toOpenClawModel),\n ...ALIAS_MODELS,\n];\n\n/**\n * Build a ModelProviderConfig for BlockRun.\n *\n * @param baseUrl - The proxy's local base URL (e.g., \"http://127.0.0.1:12345\")\n */\nexport function buildProviderModels(baseUrl: string): ModelProviderConfig {\n return {\n baseUrl: `${baseUrl}/v1`,\n api: \"openai-completions\",\n models: OPENCLAW_MODELS,\n };\n}\n\n/**\n * Check if a model is optimized for agentic workflows.\n * Agentic models continue autonomously with multi-step tasks\n * instead of stopping and waiting for user input.\n */\nexport function isAgenticModel(modelId: string): boolean {\n const model = BLOCKRUN_MODELS.find(\n (m) => m.id === modelId || m.id === modelId.replace(\"blockrun/\", \"\"),\n );\n return model?.agentic ?? false;\n}\n\n/**\n * Get all agentic-capable models.\n */\nexport function getAgenticModels(): string[] {\n return BLOCKRUN_MODELS.filter((m) => m.agentic).map((m) => m.id);\n}\n\n/**\n * Check if a model supports OpenAI-compatible structured tool/function calling.\n * Models without this flag (e.g. grok-code-fast-1) output tool invocations as\n * plain text JSON, which leaks {\"command\":\"...\"} into visible chat messages.\n */\nexport function supportsToolCalling(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.toolCalling ?? false;\n}\n\n/**\n * Check if a model supports vision (image inputs).\n * Models without this flag cannot process image_url content parts.\n */\nexport function supportsVision(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.vision ?? false;\n}\n\n/**\n * Get context window size for a model.\n * Returns undefined if model not found.\n */\nexport function getModelContextWindow(modelId: string): number | undefined {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.contextWindow;\n}\n\n/**\n * Check if a model has reasoning/thinking capabilities.\n * Reasoning models may require reasoning_content in assistant tool_call messages.\n */\nexport function isReasoningModel(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.reasoning ?? false;\n}\n","/**\n * Usage Logger\n *\n * Logs every LLM request as a JSON line to a daily log file.\n * Files: ~/.openclaw/blockrun/logs/usage-YYYY-MM-DD.jsonl\n *\n * MVP: append-only JSON lines. No rotation, no cleanup.\n * Logging never breaks the request flow — all errors are swallowed.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport type UsageEntry = {\n timestamp: string;\n model: string;\n tier: string;\n cost: number;\n baselineCost: number;\n savings: number; // 0-1 percentage\n latencyMs: number;\n /** Input (prompt) tokens reported by the provider */\n inputTokens?: number;\n /** Output (completion) tokens reported by the provider */\n outputTokens?: number;\n /** Partner service ID (e.g., \"x_users_lookup\") — only set for partner API calls */\n partnerId?: string;\n /** Partner service name (e.g., \"AttentionVC\") — only set for partner API calls */\n service?: string;\n};\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\nlet dirReady = false;\n\nasync function ensureDir(): Promise {\n if (dirReady) return;\n await mkdir(LOG_DIR, { recursive: true });\n dirReady = true;\n}\n\n/**\n * Log a usage entry as a JSON line.\n */\nexport async function logUsage(entry: UsageEntry): Promise {\n try {\n await ensureDir();\n const date = entry.timestamp.slice(0, 10); // YYYY-MM-DD\n const file = join(LOG_DIR, `usage-${date}.jsonl`);\n await appendFile(file, JSON.stringify(entry) + \"\\n\");\n } catch {\n // Never break the request flow\n }\n}\n","/**\n * Usage Statistics Aggregator\n *\n * Reads usage log files and aggregates statistics for terminal display.\n * Supports filtering by date range and provides multiple aggregation views.\n */\n\nimport { readdir, unlink } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type { UsageEntry } from \"./logger.js\";\nimport { VERSION } from \"./version.js\";\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\n\nexport type DailyStats = {\n date: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n avgLatencyMs: number;\n byTier: Record;\n byModel: Record;\n};\n\nexport type AggregatedStats = {\n period: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n savingsPercentage: number;\n avgLatencyMs: number;\n avgCostPerRequest: number;\n byTier: Record;\n byModel: Record;\n dailyBreakdown: DailyStats[];\n entriesWithBaseline: number; // Entries with valid baseline tracking\n};\n\n/**\n * Parse a JSONL log file into usage entries.\n * Handles both old format (without tier/baselineCost) and new format.\n */\nasync function parseLogFile(filePath: string): Promise {\n try {\n const content = await readTextFile(filePath);\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n const entries: UsageEntry[] = [];\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Partial;\n entries.push({\n timestamp: entry.timestamp || new Date().toISOString(),\n model: entry.model || \"unknown\",\n tier: entry.tier || \"UNKNOWN\",\n cost: entry.cost || 0,\n baselineCost: entry.baselineCost || entry.cost || 0,\n savings: entry.savings || 0,\n latencyMs: entry.latencyMs || 0,\n });\n } catch {\n // Skip malformed lines, keep valid ones\n }\n }\n return entries;\n } catch {\n return [];\n }\n}\n\n/**\n * Get list of available log files sorted by date (newest first).\n */\nasync function getLogFiles(): Promise {\n try {\n const files = await readdir(LOG_DIR);\n return files\n .filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\n/**\n * Aggregate stats for a single day.\n */\nfunction aggregateDay(date: string, entries: UsageEntry[]): DailyStats {\n const byTier: Record = {};\n const byModel: Record = {};\n let totalLatency = 0;\n\n for (const entry of entries) {\n // By tier\n if (!byTier[entry.tier]) byTier[entry.tier] = { count: 0, cost: 0 };\n byTier[entry.tier].count++;\n byTier[entry.tier].cost += entry.cost;\n\n // By model\n if (!byModel[entry.model]) byModel[entry.model] = { count: 0, cost: 0 };\n byModel[entry.model].count++;\n byModel[entry.model].cost += entry.cost;\n\n totalLatency += entry.latencyMs;\n }\n\n const totalCost = entries.reduce((sum, e) => sum + e.cost, 0);\n const totalBaselineCost = entries.reduce((sum, e) => sum + e.baselineCost, 0);\n\n return {\n date,\n totalRequests: entries.length,\n totalCost,\n totalBaselineCost,\n totalSavings: totalBaselineCost - totalCost,\n avgLatencyMs: entries.length > 0 ? totalLatency / entries.length : 0,\n byTier,\n byModel,\n };\n}\n\n/**\n * Get aggregated statistics for the last N days.\n */\nexport async function getStats(days: number = 7): Promise {\n const logFiles = await getLogFiles();\n const filesToRead = logFiles.slice(0, days);\n\n const dailyBreakdown: DailyStats[] = [];\n const allByTier: Record = {};\n const allByModel: Record = {};\n let totalRequests = 0;\n let totalCost = 0;\n let totalBaselineCost = 0;\n let totalLatency = 0;\n\n for (const file of filesToRead) {\n const date = file.replace(\"usage-\", \"\").replace(\".jsonl\", \"\");\n const filePath = join(LOG_DIR, file);\n const entries = await parseLogFile(filePath);\n\n if (entries.length === 0) continue;\n\n const dayStats = aggregateDay(date, entries);\n dailyBreakdown.push(dayStats);\n\n totalRequests += dayStats.totalRequests;\n totalCost += dayStats.totalCost;\n totalBaselineCost += dayStats.totalBaselineCost;\n totalLatency += dayStats.avgLatencyMs * dayStats.totalRequests;\n\n // Merge tier stats\n for (const [tier, stats] of Object.entries(dayStats.byTier)) {\n if (!allByTier[tier]) allByTier[tier] = { count: 0, cost: 0 };\n allByTier[tier].count += stats.count;\n allByTier[tier].cost += stats.cost;\n }\n\n // Merge model stats\n for (const [model, stats] of Object.entries(dayStats.byModel)) {\n if (!allByModel[model]) allByModel[model] = { count: 0, cost: 0 };\n allByModel[model].count += stats.count;\n allByModel[model].cost += stats.cost;\n }\n }\n\n // Calculate percentages\n const byTierWithPercentage: Record =\n {};\n for (const [tier, stats] of Object.entries(allByTier)) {\n byTierWithPercentage[tier] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const byModelWithPercentage: Record =\n {};\n for (const [model, stats] of Object.entries(allByModel)) {\n byModelWithPercentage[model] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const totalSavings = totalBaselineCost - totalCost;\n const savingsPercentage = totalBaselineCost > 0 ? (totalSavings / totalBaselineCost) * 100 : 0;\n\n // Count entries with valid baseline tracking (baseline != cost means tracking was active)\n let entriesWithBaseline = 0;\n for (const day of dailyBreakdown) {\n if (day.totalBaselineCost !== day.totalCost) {\n entriesWithBaseline += day.totalRequests;\n }\n }\n\n return {\n period: days === 1 ? \"today\" : `last ${days} days`,\n totalRequests,\n totalCost,\n totalBaselineCost,\n totalSavings,\n savingsPercentage,\n avgLatencyMs: totalRequests > 0 ? totalLatency / totalRequests : 0,\n avgCostPerRequest: totalRequests > 0 ? totalCost / totalRequests : 0,\n byTier: byTierWithPercentage,\n byModel: byModelWithPercentage,\n dailyBreakdown: dailyBreakdown.reverse(), // Oldest first for charts\n entriesWithBaseline, // How many entries have valid baseline tracking\n };\n}\n\n/**\n * Format stats as ASCII table for terminal display.\n */\nexport function formatStatsAscii(stats: AggregatedStats): string {\n const lines: string[] = [];\n\n // Header\n lines.push(\"╔════════════════════════════════════════════════════════════╗\");\n lines.push(`║ ClawRouter by BlockRun v${VERSION}`.padEnd(61) + \"║\");\n lines.push(\"║ Usage Statistics ║\");\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n\n // Summary\n lines.push(`║ Period: ${stats.period.padEnd(49)}║`);\n lines.push(`║ Total Requests: ${stats.totalRequests.toString().padEnd(41)}║`);\n lines.push(`║ Total Cost: $${stats.totalCost.toFixed(4).padEnd(43)}║`);\n lines.push(`║ Baseline Cost (Opus 4.5): $${stats.totalBaselineCost.toFixed(4).padEnd(30)}║`);\n\n // Show savings with note if some entries lack baseline tracking\n const savingsLine = `║ 💰 Total Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(1)}%)`;\n if (stats.entriesWithBaseline < stats.totalRequests && stats.entriesWithBaseline > 0) {\n lines.push(savingsLine.padEnd(61) + \"║\");\n const note = `║ (based on ${stats.entriesWithBaseline}/${stats.totalRequests} tracked requests)`;\n lines.push(note.padEnd(61) + \"║\");\n } else {\n lines.push(savingsLine.padEnd(61) + \"║\");\n }\n lines.push(`║ Avg Latency: ${stats.avgLatencyMs.toFixed(0)}ms`.padEnd(61) + \"║\");\n\n // Tier breakdown\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Routing by Tier: ║\");\n\n // Show all tiers found in data, ordered by known tiers first then others\n const knownTiers = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\", \"DIRECT\"];\n const allTiers = Object.keys(stats.byTier);\n const otherTiers = allTiers.filter((t) => !knownTiers.includes(t));\n const tierOrder = [...knownTiers.filter((t) => stats.byTier[t]), ...otherTiers];\n\n for (const tier of tierOrder) {\n const data = stats.byTier[tier];\n if (data) {\n const bar = \"█\".repeat(Math.min(20, Math.round(data.percentage / 5)));\n const displayTier = tier === \"UNKNOWN\" ? \"OTHER\" : tier;\n const line = `║ ${displayTier.padEnd(10)} ${bar.padEnd(20)} ${data.percentage.toFixed(1).padStart(5)}% (${data.count})`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n // Top models\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Top Models: ║\");\n\n const sortedModels = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 5);\n\n for (const [model, data] of sortedModels) {\n const shortModel = model.length > 25 ? model.slice(0, 22) + \"...\" : model;\n const line = `║ ${shortModel.padEnd(25)} ${data.count.toString().padStart(5)} reqs $${data.cost.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n\n // Daily breakdown (last 7 days)\n if (stats.dailyBreakdown.length > 0) {\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Daily Breakdown: ║\");\n lines.push(\"║ Date Requests Cost Saved ║\");\n\n for (const day of stats.dailyBreakdown.slice(-7)) {\n const saved = day.totalBaselineCost - day.totalCost;\n const line = `║ ${day.date} ${day.totalRequests.toString().padStart(6)} $${day.totalCost.toFixed(4).padStart(8)} $${saved.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n lines.push(\"╚════════════════════════════════════════════════════════════╝\");\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Delete all usage log files, resetting stats to zero.\n */\nexport async function clearStats(): Promise<{ deletedFiles: number }> {\n try {\n const files = await readdir(LOG_DIR);\n const logFiles = files.filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"));\n\n await Promise.all(logFiles.map((f) => unlink(join(LOG_DIR, f))));\n\n return { deletedFiles: logFiles.length };\n } catch {\n return { deletedFiles: 0 };\n }\n}\n","/**\n * Scanner-safe file reading utilities.\n *\n * Uses open() + read() to avoid false positives from openclaw's\n * potential-exfiltration heuristic in bundled output.\n */\n\nimport { open } from \"node:fs/promises\";\nimport { openSync, readSync, closeSync, fstatSync } from \"node:fs\";\n\n/** Read file contents as UTF-8 string (async). */\nexport async function readTextFile(filePath: string): Promise {\n const fh = await open(filePath, \"r\");\n try {\n const size = (await fh.stat()).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const { bytesRead } = await fh.read(buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n await fh.close();\n }\n}\n\n/** Read file contents as UTF-8 string (sync). */\nexport function readTextFileSync(filePath: string): string {\n const fd = openSync(filePath, \"r\");\n try {\n const size = fstatSync(fd).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const bytesRead = readSync(fd, buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n closeSync(fd);\n }\n}\n","/**\n * Single source of truth for version.\n * Reads from package.json at build time via tsup's define.\n */\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\n\n// Read package.json at runtime\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// In dist/, go up one level to find package.json\nconst require = createRequire(import.meta.url);\nconst pkg = require(join(__dirname, \"..\", \"package.json\")) as { version: string };\n\nexport const VERSION = pkg.version;\nexport const USER_AGENT = `clawrouter/${VERSION}`;\n","/**\n * Request Deduplication\n *\n * Prevents double-charging when OpenClaw retries a request after timeout.\n * Tracks in-flight requests and caches completed responses for a short TTL.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedResponse = {\n status: number;\n headers: Record;\n body: Buffer;\n completedAt: number;\n};\n\ntype InflightEntry = {\n resolvers: Array<(result: CachedResponse) => void>;\n};\n\nconst DEFAULT_TTL_MS = 30_000; // 30 seconds\nconst MAX_BODY_SIZE = 1_048_576; // 1MB\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical string regardless of field order.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip OpenClaw-injected timestamps from message content.\n * Format: [DAY YYYY-MM-DD HH:MM TZ] at the start of messages.\n * Example: [SUN 2026-02-07 13:30 PST] Hello world\n *\n * This ensures requests with different timestamps but same content hash identically.\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction stripTimestamps(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stripTimestamps);\n }\n const result: Record = {};\n for (const [key, value] of Object.entries(obj as Record)) {\n if (key === \"content\" && typeof value === \"string\") {\n // Strip timestamp prefix from message content\n result[key] = value.replace(TIMESTAMP_PATTERN, \"\");\n } else {\n result[key] = stripTimestamps(value);\n }\n }\n return result;\n}\n\nexport class RequestDeduplicator {\n private inflight = new Map();\n private completed = new Map();\n private ttlMs: number;\n\n constructor(ttlMs = DEFAULT_TTL_MS) {\n this.ttlMs = ttlMs;\n }\n\n /** Hash request body to create a dedup key. */\n static hash(body: Buffer): string {\n // Canonicalize JSON to ensure consistent hashing regardless of field order.\n // Also strip OpenClaw-injected timestamps so retries with different timestamps\n // still match the same dedup key.\n let content = body;\n try {\n const parsed = JSON.parse(body.toString());\n const stripped = stripTimestamps(parsed);\n const canonical = canonicalize(stripped);\n content = Buffer.from(JSON.stringify(canonical));\n } catch {\n // Not valid JSON, use raw bytes\n }\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 16);\n }\n\n /** Check if a response is cached for this key. */\n getCached(key: string): CachedResponse | undefined {\n const entry = this.completed.get(key);\n if (!entry) return undefined;\n if (Date.now() - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n return undefined;\n }\n return entry;\n }\n\n /** Check if a request with this key is currently in-flight. Returns a promise to wait on. */\n getInflight(key: string): Promise | undefined {\n const entry = this.inflight.get(key);\n if (!entry) return undefined;\n return new Promise((resolve) => {\n entry.resolvers.push(resolve);\n });\n }\n\n /** Mark a request as in-flight. */\n markInflight(key: string): void {\n this.inflight.set(key, {\n resolvers: [],\n });\n }\n\n /** Complete an in-flight request — cache result and notify waiters. */\n complete(key: string, result: CachedResponse): void {\n // Only cache responses within size limit\n if (result.body.length <= MAX_BODY_SIZE) {\n this.completed.set(key, result);\n }\n\n const entry = this.inflight.get(key);\n if (entry) {\n for (const resolve of entry.resolvers) {\n resolve(result);\n }\n this.inflight.delete(key);\n }\n\n this.prune();\n }\n\n /** Remove an in-flight entry on error (don't cache failures).\n * Also rejects any waiters so they can retry independently. */\n removeInflight(key: string): void {\n const entry = this.inflight.get(key);\n if (entry) {\n // Resolve waiters with a sentinel error response so they don't hang forever.\n // Waiters will see a 503 and can retry on their own.\n const errorBody = Buffer.from(\n JSON.stringify({\n error: { message: \"Original request failed, please retry\", type: \"dedup_origin_failed\" },\n }),\n );\n for (const resolve of entry.resolvers) {\n resolve({\n status: 503,\n headers: { \"content-type\": \"application/json\" },\n body: errorBody,\n completedAt: Date.now(),\n });\n }\n this.inflight.delete(key);\n }\n }\n\n /** Prune expired completed entries. */\n private prune(): void {\n const now = Date.now();\n for (const [key, entry] of this.completed) {\n if (now - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n }\n }\n }\n}\n","/**\n * Response Cache for LLM Completions\n *\n * Caches LLM responses by request hash (model + messages + params).\n * Inspired by LiteLLM's caching system. Returns cached responses for\n * identical requests, saving both cost and latency.\n *\n * Features:\n * - TTL-based expiration (default 10 minutes)\n * - LRU eviction when cache is full\n * - Size limits per item (1MB max)\n * - Heap-based expiration tracking for efficient pruning\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedLLMResponse = {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n cachedAt: number;\n expiresAt: number;\n};\n\nexport type ResponseCacheConfig = {\n /** Maximum number of cached responses. Default: 200 */\n maxSize?: number;\n /** Default TTL in seconds. Default: 600 (10 minutes) */\n defaultTTL?: number;\n /** Maximum size per cached item in bytes. Default: 1MB */\n maxItemSize?: number;\n /** Enable/disable cache. Default: true */\n enabled?: boolean;\n};\n\nconst DEFAULT_CONFIG: Required = {\n maxSize: 200,\n defaultTTL: 600,\n maxItemSize: 1_048_576, // 1MB\n enabled: true,\n};\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical hash.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip fields that shouldn't affect cache key:\n * - stream (we handle streaming separately)\n * - timestamps injected by OpenClaw\n * - request IDs\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction normalizeForCache(obj: Record): Record {\n const result: Record = {};\n\n for (const [key, value] of Object.entries(obj)) {\n // Skip fields that don't affect response content\n if ([\"stream\", \"user\", \"request_id\", \"x-request-id\"].includes(key)) {\n continue;\n }\n\n if (key === \"messages\" && Array.isArray(value)) {\n // Strip timestamps from message content\n result[key] = value.map((msg: unknown) => {\n if (typeof msg === \"object\" && msg !== null) {\n const m = msg as Record;\n if (typeof m.content === \"string\") {\n return { ...m, content: m.content.replace(TIMESTAMP_PATTERN, \"\") };\n }\n }\n return msg;\n });\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nexport class ResponseCache {\n private cache = new Map();\n private expirationHeap: Array<{ expiresAt: number; key: string }> = [];\n private config: Required;\n\n // Stats for monitoring\n private stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n };\n\n constructor(config: ResponseCacheConfig = {}) {\n // Filter out undefined values so they don't override defaults\n const filtered = Object.fromEntries(\n Object.entries(config).filter(([, v]) => v !== undefined),\n ) as ResponseCacheConfig;\n this.config = { ...DEFAULT_CONFIG, ...filtered };\n }\n\n /**\n * Generate cache key from request body.\n * Hashes: model + messages + temperature + max_tokens + other params\n */\n static generateKey(body: Buffer | string): string {\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n const normalized = normalizeForCache(parsed);\n const canonical = canonicalize(normalized);\n const keyContent = JSON.stringify(canonical);\n return createHash(\"sha256\").update(keyContent).digest(\"hex\").slice(0, 32);\n } catch {\n // Fallback: hash raw body\n const content = typeof body === \"string\" ? body : body.toString();\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 32);\n }\n }\n\n /**\n * Check if caching is enabled for this request.\n * Respects cache control headers and request params.\n */\n shouldCache(body: Buffer | string, headers?: Record): boolean {\n if (!this.config.enabled) return false;\n\n // Respect Cache-Control: no-cache header\n if (headers?.[\"cache-control\"]?.includes(\"no-cache\")) {\n return false;\n }\n\n // Check for explicit cache disable in body\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n if (parsed.cache === false || parsed.no_cache === true) {\n return false;\n }\n } catch {\n // Not JSON, allow caching\n }\n\n return true;\n }\n\n /**\n * Get cached response if available and not expired.\n */\n get(key: string): CachedLLMResponse | undefined {\n const entry = this.cache.get(key);\n if (!entry) {\n this.stats.misses++;\n return undefined;\n }\n\n // Check expiration\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n this.stats.misses++;\n return undefined;\n }\n\n this.stats.hits++;\n return entry;\n }\n\n /**\n * Cache a response with optional custom TTL.\n */\n set(\n key: string,\n response: {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n },\n ttlSeconds?: number,\n ): void {\n // Don't cache if disabled or maxSize is 0\n if (!this.config.enabled || this.config.maxSize <= 0) return;\n\n // Don't cache if item too large\n if (response.body.length > this.config.maxItemSize) {\n console.log(`[ResponseCache] Skipping cache - item too large: ${response.body.length} bytes`);\n return;\n }\n\n // Don't cache error responses\n if (response.status >= 400) {\n return;\n }\n\n // Evict if at capacity\n if (this.cache.size >= this.config.maxSize) {\n this.evict();\n }\n\n const now = Date.now();\n const ttl = ttlSeconds ?? this.config.defaultTTL;\n const expiresAt = now + ttl * 1000;\n\n const entry: CachedLLMResponse = {\n ...response,\n cachedAt: now,\n expiresAt,\n };\n\n this.cache.set(key, entry);\n this.expirationHeap.push({ expiresAt, key });\n }\n\n /**\n * Evict expired and oldest entries to make room.\n */\n private evict(): void {\n const now = Date.now();\n\n // First pass: remove expired entries\n this.expirationHeap.sort((a, b) => a.expiresAt - b.expiresAt);\n\n while (this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap[0];\n\n // Check if entry still exists and matches\n const entry = this.cache.get(oldest.key);\n if (!entry || entry.expiresAt !== oldest.expiresAt) {\n // Stale heap entry, remove it\n this.expirationHeap.shift();\n continue;\n }\n\n if (oldest.expiresAt <= now) {\n // Expired, remove both\n this.cache.delete(oldest.key);\n this.expirationHeap.shift();\n this.stats.evictions++;\n } else {\n // Not expired, stop\n break;\n }\n }\n\n // Second pass: if still at capacity, evict oldest\n while (this.cache.size >= this.config.maxSize && this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap.shift()!;\n if (this.cache.has(oldest.key)) {\n this.cache.delete(oldest.key);\n this.stats.evictions++;\n }\n }\n }\n\n /**\n * Get cache statistics.\n */\n getStats(): {\n size: number;\n maxSize: number;\n hits: number;\n misses: number;\n evictions: number;\n hitRate: string;\n } {\n const total = this.stats.hits + this.stats.misses;\n const hitRate = total > 0 ? ((this.stats.hits / total) * 100).toFixed(1) + \"%\" : \"0%\";\n\n return {\n size: this.cache.size,\n maxSize: this.config.maxSize,\n hits: this.stats.hits,\n misses: this.stats.misses,\n evictions: this.stats.evictions,\n hitRate,\n };\n }\n\n /**\n * Clear all cached entries.\n */\n clear(): void {\n this.cache.clear();\n this.expirationHeap = [];\n }\n\n /**\n * Check if cache is enabled.\n */\n isEnabled(): boolean {\n return this.config.enabled;\n }\n}\n","/**\n * Typed Error Classes for ClawRouter\n *\n * Provides structured errors for balance-related failures with\n * all necessary information for user-friendly error messages.\n */\n\n/**\n * Thrown when wallet has insufficient USDC balance for a request.\n */\nexport class InsufficientFundsError extends Error {\n readonly code = \"INSUFFICIENT_FUNDS\" as const;\n readonly currentBalanceUSD: string;\n readonly requiredUSD: string;\n readonly walletAddress: string;\n\n constructor(opts: { currentBalanceUSD: string; requiredUSD: string; walletAddress: string }) {\n const msg = [\n `Insufficient balance. Current: ${opts.currentBalanceUSD}, Required: ${opts.requiredUSD}`,\n `Options:`,\n ` 1. Fund wallet: ${opts.walletAddress}`,\n ` 2. Use free model: /model free`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"InsufficientFundsError\";\n this.currentBalanceUSD = opts.currentBalanceUSD;\n this.requiredUSD = opts.requiredUSD;\n this.walletAddress = opts.walletAddress;\n }\n}\n\n/**\n * Thrown when wallet has no USDC balance (or effectively zero).\n */\nexport class EmptyWalletError extends Error {\n readonly code = \"EMPTY_WALLET\" as const;\n readonly walletAddress: string;\n\n constructor(walletAddress: string) {\n const msg = [\n `No USDC balance.`,\n `Options:`,\n ` 1. Fund wallet: ${walletAddress}`,\n ` 2. Use free model: /model free`,\n ` 3. Uninstall: bash ~/.openclaw/extensions/clawrouter/scripts/uninstall.sh`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"EmptyWalletError\";\n this.walletAddress = walletAddress;\n }\n}\n\n/**\n * Type guard to check if an error is InsufficientFundsError.\n */\nexport function isInsufficientFundsError(error: unknown): error is InsufficientFundsError {\n return error instanceof Error && (error as InsufficientFundsError).code === \"INSUFFICIENT_FUNDS\";\n}\n\n/**\n * Type guard to check if an error is EmptyWalletError.\n */\nexport function isEmptyWalletError(error: unknown): error is EmptyWalletError {\n return error instanceof Error && (error as EmptyWalletError).code === \"EMPTY_WALLET\";\n}\n\n/**\n * Type guard to check if an error is a balance-related error.\n */\nexport function isBalanceError(error: unknown): error is InsufficientFundsError | EmptyWalletError {\n return isInsufficientFundsError(error) || isEmptyWalletError(error);\n}\n\n/**\n * Thrown when RPC call fails (network error, node down, etc).\n * Distinguishes infrastructure failures from actual empty wallets.\n */\nexport class RpcError extends Error {\n readonly code = \"RPC_ERROR\" as const;\n readonly originalError: unknown;\n\n constructor(message: string, originalError?: unknown) {\n super(`RPC error: ${message}. Check network connectivity.`);\n this.name = \"RpcError\";\n this.originalError = originalError;\n }\n}\n\n/**\n * Type guard to check if an error is RpcError.\n */\nexport function isRpcError(error: unknown): error is RpcError {\n return error instanceof Error && (error as RpcError).code === \"RPC_ERROR\";\n}\n","/**\n * EIP-3009 payment asset on Base network.\n * Represents a stablecoin that supports `transferWithAuthorization`\n * for gasless, single-step payment settlements.\n */\nexport type BasePaymentAsset = {\n chain: \"base\";\n asset: `0x${string}`;\n symbol: string;\n decimals: number;\n name: string;\n transferMethod: \"eip3009\";\n priority?: number;\n enabled?: boolean;\n};\n\n/** Default payment asset: USDC on Base (6 decimals, EIP-3009). */\nexport const DEFAULT_BASE_PAYMENT_ASSET: BasePaymentAsset = {\n chain: \"base\",\n asset: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n symbol: \"USDC\",\n decimals: 6,\n name: \"USD Coin\",\n transferMethod: \"eip3009\",\n};\n\ntype PaymentMetadataResponse =\n | Partial\n | { paymentAssets?: Array> }\n | { paymentAsset?: Partial }\n | { base?: Partial };\n\n/** Check if a value is a valid 0x-prefixed ERC-20 contract address (40 hex chars). */\nfunction isHexAddress(value: unknown): value is `0x${string}` {\n return typeof value === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(value);\n}\n\n/**\n * Validate and normalize a single payment asset from an API response.\n * Returns undefined if the input is missing required fields or uses a non-EIP-3009 transfer method.\n * Symbols are uppercased; names are trimmed.\n */\nexport function normalizeBasePaymentAsset(\n value: unknown,\n): BasePaymentAsset | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n\n const candidate = value as Partial;\n if (!isHexAddress(candidate.asset)) return undefined;\n if (typeof candidate.symbol !== \"string\" || candidate.symbol.trim() === \"\") return undefined;\n if (\n typeof candidate.decimals !== \"number\" ||\n !Number.isInteger(candidate.decimals) ||\n candidate.decimals < 0\n ) {\n return undefined;\n }\n if (typeof candidate.name !== \"string\" || candidate.name.trim() === \"\") return undefined;\n if (candidate.transferMethod !== undefined && candidate.transferMethod !== \"eip3009\") {\n return undefined;\n }\n\n return {\n chain: \"base\",\n asset: candidate.asset,\n symbol: candidate.symbol.trim().toUpperCase(),\n decimals: candidate.decimals,\n name: candidate.name.trim(),\n transferMethod: \"eip3009\",\n priority: typeof candidate.priority === \"number\" ? candidate.priority : undefined,\n enabled: typeof candidate.enabled === \"boolean\" ? candidate.enabled : undefined,\n };\n}\n\n/** Sort assets by priority (ascending). Assets without priority go last. */\nfunction sortAssets(assets: BasePaymentAsset[]): BasePaymentAsset[] {\n return [...assets].sort(\n (a, b) => (a.priority ?? Number.MAX_SAFE_INTEGER) - (b.priority ?? Number.MAX_SAFE_INTEGER),\n );\n}\n\n/**\n * Normalize a payment metadata response into an array of valid EIP-3009 assets.\n * Handles flat, nested (`paymentAsset`, `base`), and array (`paymentAssets`) response shapes.\n * Filters out disabled and non-EIP-3009 assets. Falls back to USDC if no valid assets found.\n */\nexport function normalizeBasePaymentAssets(value: unknown): BasePaymentAsset[] {\n if (!value || typeof value !== \"object\") return [DEFAULT_BASE_PAYMENT_ASSET];\n\n const payload = value as PaymentMetadataResponse & { paymentAssets?: unknown };\n const candidateList = Array.isArray(payload.paymentAssets)\n ? (payload.paymentAssets as unknown[])\n : [\n (payload as { paymentAsset?: unknown }).paymentAsset,\n (payload as { base?: unknown }).base,\n payload,\n ];\n\n const normalized = candidateList\n .map((candidate: unknown) => normalizeBasePaymentAsset(candidate))\n .filter((asset: BasePaymentAsset | undefined): asset is BasePaymentAsset => Boolean(asset))\n .filter((asset) => asset.enabled !== false && asset.transferMethod === \"eip3009\");\n\n return sortAssets(\n normalized.length > 0 ? normalized : [DEFAULT_BASE_PAYMENT_ASSET],\n );\n}\n\n/**\n * Fetch all available EIP-3009 payment assets from the API.\n * Falls back to the default USDC asset on network error or non-OK response.\n */\nexport async function fetchBasePaymentAssets(\n apiBase: string,\n baseFetch: typeof fetch = fetch,\n): Promise {\n try {\n const response = await baseFetch(`${apiBase.replace(/\\/+$/, \"\")}/v1/payment-metadata?chain=base`, {\n headers: { Accept: \"application/json\" },\n });\n if (!response.ok) return [DEFAULT_BASE_PAYMENT_ASSET];\n\n const payload = (await response.json()) as PaymentMetadataResponse;\n return normalizeBasePaymentAssets(payload);\n } catch {\n // Network error, JSON parse failure, or normalize exception — fall back to USDC\n return [DEFAULT_BASE_PAYMENT_ASSET];\n }\n}\n\n/**\n * Fetch the highest-priority EIP-3009 payment asset from the API.\n * Convenience wrapper around {@link fetchBasePaymentAssets} that returns only the first asset.\n */\nexport async function fetchBasePaymentAsset(\n apiBase: string,\n baseFetch: typeof fetch = fetch,\n): Promise {\n const assets = await fetchBasePaymentAssets(apiBase, baseFetch);\n return assets[0];\n}\n","/**\n * Balance Monitor for ClawRouter\n *\n * Monitors stablecoin balance on Base network with intelligent caching.\n * Supports any EIP-3009 stablecoin (USDC, fxUSD, EURC, etc.) with\n * automatic normalization from native decimals to USD micros (6 decimals).\n * Provides pre-request balance checks to prevent failed payments.\n *\n * Caching Strategy:\n * - TTL: 30 seconds (balance is cached to avoid excessive RPC calls)\n * - Optimistic deduction: after successful payment, subtract estimated cost from cache\n * - Invalidation: on payment failure, immediately refresh from RPC\n */\n\nimport { createPublicClient, http, erc20Abi } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { RpcError } from \"./errors.js\";\nimport { DEFAULT_BASE_PAYMENT_ASSET, type BasePaymentAsset } from \"./payment-asset.js\";\n\n/** Cache TTL in milliseconds (30 seconds) */\nconst CACHE_TTL_MS = 30_000;\n\n/** Balance thresholds in USD micros (6 decimals, normalized from any stablecoin) */\nexport const BALANCE_THRESHOLDS = {\n /** Low balance warning threshold: $1.00 */\n LOW_BALANCE_MICROS: 1_000_000n,\n /** Effectively zero threshold: $0.0001 (covers dust/rounding) */\n ZERO_THRESHOLD: 100n,\n} as const;\n\n/** Balance information returned by checkBalance() */\nexport type BalanceInfo = {\n /** Raw balance normalized to USD micros (6 decimals, regardless of the underlying asset's native decimals) */\n balance: bigint;\n /** Formatted balance as \"$X.XX\" */\n balanceUSD: string;\n /** Symbol of the active Base payment asset */\n assetSymbol: string;\n /** True if balance < $1.00 */\n isLow: boolean;\n /** True if balance < $0.0001 (effectively zero) */\n isEmpty: boolean;\n /** Wallet address for funding instructions */\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SufficiencyResult = {\n /** True if balance >= estimated cost */\n sufficient: boolean;\n /** Current balance info */\n info: BalanceInfo;\n /** If insufficient, the shortfall as \"$X.XX\" */\n shortfall?: string;\n};\n\n/**\n * Monitors stablecoin balance on Base network.\n *\n * Usage:\n * const monitor = new BalanceMonitor(\"0x...\");\n * const info = await monitor.checkBalance();\n * if (info.isLow) console.warn(\"Low balance!\");\n */\nexport class BalanceMonitor {\n private readonly client;\n private readonly walletAddress: `0x${string}`;\n private readonly assetMonitors = new Map();\n private state: {\n asset: BasePaymentAsset;\n cachedBalance: bigint | null;\n cachedAt: number;\n };\n\n constructor(walletAddress: string, asset: BasePaymentAsset = DEFAULT_BASE_PAYMENT_ASSET) {\n this.walletAddress = walletAddress as `0x${string}`;\n this.state = {\n asset,\n cachedBalance: null,\n cachedAt: 0,\n };\n this.client = createPublicClient({\n chain: base,\n transport: http(undefined, {\n timeout: 10_000, // 10 second timeout to prevent hanging on slow RPC\n }),\n });\n }\n\n /**\n * Check current USDC balance.\n * Uses cache if valid, otherwise fetches from RPC.\n */\n async checkBalance(): Promise {\n const state = this.state;\n const now = Date.now();\n\n // Use cache only when balance is positive and still fresh.\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n if (\n state.cachedBalance !== null &&\n state.cachedBalance > 0n &&\n now - state.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(state.cachedBalance, state.asset);\n }\n\n // Fetch from RPC\n const balance = await this.fetchBalance(state.asset);\n if (balance > 0n) {\n state.cachedBalance = balance;\n state.cachedAt = now;\n }\n\n return this.buildInfo(balance, state.asset);\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n *\n * @param estimatedCostMicros - Estimated cost in USD micros (6 decimals)\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSD(shortfall),\n };\n }\n\n private get cachedBalance(): bigint | null {\n return this.state.cachedBalance;\n }\n\n private set cachedBalance(value: bigint | null) {\n this.state.cachedBalance = value;\n }\n\n private get cachedAt(): number {\n return this.state.cachedAt;\n }\n\n private set cachedAt(value: number) {\n this.state.cachedAt = value;\n }\n\n /**\n * Optimistically deduct estimated cost from cached balance.\n * Call this after a successful payment to keep cache accurate.\n *\n * @param amountMicros - Amount to deduct in USD micros\n */\n deductEstimated(amountMicros: bigint): void {\n const state = this.state;\n if (state.cachedBalance !== null && state.cachedBalance >= amountMicros) {\n state.cachedBalance -= amountMicros;\n }\n }\n\n /**\n * Invalidate cache, forcing next checkBalance() to fetch from RPC.\n * Call this after a payment failure to get accurate balance.\n */\n invalidate(): void {\n const state = this.state;\n state.cachedBalance = null;\n state.cachedAt = 0;\n }\n\n /**\n * Force refresh balance from RPC (ignores cache).\n */\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n setAsset(asset: BasePaymentAsset): void {\n const currentAsset = this.state.asset;\n if (\n currentAsset.asset.toLowerCase() !== asset.asset.toLowerCase() ||\n currentAsset.symbol !== asset.symbol ||\n currentAsset.decimals !== asset.decimals\n ) {\n this.state = this.getSharedMonitorForAsset(asset).state;\n }\n }\n\n getAsset(): BasePaymentAsset {\n return this.state.asset;\n }\n\n /**\n * Format a stablecoin amount (normalized to USD micros) as \"$X.XX\".\n */\n formatUSD(amountMicros: bigint): string {\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n formatUSDC(amountMicros: bigint): string {\n return this.formatUSD(amountMicros);\n }\n\n /**\n * Get the wallet address being monitored.\n */\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n getAssetSymbol(): string {\n return this.state.asset.symbol;\n }\n\n getSharedMonitorForAsset(asset: BasePaymentAsset): BalanceMonitor {\n if (\n this.state.asset.asset.toLowerCase() === asset.asset.toLowerCase() &&\n this.state.asset.symbol === asset.symbol &&\n this.state.asset.decimals === asset.decimals\n ) {\n return this;\n }\n\n const key = `${asset.asset.toLowerCase()}:${asset.symbol}:${asset.decimals}`;\n const existing = this.assetMonitors.get(key);\n if (existing) return existing;\n\n const monitor = new BalanceMonitor(this.walletAddress, asset);\n this.assetMonitors.set(key, monitor);\n return monitor;\n }\n\n /** Fetch balance from RPC */\n private async fetchBalance(asset: BasePaymentAsset): Promise {\n try {\n const balance = await this.client.readContract({\n address: asset.asset,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [this.walletAddress],\n });\n return this.toUsdMicros(balance, asset);\n } catch (error) {\n // Throw typed error instead of silently returning 0\n // This allows callers to distinguish \"node down\" from \"wallet empty\"\n throw new RpcError(error instanceof Error ? error.message : \"Unknown error\", error);\n }\n }\n\n /** Build BalanceInfo from raw balance */\n private buildInfo(balance: bigint, asset: BasePaymentAsset): BalanceInfo {\n return {\n balance,\n balanceUSD: this.formatUSD(balance),\n assetSymbol: asset.symbol,\n isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,\n isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD,\n walletAddress: this.walletAddress,\n };\n }\n\n private toUsdMicros(rawAmount: bigint, asset: BasePaymentAsset): bigint {\n if (asset.decimals === 6) return rawAmount;\n if (asset.decimals > 6) {\n return rawAmount / 10n ** BigInt(asset.decimals - 6);\n }\n return rawAmount * 10n ** BigInt(6 - asset.decimals);\n }\n}\n","/**\n * BlockRun Auth Methods for OpenClaw\n *\n * Provides wallet-based authentication for the BlockRun provider.\n * Operators configure their wallet private key, which is used to\n * sign x402 micropayments for LLM inference.\n *\n * Three methods:\n * 1. Auto-generate — create a new wallet on first run, save to ~/.openclaw/blockrun/wallet.key\n * 2. Environment variable — read from BLOCKRUN_WALLET_KEY\n * 3. Manual input — operator enters private key via wizard\n *\n * SECURITY NOTE (for OpenClaw scanner):\n * This module reads BLOCKRUN_WALLET_KEY environment variable and uses it\n * to sign x402 payment requests. This is INTENTIONAL and REQUIRED behavior:\n * - The wallet key signs USDC payments on Base L2 for each LLM API call\n * - Without the key, ClawRouter cannot authorize payments to BlockRun\n * - The key is NEVER transmitted over the network, only used locally for signing\n * - This is standard x402 payment flow, not credential harvesting\n *\n * @see https://x402.org - x402 payment protocol specification\n * @see https://blockrun.ai/docs - BlockRun API documentation\n * @openclaw-security env-access=BLOCKRUN_WALLET_KEY purpose=x402-payment-signing\n */\n\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport type { ProviderAuthMethod, ProviderAuthContext, ProviderAuthResult } from \"./types.js\";\nimport {\n generateWalletMnemonic,\n isValidMnemonic,\n deriveSolanaKeyBytes,\n deriveAllKeys,\n getSolanaAddress,\n} from \"./wallet.js\";\n\nconst WALLET_DIR = join(homedir(), \".openclaw\", \"blockrun\");\nconst WALLET_FILE = join(WALLET_DIR, \"wallet.key\");\nconst MNEMONIC_FILE = join(WALLET_DIR, \"mnemonic\");\nconst CHAIN_FILE = join(WALLET_DIR, \"payment-chain\");\n\n// Export for use by wallet command and index.ts\nexport { WALLET_FILE, MNEMONIC_FILE, CHAIN_FILE };\n\n/**\n * Try to load a previously auto-generated wallet key from disk.\n */\nasync function loadSavedWallet(): Promise {\n try {\n const key = (await readTextFile(WALLET_FILE)).trim();\n if (key.startsWith(\"0x\") && key.length === 66) {\n console.log(`[ClawRouter] ✓ Loaded existing wallet from ${WALLET_FILE}`);\n return key;\n }\n // File exists but content is wrong — do NOT silently fall through to generate a new wallet.\n // This would silently replace a funded wallet with an empty one.\n console.error(`[ClawRouter] ✗ CRITICAL: Wallet file exists but has invalid format!`);\n console.error(`[ClawRouter] File: ${WALLET_FILE}`);\n console.error(`[ClawRouter] Expected: 0x followed by 64 hex characters (66 chars total)`);\n console.error(\n `[ClawRouter] To fix: restore your backup key or set BLOCKRUN_WALLET_KEY env var`,\n );\n throw new Error(\n `Wallet file at ${WALLET_FILE} is corrupted or has wrong format. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Restore your backup key or set BLOCKRUN_WALLET_KEY environment variable.`,\n );\n } catch (err) {\n // Re-throw corruption errors (not ENOENT)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n // If it's our own thrown error, re-throw as-is\n if (err instanceof Error && err.message.includes(\"Refusing to auto-generate\")) {\n throw err;\n }\n console.error(\n `[ClawRouter] ✗ Failed to read wallet file: ${err instanceof Error ? err.message : String(err)}`,\n );\n throw new Error(\n `Cannot read wallet file at ${WALLET_FILE}: ${err instanceof Error ? err.message : String(err)}. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Fix file permissions or set BLOCKRUN_WALLET_KEY environment variable.`,\n { cause: err },\n );\n }\n }\n return undefined;\n}\n\n/**\n * Load mnemonic from disk if it exists.\n * Warns on corruption but never throws — callers handle missing mnemonic gracefully.\n */\nasync function loadMnemonic(): Promise {\n try {\n const mnemonic = (await readTextFile(MNEMONIC_FILE)).trim();\n if (mnemonic && isValidMnemonic(mnemonic)) {\n return mnemonic;\n }\n // File exists but content is invalid — warn but continue.\n console.warn(`[ClawRouter] ⚠ Mnemonic file exists but has invalid format — ignoring`);\n return undefined;\n } catch (err) {\n // Only swallow ENOENT (file not found)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n console.warn(`[ClawRouter] ⚠ Cannot read mnemonic file — ignoring`);\n }\n }\n return undefined;\n}\n\n/**\n * Save mnemonic to disk.\n */\nasync function saveMnemonic(mnemonic: string): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Generate a new wallet with BIP-39 mnemonic, save to disk.\n * New users get both EVM and Solana keys derived from the same mnemonic.\n * CRITICAL: Verifies the file was actually written after generation.\n */\nasync function generateAndSaveWallet(): Promise<{\n key: string;\n address: string;\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: if a mnemonic file already exists, a Solana wallet was derived from it.\n // Generating a new wallet would overwrite the mnemonic and lose Solana funds.\n const existingMnemonic = await loadMnemonic();\n if (existingMnemonic) {\n throw new Error(\n `Mnemonic file exists at ${MNEMONIC_FILE} but wallet.key is missing.\\n` +\n `Refusing to generate a new wallet to protect existing funds.\\n\\n` +\n `Restore your EVM private key using one of:\\n` +\n ` Windows: set BLOCKRUN_WALLET_KEY=0x\\n` +\n ` Mac/Linux: export BLOCKRUN_WALLET_KEY=0x\\n\\n` +\n `Then run: npx @blockrun/clawrouter`,\n );\n }\n\n const mnemonic = generateWalletMnemonic();\n const derived = deriveAllKeys(mnemonic);\n\n // Create directory\n await mkdir(WALLET_DIR, { recursive: true });\n\n // Write wallet key file (EVM private key)\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n // Write mnemonic file\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n\n // CRITICAL: Verify the file was actually written\n try {\n const verification = (await readTextFile(WALLET_FILE)).trim();\n if (verification !== derived.evmPrivateKey) {\n throw new Error(\"Wallet file verification failed - content mismatch\");\n }\n console.log(`[ClawRouter] Wallet saved and verified at ${WALLET_FILE}`);\n } catch (err) {\n throw new Error(\n `Failed to verify wallet file after creation: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n // Derive Solana address for display\n let solanaAddress: string | undefined;\n try {\n solanaAddress = await getSolanaAddress(derived.solanaPrivateKeyBytes);\n } catch {\n // Non-fatal — Solana address display is best-effort\n }\n\n // Print prominent backup reminder after generating a new wallet\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] NEW WALLET GENERATED — BACK UP YOUR KEY NOW`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter] Key file : ${WALLET_FILE}`);\n console.log(`[ClawRouter] Mnemonic : ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Both EVM (Base) and Solana wallets are ready.`);\n console.log(`[ClawRouter] To back up, run in OpenClaw:`);\n console.log(`[ClawRouter] /wallet export`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] To restore on another machine:`);\n console.log(`[ClawRouter] export BLOCKRUN_WALLET_KEY=`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n return {\n key: derived.evmPrivateKey,\n address: derived.evmAddress,\n mnemonic,\n solanaPrivateKeyBytes: derived.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Resolve wallet key: load saved → env var → auto-generate.\n * Also loads mnemonic if available for Solana key derivation.\n * Called by index.ts before the auth wizard runs.\n */\nexport type WalletResolution = {\n key: string;\n address: string;\n source: \"saved\" | \"env\" | \"generated\";\n mnemonic?: string;\n solanaPrivateKeyBytes?: Uint8Array;\n};\n\nexport async function resolveOrGenerateWalletKey(): Promise {\n // 1. Previously saved wallet\n const saved = await loadSavedWallet();\n if (saved) {\n const account = privateKeyToAccount(saved as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: saved,\n address: account.address,\n source: \"saved\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: saved, address: account.address, source: \"saved\" };\n }\n\n // 2. Environment variable\n const envKey = process[\"env\"].BLOCKRUN_WALLET_KEY;\n if (typeof envKey === \"string\" && envKey.startsWith(\"0x\") && envKey.length === 66) {\n const account = privateKeyToAccount(envKey as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: envKey,\n address: account.address,\n source: \"env\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: envKey, address: account.address, source: \"env\" };\n }\n\n // 3. Auto-generate with BIP-39 mnemonic (new users get both chains)\n const result = await generateAndSaveWallet();\n return {\n key: result.key,\n address: result.address,\n source: \"generated\",\n mnemonic: result.mnemonic,\n solanaPrivateKeyBytes: result.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Recover wallet.key from existing mnemonic.\n *\n * ONLY works when the mnemonic was originally generated by ClawRouter\n * (i.e., both mnemonic and EVM key were derived from the same seed).\n * If the EVM key was set independently (manually or via env), the derived\n * key will be different — do NOT use this in that case.\n */\nexport async function recoverWalletFromMnemonic(): Promise {\n const mnemonic = await loadMnemonic();\n if (!mnemonic) {\n console.error(`[ClawRouter] No mnemonic found at ${MNEMONIC_FILE}`);\n console.error(`[ClawRouter] Cannot recover — no mnemonic to derive from.`);\n process.exit(1);\n }\n\n // Safety: if wallet.key already exists, refuse to overwrite\n const existing = await loadSavedWallet().catch(() => undefined);\n if (existing) {\n console.error(`[ClawRouter] wallet.key already exists at ${WALLET_FILE}`);\n console.error(`[ClawRouter] Recovery not needed.`);\n process.exit(1);\n }\n\n const derived = deriveAllKeys(mnemonic);\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const solanaAddress = await getSolanaAddress(solanaKeyBytes).catch(() => undefined);\n\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ⚠ WALLET RECOVERY FROM MNEMONIC`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] This only works if your mnemonic was originally`);\n console.log(`[ClawRouter] generated by ClawRouter (not set manually).`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Derived EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Derived Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] If the Solana address above matches your funded`);\n console.log(`[ClawRouter] wallet, recovery is safe to proceed.`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n console.log(`[ClawRouter] ✓ wallet.key restored at ${WALLET_FILE}`);\n console.log(`[ClawRouter] Run: npx @blockrun/clawrouter`);\n console.log(`[ClawRouter]`);\n}\n\n/**\n * Set up Solana wallet for existing EVM-only users.\n * Generates a new mnemonic for Solana key derivation.\n * NEVER touches the existing wallet.key file.\n */\nexport async function setupSolana(): Promise<{\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: mnemonic must not already exist\n const existing = await loadMnemonic();\n if (existing) {\n throw new Error(\"Solana wallet already set up. Mnemonic file exists at \" + MNEMONIC_FILE);\n }\n\n // Safety: wallet.key must exist (can't set up Solana without EVM wallet)\n const savedKey = await loadSavedWallet();\n if (!savedKey) {\n throw new Error(\n \"No EVM wallet found. Run ClawRouter first to generate a wallet before setting up Solana.\",\n );\n }\n\n // Generate new mnemonic for Solana derivation\n const mnemonic = generateWalletMnemonic();\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n\n // Save mnemonic (wallet.key untouched)\n await saveMnemonic(mnemonic);\n\n console.log(`[ClawRouter] Solana wallet set up successfully.`);\n console.log(`[ClawRouter] Mnemonic saved to ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter] Existing EVM wallet unchanged.`);\n\n return { mnemonic, solanaPrivateKeyBytes: solanaKeyBytes };\n}\n\n/**\n * Persist the user's payment chain selection to disk.\n */\nexport async function savePaymentChain(chain: \"base\" | \"solana\"): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(CHAIN_FILE, chain + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Load the persisted payment chain selection from disk.\n * Returns \"base\" if no file exists or the file is invalid.\n */\nexport async function loadPaymentChain(): Promise<\"base\" | \"solana\"> {\n try {\n const content = (await readTextFile(CHAIN_FILE)).trim();\n if (content === \"solana\") return \"solana\";\n return \"base\";\n } catch {\n return \"base\";\n }\n}\n\n/**\n * Resolve payment chain: env var first → persisted file second → default \"base\".\n */\nexport async function resolvePaymentChain(): Promise<\"base\" | \"solana\"> {\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"solana\") return \"solana\";\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"base\") return \"base\";\n return loadPaymentChain();\n}\n\n/**\n * Auth method: operator enters their wallet private key directly.\n */\nexport const walletKeyAuth: ProviderAuthMethod = {\n id: \"wallet-key\",\n label: \"Wallet Private Key\",\n hint: \"Enter your EVM wallet private key (0x...) for x402 payments to BlockRun\",\n kind: \"api_key\",\n run: async (ctx: ProviderAuthContext): Promise => {\n const key = await ctx.prompter.text({\n message: \"Enter your wallet private key (0x...)\",\n validate: (value: string) => {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"0x\")) return \"Key must start with 0x\";\n if (trimmed.length !== 66) return \"Key must be 66 characters (0x + 64 hex)\";\n if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) return \"Key must be valid hex\";\n return undefined;\n },\n });\n\n if (!key || typeof key !== \"string\") {\n throw new Error(\"Wallet key is required\");\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\n \"Wallet key stored securely in OpenClaw credentials.\",\n \"Your wallet signs x402 USDC payments on Base for each LLM call.\",\n \"Fund your wallet with USDC on Base to start using BlockRun models.\",\n ],\n };\n },\n};\n\n/**\n * Auth method: read wallet key from BLOCKRUN_WALLET_KEY environment variable.\n */\nexport const envKeyAuth: ProviderAuthMethod = {\n id: \"env-key\",\n label: \"Environment Variable\",\n hint: \"Use BLOCKRUN_WALLET_KEY environment variable\",\n kind: \"api_key\",\n run: async (): Promise => {\n const key = process[\"env\"].BLOCKRUN_WALLET_KEY;\n\n if (!key) {\n throw new Error(\n \"BLOCKRUN_WALLET_KEY environment variable is not set. \" +\n \"Set it to your EVM wallet private key (0x...).\",\n );\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\"Using wallet key from BLOCKRUN_WALLET_KEY environment variable.\"],\n };\n },\n};\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(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// 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 return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\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(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\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, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\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 = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, 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++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\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\nexport function validateObject(\n object: Record,\n fields: Record = {},\n optFields: Record = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _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 */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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\nfunction assertIsSquare(Fp: IField, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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 assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): (Fp: IField, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return (Fp: IField, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // 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): boolean =>\n (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 isLE: boolean;\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 isValidNot0: (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 invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): 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): IField {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security 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're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 * 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.Point.Fn.ORDER)\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 abytes(key);\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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons

> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns Fp type from Point (P_F

== P.F) */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns Fp type from PointCons (PC_F == PC.P.F) */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P == PC.P) */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper = (i: T[]) => T[];\n\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport function normalizeZ

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\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\n/** Internal wNAF opts for specific W and scalarBits */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = 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 point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\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 * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\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 const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\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 acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, 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 createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 than 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 secret keys / bigints)\n */\nexport function pippenger

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\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 const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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 P;\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

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\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 const fieldN = c.Fn;\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 = bitMask(windowSize);\n const tables = points.map((p: P) => {\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[]): P => {\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\nexport type ValidCurveParams = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: IField, isLE?: boolean): IField {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField;\n }\n}\nexport type FpFn = { Fp: IField; Fn: IField };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: Partial> = {},\n FpFnLE?: boolean\n): FpFn & { CURVE: ValidCurveParams } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abool,\n abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n memoized,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * https://paulmillr.com/posts/deterministic-signatures/\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates sigs with increased security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): Required {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n CURVE(): WeierstrassOpts;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\nexport type WeierstrassExtraOpts = Partial<{\n Fp: IField;\n Fn: IField;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n fromBytes: (bytes: Uint8Array) => AffinePoint;\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: (key: Uint8Array, message: Uint8Array) => Uint8Array;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed?: boolean\n ) => Uint8Array;\n Point: WeierstrassPointCons;\n utils: {\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Uint8Array, secretKey: Uint8Array, opts?: ECDSASignOpts) => Uint8Array;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(data);\n },\n },\n toSig(bytes: Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\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\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\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 { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: 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 x = Fp.mul(X, iz);\n const y = 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, y };\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 (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) 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 if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) 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 function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\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 WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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 // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\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 *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\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) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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(): boolean {\n return this.equals(Point.ZERO);\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 } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n hasHighS(): boolean;\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n}\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASignatureFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\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, 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, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, 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, 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, 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: IField, Fn: IField) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: Uint8Array) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey: Uint8Array, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(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: Uint8Array): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item)) return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey) return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed = true\n ): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor(): void {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: Uint8Array,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\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 toBytes(format: ECDSASignatureFormat = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\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 ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\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 *\n * Warning: we cannot assume here that message 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 */\n function prepSig(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\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 function k2sig(kBytes: Uint8Array): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\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 = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts = {}): Uint8Array {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n }) satisfies Signer;\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\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 = secp256k1_CURVE.p;\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(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\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\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(asciiToBytes(tag));\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.toBytes(true).slice(1);\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: Uint8Array) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { 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 const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\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 Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Uint8Array): Uint8Array {\n return schnorrGetExtPubKey(secretKey).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: Uint8Array,\n secretKey: Uint8Array,\n auxRand: Uint8Array = randomBytes(32)\n): Uint8Array {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(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 // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\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(Fn.toBytes(Fn.create(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: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\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 (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!Fn.isValidNot0(s)) return false;\n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\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 }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\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 ))();\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl } from './utils.ts';\n\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\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 }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1: CHash = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\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 this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5: CHash = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * const hdkey1 = HDKey.fromMasterSeed(seed);\n * const hdkey2 = HDKey.fromExtendedKey(base58key);\n * const hdkey3 = HDKey.fromJSON({ xpriv: string });\n *\n * // props\n * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];\n * console.log(hdkey2.privateKey, hdkey2.publicKey);\n * console.log(hdkey3.derive(\"m/0/2147483647'/1\"));\n * const sig = hdkey3.sign(hash);\n * hdkey3.verify(hash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.Point;\nconst { Fn } = Point;\nconst base58check = createBase58check(sha256);\n\nconst MASTER_SECRET = Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n\n/** Network-specific versioning. */\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened offset from Bitcoin, default */\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number): Uint8Array => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array;\n}\n\n/**\n * HDKey from BIP32\n * @example\n```js\nconst hdkey1 = HDKey.fromMasterSeed(seed);\nconst hdkey2 = HDKey.fromExtendedKey(base58key);\nconst hdkey3 = HDKey.fromJSON({ xpriv: string });\n```\n */\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this._privateKey || null;\n }\n get publicKey(): Uint8Array | null {\n return this._publicKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n\n static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n\n static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n readonly versions: Versions;\n readonly depth: number = 0;\n readonly index: number = 0;\n readonly chainCode: Uint8Array | null = null;\n readonly parentFingerprint: number = 0;\n private _privateKey?: Uint8Array;\n private _publicKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key');\n this._privateKey = opt.privateKey;\n this._publicKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n\n derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n deriveChild(index: number): HDKey {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = I.slice(0, 32);\n const chainCode = I.slice(32);\n if (!secp.utils.isValidSecretKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n const ctweak = Fn.fromBytes(childTweak);\n try {\n // Private parent key -> private child key\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n } else {\n const added = Point.fromBytes(this._publicKey).add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n sign(hash: Uint8Array): Uint8Array {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n\n verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n\n wipePrivateData(): this {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n","/**\n * Wallet Key Derivation\n *\n * BIP-39 mnemonic generation + BIP-44 HD key derivation for EVM and Solana.\n * Absorbed from @blockrun/clawwallet. No file I/O here - auth.ts handles persistence.\n *\n * Solana uses SLIP-10 Ed25519 derivation (Phantom/Solflare/Backpack compatible).\n * EVM uses standard BIP-32 secp256k1 derivation.\n */\n\nimport { HDKey } from \"@scure/bip32\";\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from \"@scure/bip39\";\nimport { wordlist as english } from \"@scure/bip39/wordlists/english\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha512 } from \"@noble/hashes/sha512\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst ETH_DERIVATION_PATH = \"m/44'/60'/0'/0/0\";\nconst SOLANA_HARDENED_INDICES = [44 + 0x80000000, 501 + 0x80000000, 0 + 0x80000000, 0 + 0x80000000]; // m/44'/501'/0'/0'\n\nexport interface DerivedKeys {\n mnemonic: string;\n evmPrivateKey: `0x${string}`;\n evmAddress: string;\n solanaPrivateKeyBytes: Uint8Array; // 32 bytes\n}\n\n/**\n * Generate a 24-word BIP-39 mnemonic.\n */\nexport function generateWalletMnemonic(): string {\n return generateMnemonic(english, 256);\n}\n\n/**\n * Validate a BIP-39 mnemonic.\n */\nexport function isValidMnemonic(mnemonic: string): boolean {\n return validateMnemonic(mnemonic, english);\n}\n\n/**\n * Derive EVM private key and address from a BIP-39 mnemonic.\n * Path: m/44'/60'/0'/0/0 (standard Ethereum derivation)\n */\nexport function deriveEvmKey(mnemonic: string): { privateKey: `0x${string}`; address: string } {\n const seed = mnemonicToSeedSync(mnemonic);\n const hdKey = HDKey.fromMasterSeed(seed);\n const derived = hdKey.derive(ETH_DERIVATION_PATH);\n if (!derived.privateKey) throw new Error(\"Failed to derive EVM private key\");\n const hex = `0x${Buffer.from(derived.privateKey).toString(\"hex\")}` as `0x${string}`;\n const account = privateKeyToAccount(hex);\n return { privateKey: hex, address: account.address };\n}\n\n/**\n * Derive 32-byte Solana private key using SLIP-10 Ed25519 derivation.\n * Path: m/44'/501'/0'/0' (Phantom / Solflare / Backpack compatible)\n *\n * Algorithm (SLIP-0010 for Ed25519):\n * 1. Master: HMAC-SHA512(key=\"ed25519 seed\", data=bip39_seed) → IL=key, IR=chainCode\n * 2. For each hardened child index:\n * HMAC-SHA512(key=chainCode, data=0x00 || key || ser32(index)) → split again\n * 3. Final IL (32 bytes) = Ed25519 private key seed\n */\nexport function deriveSolanaKeyBytes(mnemonic: string): Uint8Array {\n const seed = mnemonicToSeedSync(mnemonic);\n\n // Master key from SLIP-10\n let I = hmac(sha512, \"ed25519 seed\", seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n // Derive each hardened child: m/44'/501'/0'/0'\n for (const index of SOLANA_HARDENED_INDICES) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n // ser32 big-endian\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n return new Uint8Array(key);\n}\n\n/**\n * Derive both EVM and Solana keys from a single mnemonic.\n */\nexport function deriveAllKeys(mnemonic: string): DerivedKeys {\n const { privateKey: evmPrivateKey, address: evmAddress } = deriveEvmKey(mnemonic);\n const solanaPrivateKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return { mnemonic, evmPrivateKey, evmAddress, solanaPrivateKeyBytes };\n}\n\n/**\n * Get the Solana address from 32-byte private key bytes.\n * Uses @solana/kit's createKeyPairSignerFromPrivateKeyBytes (dynamic import).\n */\nexport async function getSolanaAddress(privateKeyBytes: Uint8Array): Promise {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(privateKeyBytes);\n return signer.address;\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA384 as SHA384n,\n sha384 as sha384n,\n sha512_224 as sha512_224n,\n SHA512_224 as SHA512_224n,\n sha512_256 as sha512_256n,\n SHA512_256 as SHA512_256n,\n SHA512 as SHA512n,\n sha512 as sha512n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512: typeof SHA512n = SHA512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512: typeof sha512n = sha512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA384: typeof SHA384n = SHA384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha384: typeof sha384n = sha384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_224: typeof SHA512_224n = SHA512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_224: typeof sha512_224n = sha512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_256: typeof SHA512_256n = SHA512_256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_256: typeof sha512_256n = sha512_256n;\n","/**\n * LLM-Safe Context Compression Types\n *\n * Types for the 7-layer compression system that reduces token usage\n * while preserving semantic meaning for LLM queries.\n */\n\n// Content part for multimodal messages (images, etc.)\nexport interface ContentPart {\n type: \"text\" | \"image_url\";\n text?: string;\n image_url?: {\n url: string;\n detail?: \"low\" | \"high\" | \"auto\";\n };\n}\n\n// Normalized message structure (matches OpenAI format)\n// Note: content can be an array for multimodal messages (images, etc.)\nexport interface NormalizedMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | ContentPart[] | null;\n tool_call_id?: string;\n tool_calls?: ToolCall[];\n name?: string;\n}\n\nexport interface ToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\n// Compression configuration\nexport interface CompressionConfig {\n enabled: boolean;\n preserveRaw: boolean; // Keep original for logging\n\n // Per-layer toggles\n layers: {\n deduplication: boolean;\n whitespace: boolean;\n dictionary: boolean;\n paths: boolean;\n jsonCompact: boolean;\n observation: boolean; // L6: Compress tool results (BIG WIN)\n dynamicCodebook: boolean; // L7: Build codebook from content\n };\n\n // Dictionary settings\n dictionary: {\n maxEntries: number;\n minPhraseLength: number;\n includeCodebookHeader: boolean; // Include codebook in system message\n };\n}\n\n// Compression statistics\nexport interface CompressionStats {\n duplicatesRemoved: number;\n whitespaceSavedChars: number;\n dictionarySubstitutions: number;\n pathsShortened: number;\n jsonCompactedChars: number;\n observationsCompressed: number; // L6: Tool results compressed\n observationCharsSaved: number; // L6: Chars saved from observations\n dynamicSubstitutions: number; // L7: Dynamic codebook substitutions\n dynamicCharsSaved: number; // L7: Chars saved from dynamic codebook\n}\n\n// Result from compression\nexport interface CompressionResult {\n messages: NormalizedMessage[];\n originalMessages: NormalizedMessage[]; // For logging\n\n // Token estimates\n originalChars: number;\n compressedChars: number;\n compressionRatio: number; // 0.85 = 15% reduction\n\n // Per-layer stats\n stats: CompressionStats;\n\n // Codebook used (for decompression in logs)\n codebook: Record;\n pathMap: Record;\n dynamicCodes: Record; // L7: Dynamic codebook\n}\n\n// Log data extension for compression metrics\nexport interface CompressionLogData {\n enabled: boolean;\n ratio: number;\n original_chars: number;\n compressed_chars: number;\n stats: {\n duplicates_removed: number;\n whitespace_saved: number;\n dictionary_subs: number;\n paths_shortened: number;\n json_compacted: number;\n };\n}\n\n// Default configuration - CONSERVATIVE settings for model compatibility\n// Only enable layers that don't require the model to decode anything\nexport const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {\n enabled: true,\n preserveRaw: true,\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // DISABLED: requires model to understand codebook\n paths: false, // DISABLED: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // DISABLED: may lose important context\n dynamicCodebook: false, // DISABLED: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false, // No codebook header needed\n },\n};\n","/**\n * Layer 1: Message Deduplication\n *\n * Removes exact duplicate messages from conversation history.\n * Common in heartbeat patterns and repeated tool calls.\n *\n * Safe for LLM: Identical messages add no new information.\n * Expected savings: 2-5%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport crypto from \"crypto\";\n\nexport interface DeduplicationResult {\n messages: NormalizedMessage[];\n duplicatesRemoved: number;\n originalCount: number;\n}\n\n/**\n * Generate a hash for a message based on its semantic content.\n * Uses role + content + tool_call_id to identify duplicates.\n */\nfunction hashMessage(message: NormalizedMessage): string {\n // Handle content - stringify arrays (multimodal), use string directly, or empty string\n let contentStr = \"\";\n if (typeof message.content === \"string\") {\n contentStr = message.content;\n } else if (Array.isArray(message.content)) {\n contentStr = JSON.stringify(message.content);\n }\n\n const parts = [message.role, contentStr, message.tool_call_id || \"\", message.name || \"\"];\n\n // Include tool_calls if present\n if (message.tool_calls) {\n parts.push(\n JSON.stringify(\n message.tool_calls.map((tc) => ({\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n ),\n );\n }\n\n const content = parts.join(\"|\");\n return crypto.createHash(\"md5\").update(content).digest(\"hex\");\n}\n\n/**\n * Remove exact duplicate messages from the conversation.\n *\n * Strategy:\n * - Keep first occurrence of each unique message\n * - Preserve order for semantic coherence\n * - Never dedupe system messages (they set context)\n * - Allow duplicate user messages (user might repeat intentionally)\n * - CRITICAL: Never dedupe assistant messages with tool_calls that are\n * referenced by subsequent tool messages (breaks Anthropic tool_use/tool_result pairing)\n */\nexport function deduplicateMessages(messages: NormalizedMessage[]): DeduplicationResult {\n const seen = new Set();\n const result: NormalizedMessage[] = [];\n let duplicatesRemoved = 0;\n\n // First pass: collect all tool_call_ids that are referenced by tool messages\n // These tool_calls MUST be preserved to maintain tool_use/tool_result pairing\n const referencedToolCallIds = new Set();\n for (const message of messages) {\n if (message.role === \"tool\" && message.tool_call_id) {\n referencedToolCallIds.add(message.tool_call_id);\n }\n }\n\n for (const message of messages) {\n // Always keep system messages (they set important context)\n if (message.role === \"system\") {\n result.push(message);\n continue;\n }\n\n // Always keep user messages (user might repeat intentionally)\n if (message.role === \"user\") {\n result.push(message);\n continue;\n }\n\n // Always keep tool messages (they are results of tool calls)\n // Removing them would break the tool_use/tool_result pairing\n if (message.role === \"tool\") {\n result.push(message);\n continue;\n }\n\n // For assistant messages with tool_calls, check if any are referenced\n // by subsequent tool messages - if so, we MUST keep this message\n if (message.role === \"assistant\" && message.tool_calls) {\n const hasReferencedToolCall = message.tool_calls.some((tc) =>\n referencedToolCallIds.has(tc.id),\n );\n if (hasReferencedToolCall) {\n // This assistant message has tool_calls that are referenced - keep it\n result.push(message);\n continue;\n }\n }\n\n // For other assistant messages, check for duplicates\n const hash = hashMessage(message);\n\n if (!seen.has(hash)) {\n seen.add(hash);\n result.push(message);\n } else {\n duplicatesRemoved++;\n }\n }\n\n return {\n messages: result,\n duplicatesRemoved,\n originalCount: messages.length,\n };\n}\n","/**\n * Layer 2: Whitespace Normalization\n *\n * Reduces excessive whitespace without changing semantic meaning.\n *\n * Safe for LLM: Tokenizers normalize whitespace anyway.\n * Expected savings: 3-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface WhitespaceResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Normalize whitespace in a string.\n *\n * - Max 2 consecutive newlines\n * - Remove trailing whitespace from lines\n * - Normalize tabs to spaces\n * - Trim start/end\n */\nexport function normalizeWhitespace(content: string): string {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") return content as string;\n\n return (\n content\n // Normalize line endings\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n // Max 2 consecutive newlines (preserve paragraph breaks)\n .replace(/\\n{3,}/g, \"\\n\\n\")\n // Remove trailing whitespace from each line\n .replace(/[ \\t]+$/gm, \"\")\n // Normalize multiple spaces to single (except at line start for indentation)\n .replace(/([^\\n]) {2,}/g, \"$1 \")\n // Reduce excessive indentation (more than 8 spaces → 2 spaces per level)\n .replace(/^[ ]{8,}/gm, (match) => \" \".repeat(Math.ceil(match.length / 4)))\n // Normalize tabs to 2 spaces\n .replace(/\\t/g, \" \")\n // Trim\n .trim()\n );\n}\n\n/**\n * Apply whitespace normalization to all messages.\n */\nexport function normalizeMessagesWhitespace(messages: NormalizedMessage[]): WhitespaceResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const originalLength = message.content.length;\n const normalizedContent = normalizeWhitespace(message.content);\n charsSaved += originalLength - normalizedContent.length;\n\n return {\n ...message,\n content: normalizedContent,\n };\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * Dictionary Codebook\n *\n * Static dictionary of frequently repeated phrases observed in LLM prompts.\n * Built from analysis of BlockRun production logs.\n *\n * Format: Short code ($XX) -> Long phrase\n * The LLM receives a codebook header and decodes in-context.\n */\n\n// Static codebook - common patterns from system prompts\n// Ordered by expected frequency and impact\nexport const STATIC_CODEBOOK: Record = {\n // High-impact: OpenClaw/Agent system prompt patterns (very common)\n $OC01: \"unbrowse_\", // Common prefix in tool names\n $OC02: \"\",\n $OC03: \"\",\n $OC04: \"\",\n $OC05: \"\",\n $OC06: \"\",\n $OC07: \"\",\n $OC08: \"(may need login)\",\n $OC09: \"API skill for OpenClaw\",\n $OC10: \"endpoints\",\n\n // Skill/tool markers\n $SK01: \"\",\n $SK02: \"\",\n $SK03: \"\",\n $SK04: \"\",\n\n // Schema patterns (very common in tool definitions)\n $T01: 'type: \"function\"',\n $T02: '\"type\": \"function\"',\n $T03: '\"type\": \"string\"',\n $T04: '\"type\": \"object\"',\n $T05: '\"type\": \"array\"',\n $T06: '\"type\": \"boolean\"',\n $T07: '\"type\": \"number\"',\n\n // Common descriptions\n $D01: \"description:\",\n $D02: '\"description\":',\n\n // Common instructions\n $I01: \"You are a personal assistant\",\n $I02: \"Tool names are case-sensitive\",\n $I03: \"Call tools exactly as listed\",\n $I04: \"Use when\",\n $I05: \"without asking\",\n\n // Safety phrases\n $S01: \"Do not manipulate or persuade\",\n $S02: \"Prioritize safety and human oversight\",\n $S03: \"unless explicitly requested\",\n\n // JSON patterns\n $J01: '\"required\": [\"',\n $J02: '\"properties\": {',\n $J03: '\"additionalProperties\": false',\n\n // Heartbeat patterns\n $H01: \"HEARTBEAT_OK\",\n $H02: \"Read HEARTBEAT.md if it exists\",\n\n // Role markers\n $R01: '\"role\": \"system\"',\n $R02: '\"role\": \"user\"',\n $R03: '\"role\": \"assistant\"',\n $R04: '\"role\": \"tool\"',\n\n // Common endings/phrases\n $E01: \"would you like to\",\n $E02: \"Let me know if you\",\n $E03: \"internal APIs\",\n $E04: \"session cookies\",\n\n // BlockRun model aliases (common in prompts)\n $M01: \"blockrun/\",\n $M02: \"openai/\",\n $M03: \"anthropic/\",\n $M04: \"google/\",\n $M05: \"xai/\",\n};\n\n/**\n * Get the inverse codebook for decompression.\n */\nexport function getInverseCodebook(): Record {\n const inverse: Record = {};\n for (const [code, phrase] of Object.entries(STATIC_CODEBOOK)) {\n inverse[phrase] = code;\n }\n return inverse;\n}\n\n/**\n * Generate the codebook header for inclusion in system message.\n * LLMs can decode in-context using this header.\n */\nexport function generateCodebookHeader(\n usedCodes: Set,\n pathMap: Record = {},\n): string {\n if (usedCodes.size === 0 && Object.keys(pathMap).length === 0) {\n return \"\";\n }\n\n const parts: string[] = [];\n\n // Add used dictionary codes\n if (usedCodes.size > 0) {\n const codeEntries = Array.from(usedCodes)\n .map((code) => `${code}=${STATIC_CODEBOOK[code]}`)\n .join(\", \");\n parts.push(`[Dict: ${codeEntries}]`);\n }\n\n // Add path map\n if (Object.keys(pathMap).length > 0) {\n const pathEntries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n parts.push(`[Paths: ${pathEntries}]`);\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Decompress a string using the codebook (for logging).\n */\nexport function decompressContent(\n content: string,\n codebook: Record = STATIC_CODEBOOK,\n): string {\n let result = content;\n for (const [code, phrase] of Object.entries(codebook)) {\n result = result.split(code).join(phrase);\n }\n return result;\n}\n","/**\n * Layer 3: Dictionary Encoding\n *\n * Replaces frequently repeated long phrases with short codes.\n * Uses a static codebook of common patterns from production logs.\n *\n * Safe for LLM: Reversible substitution with codebook header.\n * Expected savings: 4-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport { getInverseCodebook } from \"../codebook\";\n\nexport interface DictionaryResult {\n messages: NormalizedMessage[];\n substitutionCount: number;\n usedCodes: Set;\n charsSaved: number;\n}\n\n/**\n * Apply dictionary encoding to a string.\n * Returns the encoded string and stats.\n */\nfunction encodeContent(\n content: string,\n inverseCodebook: Record,\n): { encoded: string; substitutions: number; codes: Set; charsSaved: number } {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") {\n return { encoded: content, substitutions: 0, codes: new Set(), charsSaved: 0 };\n }\n let encoded = content;\n let substitutions = 0;\n let charsSaved = 0;\n const codes = new Set();\n\n // Sort phrases by length (longest first) to avoid partial matches\n const phrases = Object.keys(inverseCodebook).sort((a, b) => b.length - a.length);\n\n for (const phrase of phrases) {\n const code = inverseCodebook[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = encoded.match(regex);\n\n if (matches && matches.length > 0) {\n encoded = encoded.replace(regex, code);\n substitutions += matches.length;\n charsSaved += matches.length * (phrase.length - code.length);\n codes.add(code);\n }\n }\n\n return { encoded, substitutions, codes, charsSaved };\n}\n\n/**\n * Escape special regex characters in a string.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dictionary encoding to all messages.\n */\nexport function encodeMessages(messages: NormalizedMessage[]): DictionaryResult {\n const inverseCodebook = getInverseCodebook();\n let totalSubstitutions = 0;\n let totalCharsSaved = 0;\n const allUsedCodes = new Set();\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const { encoded, substitutions, codes, charsSaved } = encodeContent(\n message.content,\n inverseCodebook,\n );\n\n totalSubstitutions += substitutions;\n totalCharsSaved += charsSaved;\n codes.forEach((code) => allUsedCodes.add(code));\n\n return {\n ...message,\n content: encoded,\n };\n });\n\n return {\n messages: result,\n substitutionCount: totalSubstitutions,\n usedCodes: allUsedCodes,\n charsSaved: totalCharsSaved,\n };\n}\n","/**\n * Layer 4: Path Shortening\n *\n * Detects common filesystem path prefixes and replaces them with short codes.\n * Common in coding assistant contexts with repeated file paths.\n *\n * Safe for LLM: Lossless abbreviation with path map header.\n * Expected savings: 1-3%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface PathShorteningResult {\n messages: NormalizedMessage[];\n pathMap: Record; // $P1 -> /home/user/project/\n charsSaved: number;\n}\n\n// Regex to match filesystem paths\nconst PATH_REGEX = /(?:\\/[\\w.-]+){3,}/g;\n\n/**\n * Extract all paths from messages and find common prefixes.\n */\nfunction extractPaths(messages: NormalizedMessage[]): string[] {\n const paths: string[] = [];\n\n for (const message of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") continue;\n const matches = message.content.match(PATH_REGEX);\n if (matches) {\n paths.push(...matches);\n }\n }\n\n return paths;\n}\n\n/**\n * Group paths by their common prefixes.\n * Returns prefixes that appear at least 3 times.\n */\nfunction findFrequentPrefixes(paths: string[]): string[] {\n const prefixCounts = new Map();\n\n for (const path of paths) {\n const parts = path.split(\"/\").filter(Boolean);\n\n // Try prefixes of different lengths\n for (let i = 2; i < parts.length; i++) {\n const prefix = \"/\" + parts.slice(0, i).join(\"/\") + \"/\";\n prefixCounts.set(prefix, (prefixCounts.get(prefix) || 0) + 1);\n }\n }\n\n // Return prefixes that appear 3+ times, sorted by length (longest first)\n return Array.from(prefixCounts.entries())\n .filter(([, count]) => count >= 3)\n .sort((a, b) => b[0].length - a[0].length)\n .slice(0, 5) // Max 5 path codes\n .map(([prefix]) => prefix);\n}\n\n/**\n * Apply path shortening to all messages.\n */\nexport function shortenPaths(messages: NormalizedMessage[]): PathShorteningResult {\n const allPaths = extractPaths(messages);\n\n if (allPaths.length < 5) {\n // Not enough paths to benefit from shortening\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n const prefixes = findFrequentPrefixes(allPaths);\n\n if (prefixes.length === 0) {\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n // Create path map\n const pathMap: Record = {};\n prefixes.forEach((prefix, i) => {\n pathMap[`$P${i + 1}`] = prefix;\n });\n\n // Replace paths in messages\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n let content = message.content;\n const originalLength = content.length;\n\n // Replace prefixes (longest first to avoid partial replacements)\n for (const [code, prefix] of Object.entries(pathMap)) {\n content = content.split(prefix).join(code + \"/\");\n }\n\n charsSaved += originalLength - content.length;\n\n return {\n ...message,\n content,\n };\n });\n\n return {\n messages: result,\n pathMap,\n charsSaved,\n };\n}\n\n/**\n * Generate the path map header for the codebook.\n */\nexport function generatePathMapHeader(pathMap: Record): string {\n if (Object.keys(pathMap).length === 0) return \"\";\n\n const entries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n\n return `[Paths: ${entries}]`;\n}\n","/**\n * Layer 5: JSON Compaction\n *\n * Minifies JSON in tool_call arguments and tool results.\n * Removes pretty-print whitespace from JSON strings.\n *\n * Safe for LLM: JSON semantics unchanged.\n * Expected savings: 2-4%\n */\n\nimport { NormalizedMessage, ToolCall } from \"../types\";\n\nexport interface JsonCompactResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Compact a JSON string by parsing and re-stringifying without formatting.\n */\nfunction compactJson(jsonString: string): string {\n try {\n const parsed = JSON.parse(jsonString);\n return JSON.stringify(parsed);\n } catch {\n // Not valid JSON, return as-is\n return jsonString;\n }\n}\n\n/**\n * Check if a string looks like JSON (starts with { or [).\n */\nfunction looksLikeJson(str: string): boolean {\n const trimmed = str.trim();\n return (\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) ||\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\"))\n );\n}\n\n/**\n * Compact tool_call arguments in a message.\n */\nfunction compactToolCalls(toolCalls: ToolCall[]): ToolCall[] {\n return toolCalls.map((tc) => ({\n ...tc,\n function: {\n ...tc.function,\n arguments: compactJson(tc.function.arguments),\n },\n }));\n}\n\n/**\n * Apply JSON compaction to all messages.\n *\n * Targets:\n * - tool_call arguments (in assistant messages)\n * - tool message content (often JSON)\n */\nexport function compactMessagesJson(messages: NormalizedMessage[]): JsonCompactResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n const newMessage = { ...message };\n\n // Compact tool_calls arguments\n if (message.tool_calls && message.tool_calls.length > 0) {\n const originalLength = JSON.stringify(message.tool_calls).length;\n newMessage.tool_calls = compactToolCalls(message.tool_calls);\n const newLength = JSON.stringify(newMessage.tool_calls).length;\n charsSaved += originalLength - newLength;\n }\n\n // Compact tool message content if it looks like JSON\n // Only process string content (skip arrays for multimodal messages)\n if (\n message.role === \"tool\" &&\n message.content &&\n typeof message.content === \"string\" &&\n looksLikeJson(message.content)\n ) {\n const originalLength = message.content.length;\n const compacted = compactJson(message.content);\n charsSaved += originalLength - compacted.length;\n newMessage.content = compacted;\n }\n\n return newMessage;\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * L6: Observation Compression (AGGRESSIVE)\n *\n * Inspired by claw-compactor's 97% compression on tool results.\n * Tool call results (especially large ones) are summarized to key info only.\n *\n * This is the biggest compression win - tool outputs can be 10KB+ but\n * only ~200 chars of actual useful information.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface ObservationResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n observationsCompressed: number;\n}\n\n// Max length for tool results before compression kicks in\nconst TOOL_RESULT_THRESHOLD = 500;\n\n// Max length to compress tool results down to\nconst COMPRESSED_RESULT_MAX = 300;\n\n/**\n * Extract key information from tool result.\n * Keeps: errors, key values, status, first/last important lines.\n */\nfunction compressToolResult(content: string): string {\n if (!content || content.length <= TOOL_RESULT_THRESHOLD) {\n return content;\n }\n\n const lines = content\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter(Boolean);\n\n // Priority 1: Error messages (always keep)\n const errorLines = lines.filter(\n (l) => /error|exception|failed|denied|refused|timeout|invalid/i.test(l) && l.length < 200,\n );\n\n // Priority 2: Status/result lines\n const statusLines = lines.filter(\n (l) =>\n /success|complete|created|updated|found|result|status|total|count/i.test(l) && l.length < 150,\n );\n\n // Priority 3: Key JSON fields (extract important values)\n const jsonMatches: string[] = [];\n const jsonPattern = /\"(id|name|status|error|message|count|total|url|path)\":\\s*\"?([^\",}\\n]+)\"?/gi;\n let match;\n while ((match = jsonPattern.exec(content)) !== null) {\n jsonMatches.push(`${match[1]}: ${match[2].slice(0, 50)}`);\n }\n\n // Priority 4: First and last meaningful lines\n const firstLine = lines[0]?.slice(0, 100);\n const lastLine = lines.length > 1 ? lines[lines.length - 1]?.slice(0, 100) : \"\";\n\n // Build compressed observation\n const parts: string[] = [];\n\n if (errorLines.length > 0) {\n parts.push(\"[ERR] \" + errorLines.slice(0, 3).join(\" | \"));\n }\n\n if (statusLines.length > 0) {\n parts.push(statusLines.slice(0, 3).join(\" | \"));\n }\n\n if (jsonMatches.length > 0) {\n parts.push(jsonMatches.slice(0, 5).join(\", \"));\n }\n\n if (parts.length === 0) {\n // Fallback: keep first/last lines with truncation marker\n parts.push(firstLine || \"\");\n if (lines.length > 2) {\n parts.push(`[...${lines.length - 2} lines...]`);\n }\n if (lastLine && lastLine !== firstLine) {\n parts.push(lastLine);\n }\n }\n\n let result = parts.join(\"\\n\");\n\n // Final length cap\n if (result.length > COMPRESSED_RESULT_MAX) {\n result = result.slice(0, COMPRESSED_RESULT_MAX - 20) + \"\\n[...truncated]\";\n }\n\n return result;\n}\n\n/**\n * Compress large repeated content blocks.\n * Detects when same large block appears multiple times.\n */\nfunction deduplicateLargeBlocks(messages: NormalizedMessage[]): {\n messages: NormalizedMessage[];\n charsSaved: number;\n} {\n const blockHashes = new Map(); // hash -> first occurrence index\n let charsSaved = 0;\n\n const result = messages.map((msg, idx) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\" || msg.content.length < 500) {\n return msg;\n }\n\n // Hash first 200 chars as block identifier\n const blockKey = msg.content.slice(0, 200);\n\n if (blockHashes.has(blockKey)) {\n const firstIdx = blockHashes.get(blockKey)!;\n const original = msg.content;\n const compressed = `[See message #${firstIdx + 1} - same content]`;\n charsSaved += original.length - compressed.length;\n return { ...msg, content: compressed };\n }\n\n blockHashes.set(blockKey, idx);\n return msg;\n });\n\n return { messages: result, charsSaved };\n}\n\n/**\n * Compress tool results in messages.\n */\nexport function compressObservations(messages: NormalizedMessage[]): ObservationResult {\n let charsSaved = 0;\n let observationsCompressed = 0;\n\n // First pass: compress individual tool results\n let result = messages.map((msg) => {\n // Only compress tool role messages (these are tool call results)\n // Only process string content (skip arrays for multimodal messages)\n if (msg.role !== \"tool\" || !msg.content || typeof msg.content !== \"string\") {\n return msg;\n }\n\n const original = msg.content;\n if (original.length <= TOOL_RESULT_THRESHOLD) {\n return msg;\n }\n\n const compressed = compressToolResult(original);\n const saved = original.length - compressed.length;\n\n if (saved > 50) {\n charsSaved += saved;\n observationsCompressed++;\n return { ...msg, content: compressed };\n }\n\n return msg;\n });\n\n // Second pass: deduplicate large repeated blocks\n const dedupResult = deduplicateLargeBlocks(result);\n result = dedupResult.messages;\n charsSaved += dedupResult.charsSaved;\n\n return {\n messages: result,\n charsSaved,\n observationsCompressed,\n };\n}\n","/**\n * L7: Dynamic Codebook Builder\n *\n * Inspired by claw-compactor's frequency-based codebook.\n * Builds codebook from actual content being compressed,\n * rather than relying on static patterns.\n *\n * Finds phrases that appear 3+ times and replaces with short codes.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface DynamicCodebookResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n dynamicCodes: Record; // code -> phrase\n substitutions: number;\n}\n\n// Config\nconst MIN_PHRASE_LENGTH = 20;\nconst MAX_PHRASE_LENGTH = 200;\nconst MIN_FREQUENCY = 3;\nconst MAX_ENTRIES = 100;\nconst CODE_PREFIX = \"$D\"; // Dynamic codes: $D01, $D02, etc.\n\n/**\n * Find repeated phrases in content.\n */\nfunction findRepeatedPhrases(allContent: string): Map {\n const phrases = new Map();\n\n // Split by sentence-like boundaries\n const segments = allContent.split(/(?<=[.!?\\n])\\s+/);\n\n for (const segment of segments) {\n const trimmed = segment.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n // Also find repeated lines\n const lines = allContent.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n return phrases;\n}\n\n/**\n * Build dynamic codebook from message content.\n */\nfunction buildDynamicCodebook(messages: NormalizedMessage[]): Record {\n // Combine all content\n let allContent = \"\";\n for (const msg of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (msg.content && typeof msg.content === \"string\") {\n allContent += msg.content + \"\\n\";\n }\n }\n\n // Find repeated phrases\n const phrases = findRepeatedPhrases(allContent);\n\n // Filter by frequency and sort by savings potential\n const candidates: Array<{ phrase: string; count: number; savings: number }> = [];\n for (const [phrase, count] of phrases.entries()) {\n if (count >= MIN_FREQUENCY) {\n // Savings = (phrase length - code length) * occurrences\n const codeLength = 4; // e.g., \"$D01\"\n const savings = (phrase.length - codeLength) * count;\n if (savings > 50) {\n candidates.push({ phrase, count, savings });\n }\n }\n }\n\n // Sort by savings (descending) and take top entries\n candidates.sort((a, b) => b.savings - a.savings);\n const topCandidates = candidates.slice(0, MAX_ENTRIES);\n\n // Build codebook\n const codebook: Record = {};\n topCandidates.forEach((c, i) => {\n const code = `${CODE_PREFIX}${String(i + 1).padStart(2, \"0\")}`;\n codebook[code] = c.phrase;\n });\n\n return codebook;\n}\n\n/**\n * Escape special regex characters.\n */\nfunction escapeRegex(str: string): string {\n // Defensive type check\n if (!str || typeof str !== \"string\") return \"\";\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dynamic codebook to messages.\n */\nexport function applyDynamicCodebook(messages: NormalizedMessage[]): DynamicCodebookResult {\n // Build codebook from content\n const codebook = buildDynamicCodebook(messages);\n\n if (Object.keys(codebook).length === 0) {\n return {\n messages,\n charsSaved: 0,\n dynamicCodes: {},\n substitutions: 0,\n };\n }\n\n // Create inverse map for replacement\n const phraseToCode: Record = {};\n for (const [code, phrase] of Object.entries(codebook)) {\n phraseToCode[phrase] = code;\n }\n\n // Sort phrases by length (longest first) to avoid partial replacements\n const sortedPhrases = Object.keys(phraseToCode).sort((a, b) => b.length - a.length);\n\n let charsSaved = 0;\n let substitutions = 0;\n\n // Apply replacements\n const result = messages.map((msg) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n for (const phrase of sortedPhrases) {\n const code = phraseToCode[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = content.match(regex);\n if (matches) {\n content = content.replace(regex, code);\n charsSaved += (phrase.length - code.length) * matches.length;\n substitutions += matches.length;\n }\n }\n\n return { ...msg, content };\n });\n\n return {\n messages: result,\n charsSaved,\n dynamicCodes: codebook,\n substitutions,\n };\n}\n\n/**\n * Generate header for dynamic codes (to include in system message).\n */\nexport function generateDynamicCodebookHeader(codebook: Record): string {\n if (Object.keys(codebook).length === 0) return \"\";\n\n const entries = Object.entries(codebook)\n .slice(0, 20) // Limit header size\n .map(([code, phrase]) => {\n // Truncate long phrases in header\n const displayPhrase = phrase.length > 40 ? phrase.slice(0, 37) + \"...\" : phrase;\n return `${code}=${displayPhrase}`;\n })\n .join(\", \");\n\n return `[DynDict: ${entries}]`;\n}\n","/**\n * LLM-Safe Context Compression\n *\n * Reduces token usage by 15-40% while preserving semantic meaning.\n * Implements 7 compression layers inspired by claw-compactor.\n *\n * Usage:\n * const result = await compressContext(messages);\n * // result.messages -> compressed version to send to provider\n * // result.originalMessages -> original for logging\n */\n\nimport {\n NormalizedMessage,\n CompressionConfig,\n CompressionResult,\n CompressionStats,\n DEFAULT_COMPRESSION_CONFIG,\n} from \"./types\";\nimport { deduplicateMessages } from \"./layers/deduplication\";\nimport { normalizeMessagesWhitespace } from \"./layers/whitespace\";\nimport { encodeMessages } from \"./layers/dictionary\";\nimport { shortenPaths } from \"./layers/paths\";\nimport { compactMessagesJson } from \"./layers/json-compact\";\nimport { compressObservations } from \"./layers/observation\";\nimport { applyDynamicCodebook, generateDynamicCodebookHeader } from \"./layers/dynamic-codebook\";\nimport { generateCodebookHeader, STATIC_CODEBOOK } from \"./codebook\";\n\nexport * from \"./types\";\nexport { STATIC_CODEBOOK } from \"./codebook\";\n\n/**\n * Calculate total character count for messages.\n */\nfunction calculateTotalChars(messages: NormalizedMessage[]): number {\n return messages.reduce((total, msg) => {\n let chars = 0;\n if (typeof msg.content === \"string\") {\n chars = msg.content.length;\n } else if (Array.isArray(msg.content)) {\n // For multimodal content, stringify to get approximate size\n chars = JSON.stringify(msg.content).length;\n }\n if (msg.tool_calls) {\n chars += JSON.stringify(msg.tool_calls).length;\n }\n return total + chars;\n }, 0);\n}\n\n/**\n * Deep clone messages to preserve originals.\n */\nfunction cloneMessages(messages: NormalizedMessage[]): NormalizedMessage[] {\n return JSON.parse(JSON.stringify(messages));\n}\n\n/**\n * Prepend codebook header to the first USER message (not system).\n *\n * Why not system message?\n * - Google Gemini uses systemInstruction which doesn't support codebook format\n * - The codebook header in user message is still visible to all LLMs\n * - This ensures compatibility across all providers\n */\nfunction prependCodebookHeader(\n messages: NormalizedMessage[],\n usedCodes: Set,\n pathMap: Record,\n): NormalizedMessage[] {\n const header = generateCodebookHeader(usedCodes, pathMap);\n if (!header) return messages;\n\n // Find first user message (not system - Google's systemInstruction doesn't support codebook)\n const userIndex = messages.findIndex((m) => m.role === \"user\");\n\n if (userIndex === -1) {\n // No user message, add codebook as system (fallback)\n return [{ role: \"system\", content: header }, ...messages];\n }\n\n // Prepend to first user message (only if content is a string)\n return messages.map((msg, i) => {\n if (i === userIndex) {\n // Only prepend to string content - skip arrays (multimodal messages)\n if (typeof msg.content === \"string\") {\n return {\n ...msg,\n content: `${header}\\n\\n${msg.content}`,\n };\n }\n // For non-string content, don't modify the message\n // The codebook header would corrupt array content\n }\n return msg;\n });\n}\n\n/**\n * Main compression function.\n *\n * Applies 5 layers in sequence:\n * 1. Deduplication - Remove exact duplicate messages\n * 2. Whitespace - Normalize excessive whitespace\n * 3. Dictionary - Replace common phrases with codes\n * 4. Paths - Shorten repeated file paths\n * 5. JSON - Compact JSON in tool calls\n *\n * Then prepends a codebook header for the LLM to decode in-context.\n */\nexport async function compressContext(\n messages: NormalizedMessage[],\n config: Partial = {},\n): Promise {\n const fullConfig: CompressionConfig = {\n ...DEFAULT_COMPRESSION_CONFIG,\n ...config,\n layers: {\n ...DEFAULT_COMPRESSION_CONFIG.layers,\n ...config.layers,\n },\n dictionary: {\n ...DEFAULT_COMPRESSION_CONFIG.dictionary,\n ...config.dictionary,\n },\n };\n\n // If compression disabled, return as-is\n if (!fullConfig.enabled) {\n const originalChars = calculateTotalChars(messages);\n return {\n messages,\n originalMessages: messages,\n originalChars,\n compressedChars: originalChars,\n compressionRatio: 1,\n stats: {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n },\n codebook: {},\n pathMap: {},\n dynamicCodes: {},\n };\n }\n\n // Preserve originals for logging\n const originalMessages = fullConfig.preserveRaw ? cloneMessages(messages) : messages;\n const originalChars = calculateTotalChars(messages);\n\n // Initialize stats\n const stats: CompressionStats = {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n };\n\n let result = cloneMessages(messages);\n let usedCodes = new Set();\n let pathMap: Record = {};\n let dynamicCodes: Record = {};\n\n // Layer 1: Deduplication\n if (fullConfig.layers.deduplication) {\n const dedupResult = deduplicateMessages(result);\n result = dedupResult.messages;\n stats.duplicatesRemoved = dedupResult.duplicatesRemoved;\n }\n\n // Layer 2: Whitespace normalization\n if (fullConfig.layers.whitespace) {\n const wsResult = normalizeMessagesWhitespace(result);\n result = wsResult.messages;\n stats.whitespaceSavedChars = wsResult.charsSaved;\n }\n\n // Layer 3: Dictionary encoding\n if (fullConfig.layers.dictionary) {\n const dictResult = encodeMessages(result);\n result = dictResult.messages;\n stats.dictionarySubstitutions = dictResult.substitutionCount;\n usedCodes = dictResult.usedCodes;\n }\n\n // Layer 4: Path shortening\n if (fullConfig.layers.paths) {\n const pathResult = shortenPaths(result);\n result = pathResult.messages;\n pathMap = pathResult.pathMap;\n stats.pathsShortened = Object.keys(pathMap).length;\n }\n\n // Layer 5: JSON compaction\n if (fullConfig.layers.jsonCompact) {\n const jsonResult = compactMessagesJson(result);\n result = jsonResult.messages;\n stats.jsonCompactedChars = jsonResult.charsSaved;\n }\n\n // Layer 6: Observation compression (BIG WIN - 97% on tool results)\n if (fullConfig.layers.observation) {\n const obsResult = compressObservations(result);\n result = obsResult.messages;\n stats.observationsCompressed = obsResult.observationsCompressed;\n stats.observationCharsSaved = obsResult.charsSaved;\n }\n\n // Layer 7: Dynamic codebook (learns from actual content)\n if (fullConfig.layers.dynamicCodebook) {\n const dynResult = applyDynamicCodebook(result);\n result = dynResult.messages;\n stats.dynamicSubstitutions = dynResult.substitutions;\n stats.dynamicCharsSaved = dynResult.charsSaved;\n dynamicCodes = dynResult.dynamicCodes;\n }\n\n // Add codebook header if enabled and we have codes to include\n if (\n fullConfig.dictionary.includeCodebookHeader &&\n (usedCodes.size > 0 || Object.keys(pathMap).length > 0 || Object.keys(dynamicCodes).length > 0)\n ) {\n result = prependCodebookHeader(result, usedCodes, pathMap);\n // Also add dynamic codebook header if we have dynamic codes\n if (Object.keys(dynamicCodes).length > 0) {\n const dynHeader = generateDynamicCodebookHeader(dynamicCodes);\n if (dynHeader) {\n const systemIndex = result.findIndex((m) => m.role === \"system\");\n // Only prepend to string content - skip arrays (multimodal messages)\n if (systemIndex >= 0 && typeof result[systemIndex].content === \"string\") {\n result[systemIndex] = {\n ...result[systemIndex],\n content: `${dynHeader}\\n${result[systemIndex].content}`,\n };\n }\n }\n }\n }\n\n // Calculate final stats\n const compressedChars = calculateTotalChars(result);\n const compressionRatio = compressedChars / originalChars;\n\n // Build used codebook for logging\n const usedCodebook: Record = {};\n usedCodes.forEach((code) => {\n usedCodebook[code] = STATIC_CODEBOOK[code];\n });\n\n return {\n messages: result,\n originalMessages,\n originalChars,\n compressedChars,\n compressionRatio,\n stats,\n codebook: usedCodebook,\n pathMap,\n dynamicCodes,\n };\n}\n\n/**\n * Quick check if compression would benefit these messages.\n * Returns true if messages are large enough to warrant compression.\n */\nexport function shouldCompress(messages: NormalizedMessage[]): boolean {\n const chars = calculateTotalChars(messages);\n // Only compress if > 5000 chars (roughly 1000 tokens)\n return chars > 5000;\n}\n","/**\n * Session Persistence Store\n *\n * Tracks model selections per session to prevent model switching mid-task.\n * When a session is active, the router will continue using the same model\n * instead of re-routing each request.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type SessionEntry = {\n model: string;\n tier: string;\n createdAt: number;\n lastUsedAt: number;\n requestCount: number;\n // --- Three-strike escalation ---\n recentHashes: string[]; // Sliding window of last 3 request content fingerprints\n strikes: number; // Consecutive similar request count\n escalated: boolean; // Whether session was already escalated via three-strike\n // --- Cost accumulation for maxCostPerRun ---\n sessionCostMicros: bigint; // Total estimated cost for this session run (USDC 6-decimal)\n};\n\nexport type SessionConfig = {\n /** Enable session persistence (default: false) */\n enabled: boolean;\n /** Session timeout in ms (default: 30 minutes) */\n timeoutMs: number;\n /** Header name for session ID (default: X-Session-ID) */\n headerName: string;\n};\n\nexport const DEFAULT_SESSION_CONFIG: SessionConfig = {\n enabled: true,\n timeoutMs: 30 * 60 * 1000, // 30 minutes\n headerName: \"x-session-id\",\n};\n\n/**\n * Session persistence store for maintaining model selections.\n */\nexport class SessionStore {\n private sessions: Map = new Map();\n private config: SessionConfig;\n private cleanupInterval: ReturnType | null = null;\n\n constructor(config: Partial = {}) {\n this.config = { ...DEFAULT_SESSION_CONFIG, ...config };\n\n // Start cleanup interval (every 5 minutes)\n if (this.config.enabled) {\n this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1000);\n }\n }\n\n /**\n * Get the pinned model for a session, if any.\n */\n getSession(sessionId: string): SessionEntry | undefined {\n if (!this.config.enabled || !sessionId) {\n return undefined;\n }\n\n const entry = this.sessions.get(sessionId);\n if (!entry) {\n return undefined;\n }\n\n // Check if session has expired\n const now = Date.now();\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(sessionId);\n return undefined;\n }\n\n return entry;\n }\n\n /**\n * Pin a model to a session.\n */\n setSession(sessionId: string, model: string, tier: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const existing = this.sessions.get(sessionId);\n const now = Date.now();\n\n if (existing) {\n existing.lastUsedAt = now;\n existing.requestCount++;\n // Update model if different (e.g., fallback)\n if (existing.model !== model) {\n existing.model = model;\n existing.tier = tier;\n }\n } else {\n this.sessions.set(sessionId, {\n model,\n tier,\n createdAt: now,\n lastUsedAt: now,\n requestCount: 1,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n });\n }\n }\n\n /**\n * Touch a session to extend its timeout.\n */\n touchSession(sessionId: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const entry = this.sessions.get(sessionId);\n if (entry) {\n entry.lastUsedAt = Date.now();\n entry.requestCount++;\n }\n }\n\n /**\n * Clear a specific session.\n */\n clearSession(sessionId: string): void {\n this.sessions.delete(sessionId);\n }\n\n /**\n * Clear all sessions.\n */\n clearAll(): void {\n this.sessions.clear();\n }\n\n /**\n * Get session stats for debugging.\n */\n getStats(): { count: number; sessions: Array<{ id: string; model: string; age: number }> } {\n const now = Date.now();\n const sessions = Array.from(this.sessions.entries()).map(([id, entry]) => ({\n id: id.slice(0, 8) + \"...\",\n model: entry.model,\n age: Math.round((now - entry.createdAt) / 1000),\n }));\n return { count: this.sessions.size, sessions };\n }\n\n /**\n * Clean up expired sessions.\n */\n private cleanup(): void {\n const now = Date.now();\n for (const [id, entry] of this.sessions) {\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(id);\n }\n }\n }\n\n /**\n * Record a request content hash and detect repetitive patterns.\n * Returns true if escalation should be triggered (3+ consecutive similar requests).\n */\n recordRequestHash(sessionId: string, hash: string): boolean {\n const entry = this.sessions.get(sessionId);\n if (!entry) return false;\n\n const prev = entry.recentHashes;\n if (prev.length > 0 && prev[prev.length - 1] === hash) {\n entry.strikes++;\n } else {\n entry.strikes = 0;\n }\n\n entry.recentHashes.push(hash);\n if (entry.recentHashes.length > 3) {\n entry.recentHashes.shift();\n }\n\n return entry.strikes >= 2 && !entry.escalated;\n }\n\n /**\n * Escalate session to next tier. Returns the new model/tier or null if already at max.\n */\n escalateSession(\n sessionId: string,\n tierConfigs: Record,\n ): { model: string; tier: string } | null {\n const entry = this.sessions.get(sessionId);\n if (!entry) return null;\n\n const TIER_ORDER = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\"];\n const currentIdx = TIER_ORDER.indexOf(entry.tier);\n if (currentIdx < 0 || currentIdx >= TIER_ORDER.length - 1) return null;\n\n const nextTier = TIER_ORDER[currentIdx + 1];\n const nextConfig = tierConfigs[nextTier];\n if (!nextConfig) return null;\n\n entry.model = nextConfig.primary;\n entry.tier = nextTier;\n entry.strikes = 0;\n entry.escalated = true;\n\n return { model: nextConfig.primary, tier: nextTier };\n }\n\n /**\n * Add cost to a session's running total for maxCostPerRun tracking.\n * Cost is in USDC 6-decimal units (micros).\n * Creates a cost-tracking-only entry if none exists (e.g., explicit model requests\n * that never go through the routing path).\n */\n addSessionCost(sessionId: string, additionalMicros: bigint): void {\n let entry = this.sessions.get(sessionId);\n if (!entry) {\n const now = Date.now();\n entry = {\n model: \"\",\n tier: \"DIRECT\",\n createdAt: now,\n lastUsedAt: now,\n requestCount: 0,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n };\n this.sessions.set(sessionId, entry);\n }\n entry.sessionCostMicros += additionalMicros;\n }\n\n /**\n * Get the total accumulated cost for a session in USD.\n */\n getSessionCostUsd(sessionId: string): number {\n const entry = this.sessions.get(sessionId);\n if (!entry) return 0;\n return Number(entry.sessionCostMicros) / 1_000_000;\n }\n\n /**\n * Stop the cleanup interval.\n */\n close(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n}\n\n/**\n * Generate a session ID from request headers or create a default.\n */\nexport function getSessionId(\n headers: Record,\n headerName: string = DEFAULT_SESSION_CONFIG.headerName,\n): string | undefined {\n const value = headers[headerName] || headers[headerName.toLowerCase()];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n if (Array.isArray(value) && value.length > 0) {\n return value[0];\n }\n return undefined;\n}\n\n/**\n * Derive a stable session ID from message content when no explicit session\n * header is provided. Uses the first user message as the conversation anchor —\n * same opening message = same session ID across all subsequent turns.\n *\n * This prevents model-switching mid-conversation even when OpenClaw doesn't\n * send an x-session-id header (which is the default OpenClaw behaviour).\n */\nexport function deriveSessionId(\n messages: Array<{ role: string; content: unknown }>,\n): string | undefined {\n const firstUser = messages.find((m) => m.role === \"user\");\n if (!firstUser) return undefined;\n\n const content =\n typeof firstUser.content === \"string\" ? firstUser.content : JSON.stringify(firstUser.content);\n\n // 8-char hex prefix of SHA-256 — short enough for logs, collision-resistant\n // enough for session tracking within a single gateway instance.\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 8);\n}\n\n/**\n * Generate a short hash fingerprint from request content.\n * Captures: last user message text + tool call names (if any).\n * Normalizes whitespace to avoid false negatives from minor formatting diffs.\n */\nexport function hashRequestContent(lastUserContent: string, toolCallNames?: string[]): string {\n const normalized = lastUserContent.replace(/\\s+/g, \" \").trim().slice(0, 500);\n const toolSuffix = toolCallNames?.length ? `|tools:${toolCallNames.sort().join(\",\")}` : \"\";\n return createHash(\"sha256\")\n .update(normalized + toolSuffix)\n .digest(\"hex\")\n .slice(0, 12);\n}\n","/**\n * Auto-update checker for ClawRouter.\n * Checks npm registry on startup and notifies user if update available.\n */\n\nimport { VERSION } from \"./version.js\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org/@blockrun/clawrouter/latest\";\nconst CHECK_TIMEOUT_MS = 5_000; // Don't block startup for more than 5s\n\n/**\n * Compare semver versions. Returns:\n * 1 if a > b\n * 0 if a === b\n * -1 if a < b\n */\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split(\".\").map(Number);\n const pb = b.split(\".\").map(Number);\n for (let i = 0; i < 3; i++) {\n if ((pa[i] || 0) > (pb[i] || 0)) return 1;\n if ((pa[i] || 0) < (pb[i] || 0)) return -1;\n }\n return 0;\n}\n\n/**\n * Check npm registry for latest version.\n * Non-blocking, silent on errors.\n */\nexport async function checkForUpdates(): Promise {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);\n\n const res = await fetch(NPM_REGISTRY, {\n signal: controller.signal,\n headers: { Accept: \"application/json\" },\n });\n clearTimeout(timeout);\n\n if (!res.ok) return;\n\n const data = (await res.json()) as { version?: string };\n const latest = data.version;\n\n if (!latest) return;\n\n if (compareSemver(latest, VERSION) > 0) {\n console.log(\"\");\n console.log(`\\x1b[33m⬆️ ClawRouter ${latest} available (you have ${VERSION})\\x1b[0m`);\n console.log(` Run: \\x1b[36mnpx @blockrun/clawrouter@latest\\x1b[0m`);\n console.log(\"\");\n }\n } catch {\n // Silent fail - don't disrupt startup\n }\n}\n","/**\n * Exclude-models persistence module.\n *\n * Manages a user-configurable list of model IDs that the smart router\n * should never select. Stored as a sorted JSON array on disk.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { resolveModelAlias } from \"./models.js\";\n\nconst DEFAULT_FILE_PATH = join(homedir(), \".openclaw\", \"blockrun\", \"exclude-models.json\");\n\n/**\n * Load the exclude list from disk.\n * Returns an empty set if the file does not exist.\n */\nexport function loadExcludeList(filePath: string = DEFAULT_FILE_PATH): Set {\n try {\n const raw = readFileSync(filePath, \"utf-8\");\n const arr: unknown = JSON.parse(raw);\n if (Array.isArray(arr)) {\n return new Set(arr.filter((x): x is string => typeof x === \"string\"));\n }\n return new Set();\n } catch {\n return new Set();\n }\n}\n\n/**\n * Save a set of model IDs to disk as a sorted JSON array.\n */\nfunction saveExcludeList(set: Set, filePath: string): void {\n const sorted = [...set].sort();\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n writeFileSync(filePath, JSON.stringify(sorted, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Add a model to the exclude list.\n * Resolves aliases before persisting.\n * @returns The resolved model ID.\n */\nexport function addExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): string {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n set.add(resolved);\n saveExcludeList(set, filePath);\n return resolved;\n}\n\n/**\n * Remove a model from the exclude list.\n * Resolves aliases before removing.\n * @returns true if the model was present and removed, false otherwise.\n */\nexport function removeExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): boolean {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n const had = set.delete(resolved);\n if (had) {\n saveExcludeList(set, filePath);\n }\n return had;\n}\n\n/**\n * Clear the entire exclude list.\n */\nexport function clearExclusions(filePath: string = DEFAULT_FILE_PATH): void {\n saveExcludeList(new Set(), filePath);\n}\n","/**\n * Configuration Module\n *\n * Reads environment variables at module load time.\n * Separated from network code to avoid security scanner false positives.\n */\n\nconst DEFAULT_PORT = 8402;\n\n/**\n * Proxy port configuration - resolved once at module load.\n * Reads BLOCKRUN_PROXY_PORT env var or defaults to 8402.\n */\nexport const PROXY_PORT = (() => {\n const envPort = process[\"env\"].BLOCKRUN_PROXY_PORT;\n if (envPort) {\n const parsed = parseInt(envPort, 10);\n if (!isNaN(parsed) && parsed > 0 && parsed < 65536) {\n return parsed;\n }\n }\n return DEFAULT_PORT;\n})();\n","/**\n * Session Journal - Memory layer for ClawRouter\n *\n * Maintains a compact record of key actions per session, enabling agents\n * to recall earlier work even when OpenClaw's sessions_history is truncated.\n *\n * How it works:\n * 1. As LLM responses flow through, extracts key actions (\"I created X\", \"I fixed Y\")\n * 2. Stores them in a compact journal per session\n * 3. When a request mentions past work (\"what did you do today?\"), injects the journal\n */\n\nexport interface JournalEntry {\n timestamp: number;\n action: string; // Compact description: \"Created login component\"\n model?: string;\n}\n\nexport interface SessionJournalConfig {\n /** Maximum entries per session (default: 100) */\n maxEntries?: number;\n /** Maximum age of entries in ms (default: 24 hours) */\n maxAgeMs?: number;\n /** Maximum events to extract per response (default: 5) */\n maxEventsPerResponse?: number;\n}\n\nconst DEFAULT_CONFIG: Required = {\n maxEntries: 100,\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxEventsPerResponse: 5,\n};\n\nexport class SessionJournal {\n private journals: Map = new Map();\n private config: Required;\n\n constructor(config?: SessionJournalConfig) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Extract key events from assistant response content.\n * Looks for patterns like \"I created...\", \"I fixed...\", \"Successfully...\"\n */\n extractEvents(content: string): string[] {\n if (!content || typeof content !== \"string\") {\n return [];\n }\n\n const events: string[] = [];\n const seen = new Set();\n\n // Patterns for identifying key actions\n // Note: Patterns allow optional words like \"also\", \"then\", \"have\" between \"I\" and verb\n const patterns = [\n // Creation patterns\n /I (?:also |then |have |)?(?:created|implemented|added|wrote|built|generated|set up|initialized) ([^.!?\\n]{10,150})/gi,\n // Fix patterns\n /I (?:also |then |have |)?(?:fixed|resolved|solved|patched|corrected|addressed|debugged) ([^.!?\\n]{10,150})/gi,\n // Completion patterns\n /I (?:also |then |have |)?(?:completed|finished|done with|wrapped up) ([^.!?\\n]{10,150})/gi,\n // Update patterns\n /I (?:also |then |have |)?(?:updated|modified|changed|refactored|improved|enhanced|optimized) ([^.!?\\n]{10,150})/gi,\n // Success patterns\n /Successfully ([^.!?\\n]{10,150})/gi,\n // Tool usage patterns (when agent uses tools)\n /I (?:also |then |have |)?(?:ran|executed|called|invoked) ([^.!?\\n]{10,100})/gi,\n ];\n\n for (const pattern of patterns) {\n // Reset pattern lastIndex for each iteration\n pattern.lastIndex = 0;\n\n let match;\n while ((match = pattern.exec(content)) !== null) {\n const action = match[0].trim();\n\n // Skip if already seen (dedup)\n const normalized = action.toLowerCase();\n if (seen.has(normalized)) {\n continue;\n }\n\n // Validate length (not too short or too long)\n if (action.length >= 15 && action.length <= 200) {\n events.push(action);\n seen.add(normalized);\n }\n\n // Stop if we have enough events\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n return events;\n }\n\n /**\n * Record events to the session journal.\n */\n record(sessionId: string, events: string[], model?: string): void {\n if (!sessionId || !events.length) {\n return;\n }\n\n const journal = this.journals.get(sessionId) || [];\n const now = Date.now();\n\n for (const action of events) {\n journal.push({\n timestamp: now,\n action,\n model,\n });\n }\n\n // Trim old entries and enforce max count\n const cutoff = now - this.config.maxAgeMs;\n const trimmed = journal.filter((e) => e.timestamp > cutoff).slice(-this.config.maxEntries);\n\n this.journals.set(sessionId, trimmed);\n }\n\n /**\n * Check if the user message indicates a need for historical context.\n */\n needsContext(lastUserMessage: string): boolean {\n if (!lastUserMessage || typeof lastUserMessage !== \"string\") {\n return false;\n }\n\n const lower = lastUserMessage.toLowerCase();\n\n // Trigger phrases that indicate user wants to recall past work\n const triggers = [\n // Direct questions about past work\n \"what did you do\",\n \"what have you done\",\n \"what did we do\",\n \"what have we done\",\n // Temporal references\n \"earlier\",\n \"before\",\n \"previously\",\n \"this session\",\n \"today\",\n \"so far\",\n // Summary requests\n \"remind me\",\n \"summarize\",\n \"summary of\",\n \"recap\",\n // Progress inquiries\n \"your work\",\n \"your progress\",\n \"accomplished\",\n \"achievements\",\n \"completed tasks\",\n ];\n\n return triggers.some((t) => lower.includes(t));\n }\n\n /**\n * Format the journal for injection into system message.\n * Returns null if journal is empty.\n */\n format(sessionId: string): string | null {\n const journal = this.journals.get(sessionId);\n if (!journal?.length) {\n return null;\n }\n\n const lines = journal.map((e) => {\n const time = new Date(e.timestamp).toLocaleTimeString(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n });\n return `- ${time}: ${e.action}`;\n });\n\n return `[Session Memory - Key Actions]\\n${lines.join(\"\\n\")}`;\n }\n\n /**\n * Get the raw journal entries for a session (for debugging/testing).\n */\n getEntries(sessionId: string): JournalEntry[] {\n return this.journals.get(sessionId) || [];\n }\n\n /**\n * Clear journal for a specific session.\n */\n clear(sessionId: string): void {\n this.journals.delete(sessionId);\n }\n\n /**\n * Clear all journals.\n */\n clearAll(): void {\n this.journals.clear();\n }\n\n /**\n * Get stats about the journal.\n */\n getStats(): { sessions: number; totalEntries: number } {\n let totalEntries = 0;\n for (const entries of this.journals.values()) {\n totalEntries += entries.length;\n }\n return {\n sessions: this.journals.size,\n totalEntries,\n };\n }\n}\n","/**\n * Cost Report Generator\n */\n\nimport { getStats } from \"./stats.js\";\nimport type { AggregatedStats } from \"./stats.js\";\n\nexport type ReportPeriod = \"daily\" | \"weekly\" | \"monthly\";\n\nexport async function generateReport(period: ReportPeriod, json: boolean = false): Promise {\n const days = period === \"daily\" ? 1 : period === \"weekly\" ? 7 : 30;\n const stats = await getStats(days);\n\n if (json) {\n return JSON.stringify(stats, null, 2);\n }\n\n return formatMarkdownReport(period, days, stats);\n}\n\nfunction formatMarkdownReport(period: ReportPeriod, days: number, stats: AggregatedStats): string {\n const lines: string[] = [];\n\n lines.push(`# ClawRouter ${capitalize(period)} Report`);\n lines.push(`**Period:** Last ${days} day${days > 1 ? \"s\" : \"\"}`);\n lines.push(`**Generated:** ${new Date().toISOString()}`);\n lines.push(\"\");\n\n lines.push(\"## 📊 Usage Summary\");\n lines.push(\"\");\n lines.push(`| Metric | Value |`);\n lines.push(`|--------|-------|`);\n lines.push(`| Total Requests | ${stats.totalRequests} |`);\n lines.push(`| Total Cost | $${stats.totalCost.toFixed(4)} |`);\n lines.push(`| Baseline Cost | $${stats.totalBaselineCost.toFixed(4)} |`);\n lines.push(`| **Savings** | **$${stats.totalSavings.toFixed(4)}** |`);\n lines.push(`| Savings % | ${stats.savingsPercentage.toFixed(1)}% |`);\n lines.push(`| Avg Latency | ${stats.avgLatencyMs.toFixed(0)}ms |`);\n lines.push(\"\");\n\n lines.push(\"## 🤖 Model Distribution\");\n lines.push(\"\");\n const sortedModels = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 10);\n for (const [model, data] of sortedModels) {\n lines.push(`- ${model}: ${data.count} reqs, $${data.cost.toFixed(4)}`);\n }\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\nfunction capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n","/**\n * BlockRun Doctor - AI-Powered Diagnostics\n *\n * Collects system diagnostics and sends to Claude Opus 4.6 for analysis.\n * Works independently of OpenClaw - direct x402 payment to BlockRun API.\n */\n\nimport { platform, arch, freemem, totalmem } from \"node:os\";\nimport { createPublicClient, http } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { wrapFetchWithPayment, x402Client } from \"@x402/fetch\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { toClientEvmSigner } from \"@x402/evm\";\nimport { resolveOrGenerateWalletKey, resolvePaymentChain, WALLET_FILE } from \"./auth.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport {\n DEFAULT_BASE_PAYMENT_ASSET,\n fetchBasePaymentAssets,\n type BasePaymentAsset,\n} from \"./payment-asset.js\";\nimport { getSolanaAddress } from \"./wallet.js\";\nimport { getStats } from \"./stats.js\";\nimport { getProxyPort } from \"./proxy.js\";\nimport { VERSION } from \"./version.js\";\n\n// Types\ninterface SystemInfo {\n os: string;\n arch: string;\n nodeVersion: string;\n memoryFree: string;\n memoryTotal: string;\n}\n\ninterface WalletInfo {\n exists: boolean;\n valid: boolean;\n address: string | null;\n solanaAddress: string | null;\n balance: string | null;\n isLow: boolean;\n isEmpty: boolean;\n source: \"saved\" | \"env\" | \"generated\" | null;\n paymentChain: \"base\" | \"solana\";\n paymentAsset: BasePaymentAsset;\n}\n\ninterface NetworkInfo {\n blockrunApi: { reachable: boolean; latencyMs: number | null };\n localProxy: { running: boolean; port: number };\n}\n\ninterface LogInfo {\n requestsLast24h: number;\n costLast24h: string;\n errorsFound: number;\n}\n\ninterface DiagnosticResult {\n version: string;\n timestamp: string;\n system: SystemInfo;\n wallet: WalletInfo;\n network: NetworkInfo;\n logs: LogInfo;\n issues: string[];\n}\n\n// Helpers\nfunction formatBytes(bytes: number): string {\n const gb = bytes / (1024 * 1024 * 1024);\n return `${gb.toFixed(1)}GB`;\n}\n\nfunction green(text: string): string {\n return `\\x1b[32m✓\\x1b[0m ${text}`;\n}\n\nfunction red(text: string): string {\n return `\\x1b[31m✗\\x1b[0m ${text}`;\n}\n\nfunction yellow(text: string): string {\n return `\\x1b[33m⚠\\x1b[0m ${text}`;\n}\n\nfunction getBuyLinkForAsset(symbol: string): { label: string; url: string } {\n const normalized = symbol.trim().toUpperCase();\n const knownLinks: Record = {\n USDC: \"https://www.coinbase.com/price/usd-coin\",\n EURC: \"https://www.coinbase.com/price/euro-coin\",\n };\n const knownUrl = knownLinks[normalized];\n if (knownUrl) {\n return { label: `Get ${normalized}`, url: knownUrl };\n }\n return {\n label: `Find ${normalized} on Coinbase`,\n url: `https://www.coinbase.com/search?q=${encodeURIComponent(normalized)}`,\n };\n}\n\n// Collect system info\nfunction collectSystemInfo(): SystemInfo {\n return {\n os: `${platform()} ${arch()}`,\n arch: arch(),\n nodeVersion: process.version,\n memoryFree: formatBytes(freemem()),\n memoryTotal: formatBytes(totalmem()),\n };\n}\n\n// Collect wallet info\nasync function collectWalletInfo(): Promise {\n try {\n const { key, address, source, solanaPrivateKeyBytes } = await resolveOrGenerateWalletKey();\n\n if (!key || !address) {\n return {\n exists: false,\n valid: false,\n address: null,\n solanaAddress: null,\n balance: null,\n isLow: false,\n isEmpty: true,\n source: null,\n paymentChain: \"base\",\n paymentAsset: DEFAULT_BASE_PAYMENT_ASSET,\n };\n }\n\n // Derive Solana address if mnemonic-based wallet\n let solanaAddress: string | null = null;\n if (solanaPrivateKeyBytes) {\n try {\n solanaAddress = await getSolanaAddress(solanaPrivateKeyBytes);\n } catch {\n // Non-fatal\n }\n }\n\n // Check balance on the active payment chain\n const paymentChain = await resolvePaymentChain();\n let paymentAsset = DEFAULT_BASE_PAYMENT_ASSET;\n try {\n let balanceInfo: { balanceUSD: string; isLow: boolean; isEmpty: boolean };\n if (paymentChain === \"solana\" && solanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n const monitor = new SolanaBalanceMonitor(solanaAddress);\n balanceInfo = await monitor.checkBalance();\n } else {\n const paymentAssets =\n (await fetchBasePaymentAssets(\"https://blockrun.ai/api\").catch(() => undefined)) ??\n [DEFAULT_BASE_PAYMENT_ASSET];\n const assetBalances = await Promise.all(\n paymentAssets.map(async (asset) => {\n const monitor = new BalanceMonitor(address, asset);\n const info = await monitor.checkBalance();\n return { asset, info };\n }),\n );\n const selectedBalance =\n assetBalances.find(({ info }) => !info.isLow && !info.isEmpty) ??\n assetBalances.find(({ info }) => !info.isEmpty) ??\n assetBalances[0];\n paymentAsset = selectedBalance?.asset ?? DEFAULT_BASE_PAYMENT_ASSET;\n balanceInfo = {\n balanceUSD: selectedBalance?.info.balanceUSD ?? null,\n isLow:\n assetBalances.length > 0 ? assetBalances.every(({ info }) => info.isLow) : false,\n isEmpty:\n assetBalances.length > 0 ? assetBalances.every(({ info }) => info.isEmpty) : true,\n };\n }\n return {\n exists: true,\n valid: true,\n address,\n solanaAddress,\n balance: balanceInfo.balanceUSD,\n isLow: balanceInfo.isLow,\n isEmpty: balanceInfo.isEmpty,\n source,\n paymentChain,\n paymentAsset,\n };\n } catch {\n return {\n exists: true,\n valid: true,\n address,\n solanaAddress,\n balance: null,\n isLow: false,\n isEmpty: false,\n source,\n paymentChain,\n paymentAsset,\n };\n }\n } catch {\n return {\n exists: false,\n valid: false,\n address: null,\n solanaAddress: null,\n balance: null,\n isLow: false,\n isEmpty: true,\n source: null,\n paymentChain: \"base\",\n paymentAsset: DEFAULT_BASE_PAYMENT_ASSET,\n };\n }\n}\n\n// Collect network info\nasync function collectNetworkInfo(): Promise {\n const port = getProxyPort();\n\n // Check BlockRun API\n let blockrunReachable = false;\n let blockrunLatency: number | null = null;\n try {\n const start = Date.now();\n const response = await fetch(\"https://blockrun.ai/api/v1/models\", {\n method: \"GET\",\n signal: AbortSignal.timeout(10000),\n });\n blockrunLatency = Date.now() - start;\n blockrunReachable = response.ok || response.status === 402;\n } catch {\n // blockrunReachable already false\n }\n\n // Check local proxy\n let proxyRunning = false;\n try {\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n method: \"GET\",\n signal: AbortSignal.timeout(3000),\n });\n proxyRunning = response.ok;\n } catch {\n // proxyRunning already false\n }\n\n return {\n blockrunApi: { reachable: blockrunReachable, latencyMs: blockrunLatency },\n localProxy: { running: proxyRunning, port },\n };\n}\n\n// Collect log info\nasync function collectLogInfo(): Promise {\n try {\n const stats = await getStats(1); // Last 1 day\n return {\n requestsLast24h: stats.totalRequests,\n costLast24h: `$${stats.totalCost.toFixed(4)}`,\n errorsFound: 0, // TODO: parse error logs\n };\n } catch {\n return {\n requestsLast24h: 0,\n costLast24h: \"$0.00\",\n errorsFound: 0,\n };\n }\n}\n\n// Identify issues\nfunction identifyIssues(result: DiagnosticResult): string[] {\n const issues: string[] = [];\n\n if (!result.wallet.exists) {\n issues.push(\"No wallet found\");\n }\n if (result.wallet.isEmpty) {\n if (result.wallet.paymentChain === \"solana\") {\n issues.push(\"Wallet is empty - need to fund with USDC on Solana\");\n } else {\n issues.push(`Wallet is empty - need to fund with ${result.wallet.paymentAsset.symbol} on Base`);\n }\n if (result.wallet.paymentChain === \"base\" && result.wallet.solanaAddress) {\n issues.push(\"Tip: if you funded Solana, run /wallet solana to switch chains\");\n }\n } else if (result.wallet.isLow) {\n issues.push(\"Wallet balance is low (< $1.00)\");\n }\n if (!result.network.blockrunApi.reachable) {\n issues.push(\"Cannot reach BlockRun API - check internet connection\");\n }\n if (!result.network.localProxy.running) {\n issues.push(`Local proxy not running on port ${result.network.localProxy.port}`);\n }\n\n return issues;\n}\n\n// Print diagnostics to terminal\nfunction printDiagnostics(result: DiagnosticResult): void {\n console.log(\"\\n🔍 Collecting diagnostics...\\n\");\n\n // System\n console.log(\"System\");\n console.log(` ${green(`OS: ${result.system.os}`)}`);\n console.log(` ${green(`Node: ${result.system.nodeVersion}`)}`);\n console.log(\n ` ${green(`Memory: ${result.system.memoryFree} free / ${result.system.memoryTotal}`)}`,\n );\n\n // Wallet\n console.log(\"\\nWallet\");\n if (result.wallet.exists && result.wallet.valid) {\n console.log(` ${green(`Key: ${WALLET_FILE} (${result.wallet.source})`)}`);\n console.log(` ${green(`EVM Address: ${result.wallet.address}`)}`);\n if (result.wallet.solanaAddress) {\n console.log(` ${green(`Solana Address: ${result.wallet.solanaAddress}`)}`);\n }\n const chainLabel = result.wallet.paymentChain === \"solana\" ? \"Solana\" : \"Base\";\n const assetLabel = result.wallet.paymentChain === \"solana\" ? \"USDC\" : result.wallet.paymentAsset.symbol;\n console.log(` ${green(`Chain: ${chainLabel}`)}`);\n if (result.wallet.isEmpty) {\n console.log(\n ` ${red(`Balance: $0.00 - NEED TO FUND WITH ${assetLabel} ON ${chainLabel.toUpperCase()}!`)}`,\n );\n if (result.wallet.paymentChain === \"base\" && result.wallet.solanaAddress) {\n console.log(` ${yellow(`Tip: funded Solana instead? Run /wallet solana to switch`)}`);\n }\n } else if (result.wallet.isLow) {\n console.log(` ${yellow(`Balance: ${result.wallet.balance} (low)`)}`);\n } else if (result.wallet.balance) {\n console.log(` ${green(`Balance: ${result.wallet.balance}`)}`);\n } else {\n console.log(` ${yellow(`Balance: checking...`)}`);\n }\n } else {\n console.log(` ${red(\"No wallet found\")}`);\n }\n\n // Network\n console.log(\"\\nNetwork\");\n if (result.network.blockrunApi.reachable) {\n console.log(\n ` ${green(`BlockRun API: reachable (${result.network.blockrunApi.latencyMs}ms)`)}`,\n );\n } else {\n console.log(` ${red(\"BlockRun API: unreachable\")}`);\n }\n if (result.network.localProxy.running) {\n console.log(` ${green(`Local proxy: running on :${result.network.localProxy.port}`)}`);\n } else {\n console.log(` ${red(`Local proxy: not running on :${result.network.localProxy.port}`)}`);\n }\n\n // Logs\n console.log(\"\\nLogs\");\n console.log(\n ` ${green(`Last 24h: ${result.logs.requestsLast24h} requests, ${result.logs.costLast24h} spent`)}`,\n );\n if (result.logs.errorsFound > 0) {\n console.log(` ${yellow(`${result.logs.errorsFound} errors found in logs`)}`);\n }\n\n // Issues summary\n if (result.issues.length > 0) {\n console.log(\"\\n⚠️ Issues Found:\");\n for (const issue of result.issues) {\n console.log(` • ${issue}`);\n }\n }\n}\n\n// Model options for doctor command\ntype DoctorModel = \"sonnet\" | \"opus\";\n\nconst DOCTOR_MODELS: Record = {\n sonnet: {\n id: \"anthropic/claude-sonnet-4.6\",\n name: \"Claude Sonnet 4.6\",\n cost: \"~$0.003\",\n },\n opus: {\n id: \"anthropic/claude-opus-4.6\",\n name: \"Claude Opus 4.6\",\n cost: \"~$0.01\",\n },\n};\n\n// Send to AI for analysis\nasync function analyzeWithAI(\n diagnostics: DiagnosticResult,\n userQuestion?: string,\n model: DoctorModel = \"sonnet\",\n): Promise {\n // Check if wallet has funds\n if (diagnostics.wallet.isEmpty) {\n const paymentAsset = diagnostics.wallet.paymentAsset;\n const buyLink = getBuyLinkForAsset(paymentAsset.symbol);\n console.log(\"\\n💳 Wallet is empty - cannot call AI for analysis.\");\n console.log(\n diagnostics.wallet.paymentChain === \"solana\"\n ? ` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress ?? diagnostics.wallet.address}`\n : ` Fund your EVM wallet with ${paymentAsset.symbol} on Base: ${diagnostics.wallet.address}`,\n );\n if (diagnostics.wallet.paymentChain === \"base\" && diagnostics.wallet.solanaAddress) {\n console.log(` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress}`);\n }\n console.log(\n diagnostics.wallet.paymentChain === \"solana\"\n ? \" Get USDC: https://www.coinbase.com/price/usd-coin\"\n : ` ${buyLink.label}: ${buyLink.url}`,\n );\n console.log(\" Bridge to Base: https://bridge.base.org\\n\");\n return;\n }\n\n const modelConfig = DOCTOR_MODELS[model];\n console.log(`\\n📤 Sending to ${modelConfig.name} (${modelConfig.cost})...\\n`);\n\n try {\n const { key } = await resolveOrGenerateWalletKey();\n const account = privateKeyToAccount(key as `0x${string}`);\n const publicClient = createPublicClient({ chain: base, transport: http() });\n const evmSigner = toClientEvmSigner(account, publicClient);\n const x402 = new x402Client();\n registerExactEvmScheme(x402, { signer: evmSigner });\n const paymentFetch = wrapFetchWithPayment(fetch, x402);\n\n const response = await paymentFetch(\"https://blockrun.ai/api/v1/chat/completions\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: modelConfig.id,\n stream: false,\n messages: [\n {\n role: \"system\",\n content: `You are a technical support expert for BlockRun and ClawRouter.\nAnalyze the diagnostics and:\n1. Identify the root cause of any issues\n2. Provide specific, actionable fix commands (bash)\n3. Explain why the issue occurred briefly\n4. Be concise but thorough\n5. Format commands in code blocks`,\n },\n {\n role: \"user\",\n content: userQuestion\n ? `Here are my system diagnostics:\\n\\n${JSON.stringify(diagnostics, null, 2)}\\n\\nUser's question: ${userQuestion}`\n : `Here are my system diagnostics:\\n\\n${JSON.stringify(diagnostics, null, 2)}\\n\\nPlease analyze and help me fix any issues.`,\n },\n ],\n max_tokens: 1000,\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n console.log(`Error: ${response.status} - ${text}`);\n return;\n }\n\n const data = await response.json();\n const content = data.choices?.[0]?.message?.content;\n\n if (content) {\n console.log(\"🤖 AI Analysis:\\n\");\n console.log(content);\n console.log();\n } else {\n console.log(\"Error: No response from AI\");\n }\n } catch (err) {\n console.log(`\\nError calling AI: ${err instanceof Error ? err.message : String(err)}`);\n console.log(\"Try again or check your wallet balance.\\n\");\n }\n}\n\n// Main entry point\nexport async function runDoctor(\n userQuestion?: string,\n model: \"sonnet\" | \"opus\" = \"sonnet\",\n): Promise {\n console.log(`\\n🩺 BlockRun Doctor v${VERSION}\\n`);\n\n // Collect all diagnostics\n const [system, wallet, network, logs] = await Promise.all([\n collectSystemInfo(),\n collectWalletInfo(),\n collectNetworkInfo(),\n collectLogInfo(),\n ]);\n\n const result: DiagnosticResult = {\n version: VERSION,\n timestamp: new Date().toISOString(),\n system,\n wallet,\n network,\n logs,\n issues: [],\n };\n\n // Identify issues\n result.issues = identifyIssues(result);\n\n // Print to terminal\n printDiagnostics(result);\n\n // Send to AI for analysis\n await analyzeWithAI(result, userQuestion, model);\n}\n","/**\n * Partner Service Registry\n *\n * Defines available partner APIs that can be called through ClawRouter's proxy.\n * Partners provide specialized data (Twitter/X, etc.) via x402 micropayments.\n * The same wallet used for LLM calls pays for partner API calls — zero extra setup.\n */\n\nexport type PartnerServiceParam = {\n name: string;\n type: \"string\" | \"string[]\" | \"number\";\n description: string;\n required: boolean;\n};\n\nexport type PartnerServiceDefinition = {\n /** Unique service ID used in tool names: blockrun_{id} */\n id: string;\n /** Human-readable name */\n name: string;\n /** Partner providing this service */\n partner: string;\n /** Short description for tool listing */\n description: string;\n /** Proxy path (relative to /v1) */\n proxyPath: string;\n /** HTTP method */\n method: \"GET\" | \"POST\";\n /** Parameters for the tool's JSON Schema */\n params: PartnerServiceParam[];\n /** Pricing info for display */\n pricing: {\n perUnit: string;\n unit: string;\n minimum: string;\n maximum: string;\n };\n /** Example usage for help text */\n example: {\n input: Record;\n description: string;\n };\n};\n\n/**\n * All registered partner services.\n * New partners are added here — the rest of the system picks them up automatically.\n */\nexport const PARTNER_SERVICES: PartnerServiceDefinition[] = [\n {\n id: \"x_users_lookup\",\n name: \"Twitter/X User Lookup\",\n partner: \"AttentionVC\",\n description:\n \"Look up real-time Twitter/X user profiles by username. \" +\n \"Call this ONLY when the user explicitly asks to look up, check, or get information about a specific Twitter/X user's profile (follower count, bio, verification status, etc.). \" +\n \"Do NOT call this for messages that merely contain x.com or twitter.com URLs — only invoke when the user is asking for profile information about a specific account. \" +\n \"Returns: follower count, verification badge, bio, location, join date. \" +\n \"Accepts up to 100 usernames per request (without @ prefix).\",\n proxyPath: \"/x/users/lookup\",\n method: \"POST\",\n params: [\n {\n name: \"usernames\",\n type: \"string[]\",\n description:\n 'Array of Twitter/X usernames to look up (without @ prefix). Example: [\"elonmusk\", \"naval\"]',\n required: true,\n },\n ],\n pricing: {\n perUnit: \"$0.001\",\n unit: \"user\",\n minimum: \"$0.01 (10 users)\",\n maximum: \"$0.10 (100 users)\",\n },\n example: {\n input: { usernames: [\"elonmusk\", \"naval\", \"balaboris\"] },\n description: \"Look up 3 Twitter/X user profiles\",\n },\n },\n];\n\n/**\n * Get a partner service by ID.\n */\nexport function getPartnerService(id: string): PartnerServiceDefinition | undefined {\n return PARTNER_SERVICES.find((s) => s.id === id);\n}\n","#!/usr/bin/env node\n/**\n * ClawRouter CLI\n *\n * Standalone proxy for deployed setups where the proxy needs to survive gateway restarts.\n *\n * Usage:\n * npx @blockrun/clawrouter # Start standalone proxy\n * npx @blockrun/clawrouter --version # Show version\n * npx @blockrun/clawrouter --port 8402 # Custom port\n *\n * For production deployments, use with PM2:\n * pm2 start \"npx @blockrun/clawrouter\" --name clawrouter\n */\n\nimport { startProxy, getProxyPort } from \"./proxy.js\";\nimport { VERSION } from \"./version.js\";\nimport {\n resolveOrGenerateWalletKey,\n resolvePaymentChain,\n recoverWalletFromMnemonic,\n savePaymentChain,\n} from \"./auth.js\";\nimport { getSolanaAddress } from \"./wallet.js\";\nimport { generateReport } from \"./report.js\";\nimport { runDoctor } from \"./doctor.js\";\nimport { PARTNER_SERVICES } from \"./partners/index.js\";\n\nfunction printHelp(): void {\n console.log(`\nClawRouter v${VERSION} - Smart LLM Router\n\nUsage:\n clawrouter [options]\n clawrouter doctor [opus] [question]\n clawrouter partners [test]\n clawrouter report [daily|weekly|monthly] [--json]\n\nOptions:\n --version, -v Show version number\n --help, -h Show this help message\n --port Port to listen on (default: ${getProxyPort()})\n\nCommands:\n doctor AI-powered diagnostics (default: Sonnet ~$0.003)\n doctor opus Use Opus for deeper analysis (~$0.01)\n partners List available partner APIs with pricing\n partners test Test partner API endpoints (expect 402 = alive)\n wallet recover Restore wallet.key from mnemonic (if generated by ClawRouter)\n chain solana Switch to Solana (persists). Aliases: /wallet solana, wallet solana\n chain base Switch to Base EVM (persists). Aliases: /wallet base, wallet base\n\nExamples:\n # Start standalone proxy\n npx @blockrun/clawrouter\n\n # Run diagnostics (uses Sonnet by default)\n npx @blockrun/clawrouter doctor\n\n # Use Opus for complex issues\n npx @blockrun/clawrouter doctor opus\n\n # Ask a specific question\n npx @blockrun/clawrouter doctor \"why is my request failing?\"\n\n # Opus + question\n npx @blockrun/clawrouter doctor opus \"深度分析我的配置问题\"\n\nEnvironment Variables:\n BLOCKRUN_WALLET_KEY Private key for x402 payments (auto-generated if not set)\n BLOCKRUN_PROXY_PORT Default proxy port (default: 8402)\n\nFor more info: https://github.com/BlockRunAI/ClawRouter\n`);\n}\n\nfunction parseArgs(args: string[]): {\n version: boolean;\n help: boolean;\n doctor: boolean;\n partners: boolean;\n partnersTest: boolean;\n report: boolean;\n reportPeriod: \"daily\" | \"weekly\" | \"monthly\";\n reportJson: boolean;\n walletRecover: boolean;\n chain?: \"solana\" | \"base\";\n port?: number;\n} {\n const result = {\n version: false,\n help: false,\n doctor: false,\n partners: false,\n partnersTest: false,\n report: false,\n reportPeriod: \"daily\" as \"daily\" | \"weekly\" | \"monthly\",\n reportJson: false,\n walletRecover: false,\n chain: undefined as \"solana\" | \"base\" | undefined,\n port: undefined as number | undefined,\n };\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"--version\" || arg === \"-v\") {\n result.version = true;\n } else if (arg === \"--help\" || arg === \"-h\") {\n result.help = true;\n } else if (arg === \"doctor\" || arg === \"--doctor\") {\n result.doctor = true;\n } else if (arg === \"partners\") {\n result.partners = true;\n // Check for \"test\" subcommand\n if (args[i + 1] === \"test\") {\n result.partnersTest = true;\n i++;\n }\n } else if (arg === \"report\") {\n result.report = true;\n const next = args[i + 1];\n if (next && [\"daily\", \"weekly\", \"monthly\"].includes(next)) {\n result.reportPeriod = next as \"daily\" | \"weekly\" | \"monthly\";\n i++;\n if (args[i + 1] === \"--json\") {\n result.reportJson = true;\n i++;\n }\n } else if (next === \"--json\") {\n result.reportJson = true;\n i++;\n }\n } else if (arg === \"wallet\" && args[i + 1] === \"recover\") {\n result.walletRecover = true;\n i++;\n } else if (\n (arg === \"chain\" || arg === \"/wallet\" || arg === \"wallet\") &&\n (args[i + 1] === \"solana\" || args[i + 1] === \"base\")\n ) {\n result.chain = args[i + 1] as \"solana\" | \"base\";\n i++;\n } else if (arg === \"--port\" && args[i + 1]) {\n result.port = parseInt(args[i + 1], 10);\n i++; // Skip next arg\n }\n }\n\n return result;\n}\n\nasync function main(): Promise {\n const args = parseArgs(process.argv.slice(2));\n\n if (args.version) {\n console.log(VERSION);\n process.exit(0);\n }\n\n if (args.help) {\n printHelp();\n process.exit(0);\n }\n\n if (args.doctor) {\n // Parse: doctor [opus|sonnet] [question...]\n const rawArgs = process.argv.slice(2);\n const doctorIndex = rawArgs.findIndex((a) => a === \"doctor\" || a === \"--doctor\");\n const afterDoctor = rawArgs.slice(doctorIndex + 1);\n\n // Check if first arg is model selection\n let model: \"sonnet\" | \"opus\" = \"sonnet\"; // default to cheaper\n let questionArgs = afterDoctor;\n\n if (afterDoctor[0] === \"opus\") {\n model = \"opus\";\n questionArgs = afterDoctor.slice(1);\n } else if (afterDoctor[0] === \"sonnet\") {\n model = \"sonnet\";\n questionArgs = afterDoctor.slice(1);\n }\n\n const userQuestion = questionArgs.join(\" \").trim() || undefined;\n await runDoctor(userQuestion, model);\n process.exit(0);\n }\n\n if (args.partners) {\n if (PARTNER_SERVICES.length === 0) {\n console.log(\"No partner APIs available.\");\n process.exit(0);\n }\n\n console.log(`\\nClawRouter Partner APIs (v${VERSION})\\n`);\n\n for (const svc of PARTNER_SERVICES) {\n console.log(` ${svc.name} (${svc.partner})`);\n console.log(` ${svc.description}`);\n console.log(` Tool: blockrun_${svc.id}`);\n console.log(` Method: ${svc.method} /v1${svc.proxyPath}`);\n console.log(\n ` Pricing: ${svc.pricing.perUnit} per ${svc.pricing.unit} (min ${svc.pricing.minimum}, max ${svc.pricing.maximum})`,\n );\n console.log();\n }\n\n if (args.partnersTest) {\n console.log(\"Testing partner endpoints...\\n\");\n const apiBase = \"https://blockrun.ai/api\";\n for (const svc of PARTNER_SERVICES) {\n const url = `${apiBase}/v1${svc.proxyPath}`;\n try {\n const response = await fetch(url, { method: \"GET\" });\n const status = response.status;\n const ok = status === 402 ? \"alive (402 = payment required)\" : `status ${status}`;\n console.log(` ${svc.id}: ${ok}`);\n } catch (err) {\n console.log(` ${svc.id}: error - ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n console.log();\n }\n\n process.exit(0);\n }\n\n if (args.walletRecover) {\n await recoverWalletFromMnemonic();\n process.exit(0);\n }\n\n if (args.chain) {\n await savePaymentChain(args.chain);\n console.log(`[ClawRouter] Payment chain set to: ${args.chain}`);\n console.log(`[ClawRouter] This persists across restarts.`);\n console.log(`[ClawRouter] Run: npx @blockrun/clawrouter`);\n process.exit(0);\n }\n\n if (args.report) {\n const report = await generateReport(args.reportPeriod, args.reportJson);\n console.log(report);\n process.exit(0);\n }\n\n // Resolve wallet key\n const wallet = await resolveOrGenerateWalletKey();\n\n if (wallet.source === \"generated\") {\n console.log(`[ClawRouter] Generated new wallet: ${wallet.address}`);\n } else if (wallet.source === \"saved\") {\n console.log(`[ClawRouter] Using saved wallet: ${wallet.address}`);\n } else {\n console.log(`[ClawRouter] Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);\n }\n\n // Show Solana address if available\n if (wallet.solanaPrivateKeyBytes) {\n try {\n const solAddr = await getSolanaAddress(wallet.solanaPrivateKeyBytes);\n console.log(`[ClawRouter] Solana address: ${solAddr}`);\n } catch {\n // Non-fatal\n }\n }\n\n // Start the proxy\n const proxy = await startProxy({\n wallet,\n port: args.port,\n onReady: (port) => {\n console.log(`[ClawRouter] v${VERSION} | Proxy listening on http://127.0.0.1:${port}`);\n console.log(`[ClawRouter] Health check: http://127.0.0.1:${port}/health`);\n },\n onError: (error) => {\n console.error(`[ClawRouter] Error: ${error.message}`);\n },\n onRouted: (decision) => {\n const cost = decision.costEstimate.toFixed(4);\n const saved = (decision.savings * 100).toFixed(0);\n console.log(`[ClawRouter] [${decision.tier}] ${decision.model} $${cost} (saved ${saved}%)`);\n },\n onLowBalance: (info) => {\n console.warn(\n `[ClawRouter] Low balance: ${info.balanceUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}`,\n );\n },\n onInsufficientFunds: (info) => {\n console.error(\n `[ClawRouter] Insufficient funds. Balance: ${info.balanceUSD}, Need: ${info.requiredUSD}`,\n );\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n },\n });\n\n // Check balance on the active payment chain\n const paymentChain = await resolvePaymentChain();\n const displayAddress =\n paymentChain === \"solana\" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address;\n try {\n const balance = await proxy.balanceMonitor.checkBalance();\n if (balance.isEmpty) {\n console.log(`[ClawRouter] Wallet balance: $0.00 (using FREE model)`);\n console.log(\n `[ClawRouter] Fund wallet with ${balance.assetSymbol} for premium models: ${displayAddress}`,\n );\n } else if (balance.isLow) {\n console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD} (low)`);\n } else {\n console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD}`);\n }\n // Invalidate after display so the first real request always gets a fresh check.\n // Prevents a flaky RPC at startup from caching a false $0.00 and triggering\n // free-model fallback on the first request.\n proxy.balanceMonitor.invalidate();\n } catch {\n console.log(`[ClawRouter] Wallet: ${displayAddress} (balance check pending)`);\n }\n\n console.log(`[ClawRouter] Ready - Ctrl+C to stop`);\n\n // Handle graceful shutdown\n const shutdown = async (signal: string) => {\n console.log(`\\n[ClawRouter] Received ${signal}, shutting down...`);\n try {\n await proxy.close();\n console.log(`[ClawRouter] Proxy closed`);\n process.exit(0);\n } catch (err) {\n console.error(`[ClawRouter] Error during shutdown: ${err}`);\n process.exit(1);\n }\n };\n\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n\n // Keep process alive\n await new Promise(() => {});\n}\n\nmain().catch((err) => {\n console.error(`[ClawRouter] Fatal error: ${err.message}`);\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa;AAAb;;;AAAO,IAAM,UAAU;;;;;ACCvB,IASa;AATb;;;;AASM,IAAO,YAAP,MAAO,mBAAkB,MAAK;MAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,cAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,cAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,cAAM,UAAU;UACd,gBAAgB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8BAA8B,YAAY;EACxE;AACA,SAAO;AACT;AApGA,IAAAC,sBAAA;;;;AAIA;AAIA;AAYA;AACA;;;;;ACrBA,IAAa,SACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WAEA,SACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WAEA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA;AAjGb;;;AAAO,IAAM,UAAU,OAAO,KAAK,MAAM;AAClC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,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A,qDACA,yDACA,qDACA,wCACA,qDACA,2DACA,uDACA,uDACA,8DACA,mDACA,oDAIA,2CACA,wDACA,kDACA,kDACA,6DAIA,6DACA,mDACA,8DACA,4DACA,8DACA,0DACA,4DACA,gEAIA,4DAIA,kDACA,qDACA,mDACA,0DACA,uDAIA,sDACA,kDACA,gDAKA,0CACA,gDACA,mDACA,2DACA,uDACA,yDACA,qDACA,uDACA,6DACA,8DACA,wDACA,yDACA,sDACA,iEACA,iEACA,0DACA,yDACA,0DACA,sDACA,sDACA,0DACA,4DACA,yDACA,wDACA,6DACA,gEACA,yCACA,gDACA,2DACA,4DACA,qEACA,yDACA,6CACA,kDACA,yDACA,2DACA,gDACA,kDACA,gEACA,uDACA,oEACA,6DACA,4DACA,4CACA,sDACA,iDACA,0DACA,wDACA,sDACA,qDACA,gDACA,yEACA,wDACA,wEACA,8EAIA,4DACA,gDACA,+CACA,yDACA,uDACA,mDACA,6DACA,2DACA,2DACA,wEACA,0DACA,sDAIA,yDACA,8EACA,+EACA,wEACA,yDACA,qEACA,8DACA,yDACA,yDACA,2DACA,wEACA,oDACA,2DACA,wEACA,oDACA,4DACA,4DACA,gEAIA,6DACA,kEACA,wDACA,oDACA,wDACA,sFACA,wFACA,sFACA,kEACA,+CACA,4CACA,8CACA,wDACA,2EACA,8FACA,8DACA,gEACA,wDACA,6DACA,6EACA,+CACA,yDACA,oEAKA,0CACA,iDACA,uDACA,oDACA,4DACA,6DACA,0DACA,oDACA,sDAEA,sDACA,4DACA,wDACA,oDACA,gEACA,mDACA,sDACA,6DACA,oEACA,sDACA,2DACA,sEACA,wEACA,yDACA,iEACA,qEACA,oEACA,qEACA,8DACA,mEACA,wEACA,wDACA,8DACA,yEACA,0EACA,wDACA,2EACA,yDAIA,kEACA,kEACA,yDACA,qEACA,gFACA,kFACA,8DACA,8DACA,qEACA,8EAIA,sDACA,2CACA,6CACA,gDACA,mEACA,2DACA,yDACA,+CACA,uDACA,2DACA,4CACA,2CACA,+CACA,qDACA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AAS,KAAK;AACZ,cAAQ,MAAM,uCAAuC,GAAG,EAAE;AAC1D,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAEA,UAAQ,GAAG,UAAU,MAAM,SAAS,QAAQ,CAAC;AAC7C,UAAQ,GAAG,WAAW,MAAM,SAAS,SAAS,CAAC;AAG/C,QAAM,IAAI,QAAQ,MAAM;AAAA,EAAC,CAAC;AAC5B;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,6BAA6B,IAAI,OAAO,EAAE;AACxD,UAAQ,MAAM,8DAA8D;AAC5E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["docsPath","signature","signature","signature","signature","signature","abi","signature","signature","signature","length","formatAbiItem","init_formatAbiItem","version","init_version","BaseError","init_version","docsPath","version","init_formatAbiItem","BaseError","docsPath","size","signature","formatAbiItem","BaseError","size","size","BaseError","size","size","size","index","BaseError","encoder","l","s","crypto","toBytes","pad","crypto","init_utils","s","init_utils","l","toBytes","signature","BaseError","BaseError","address","size","hash","address","address","cacheKey","concatBytes","bytesRegex","integerRegex","init_regex","size","integerRegex","length","BaseError","index","init_regex","abi","index","abi","docsPath","formatAbiItem","init_formatAbiItem","abi","signature","BaseError","init_cursor","size","data","length","consumed","value","size","init_cursor","abi","signature","formatAbiItem","init_formatAbiItem","value","address","BaseError","BaseError","docsPath","chain","hash","index","init_utils","address","init_formatAbiItem","init_utils","BaseError","docsPath","chain","abi","formatAbiItem","signature","init_utils","BaseError","BaseError","docsPath","isLE","_32n","l","init_utils","toBytes","buffer","finished","init_utils","D","init_utils","hash","toBytes","pad","finished","isBytes","abytes","num","hexToNumber","_0n","bytesToHex","hexes","hexToBytes","e","concatBytes","pad","utf8ToBytes","_1n","gen","init_utils","_0n","modulo","_1n","gcd","_2n","P","num","bitLen","isLE","init_utils","_1n","s","P","_0n","base","wbits","init_utils","num","size","bytesToHex","Fn","toBytes","concatBytes","fromBytes","_3n","_4n","_1n","isBytes","Point","P","endo","_0n","a","modN","s","from","l","hexToBytes","utils","hash","randomBytes","e","sign","signature","isHex","o","_2n","tv5","c1","c2","init_utils","hash","create","init_utils","abytes","concatBytes","utf8ToBytes","hash","e","createHasher","Point","num","P","init_utils","P","_3n","_2n","concatBytes","_1n","_0n","e","signature","s","init_utils","createHasher","BaseError","BaseError","e","formatted","address","init_stateOverride","abi","docsPath","isBytes","abytes","abool","numberToHexUnpadded","num","hexToNumber","_0n","bytesToHex","hasHexBuiltin","hexes","asciiToBase16","asciis","hexToBytes","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","e","concatBytes","pad","inRange","isPosBig","aInRange","bitLen","_1n","createHmacDrbg","u8n","u8fr","gen","validateObject","validatorFns","memoized","bitMask","init_utils","version","init_version","version","init_errors","init_version","walk","BaseError","init_errors","docsPath","version","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","charCodeToBase16","charCodeMap","pad","SizeExceedsPaddingSizeError","trim","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","pad","SizeExceedsPaddingSizeError","trim","stringify","value","size","assertSize","index","charCodeToBase16","BaseError","encoder","padRight","pad","slice","assertStartOffset","assertEndOffset","toBigInt","InvalidBytesBooleanError","toNumber","trim","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","stringify","assert","concat","from","assertSize","hexes","size","IntegerOutOfRangeError","fromString","encoder","pad","slice","assertStartOffset","assertEndOffset","trimLeft","trim","validate","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","BaseError","stringify","toRpc","init_contract","BaseError","chain","abi","docsPath","chain","docsPath","cause","wait","args","split","init_utils","BaseError","abi","signature","formatAbiItem","init_formatAbiItem","abi","docsPath","formatAbiItem","signature","init_formatAbiItem","abi","docsPath","ccipRequest","init_ccip","BaseError","toRpc","base","data","offchainLookup","offchainLookupSignature","wait","args","size","init_contract","init_stateOverride","e","isSolanaError","index","ORDERED_ERROR_NAMES","padBytes","slice","index","encoder","decoder","SolanaError","size","buffer","alphabet","base","charCodeToBase16","TextDecoder","TextEncoder","createEncoder","SolanaError","SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE","hexBytes","createDecoder","combineCodec","buffer","decoder","address","index","SolanaError","SolanaError","isAddress","base58Encoder","mod","pow2","SolanaError","address","e","encode","decode","Endian","combineCodec","createEncoder","createDecoder","size","newOffset","createEncoder","createDecoder","slice","combineCodec","getBase16Decoder","SolanaError","index","getEncodedSize","isFixedSize","getU8Encoder","transformEncoder","getU8Decoder","transformDecoder","l","encoder","decoder","containsBytes","init_index_node","AccountRole","isAddress","SolanaError","combineCodec","assertValidBaseString","alphabet","SolanaError","partitionLeadingZeroes","getBigIntFromBaseX","base","getBaseXFromBigInt","getU8Encoder","getU8Decoder","getStructEncoder","getStructDecoder","getArrayEncoder","getShortU16Encoder","getArrayDecoder","getShortU16Decoder","createEncoder","createDecoder","version","combineCodec","transformEncoder","getBase58Encoder","getAddressEncoder","getAddressDecoder","getBase58Decoder","transformDecoder","address","TYPE","index","AccountRole","getAddressComparator","isWritableRole","isSignerRole","l","getBaseXEncoder","getBaseXDecoder","SolanaError","signature","randomBytes","privateKey","signature","getBytesEncoder","SolanaError","address","index","SYSTEM_PROGRAM_ADDRESS","isAdvanceNonceAccountInstructionData","isAddress","signatureBytes","signTransaction","SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT","index","appendTransactionMessageInstruction","SolanaError","signature","context","traverse","traverseSequential","traverseParallel","traverseSingle","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND","candidate","message","appendTransactionMessageInstructions","getAbortablePromise","getTransactionMessageSize","TRANSACTION_SIZE_LIMIT","isSolanaError","SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND","isAddress","version","SolanaError","transformEncoder","getAddressDecoder","getSignaturesToEncode","signature","getSignaturesEncoder","getU8Encoder","getStructEncoder","getBytesEncoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO","address","transformDecoder","getStructDecoder","getArrayDecoder","getBytesDecoder","getU8Decoder","combineCodec","index","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO","getArrayEncoder","getAddressEncoder","getUtf8Encoder","fixDecoderSize","getTupleDecoder","getUtf8Decoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY","getTupleEncoder","getHiddenPrefixDecoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED","encoder","SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE","signatureBytes","OffchainMessageContentFormat","unwrapBigIntValueObject","wrapBigIntValueObject","traverse","pipe","SolanaError","stringify","e","normalizeHeaders","AbortController","args","setMaxListeners","init_index_node","createExplicitAbortToken","e","EXPLICIT_ABORT_TOKEN","AbortController","EventTarget","args","setMaxListeners","e","SolanaError","AbortController","args","setMaxListeners","getAllowedNumericKeypaths","memoizedKeypaths","concat","buffer","toArrayBuffer","e","num","data","e","concat","toArrayBuffer","Receiver","num","Sender","http","randomBytes","createHash","URL","Receiver","Sender","WebSocket","address","e","key","WebSocket","createWebSocketStream","err","open","protocol","http","createHash","WebSocket","WebSocketServer","index","version","WebSocket","s","EventTarget","index_node_default","args","setMaxListeners","WebSocketImpl","createSolanaJsonRpcIntegerOverflowError","e","index","pipe","transformChannelInboundMessages","transformChannelOutboundMessages","cache","AbortController","args","setMaxListeners","SolanaError","address","isAddress","offchainMessageEnvelope","SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING","signature","transaction","o","TextEncoder","e","base58Decoder","SolanaError","signature","safeRace","getTimeoutPromise","AbortController","args","setMaxListeners","lamports","l","createRecentSignatureConfirmationPromiseFactory","signature","e","commitmentComparator","CACHE_TTL_MS","init_index_node","fixDecoderSize","getBytesDecoder","getStructDecoder","getU64Decoder","getU16Decoder","getOptionDecoder","getAddressDecoder","getU32Decoder","getBooleanDecoder","address","isTransactionSigner","kitIsTransactionSigner","getAddressEncoder","transformEncoder","getStructEncoder","getU8Encoder","getU64Encoder","AccountRole","ASSOCIATED_TOKEN_ERROR__INVALID_OWNER","associatedTokenErrorMessages","AccountState","init_index_node","transformEncoder","getStructEncoder","getU8Encoder","getU32Encoder","appendTransactionMessageInstruction","init_src","init_index_node","x402Version","tx","NETWORKS","init_src","init_index_node","x402Version","tx","NETWORKS","homedir","join","mkdir","writeFile","readFileSync","BaseError","init_formatAbiItem","abi","formatAbiItem","signature","address","abi","abi","address","docsPath","BaseError","err","address","hash","signature","secp256k1","s","yParityOrV","recoveryBit","hash","signature","init_cursor","encode","BaseError","address","hash","signature","BaseError","docsPath","chain","docsPath","cause","init_stateOverride","BaseError","BaseError","formatAuthorizationList","chain","chain","base","address","sha256","sha256","version","sha256","version","BaseError","size","hash","version","init_cursor","size","docsPath","cause","chain","format","base","chain","prepareTransactionRequest","getChainId","chainId","from","gas","nonce","type","e","error","getBlock","block","BaseError","abi","address","init_formatAbiItem","docsPath","abi","signature","formatAbiItem","abi","isEqual","index","value","input","address","event","abi","address","abi","address","abi","address","listeners","cleanup","poll","cacheKey","cache","abi","address","transport","eventName","args","shouldRetry","size","chain","base","key","BaseError","e","hash","hash","chain","address","BaseError","res","chain","address","chain","chain","address","event","address","address","address","BaseError","address","address","version","e","address","hash","version","BaseError","address","signature","blobs","commitments","proofs","v","s","signature","address","signature","promiseCache","uid","BaseError","chain","base","body","response","BaseError","init_regex","integerRegex","base","bytesRegex","struct","assert","from","validate","LruMap","size","LruMap","keccak256","assert","from","validate","fromHex","fromBytes","assert","x","slice","prefix","toHex","assert","concat","BaseError","stringify","size","from","addressRegex","assert","InvalidAddressError","checksum","address","hash","keccak256","from","toHex","validate","address","assert","InvalidAddressError","BaseError","bytesRegex","integerRegex","maxInt8","maxInt16","maxInt24","maxInt32","maxInt40","maxInt48","maxInt56","maxInt64","maxInt72","maxInt80","maxInt88","maxInt96","maxInt104","maxInt112","maxInt120","maxInt128","maxInt136","maxInt144","maxInt152","maxInt160","maxInt168","maxInt176","maxInt184","maxInt192","maxInt200","maxInt208","maxInt216","maxInt224","maxInt232","maxInt240","maxInt248","maxInt256","minInt8","minInt16","minInt24","minInt32","minInt40","minInt48","minInt56","minInt64","minInt72","minInt80","minInt88","minInt96","minInt104","minInt112","minInt120","minInt128","minInt136","minInt144","minInt152","minInt160","minInt168","minInt176","minInt184","minInt192","minInt200","minInt208","minInt216","minInt224","minInt232","minInt240","minInt248","minInt256","maxUint8","maxUint16","maxUint24","maxUint32","maxUint40","maxUint48","maxUint56","maxUint64","maxUint72","maxUint80","maxUint88","maxUint96","maxUint104","maxUint112","maxUint120","maxUint128","maxUint136","maxUint144","maxUint152","maxUint160","maxUint168","maxUint176","maxUint184","maxUint192","maxUint200","maxUint208","maxUint216","maxUint224","maxUint232","maxUint240","maxUint248","maxUint256","decodeParameter","checksumAddress","getArrayComponents","decodeArray","decodeTuple","decodeAddress","decodeBool","decodeBytes","decodeNumber","decodeString","sizeOfLength","sizeOfOffset","checksum","wrap","address","slice","toNumber","length","hasDynamicChild","consumed","value","size","toBigInt","encodeArray","encodeTuple","encodeAddress","integerRegex","encodeNumber","encodeBytes","encodeString","concat","assert","InvalidArrayError","BytesSizeMismatchError","BaseError","IntegerOutOfRangeError","fromString","index","staticCursor","RecursiveReadLimitExceededError","PositionOutOfBoundsError","NegativeOffsetError","size","BaseError","checksumAddress","size","data","decodeParameter","encode","concat","encodePacked","address","assert","fromString","integerRegex","bytesRegex","BytesSizeMismatchError","from","BaseError","size","BytesSizeMismatchError","InvalidArrayError","from","getEncodable","fromHex","from","getEncodable","getEncodableList","getEncodableBytes","getSizeOfLength","encode","BaseError","init_utils","init_utils","_0n","_1n","_2n","_3n","_4n","_5n","_8n","mod","pow2","modulo","_0n","invert","mod","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","tonelliShanks","P","Field","FpLegendre","FpSqrt","_3n","FIELD_FIELDS","validateField","validateObject","FpPow","num","_0n","_1n","FpInvertBatch","FpLegendre","_1n","_2n","nLength","Field","bitLen","isLE","_0n","bitMask","_1n","num","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","num","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","init_utils","_0n","_1n","constTimeNegate","validateW","calcWOpts","bitMask","calcOffsets","validateMSMPoints","validateMSMScalars","s","pointPrecomputes","pointWindowSizes","getW","P","wNAF","base","pippenger","bitLen","wbits","validateBasic","validateField","validateObject","nLength","init_utils","validateSigVerOpts","abool","validatePointOpts","validateBasic","validateObject","DERErr","DER","numberToHexUnpadded","num","_0n","bytesToNumberBE","ensureBytes","numToSizedHex","size","bytesToHex","numberToBytesBE","_1n","_2n","_3n","_4n","weierstrassPoints","Fn","Field","toBytes","concatBytes","fromBytes","inRange","isBytes","mod","aInRange","Point","memoized","FpInvertBatch","P","pippenger","endo","a","wNAF","validateOpts","weierstrass","modN","invert","s","from","l","hexToBytes","utils","getMinHashLength","mapHashToField","bitMask","hash","randomBytes","e","sign","createHmacDrbg","signature","isHex","getHash","hash","createCurve","create","weierstrass","secp256k1P","secp256k1N","_0n","_1n","_2n","divNearest","sqrtMod","P","_3n","pow2","Fpk1","Field","secp256k1","createCurve","mod","assert","signature","maxUint256","fromBytes","fromHex","InvalidSerializedSizeError","slice","s","yParity","extract","from","fromRpc","signature","fromRpc","yParity","signature","s","trimLeft","InvalidSerializedSizeError","BaseError","signature","size","from","stringify","from","fromRpc","address","signature","extract","hash","keccak256","concat","fromHex","toTuple","toTuple","address","signature","extract","recoverAddress","recoverPublicKey","signature","s","secp256k1","from","from","assert","slice","signature","recoverAddress","encode","size","concat","validate","BaseError","address","address","hash","index","hash","hash","contracts","abi","address","result","BaseError","init_stateOverride","block","toRpc","call","abi","result","error","e","normalizeSignature","signature","BaseError","isArgOfType","validate","index","getAmbiguousTypes","from","abi","validate","abiItem","slice","index","isArgOfType","getAmbiguousTypes","signature","normalizeSignature","keccak256","fromString","BaseError","encode","abi","options","fromAbi","concat","from","fromAbi","abi","item","encodeData","abi","args","fromAbi","abiFunction","getSelector","encode","concat","from","fromAbi","abi","getSelector","BaseError","encode","from","encodeData","call","address","InvalidWrappedSignatureError","assert","from","magicBytes","unwrap","validate","wrap","magicBytes","assert","slice","InvalidWrappedSignatureError","from","unwrap","signature","wrap","concat","encode","validate","BaseError","s","signature","address","chain","hash","signature","address","signature","hash","address","signature","hash","transport","hash","from","block","transport","address","transport","event","args","hash","address","address","signature","hash","uid","BaseError","chain","wait","body","serializeTransaction","signature","from","isBytes","anumber","wrap","encode","decode","l","from","from","anumber","padding","num","isBytes","checksum","anumber","isBytes","init_utils","hash","init_utils","wordlist","e","hash","s","signature","address","signature","signature","address","hash","decoder","x402Version","fetch","cache","cacheKey","payload","response","randomBytes","x402Version","signature","version","x402Version","signature","version","getAddress","getAddress","signature","from","encodeFunctionData","x402Version","readContract","signTransaction","getTransactionCount","estimateFeesPerGas","confidence","supportsToolCalling","supportsVision","decision","join","size","join","homedir","join","require","LOG_DIR","join","homedir","e","LOG_DIR","join","DEFAULT_TTL_MS","createHash","canonicalize","TIMESTAMP_PATTERN","RpcError","RpcError","mkdir","join","homedir","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","hasHexBuiltin","hexes","bytesToHex","abytes","asciis","asciiToBase16","hexToBytes","concatBytes","abytes","pad","createHasher","randomBytes","Chi","Maj","HashMD","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","SHA256_IV","SHA256_K","SHA256_W","HashMD","D","rotr","Chi","Maj","clean","SHA256_IV","sha256","createHasher","_0n","_1n","abool","isPosBig","anumber","numberToHexUnpadded","num","hexToNumber","_0n","bytesToNumberBE","bytesToHex","bytesToNumberLE","abytes","numberToBytesBE","anumber","hexToBytes","numberToBytesLE","isPosBig","_0n","inRange","aInRange","bitLen","_1n","bitMask","_1n","createHmacDrbg","anumber","u8n","concatBytes","gen","validateObject","memoized","_0n","_1n","_2n","_3n","_4n","_5n","_7n","_8n","mod","pow2","modulo","_0n","invert","mod","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","P","Field","tonelliShanks","_7n","e2","e3","_3n","FpLegendre","FpSqrt","FIELD_FIELDS","validateField","validateObject","FpPow","num","_0n","_1n","FpInvertBatch","FpLegendre","_1n","_2n","nLength","anumber","_0n","_1n","num","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","abytes","isLE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","Field","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","abytes","num","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","_0n","_1n","FpInvertBatch","validateW","calcWOpts","bitMask","calcOffsets","pointPrecomputes","pointWindowSizes","getW","P","_0n","wNAF","Point","_1n","calcWOpts","base","calcOffsets","validateW","isLE","validateField","Field","_0n","Fn","hash","ahash","abytes","pad","clean","aexists","finished","hmac","divNearest","num","_2n","_0n","bitMask","bitLen","_1n","abool","DERErr","DER","numberToHexUnpadded","bytesToNumberBE","abytes","_3n","_4n","weierstrass","Fn","validateObject","pointToBytes","concatBytes","Point","memoized","P","hexToBytes","endo","bytesToHex","wNAF","Fn","Point","randomBytes","getMinHashLength","num","l","mapHashToField","abytes","isBytes","s","utils","hash","ahash","validateObject","hmac","_2n","_1n","size","r","DER","hexToBytes","concatBytes","bytesToHex","bytesToNumberBE","bitMask","aInRange","_0n","extraEntropy","e","sign","createHmacDrbg","signature","P","recoverPublicKey","_2n","sqrtMod","P","_3n","pow2","Fpk1","Field","weierstrass","secp256k1","sha256","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","concatBytes","abytes","pad","createHasher","oidNist","_HMAC","hash","ahash","abytes","pad","clean","aexists","finished","hmac","Chi","Maj","HashMD","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","SHA256_IV","SHA512_IV","HashMD","clean","createHasher","U32_MASK64","_32n","fromBig","split","l","shrSH","s","shrSL","l","rotrSH","rotrSL","rotrBH","rotrBL","add","l","add3L","add3H","add4L","add4H","add5L","add5H","SHA256_K","SHA256_W","SHA2_32B","HashMD","D","rotr","Chi","Maj","clean","_SHA256","SHA256_IV","K512","split","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","HashMD","rotrSH","shrSH","rotrSL","shrSL","rotrBH","rotrBL","add4L","add4H","add5L","add5H","add","add3L","add3H","clean","SHA512_IV","sha256","createHasher","_SHA256","oidNist","sha512","createHasher","oidNist","isBytes","isArrayOf","afn","astr","anumber","aArr","astrArr","anumArr","chain","wrap","encode","decode","alphabet","l","join","from","convertRadix","from","aArr","anumber","radix","num","anumber","isBytes","convertRadix","anumArr","checksum","anumber","afn","isBytes","chain","radix","alphabet","join","sha256","chain","checksum","Point","secp256k1","sha256","createView","concatBytes","abytes","hmac","sha512","version","index","hash","signature","sha512","sha512","index","createKeyPairSignerFromPrivateKeyBytes","join","homedir","mkdir","chain","mkdir","crypto","hashMessage","hash","l","escapeRegex","originalChars","createHash","hash","join","dirname","homedir","join","homedir","DEFAULT_CONFIG","e","join","homedir","sanitized","size","readFileSync","buffer","account","baseUrl","createKeyPairSignerFromPrivateKeyBytes","SolanaBalanceMonitor","registerExactSvmScheme","chain","responseCache","s","mkdir","port","writeFile","normalizedModel","cacheKey","sufficiency","index","address","SolanaBalanceMonitor"]} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index ec998a0..fcb631a 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -362,10 +362,41 @@ declare class ResponseCache { isEnabled(): boolean; } +/** + * EIP-3009 payment asset on Base network. + * Represents a stablecoin that supports `transferWithAuthorization` + * for gasless, single-step payment settlements. + */ +type BasePaymentAsset = { + chain: "base"; + asset: `0x${string}`; + symbol: string; + decimals: number; + name: string; + transferMethod: "eip3009"; + priority?: number; + enabled?: boolean; +}; +/** Default payment asset: USDC on Base (6 decimals, EIP-3009). */ +declare const DEFAULT_BASE_PAYMENT_ASSET: BasePaymentAsset; +/** + * Validate and normalize a single payment asset from an API response. + * Returns undefined if the input is missing required fields or uses a non-EIP-3009 transfer method. + * Symbols are uppercased; names are trimmed. + */ +declare function normalizeBasePaymentAsset(value: unknown): BasePaymentAsset | undefined; +/** + * Fetch the highest-priority EIP-3009 payment asset from the API. + * Convenience wrapper around {@link fetchBasePaymentAssets} that returns only the first asset. + */ +declare function fetchBasePaymentAsset(apiBase: string, baseFetch?: typeof fetch): Promise; + /** * Balance Monitor for ClawRouter * - * Monitors USDC balance on Base network with intelligent caching. + * Monitors stablecoin balance on Base network with intelligent caching. + * Supports any EIP-3009 stablecoin (USDC, fxUSD, EURC, etc.) with + * automatic normalization from native decimals to USD micros (6 decimals). * Provides pre-request balance checks to prevent failed payments. * * Caching Strategy: @@ -373,7 +404,8 @@ declare class ResponseCache { * - Optimistic deduction: after successful payment, subtract estimated cost from cache * - Invalidation: on payment failure, immediately refresh from RPC */ -/** Balance thresholds in USDC smallest unit (6 decimals) */ + +/** Balance thresholds in USD micros (6 decimals, normalized from any stablecoin) */ declare const BALANCE_THRESHOLDS: { /** Low balance warning threshold: $1.00 */ readonly LOW_BALANCE_MICROS: 1000000n; @@ -382,10 +414,12 @@ declare const BALANCE_THRESHOLDS: { }; /** Balance information returned by checkBalance() */ type BalanceInfo = { - /** Raw balance in USDC smallest unit (6 decimals) */ + /** Raw balance normalized to USD micros (6 decimals, regardless of the underlying asset's native decimals) */ balance: bigint; /** Formatted balance as "$X.XX" */ balanceUSD: string; + /** Symbol of the active Base payment asset */ + assetSymbol: string; /** True if balance < $1.00 */ isLow: boolean; /** True if balance < $0.0001 (effectively zero) */ @@ -403,7 +437,7 @@ type SufficiencyResult = { shortfall?: string; }; /** - * Monitors USDC balance on Base network. + * Monitors stablecoin balance on Base network. * * Usage: * const monitor = new BalanceMonitor("0x..."); @@ -413,11 +447,9 @@ type SufficiencyResult = { declare class BalanceMonitor { private readonly client; private readonly walletAddress; - /** Cached balance (null = not yet fetched) */ - private cachedBalance; - /** Timestamp when cache was last updated */ - private cachedAt; - constructor(walletAddress: string); + private readonly assetMonitors; + private state; + constructor(walletAddress: string, asset?: BasePaymentAsset); /** * Check current USDC balance. * Uses cache if valid, otherwise fetches from RPC. @@ -426,14 +458,18 @@ declare class BalanceMonitor { /** * Check if balance is sufficient for an estimated cost. * - * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals) + * @param estimatedCostMicros - Estimated cost in USD micros (6 decimals) */ checkSufficient(estimatedCostMicros: bigint): Promise; + private get cachedBalance(); + private set cachedBalance(value); + private get cachedAt(); + private set cachedAt(value); /** * Optimistically deduct estimated cost from cached balance. * Call this after a successful payment to keep cache accurate. * - * @param amountMicros - Amount to deduct in USDC smallest unit + * @param amountMicros - Amount to deduct in USD micros */ deductEstimated(amountMicros: bigint): void; /** @@ -445,18 +481,24 @@ declare class BalanceMonitor { * Force refresh balance from RPC (ignores cache). */ refresh(): Promise; + setAsset(asset: BasePaymentAsset): void; + getAsset(): BasePaymentAsset; /** - * Format USDC amount (in micros) as "$X.XX". + * Format a stablecoin amount (normalized to USD micros) as "$X.XX". */ + formatUSD(amountMicros: bigint): string; formatUSDC(amountMicros: bigint): string; /** * Get the wallet address being monitored. */ getWalletAddress(): string; + getAssetSymbol(): string; + getSharedMonitorForAsset(asset: BasePaymentAsset): BalanceMonitor; /** Fetch balance from RPC */ private fetchBalance; /** Build BalanceInfo from raw balance */ private buildInfo; + private toUsdMicros; } /** @@ -468,6 +510,7 @@ declare class BalanceMonitor { type SolanaBalanceInfo = { balance: bigint; balanceUSD: string; + assetSymbol: string; isLow: boolean; isEmpty: boolean; walletAddress: string; @@ -497,6 +540,7 @@ declare class SolanaBalanceMonitor { */ formatUSDC(amountMicros: bigint): string; getWalletAddress(): string; + getAssetSymbol(): string; /** * Check native SOL balance (in lamports). Useful for detecting users who * funded with SOL instead of USDC. @@ -652,12 +696,14 @@ declare function getProxyPort(): number; type LowBalanceInfo = { balanceUSD: string; walletAddress: string; + assetSymbol: string; }; /** Callback info for insufficient funds error */ type InsufficientFundsInfo = { balanceUSD: string; requiredUSD: string; walletAddress: string; + assetSymbol: string; }; /** * Wallet config: either a plain EVM private key string, or the full @@ -744,6 +790,8 @@ type ProxyHandle = { baseUrl: string; walletAddress: string; solanaAddress?: string; + paymentAsset?: BasePaymentAsset; + paymentAssets?: BasePaymentAsset[]; balanceMonitor: AnyBalanceMonitor; close: () => Promise; }; @@ -1382,4 +1430,4 @@ declare function buildPartnerTools(proxyBaseUrl: string): PartnerToolDefinition[ declare const plugin: OpenClawPluginDefinition; -export { type AggregatedStats, BALANCE_THRESHOLDS, BLOCKRUN_MODELS, type BalanceInfo, BalanceMonitor, type CachedLLMResponse, type CachedResponse, type CheckResult, DEFAULT_RETRY_CONFIG, DEFAULT_ROUTING_CONFIG, DEFAULT_SESSION_CONFIG, type DailyStats, type DerivedKeys, EmptyWalletError, FileSpendControlStorage, InMemorySpendControlStorage, InsufficientFundsError, type InsufficientFundsInfo, type LowBalanceInfo, MODEL_ALIASES, OPENCLAW_MODELS, PARTNER_SERVICES, type PartnerServiceDefinition, type PartnerToolDefinition, type PaymentChain, type ProxyHandle, type ProxyOptions, RequestDeduplicator, ResponseCache, type ResponseCacheConfig, type RetryConfig, type RoutingConfig, type RoutingDecision, RpcError, type SessionConfig, type SessionEntry, SessionStore, type SolanaBalanceInfo, SolanaBalanceMonitor, SpendControl, type SpendControlOptions, type SpendControlStorage, type SpendLimits, type SpendRecord, type SpendWindow, type SpendingStatus, type SufficiencyResult, type Tier, type UsageEntry, type WalletConfig, type WalletResolution, blockrunProvider, buildPartnerTools, buildProviderModels, calculateModelCost, clearStats, plugin as default, deriveAllKeys, deriveEvmKey, deriveSolanaKeyBytes, fetchWithRetry, formatDuration, formatStatsAscii, generateWalletMnemonic, getAgenticModels, getFallbackChain, getFallbackChainFiltered, getModelContextWindow, getPartnerService, getProxyPort, getSessionId, getStats, hashRequestContent, isAgenticModel, isBalanceError, isEmptyWalletError, isInsufficientFundsError, isRetryable, isRpcError, isValidMnemonic, loadPaymentChain, logUsage, resolveModelAlias, resolvePaymentChain, route, savePaymentChain, setupSolana, startProxy }; +export { type AggregatedStats, BALANCE_THRESHOLDS, BLOCKRUN_MODELS, type BalanceInfo, BalanceMonitor, type BasePaymentAsset, type CachedLLMResponse, type CachedResponse, type CheckResult, DEFAULT_BASE_PAYMENT_ASSET, DEFAULT_RETRY_CONFIG, DEFAULT_ROUTING_CONFIG, DEFAULT_SESSION_CONFIG, type DailyStats, type DerivedKeys, EmptyWalletError, FileSpendControlStorage, InMemorySpendControlStorage, InsufficientFundsError, type InsufficientFundsInfo, type LowBalanceInfo, MODEL_ALIASES, OPENCLAW_MODELS, PARTNER_SERVICES, type PartnerServiceDefinition, type PartnerToolDefinition, type PaymentChain, type ProxyHandle, type ProxyOptions, RequestDeduplicator, ResponseCache, type ResponseCacheConfig, type RetryConfig, type RoutingConfig, type RoutingDecision, RpcError, type SessionConfig, type SessionEntry, SessionStore, type SolanaBalanceInfo, SolanaBalanceMonitor, SpendControl, type SpendControlOptions, type SpendControlStorage, type SpendLimits, type SpendRecord, type SpendWindow, type SpendingStatus, type SufficiencyResult, type Tier, type UsageEntry, type WalletConfig, type WalletResolution, blockrunProvider, buildPartnerTools, buildProviderModels, calculateModelCost, clearStats, plugin as default, deriveAllKeys, deriveEvmKey, deriveSolanaKeyBytes, fetchBasePaymentAsset, fetchWithRetry, formatDuration, formatStatsAscii, generateWalletMnemonic, getAgenticModels, getFallbackChain, getFallbackChainFiltered, getModelContextWindow, getPartnerService, getProxyPort, getSessionId, getStats, hashRequestContent, isAgenticModel, isBalanceError, isEmptyWalletError, isInsufficientFundsError, isRetryable, isRpcError, isValidMnemonic, loadPaymentChain, logUsage, normalizeBasePaymentAsset, resolveModelAlias, resolvePaymentChain, route, savePaymentChain, setupSolana, startProxy }; diff --git a/dist/index.js b/dist/index.js index ac7246e..f297dae 100644 --- a/dist/index.js +++ b/dist/index.js @@ -31728,6 +31728,9 @@ var init_solana_balance = __esm({ getWalletAddress() { return this.walletAddress; } + getAssetSymbol() { + return "USDC"; + } /** * Check native SOL balance (in lamports). Useful for detecting users who * funded with SOL instead of USDC. @@ -31781,6 +31784,7 @@ var init_solana_balance = __esm({ return { balance, balanceUSD: `$${dollars.toFixed(2)}`, + assetSymbol: "USDC", isLow: balance < 1000000n, isEmpty: balance < 100n, walletAddress: this.walletAddress @@ -45742,8 +45746,77 @@ function isRpcError(error) { return error instanceof Error && error.code === "RPC_ERROR"; } +// src/payment-asset.ts +var DEFAULT_BASE_PAYMENT_ASSET = { + chain: "base", + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + symbol: "USDC", + decimals: 6, + name: "USD Coin", + transferMethod: "eip3009" +}; +function isHexAddress(value) { + return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value); +} +function normalizeBasePaymentAsset(value) { + if (!value || typeof value !== "object") return void 0; + const candidate = value; + if (!isHexAddress(candidate.asset)) return void 0; + if (typeof candidate.symbol !== "string" || candidate.symbol.trim() === "") return void 0; + if (typeof candidate.decimals !== "number" || !Number.isInteger(candidate.decimals) || candidate.decimals < 0) { + return void 0; + } + if (typeof candidate.name !== "string" || candidate.name.trim() === "") return void 0; + if (candidate.transferMethod !== void 0 && candidate.transferMethod !== "eip3009") { + return void 0; + } + return { + chain: "base", + asset: candidate.asset, + symbol: candidate.symbol.trim().toUpperCase(), + decimals: candidate.decimals, + name: candidate.name.trim(), + transferMethod: "eip3009", + priority: typeof candidate.priority === "number" ? candidate.priority : void 0, + enabled: typeof candidate.enabled === "boolean" ? candidate.enabled : void 0 + }; +} +function sortAssets(assets) { + return [...assets].sort( + (a, b) => (a.priority ?? Number.MAX_SAFE_INTEGER) - (b.priority ?? Number.MAX_SAFE_INTEGER) + ); +} +function normalizeBasePaymentAssets(value) { + if (!value || typeof value !== "object") return [DEFAULT_BASE_PAYMENT_ASSET]; + const payload = value; + const candidateList = Array.isArray(payload.paymentAssets) ? payload.paymentAssets : [ + payload.paymentAsset, + payload.base, + payload + ]; + const normalized = candidateList.map((candidate) => normalizeBasePaymentAsset(candidate)).filter((asset) => Boolean(asset)).filter((asset) => asset.enabled !== false && asset.transferMethod === "eip3009"); + return sortAssets( + normalized.length > 0 ? normalized : [DEFAULT_BASE_PAYMENT_ASSET] + ); +} +async function fetchBasePaymentAssets(apiBase, baseFetch = fetch) { + try { + const response = await baseFetch(`${apiBase.replace(/\/+$/, "")}/v1/payment-metadata?chain=base`, { + headers: { Accept: "application/json" } + }); + if (!response.ok) return [DEFAULT_BASE_PAYMENT_ASSET]; + const payload = await response.json(); + return normalizeBasePaymentAssets(payload); + } catch { + return [DEFAULT_BASE_PAYMENT_ASSET]; + } +} +async function fetchBasePaymentAsset(apiBase, baseFetch = fetch) { + const assets = await fetchBasePaymentAssets(apiBase, baseFetch); + return assets[0]; +} + // src/balance.ts -var USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; var CACHE_TTL_MS = 3e4; var BALANCE_THRESHOLDS = { /** Low balance warning threshold: $1.00 */ @@ -45751,15 +45824,18 @@ var BALANCE_THRESHOLDS = { /** Effectively zero threshold: $0.0001 (covers dust/rounding) */ ZERO_THRESHOLD: 100n }; -var BalanceMonitor = class { +var BalanceMonitor = class _BalanceMonitor { client; walletAddress; - /** Cached balance (null = not yet fetched) */ - cachedBalance = null; - /** Timestamp when cache was last updated */ - cachedAt = 0; - constructor(walletAddress) { + assetMonitors = /* @__PURE__ */ new Map(); + state; + constructor(walletAddress, asset = DEFAULT_BASE_PAYMENT_ASSET) { this.walletAddress = walletAddress; + this.state = { + asset, + cachedBalance: null, + cachedAt: 0 + }; this.client = createPublicClient({ chain: base, transport: http(void 0, { @@ -45773,21 +45849,22 @@ var BalanceMonitor = class { * Uses cache if valid, otherwise fetches from RPC. */ async checkBalance() { + const state = this.state; const now = Date.now(); - if (this.cachedBalance !== null && this.cachedBalance > 0n && now - this.cachedAt < CACHE_TTL_MS) { - return this.buildInfo(this.cachedBalance); + if (state.cachedBalance !== null && state.cachedBalance > 0n && now - state.cachedAt < CACHE_TTL_MS) { + return this.buildInfo(state.cachedBalance, state.asset); } - const balance = await this.fetchBalance(); + const balance = await this.fetchBalance(state.asset); if (balance > 0n) { - this.cachedBalance = balance; - this.cachedAt = now; + state.cachedBalance = balance; + state.cachedAt = now; } - return this.buildInfo(balance); + return this.buildInfo(balance, state.asset); } /** * Check if balance is sufficient for an estimated cost. * - * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals) + * @param estimatedCostMicros - Estimated cost in USD micros (6 decimals) */ async checkSufficient(estimatedCostMicros) { const info = await this.checkBalance(); @@ -45798,18 +45875,31 @@ var BalanceMonitor = class { return { sufficient: false, info, - shortfall: this.formatUSDC(shortfall) + shortfall: this.formatUSD(shortfall) }; } + get cachedBalance() { + return this.state.cachedBalance; + } + set cachedBalance(value) { + this.state.cachedBalance = value; + } + get cachedAt() { + return this.state.cachedAt; + } + set cachedAt(value) { + this.state.cachedAt = value; + } /** * Optimistically deduct estimated cost from cached balance. * Call this after a successful payment to keep cache accurate. * - * @param amountMicros - Amount to deduct in USDC smallest unit + * @param amountMicros - Amount to deduct in USD micros */ deductEstimated(amountMicros) { - if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) { - this.cachedBalance -= amountMicros; + const state = this.state; + if (state.cachedBalance !== null && state.cachedBalance >= amountMicros) { + state.cachedBalance -= amountMicros; } } /** @@ -45817,8 +45907,9 @@ var BalanceMonitor = class { * Call this after a payment failure to get accurate balance. */ invalidate() { - this.cachedBalance = null; - this.cachedAt = 0; + const state = this.state; + state.cachedBalance = null; + state.cachedAt = 0; } /** * Force refresh balance from RPC (ignores cache). @@ -45827,43 +45918,77 @@ var BalanceMonitor = class { this.invalidate(); return this.checkBalance(); } + setAsset(asset) { + const currentAsset = this.state.asset; + if (currentAsset.asset.toLowerCase() !== asset.asset.toLowerCase() || currentAsset.symbol !== asset.symbol || currentAsset.decimals !== asset.decimals) { + this.state = this.getSharedMonitorForAsset(asset).state; + } + } + getAsset() { + return this.state.asset; + } /** - * Format USDC amount (in micros) as "$X.XX". + * Format a stablecoin amount (normalized to USD micros) as "$X.XX". */ - formatUSDC(amountMicros) { + formatUSD(amountMicros) { const dollars = Number(amountMicros) / 1e6; return `$${dollars.toFixed(2)}`; } + formatUSDC(amountMicros) { + return this.formatUSD(amountMicros); + } /** * Get the wallet address being monitored. */ getWalletAddress() { return this.walletAddress; } + getAssetSymbol() { + return this.state.asset.symbol; + } + getSharedMonitorForAsset(asset) { + if (this.state.asset.asset.toLowerCase() === asset.asset.toLowerCase() && this.state.asset.symbol === asset.symbol && this.state.asset.decimals === asset.decimals) { + return this; + } + const key = `${asset.asset.toLowerCase()}:${asset.symbol}:${asset.decimals}`; + const existing = this.assetMonitors.get(key); + if (existing) return existing; + const monitor = new _BalanceMonitor(this.walletAddress, asset); + this.assetMonitors.set(key, monitor); + return monitor; + } /** Fetch balance from RPC */ - async fetchBalance() { + async fetchBalance(asset) { try { const balance = await this.client.readContract({ - address: USDC_BASE, + address: asset.asset, abi: erc20Abi, functionName: "balanceOf", args: [this.walletAddress] }); - return balance; + return this.toUsdMicros(balance, asset); } catch (error) { throw new RpcError2(error instanceof Error ? error.message : "Unknown error", error); } } /** Build BalanceInfo from raw balance */ - buildInfo(balance) { + buildInfo(balance, asset) { return { balance, - balanceUSD: this.formatUSDC(balance), + balanceUSD: this.formatUSD(balance), + assetSymbol: asset.symbol, isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS, isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD, walletAddress: this.walletAddress }; } + toUsdMicros(rawAmount, asset) { + if (asset.decimals === 6) return rawAmount; + if (asset.decimals > 6) { + return rawAmount / 10n ** BigInt(asset.decimals - 6); + } + return rawAmount * 10n ** BigInt(6 - asset.decimals); + } }; // src/auth.ts @@ -47359,7 +47484,16 @@ async function readBodyWithTimeout(body, timeoutMs = MODEL_BODY_READ_TIMEOUT_MS) } return chunks; } -function transformPaymentError(errorBody) { +function transformPaymentError(errorBody, opts) { + const baseAssetSymbol = opts?.baseAssetSymbol || DEFAULT_BASE_PAYMENT_ASSET.symbol; + const baseAssetDecimals = opts?.baseAssetDecimals ?? DEFAULT_BASE_PAYMENT_ASSET.decimals; + const formatRawAssetAmount = (amountRaw, decimals) => { + const divisor = 10n ** BigInt(decimals); + const whole = amountRaw / divisor; + const remainder = amountRaw % divisor; + const scaledFraction = decimals >= 6 ? remainder / 10n ** BigInt(decimals - 6) : remainder * 10n ** BigInt(6 - decimals); + return `${whole.toString()}.${scaledFraction.toString().padStart(6, "0")}`; + }; try { const parsed = JSON.parse(errorBody); if (parsed.error === "Payment verification failed" && parsed.details) { @@ -47371,20 +47505,20 @@ function transformPaymentError(errorBody) { /insufficient balance:\s*(\d+)\s*<\s*(\d+)/i ); if (balanceMatch) { - const currentMicros = parseInt(balanceMatch[1], 10); - const requiredMicros = parseInt(balanceMatch[2], 10); - const currentUSD = (currentMicros / 1e6).toFixed(6); - const requiredUSD = (requiredMicros / 1e6).toFixed(6); + const currentRaw = BigInt(balanceMatch[1]); + const requiredRaw = BigInt(balanceMatch[2]); + const currentUSD = formatRawAssetAmount(currentRaw, baseAssetDecimals); + const requiredUSD = formatRawAssetAmount(requiredRaw, baseAssetDecimals); const wallet = innerJson.payer || "unknown"; const shortWallet = wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet; return JSON.stringify({ error: { - message: `Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`, + message: `Insufficient ${baseAssetSymbol} balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`, type: "insufficient_funds", wallet, current_balance_usd: currentUSD, required_usd: requiredUSD, - help: `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free` + help: `Fund wallet ${shortWallet} with ${baseAssetSymbol} on Base, or use free model: /model free` } }); } @@ -47481,6 +47615,13 @@ function transformPaymentError(errorBody) { } return errorBody; } +function formatStableAmount(amountRaw, decimals) { + const divisor = 10n ** BigInt(decimals); + const whole = amountRaw / divisor; + const remainder = amountRaw % divisor; + const scaledFraction = decimals >= 6 ? remainder / 10n ** BigInt(decimals - 6) : remainder * 10n ** BigInt(6 - decimals); + return `${whole.toString()}.${scaledFraction.toString().padStart(6, "0")}`; +} function categorizeError(status, body) { if (status === 401) return "auth_failure"; if (status === 402) return "payment_error"; @@ -47580,7 +47721,12 @@ async function checkExistingProxy(port) { if (response.ok) { const data = await response.json(); if (data.status === "ok" && data.wallet) { - return { wallet: data.wallet, paymentChain: data.paymentChain }; + return { + wallet: data.wallet, + paymentChain: data.paymentChain, + paymentAssets: data.paymentAssets, + selectedPaymentAsset: data.selectedPaymentAsset ?? data.paymentAsset + }; } } return void 0; @@ -48041,6 +48187,9 @@ async function startProxy(options) { const solanaPrivateKeyBytes = typeof options.wallet === "string" ? void 0 : options.wallet.solanaPrivateKeyBytes; const paymentChain = options.paymentChain ?? await resolvePaymentChain(); const apiBase = options.apiBase ?? (paymentChain === "solana" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API); + let activeBasePaymentAssets = paymentChain === "base" ? await fetchBasePaymentAssets(apiBase).catch(() => void 0) ?? [DEFAULT_BASE_PAYMENT_ASSET] : [DEFAULT_BASE_PAYMENT_ASSET]; + let activeBasePaymentAsset = activeBasePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET; + let lastSelectedBasePaymentAsset = activeBasePaymentAsset; if (paymentChain === "solana" && !solanaPrivateKeyBytes) { console.warn( `[ClawRouter] \u26A0 Payment chain is Solana but no mnemonic found \u2014 falling back to Base (EVM).` @@ -48053,19 +48202,18 @@ async function startProxy(options) { console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`); } const listenPort = options.port ?? getProxyPort(); - const existingProxy = await checkExistingProxy(listenPort); - if (existingProxy) { + const buildReuseHandle = async (existingProxyData) => { const account2 = privateKeyToAccount(walletKey); const baseUrl2 = `http://127.0.0.1:${listenPort}`; - if (existingProxy.wallet !== account2.address) { + if (existingProxyData.wallet !== account2.address) { console.warn( - `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account2.address}. Reusing existing proxy.` + `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxyData.wallet}, but current config uses ${account2.address}. Reusing existing proxy.` ); } - if (existingProxy.paymentChain) { - if (existingProxy.paymentChain !== paymentChain) { + if (existingProxyData.paymentChain) { + if (existingProxyData.paymentChain !== paymentChain) { throw new Error( - `Existing proxy on port ${listenPort} is using ${existingProxy.paymentChain} but ${paymentChain} was requested. Stop the existing proxy first or use a different port.` + `Existing proxy on port ${listenPort} is using ${existingProxyData.paymentChain} but ${paymentChain} was requested. Stop the existing proxy first or use a different port.` ); } } else if (paymentChain !== "base") { @@ -48082,23 +48230,38 @@ async function startProxy(options) { const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes); reuseSolanaAddress = solanaSigner.address; } - let balanceMonitor2; + let reuseBalanceMonitor; if (paymentChain === "solana" && reuseSolanaAddress) { const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports)); - balanceMonitor2 = new SolanaBalanceMonitor2(reuseSolanaAddress); + reuseBalanceMonitor = new SolanaBalanceMonitor2(reuseSolanaAddress); } else { - balanceMonitor2 = new BalanceMonitor(account2.address); + if (existingProxyData.paymentAssets?.length) { + activeBasePaymentAssets = existingProxyData.paymentAssets; + } + const selectedPaymentAssetId = typeof existingProxyData.selectedPaymentAsset === "string" ? existingProxyData.selectedPaymentAsset.toLowerCase() : existingProxyData.selectedPaymentAsset?.asset?.toLowerCase(); + const selectedPaymentAsset = selectedPaymentAssetId ? activeBasePaymentAssets.find((asset) => asset.asset.toLowerCase() === selectedPaymentAssetId) : void 0; + if (selectedPaymentAsset) { + activeBasePaymentAsset = selectedPaymentAsset; + lastSelectedBasePaymentAsset = selectedPaymentAsset; + } + reuseBalanceMonitor = new BalanceMonitor(account2.address, activeBasePaymentAsset); } options.onReady?.(listenPort); return { port: listenPort, baseUrl: baseUrl2, - walletAddress: existingProxy.wallet, + walletAddress: existingProxyData.wallet, solanaAddress: reuseSolanaAddress, - balanceMonitor: balanceMonitor2, + paymentAsset: paymentChain === "base" ? activeBasePaymentAsset : void 0, + paymentAssets: paymentChain === "base" ? activeBasePaymentAssets : void 0, + balanceMonitor: reuseBalanceMonitor, close: async () => { } }; + }; + const existingProxy = await checkExistingProxy(listenPort); + if (existingProxy) { + return buildReuseHandle(existingProxy); } const account = privateKeyToAccount(walletKey); const evmPublicClient = createPublicClient({ chain: base, transport: http() }); @@ -48116,12 +48279,27 @@ async function startProxy(options) { } x402.onAfterPaymentCreation(async (context) => { const network = context.selectedRequirements.network; + if (network.startsWith("eip155")) { + activeBasePaymentAssets = await fetchBasePaymentAssets(apiBase).catch(() => void 0) ?? activeBasePaymentAssets; + const refreshedActiveAsset = activeBasePaymentAssets.find( + (asset) => asset.asset.toLowerCase() === activeBasePaymentAsset.asset.toLowerCase() + ); + if (refreshedActiveAsset) { + activeBasePaymentAsset = refreshedActiveAsset; + } + } const chain3 = network.startsWith("eip155") ? "Base (EVM)" : network.startsWith("solana") ? "Solana" : network; - const amountMicros = parseInt(context.selectedRequirements.amount || "0", 10); - const amountUsd = amountMicros / 1e6; + const amountRaw = BigInt(context.selectedRequirements.amount || "0"); + const selectedRequirementsWithDecimals = context.selectedRequirements; + const amountDecimals = selectedRequirementsWithDecimals.decimals ?? (network.startsWith("eip155") ? activeBasePaymentAsset.decimals : 6); + const amountUsdText = formatStableAmount(amountRaw, amountDecimals); + const amountUsd = Number.parseFloat(amountUsdText); const store = paymentStore.getStore(); - if (store) store.amountUsd = amountUsd; - console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsd.toFixed(6)}`); + if (store) { + store.amountUsd = amountUsd; + store.amountUsdText = amountUsdText; + } + console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsdText}`); }); const payFetch = createPayFetchWithPreAuth(fetch, x402, void 0, { skipPreAuth: paymentChain === "solana" @@ -48133,7 +48311,7 @@ async function startProxy(options) { const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports)); balanceMonitor = new SolanaBalanceMonitor2(solanaAddress); } else { - balanceMonitor = new BalanceMonitor(account.address); + balanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset); } const routingConfig = mergeRoutingConfig(options.routingConfig); const modelPricing = buildModelPricing(); @@ -48147,7 +48325,7 @@ async function startProxy(options) { const sessionJournal = new SessionJournal(); const connections = /* @__PURE__ */ new Set(); const server = createServer((req, res) => { - paymentStore.run({ amountUsd: 0 }, async () => { + paymentStore.run({ amountUsd: 0, amountUsdText: "0.000000" }, async () => { req.on("error", (err) => { console.error(`[ClawRouter] Request stream error: ${err.message}`); }); @@ -48172,15 +48350,44 @@ async function startProxy(options) { wallet: account.address, paymentChain }; + if (paymentChain === "base") { + response.paymentAsset = activeBasePaymentAsset.asset; + response.paymentAssetSymbol = activeBasePaymentAsset.symbol; + response.paymentAssetDecimals = activeBasePaymentAsset.decimals; + response.paymentAssets = activeBasePaymentAssets; + response.selectedPaymentAsset = lastSelectedBasePaymentAsset.asset; + response.selectedPaymentAssetSymbol = lastSelectedBasePaymentAsset.symbol; + } if (solanaAddress) { response.solana = solanaAddress; } if (full) { try { - const balanceInfo = await balanceMonitor.checkBalance(); - response.balance = balanceInfo.balanceUSD; - response.isLow = balanceInfo.isLow; - response.isEmpty = balanceInfo.isEmpty; + if (paymentChain === "base") { + const assetBalances = await Promise.all( + activeBasePaymentAssets.map(async (asset) => { + const monitor = new BalanceMonitor(account.address, asset); + const balanceInfo = await monitor.checkBalance(); + return { + asset: asset.asset, + symbol: asset.symbol, + decimals: asset.decimals, + balance: balanceInfo.balanceUSD, + isLow: balanceInfo.isLow, + isEmpty: balanceInfo.isEmpty + }; + }) + ); + response.assetBalances = assetBalances; + response.balance = assetBalances[0]?.balance ?? "$0.00"; + response.isLow = assetBalances[0]?.isLow ?? true; + response.isEmpty = assetBalances.every((asset) => asset.isEmpty); + } else { + const balanceInfo = await balanceMonitor.checkBalance(); + response.balance = balanceInfo.balanceUSD; + response.isLow = balanceInfo.isLow; + response.isEmpty = balanceInfo.isEmpty; + } } catch { response.balanceError = "Could not fetch balance"; } @@ -48526,7 +48733,13 @@ async function startProxy(options) { balanceMonitor, sessionStore, responseCache2, - sessionJournal + sessionJournal, + () => activeBasePaymentAsset.symbol, + () => activeBasePaymentAssets, + (asset) => { + lastSelectedBasePaymentAsset = asset; + activeBasePaymentAsset = asset; + } ); } catch (err) { const error = err instanceof Error ? err : new Error(String(err)); @@ -48561,7 +48774,9 @@ async function startProxy(options) { rejectAttempt({ code: "REUSE_EXISTING", wallet: existingProxy2.wallet, - existingChain: existingProxy2.paymentChain + existingChain: existingProxy2.paymentChain, + paymentAssets: existingProxy2.paymentAssets, + selectedPaymentAsset: existingProxy2.selectedPaymentAsset }); return; } @@ -48601,16 +48816,12 @@ async function startProxy(options) { { cause: err } ); } - const baseUrl2 = `http://127.0.0.1:${listenPort}`; - options.onReady?.(listenPort); - return { - port: listenPort, - baseUrl: baseUrl2, - walletAddress: error.wallet, - balanceMonitor, - close: async () => { - } - }; + return buildReuseHandle({ + wallet: error.wallet, + paymentChain: error.existingChain, + paymentAssets: error.paymentAssets, + selectedPaymentAsset: error.selectedPaymentAsset + }); } if (error.code === "RETRY") { await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS)); @@ -48659,6 +48870,8 @@ async function startProxy(options) { baseUrl, walletAddress: account.address, solanaAddress, + paymentAsset: paymentChain === "base" ? activeBasePaymentAsset : void 0, + paymentAssets: paymentChain === "base" ? activeBasePaymentAssets : void 0, balanceMonitor, close: () => new Promise((res, rej) => { const timeout = setTimeout(() => { @@ -48759,7 +48972,7 @@ async function tryModelRequest(upstreamUrl, method, headers, body, modelId, maxT }; } } -async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, deduplicator, balanceMonitor, sessionStore, responseCache2, sessionJournal) { +async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, deduplicator, balanceMonitor, sessionStore, responseCache2, sessionJournal, getBaseAssetSymbol, getBasePaymentAssets, onBaseAssetSelected) { const startTime = Date.now(); const upstreamUrl = `${apiBase}${req.url}`; const bodyChunks = []; @@ -48782,6 +48995,8 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de let accumulatedContent = ""; let responseInputTokens; let responseOutputTokens; + let requestBalanceMonitor = balanceMonitor; + let requestBasePaymentAsset = getBasePaymentAssets()[0]; const isChatCompletion = req.url?.includes("/chat/completions"); const sessionId = getSessionId(req.headers); let effectiveSessionId = sessionId; @@ -49552,7 +49767,30 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de if (estimated) { estimatedCostMicros = BigInt(estimated); const bufferedCostMicros = estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100)) / 100n; - const sufficiency = await balanceMonitor.checkSufficient(bufferedCostMicros); + if (balanceMonitor instanceof BalanceMonitor) { + const baseAssets = getBasePaymentAssets(); + let selected; + for (const asset of baseAssets) { + const monitor = balanceMonitor.getSharedMonitorForAsset(asset); + const sufficiency2 = await monitor.checkSufficient(bufferedCostMicros); + if (!selected) { + selected = { asset, monitor, sufficiency: sufficiency2 }; + } + if (sufficiency2.sufficient) { + selected = { asset, monitor, sufficiency: sufficiency2 }; + break; + } + } + if (selected) { + requestBasePaymentAsset = selected.asset; + requestBalanceMonitor = selected.monitor; + onBaseAssetSelected(selected.asset); + console.log( + `[ClawRouter] Base payment asset selected: ${selected.asset.symbol} (${selected.sufficiency.info.balanceUSD})` + ); + } + } + const sufficiency = await requestBalanceMonitor.checkSufficient(bufferedCostMicros); if (sufficiency.info.isEmpty || !sufficiency.sufficient) { const originalModel = modelId; console.log( @@ -49570,12 +49808,14 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de `; options.onLowBalance?.({ balanceUSD: sufficiency.info.balanceUSD, - walletAddress: sufficiency.info.walletAddress + walletAddress: sufficiency.info.walletAddress, + assetSymbol: sufficiency.info.assetSymbol }); } else if (sufficiency.info.isLow) { options.onLowBalance?.({ balanceUSD: sufficiency.info.balanceUSD, - walletAddress: sufficiency.info.walletAddress + walletAddress: sufficiency.info.walletAddress, + assetSymbol: sufficiency.info.assetSymbol }); } } @@ -49908,7 +50148,7 @@ data: [DONE] i = freeIdx - 1; continue; } - if (freeIdx === -1) { + if (freeIdx === -1 && !excludeList.has(FREE_MODEL)) { modelsToTry.push(FREE_MODEL); console.log(`[ClawRouter] Payment error \u2014 appending free model: ${FREE_MODEL}`); continue; @@ -50045,7 +50285,10 @@ data: [DONE] console.log(`[ClawRouter] ${structuredMessage}`); const rawErrBody = lastError?.body || structuredMessage; const errStatus = lastError?.status || 502; - const transformedErr = transformPaymentError(rawErrBody); + const transformedErr = transformPaymentError(rawErrBody, { + baseAssetSymbol: requestBasePaymentAsset.symbol, + baseAssetDecimals: requestBasePaymentAsset.decimals + }); if (headersSentEarly) { let errPayload; try { @@ -50347,7 +50590,7 @@ data: [DONE] } } if (estimatedCostMicros !== void 0) { - balanceMonitor.deductEstimated(estimatedCostMicros); + requestBalanceMonitor.deductEstimated(estimatedCostMicros); } completed = true; } catch (err) { @@ -50357,7 +50600,7 @@ data: [DONE] heartbeatInterval = void 0; } deduplicator.removeInflight(dedupKey); - balanceMonitor.invalidate(); + requestBalanceMonitor.invalidate(); if (err instanceof Error && err.name === "AbortError") { throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err }); } @@ -51189,11 +51432,13 @@ async function startProxyInBackground(api) { ); }, onLowBalance: (info) => { - api.logger.warn(`[!] Low balance: ${info.balanceUSD}. Fund wallet: ${info.walletAddress}`); + api.logger.warn( + `[!] Low balance: ${info.balanceUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}` + ); }, onInsufficientFunds: (info) => { api.logger.error( - `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund wallet: ${info.walletAddress}` + `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}` ); } }); @@ -51210,11 +51455,12 @@ async function startProxyInBackground(api) { const currentChain = await resolvePaymentChain(); const displayAddress = currentChain === "solana" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address; const network = currentChain === "solana" ? "Solana" : "Base"; + const paymentAssetLabel = currentChain === "solana" ? "USDC" : proxy.paymentAsset?.symbol ?? DEFAULT_BASE_PAYMENT_ASSET.symbol; proxy.balanceMonitor.checkBalance().then(async (balance) => { if (balance.isEmpty) { api.logger.info(`Wallet (${network}): ${displayAddress}`); api.logger.info( - `Balance: $0.00 \u2014 send USDC on ${network} to the address above to unlock paid models.` + `Balance: $0.00 \u2014 send ${paymentAssetLabel} on ${network} to the address above to unlock paid models.` ); } else if (balance.isLow) { api.logger.info( @@ -51490,13 +51736,26 @@ Run \`openclaw plugins install @blockrun/clawrouter\` to generate a wallet.`, }; } } - let evmBalanceText; + const basePaymentAssets = await fetchBasePaymentAssets("https://blockrun.ai/api").catch(() => void 0) ?? [DEFAULT_BASE_PAYMENT_ASSET]; + let basePaymentAsset = basePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET; + let evmBalanceText = "Balance: (could not check)"; + let baseAssetLines = []; try { - const monitor = new BalanceMonitor(address2); - const balance = await monitor.checkBalance(); - evmBalanceText = `Balance: ${balance.balanceUSD}`; + for (const asset of basePaymentAssets) { + try { + const assetMonitor = new BalanceMonitor(address2, asset); + const assetBalance = await assetMonitor.checkBalance(); + baseAssetLines.push(` ${asset.symbol}: ${assetBalance.balanceUSD}`); + if (assetBalance.balance > 0n && evmBalanceText === "Balance: (could not check)") { + basePaymentAsset = asset; + evmBalanceText = `Balance: ${assetBalance.balanceUSD}`; + } + } catch { + baseAssetLines.push(` ${asset.symbol}: (could not check)`); + } + } } catch { - evmBalanceText = "Balance: (could not check)"; + baseAssetLines = basePaymentAssets.map((asset) => ` ${asset.symbol}: (could not check)`); } let solanaSection = ""; try { @@ -51557,7 +51816,9 @@ Run \`openclaw plugins install @blockrun/clawrouter\` to generate a wallet.`, "**Base (EVM):**", ` Address: \`${address2}\``, ` ${evmBalanceText}`, - ` Fund (USDC only): https://basescan.org/address/${address2}`, + ` Supported assets (priority order):`, + ...baseAssetLines, + ` Fund supported Base assets: https://basescan.org/address/${address2}`, solanaSection, usageSection, "", @@ -51729,6 +51990,7 @@ export { BALANCE_THRESHOLDS, BLOCKRUN_MODELS, BalanceMonitor, + DEFAULT_BASE_PAYMENT_ASSET, DEFAULT_RETRY_CONFIG, DEFAULT_ROUTING_CONFIG, DEFAULT_SESSION_CONFIG, @@ -51754,6 +52016,7 @@ export { deriveAllKeys, deriveEvmKey, deriveSolanaKeyBytes, + fetchBasePaymentAsset, fetchWithRetry, formatDuration, formatStatsAscii, @@ -51776,6 +52039,7 @@ export { isValidMnemonic, loadPaymentChain, logUsage, + normalizeBasePaymentAsset, resolveModelAlias, resolvePaymentChain, route, diff --git a/dist/index.js.map b/dist/index.js.map index f15fd15..8443332 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +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/abitype/src/human-readable/parseAbiItem.ts","../node_modules/abitype/src/human-readable/parseAbiParameters.ts","../node_modules/abitype/src/exports/index.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/version.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/errors/data.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/@noble/hashes/src/_u64.ts","../node_modules/@noble/hashes/src/cryptoNode.ts","../node_modules/@noble/hashes/src/utils.ts","../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/toEventSelector.ts","../node_modules/viem/errors/address.ts","../node_modules/viem/utils/lru.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/address/isAddress.ts","../node_modules/viem/utils/data/concat.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/regex.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/utils/hash/toFunctionSelector.ts","../node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/viem/constants/solidity.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/utils/encoding/fromBytes.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/abi/formatAbiItemWithArgs.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/errors/request.ts","../node_modules/viem/errors/rpc.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/hashes/src/sha2.ts","../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","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/utils/authorization/hashAuthorization.ts","../node_modules/viem/errors/node.ts","../node_modules/viem/utils/errors/getNodeError.ts","../node_modules/viem/utils/formatters/extract.ts","../node_modules/viem/utils/formatters/formatter.ts","../node_modules/viem/utils/formatters/transactionRequest.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/getTransactionCount.ts","../node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/@noble/hashes/src/sha256.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/utils/transaction/getTransactionType.ts","../node_modules/viem/utils/address/isAddressEqual.ts","../node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/ox/core/version.ts","../node_modules/ox/core/internal/errors.ts","../node_modules/ox/core/Errors.ts","../node_modules/ox/core/internal/bytes.ts","../node_modules/ox/core/internal/hex.ts","../node_modules/ox/core/Json.ts","../node_modules/ox/core/Bytes.ts","../node_modules/ox/core/Hex.ts","../node_modules/ox/core/Withdrawal.ts","../node_modules/ox/core/BlockOverrides.ts","../node_modules/viem/constants/abis.ts","../node_modules/viem/constants/contract.ts","../node_modules/viem/constants/contracts.ts","../node_modules/viem/errors/chain.ts","../node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/viem/utils/errors/getCallError.ts","../node_modules/viem/utils/promise/withResolvers.ts","../node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/viem/errors/ccip.ts","../node_modules/viem/utils/abi/decodeFunctionData.ts","../node_modules/viem/utils/abi/encodeErrorResult.ts","../node_modules/viem/utils/abi/encodeFunctionResult.ts","../node_modules/viem/utils/ens/localBatchGatewayRequest.ts","../node_modules/viem/utils/ccip.ts","../node_modules/viem/actions/public/call.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/utils/authorization/serializeAuthorizationList.ts","../node_modules/viem/constants/strings.ts","../node_modules/viem/utils/signature/toPrefixedMessage.ts","../node_modules/viem/utils/signature/hashMessage.ts","../node_modules/viem/errors/typedData.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/utils/signature/hashTypedData.ts","../node_modules/viem/utils/signature/serializeSignature.ts","../node_modules/@scure/base/index.ts","../node_modules/@noble/hashes/src/pbkdf2.ts","../node_modules/@scure/bip39/esm/index.js","../node_modules/viem/accounts/toAccount.ts","../node_modules/viem/accounts/utils/sign.ts","../node_modules/viem/accounts/utils/signAuthorization.ts","../node_modules/viem/accounts/utils/signMessage.ts","../node_modules/viem/accounts/utils/signTransaction.ts","../node_modules/viem/accounts/utils/signTypedData.ts","../node_modules/viem/accounts/privateKeyToAccount.ts","../node_modules/@scure/bip39/esm/wordlists/english.js","../node_modules/viem/accounts/index.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@noble/curves/src/utils.ts","../node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/@noble/curves/src/secp256k1.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_md.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/legacy.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@scure/bip32/node_modules/@scure/base/index.ts","../node_modules/@scure/bip32/index.ts","../node_modules/@noble/hashes/src/sha512.ts","../node_modules/@solana/errors/src/codes.ts","../node_modules/@solana/errors/src/context.ts","../node_modules/@solana/errors/src/messages.ts","../node_modules/@solana/errors/src/message-formatter.ts","../node_modules/@solana/errors/src/error.ts","../node_modules/@solana/errors/src/stack-trace.ts","../node_modules/@solana/errors/src/rpc-enum-errors.ts","../node_modules/@solana/errors/src/instruction-error.ts","../node_modules/@solana/errors/src/transaction-error.ts","../node_modules/@solana/errors/src/json-rpc-error.ts","../node_modules/@solana/errors/src/simulation-errors.ts","../node_modules/@solana/codecs-core/src/bytes.ts","../node_modules/@solana/codecs-core/src/codec.ts","../node_modules/@solana/codecs-core/src/combine-codec.ts","../node_modules/@solana/codecs-core/src/add-codec-sentinel.ts","../node_modules/@solana/codecs-core/src/assertions.ts","../node_modules/@solana/codecs-core/src/add-codec-size-prefix.ts","../node_modules/@solana/codecs-core/src/array-buffers.ts","../node_modules/@solana/codecs-core/src/decoder-entire-byte-array.ts","../node_modules/@solana/codecs-core/src/fix-codec-size.ts","../node_modules/@solana/codecs-core/src/offset-codec.ts","../node_modules/@solana/codecs-core/src/resize-codec.ts","../node_modules/@solana/codecs-core/src/pad-codec.ts","../node_modules/@solana/codecs-core/src/reverse-codec.ts","../node_modules/@solana/codecs-core/src/transform-codec.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base10.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/codecs-strings/src/baseX-reslice.ts","../node_modules/@solana/codecs-strings/src/base64.ts","../node_modules/@solana/codecs-strings/src/null-characters.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/codecs-strings/src/utf8.ts","../node_modules/@solana/accounts/src/account.ts","../node_modules/@solana/accounts/src/decode-account.ts","../node_modules/@solana/accounts/src/parse-account.ts","../node_modules/@solana/accounts/src/fetch-account.ts","../node_modules/@solana/accounts/src/maybe-account.ts","../node_modules/@solana/assertions/src/crypto.ts","../node_modules/@solana/assertions/src/subtle-crypto.ts","../node_modules/@solana/addresses/src/address.ts","../node_modules/@solana/addresses/src/vendor/noble/ed25519.ts","../node_modules/@solana/addresses/src/curve-internal.ts","../node_modules/@solana/addresses/src/curve.ts","../node_modules/@solana/addresses/src/program-derived-address.ts","../node_modules/@solana/addresses/src/public-key.ts","../node_modules/@solana/codecs-numbers/src/assertions.ts","../node_modules/@solana/codecs-numbers/src/common.ts","../node_modules/@solana/codecs-numbers/src/utils.ts","../node_modules/@solana/codecs-numbers/src/f32.ts","../node_modules/@solana/codecs-numbers/src/f64.ts","../node_modules/@solana/codecs-numbers/src/i128.ts","../node_modules/@solana/codecs-numbers/src/i16.ts","../node_modules/@solana/codecs-numbers/src/i32.ts","../node_modules/@solana/codecs-numbers/src/i64.ts","../node_modules/@solana/codecs-numbers/src/i8.ts","../node_modules/@solana/codecs-numbers/src/short-u16.ts","../node_modules/@solana/codecs-numbers/src/u128.ts","../node_modules/@solana/codecs-numbers/src/u16.ts","../node_modules/@solana/codecs-numbers/src/u32.ts","../node_modules/@solana/codecs-numbers/src/u64.ts","../node_modules/@solana/codecs-numbers/src/u8.ts","../node_modules/@solana/codecs-data-structures/src/assertions.ts","../node_modules/@solana/codecs-data-structures/src/utils.ts","../node_modules/@solana/codecs-data-structures/src/array.ts","../node_modules/@solana/codecs-data-structures/src/bit-array.ts","../node_modules/@solana/codecs-data-structures/src/boolean.ts","../node_modules/@solana/codecs-data-structures/src/bytes.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-data-structures/src/constant.ts","../node_modules/@solana/codecs-data-structures/src/tuple.ts","../node_modules/@solana/codecs-data-structures/src/union.ts","../node_modules/@solana/codecs-data-structures/src/discriminated-union.ts","../node_modules/@solana/codecs-data-structures/src/enum-helpers.ts","../node_modules/@solana/codecs-data-structures/src/enum.ts","../node_modules/@solana/codecs-data-structures/src/hidden-prefix.ts","../node_modules/@solana/codecs-data-structures/src/hidden-suffix.ts","../node_modules/@solana/codecs-data-structures/src/literal-union.ts","../node_modules/@solana/codecs-data-structures/src/map.ts","../node_modules/@solana/codecs-data-structures/src/unit.ts","../node_modules/@solana/codecs-data-structures/src/nullable.ts","../node_modules/@solana/codecs-data-structures/src/set.ts","../node_modules/@solana/codecs-data-structures/src/struct.ts","../node_modules/@solana/options/src/option.ts","../node_modules/@solana/options/src/unwrap-option.ts","../node_modules/@solana/options/src/option-codec.ts","../node_modules/@solana/options/src/unwrap-option-recursively.ts","../node_modules/@solana/codecs/dist/index.node.mjs","../node_modules/@solana/functional/src/pipe.ts","../node_modules/@solana/instructions/src/instruction.ts","../node_modules/@solana/instructions/src/roles.ts","../node_modules/@solana/rpc-types/src/blockhash.ts","../node_modules/@solana/rpc-types/src/cluster-url.ts","../node_modules/@solana/rpc-types/src/commitment.ts","../node_modules/@solana/rpc-types/src/lamports.ts","../node_modules/@solana/rpc-types/src/stringified-bigint.ts","../node_modules/@solana/rpc-types/src/stringified-number.ts","../node_modules/@solana/rpc-types/src/unix-timestamp.ts","../node_modules/@solana/transaction-messages/src/blockhash.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/transaction-messages/src/codecs/address-table-lookup.ts","../node_modules/@solana/transaction-messages/src/codecs/header.ts","../node_modules/@solana/transaction-messages/src/codecs/instruction.ts","../node_modules/@solana/transaction-messages/src/transaction-message.ts","../node_modules/@solana/transaction-messages/src/codecs/transaction-version.ts","../node_modules/@solana/transaction-messages/src/codecs/message.ts","../node_modules/@solana/transaction-messages/src/compile/accounts.ts","../node_modules/@solana/transaction-messages/src/compile/address-table-lookups.ts","../node_modules/@solana/transaction-messages/src/compile/header.ts","../node_modules/@solana/transaction-messages/src/compile/instructions.ts","../node_modules/@solana/transaction-messages/src/compile/lifetime-token.ts","../node_modules/@solana/transaction-messages/src/compile/static-accounts.ts","../node_modules/@solana/transaction-messages/src/compile/message.ts","../node_modules/@solana/transaction-messages/src/compress-transaction-message.ts","../node_modules/@solana/transaction-messages/src/create-transaction-message.ts","../node_modules/@solana/transaction-messages/src/durable-nonce-instruction.ts","../node_modules/@solana/transaction-messages/src/durable-nonce.ts","../node_modules/@solana/transaction-messages/src/fee-payer.ts","../node_modules/@solana/transaction-messages/src/instructions.ts","../node_modules/@solana/transaction-messages/src/decompile-message.ts","../node_modules/@solana/keys/src/algorithm.ts","../node_modules/@solana/keys/src/private-key.ts","../node_modules/@solana/keys/src/public-key.ts","../node_modules/@solana/keys/src/signatures.ts","../node_modules/@solana/keys/src/key-pair.ts","../node_modules/@solana/transactions/src/codecs/signatures-encoder.ts","../node_modules/@solana/transactions/src/codecs/transaction-codec.ts","../node_modules/@solana/transactions/src/lifetime.ts","../node_modules/@solana/transactions/src/compile-transaction.ts","../node_modules/@solana/transactions/src/signatures.ts","../node_modules/@solana/transactions/src/wire-transaction.ts","../node_modules/@solana/transactions/src/transaction-size.ts","../node_modules/@solana/transactions/src/sendable-transaction.ts","../node_modules/@solana/transactions/src/transaction-message-size.ts","../node_modules/@solana/promises/src/race.ts","../node_modules/@solana/promises/src/abortable.ts","../node_modules/@solana/instruction-plans/src/instruction-plan.ts","../node_modules/@solana/instruction-plans/src/append-instruction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-result.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-executor.ts","../node_modules/@solana/instruction-plans/src/transaction-planner.ts","../node_modules/@solana/offchain-messages/src/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/signing-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-common.ts","../node_modules/@solana/offchain-messages/src/codecs/signatures.ts","../node_modules/@solana/offchain-messages/src/codecs/envelope.ts","../node_modules/@solana/offchain-messages/src/content.ts","../node_modules/@solana/offchain-messages/src/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/content.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message.ts","../node_modules/@solana/offchain-messages/src/envelope-common.ts","../node_modules/@solana/offchain-messages/src/envelope-v0.ts","../node_modules/@solana/offchain-messages/src/envelope-v1.ts","../node_modules/@solana/offchain-messages/src/envelope.ts","../node_modules/@solana/offchain-messages/src/signatures.ts","../node_modules/@solana/plugin-core/src/client.ts","../node_modules/@solana/programs/src/program-error.ts","../node_modules/@solana/rpc-spec-types/src/parse-json-with-bigints.ts","../node_modules/@solana/rpc-spec-types/src/rpc-message.ts","../node_modules/@solana/rpc-spec-types/src/stringify-json-with-bigints.ts","../node_modules/@solana/rpc-spec/src/rpc.ts","../node_modules/@solana/rpc-spec/src/rpc-api.ts","../node_modules/@solana/rpc-spec/src/rpc-transport.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast-internal.ts","../node_modules/@solana/rpc-transformers/src/tree-traversal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-options-object-position-config.ts","../node_modules/@solana/rpc-transformers/src/request-transformer.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast-internal.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-result.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-allowed-numeric-values.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-throw-solana-error.ts","../node_modules/@solana/rpc-transformers/src/response-transformer.ts","../node_modules/@solana/rpc-api/src/index.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-headers.ts","../node_modules/@solana/rpc-transport-http/src/http-transport.ts","../node_modules/@solana/rpc-transport-http/src/is-solana-request.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-for-solana-rpc.ts","../node_modules/@solana/fast-stable-stringify/src/index.ts","../node_modules/@solana/rpc/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc/src/rpc-request-coalescer.ts","../node_modules/@solana/rpc/src/rpc-request-deduplication.ts","../node_modules/@solana/rpc/src/rpc-transport.ts","../node_modules/@solana/rpc/src/rpc.ts","../node_modules/@solana/rpc-parsed-types/dist/index.node.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/subscribable/src/async-iterable.ts","../node_modules/@solana/subscribable/src/data-publisher.ts","../node_modules/@solana/subscribable/src/demultiplex.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-api.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-channel.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-pubsub-plan.ts","../node_modules/@solana/rpc-subscriptions-api/src/index.ts","../node_modules/ws/lib/constants.js","../node_modules/ws/lib/buffer-util.js","../node_modules/ws/lib/limiter.js","../node_modules/ws/lib/permessage-deflate.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/stream.js","../node_modules/ws/lib/subprotocol.js","../node_modules/ws/lib/websocket-server.js","../node_modules/ws/wrapper.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/ws-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-channel-websocket/src/websocket-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-autopinger.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool-internal.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json-bigint.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-coalescer.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-transport.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions.ts","../node_modules/@solana/signers/src/deduplicate-signers.ts","../node_modules/@solana/signers/src/transaction-modifying-signer.ts","../node_modules/@solana/signers/src/transaction-partial-signer.ts","../node_modules/@solana/signers/src/transaction-sending-signer.ts","../node_modules/@solana/signers/src/transaction-signer.ts","../node_modules/@solana/signers/src/account-signer-meta.ts","../node_modules/@solana/signers/src/add-signers.ts","../node_modules/@solana/signers/src/fee-payer-signer.ts","../node_modules/@solana/signers/src/message-partial-signer.ts","../node_modules/@solana/signers/src/keypair-signer.ts","../node_modules/@solana/signers/src/message-modifying-signer.ts","../node_modules/@solana/signers/src/message-signer.ts","../node_modules/@solana/signers/src/noop-signer.ts","../node_modules/@solana/signers/src/offchain-message-signer.ts","../node_modules/@solana/signers/src/sign-offchain-message.ts","../node_modules/@solana/signers/src/transaction-with-single-sending-signer.ts","../node_modules/@solana/signers/src/sign-transaction.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/signers/src/signable-message.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-blockheight.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-nonce.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-recent-signature.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-timeout.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-racer.ts","../node_modules/@solana/transaction-confirmation/src/waiters.ts","../node_modules/@solana/kit/src/airdrop-internal.ts","../node_modules/@solana/kit/src/airdrop.ts","../node_modules/@solana/kit/src/fetch-lookup-tables.ts","../node_modules/@solana/kit/src/decompile-transaction-message-fetching-lookup-tables.ts","../node_modules/@solana/kit/src/get-minimum-balance-for-rent-exemption.ts","../node_modules/@solana/kit/src/send-transaction-internal.ts","../node_modules/@solana/kit/src/send-and-confirm-durable-nonce-transaction.ts","../node_modules/@solana/kit/src/send-and-confirm-transaction.ts","../node_modules/@solana/kit/src/send-transaction-without-confirming.ts","../src/wallet.ts","../src/solana-balance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/programs/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/errors/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/instructions/createAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/createMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/mintToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/transferToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/decryptableBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/encryptedBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extension.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extensionType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/tokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/transferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/applyConfidentialPendingBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialDeposit.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransferWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialWithdraw.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/configureConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createNativeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emitTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emptyConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMintCloseAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeNonTransferableMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePausableConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePermanentDelegate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeScaledUiAmountMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroup.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroupMember.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferFeeConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/pause.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/reallocate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/removeTokenMetadataKey.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/resume.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferCheckedWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMultiplierScaledUiMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateRateInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupMaxSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawExcessLamports.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccounts.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccountsForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getInitializeInstructionsForExtensions.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getTokenSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getMintSize.ts","../node_modules/@x402/svm/src/constants.ts","../node_modules/@x402/svm/src/utils.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/programs/computeBudget.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestHeapFrame.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestUnits.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitPrice.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setLoadedAccountsDataSizeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/constants.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/internal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateAndSetComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimitInternal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputePrice.ts","../node_modules/@x402/svm/src/exact/client/scheme.ts","../node_modules/@x402/svm/src/v1/index.ts","../node_modules/@x402/svm/src/exact/v1/client/scheme.ts","../node_modules/@x402/svm/src/exact/client/register.ts","../src/models.ts","../src/provider.ts","../src/proxy.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/utils/abi/encodeEventTopics.ts","../node_modules/viem/errors/log.ts","../node_modules/viem/actions/public/createContractEventFilter.ts","../node_modules/viem/utils/filters/createFilterRequestScope.ts","../node_modules/viem/actions/public/estimateContractGas.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/viem/utils/authorization/recoverAuthorizationAddress.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/fillTransaction.ts","../node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/public/getContractEvents.ts","../node_modules/viem/utils/abi/parseEventLogs.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/actions/public/getLogs.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/viem/actions/public/watchContractEvent.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/getFilterChanges.ts","../node_modules/viem/actions/public/uninstallFilter.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/viem/actions/ens/getEnsResolver.ts","../node_modules/viem/clients/decorators/public.ts","../node_modules/viem/actions/public/createAccessList.ts","../node_modules/viem/actions/public/createBlockFilter.ts","../node_modules/viem/actions/public/createEventFilter.ts","../node_modules/viem/actions/public/createPendingTransactionFilter.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/getBlobBaseFee.ts","../node_modules/viem/actions/public/getBlockTransactionCount.ts","../node_modules/viem/actions/public/getCode.ts","../node_modules/viem/actions/public/getDelegation.ts","../node_modules/viem/errors/eip712.ts","../node_modules/viem/actions/public/getEip712Domain.ts","../node_modules/viem/actions/public/getFeeHistory.ts","../node_modules/viem/utils/formatters/feeHistory.ts","../node_modules/viem/actions/public/getFilterLogs.ts","../node_modules/viem/actions/public/getProof.ts","../node_modules/viem/utils/authorization/verifyAuthorization.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/utils/promise/withDedupe.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/utils/index.ts","../node_modules/viem/utils/rpc/http.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/utils/rpc/id.ts","../node_modules/ox/erc8010/SignatureErc8010.ts","../node_modules/ox/core/AbiParameters.ts","../node_modules/ox/core/Address.ts","../node_modules/ox/core/internal/lru.ts","../node_modules/ox/core/Caches.ts","../node_modules/ox/core/Hash.ts","../node_modules/ox/core/PublicKey.ts","../node_modules/ox/core/internal/abiParameters.ts","../node_modules/ox/core/Solidity.ts","../node_modules/ox/core/internal/cursor.ts","../node_modules/ox/core/Authorization.ts","../node_modules/ox/core/Rlp.ts","../node_modules/ox/node_modules/@noble/curves/src/secp256k1.ts","../node_modules/ox/node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/ox/core/Signature.ts","../node_modules/ox/core/Secp256k1.ts","../node_modules/viem/utils/formatters/proof.ts","../node_modules/viem/actions/public/getStorageAt.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/actions/public/getTransactionConfirmations.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/viem/actions/public/simulateBlocks.ts","../node_modules/ox/core/AbiItem.ts","../node_modules/ox/core/internal/abiItem.ts","../node_modules/ox/core/AbiConstructor.ts","../node_modules/ox/core/AbiFunction.ts","../node_modules/viem/actions/public/simulateCalls.ts","../node_modules/viem/constants/address.ts","../node_modules/ox/erc6492/SignatureErc6492.ts","../node_modules/viem/actions/public/verifyHash.ts","../node_modules/viem/actions/public/verifyMessage.ts","../node_modules/viem/actions/public/verifyTypedData.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/actions/public/watchBlocks.ts","../node_modules/viem/actions/public/watchEvent.ts","../node_modules/viem/actions/public/watchPendingTransactions.ts","../node_modules/viem/actions/siwe/verifySiweMessage.ts","../node_modules/viem/utils/siwe/parseSiweMessage.ts","../node_modules/viem/utils/siwe/validateSiweMessage.ts","../node_modules/viem/actions/wallet/sendRawTransactionSync.ts","../node_modules/viem/clients/createPublicClient.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/index.ts","../node_modules/viem/op-stack/contracts.ts","../node_modules/viem/op-stack/formatters.ts","../node_modules/viem/op-stack/serializers.ts","../node_modules/viem/op-stack/chainConfig.ts","../node_modules/viem/chains/definitions/base.ts","../node_modules/@x402/core/src/index.ts","../node_modules/@x402/core/src/utils/index.ts","../node_modules/@x402/core/src/http/x402HTTPResourceServer.ts","../node_modules/@x402/core/src/http/httpFacilitatorClient.ts","../node_modules/@x402/core/src/http/x402HTTPClient.ts","../node_modules/@x402/core/src/http/index.ts","../node_modules/@x402/core/src/client/x402Client.ts","../src/payment-preauth.ts","../node_modules/@x402/evm/src/exact/extensions.ts","../node_modules/@x402/evm/src/exact/v1/client/scheme.ts","../node_modules/@x402/evm/src/constants.ts","../node_modules/@x402/evm/src/utils.ts","../node_modules/@x402/evm/src/exact/v1/facilitator/scheme.ts","../node_modules/@x402/evm/src/exact/facilitator/errors.ts","../node_modules/@x402/evm/src/exact/facilitator/eip3009-utils.ts","../node_modules/@x402/evm/src/multicall.ts","../node_modules/@x402/evm/src/v1/index.ts","../node_modules/@x402/evm/src/exact/client/scheme.ts","../node_modules/@x402/evm/src/exact/client/eip3009.ts","../node_modules/@x402/evm/src/exact/client/permit2.ts","../node_modules/@x402/evm/src/exact/client/eip2612.ts","../node_modules/@x402/evm/src/exact/client/erc20approval.ts","../node_modules/@x402/evm/src/exact/client/rpc.ts","../node_modules/@x402/evm/src/exact/client/register.ts","../node_modules/@x402/evm/src/signer.ts","../src/router/rules.ts","../src/router/selector.ts","../src/router/strategy.ts","../src/router/config.ts","../src/router/index.ts","../src/logger.ts","../src/stats.ts","../src/fs-read.ts","../src/version.ts","../src/dedup.ts","../src/response-cache.ts","../src/errors.ts","../src/balance.ts","../src/auth.ts","../src/compression/types.ts","../src/compression/layers/deduplication.ts","../src/compression/layers/whitespace.ts","../src/compression/codebook.ts","../src/compression/layers/dictionary.ts","../src/compression/layers/paths.ts","../src/compression/layers/json-compact.ts","../src/compression/layers/observation.ts","../src/compression/layers/dynamic-codebook.ts","../src/compression/index.ts","../src/session.ts","../src/updater.ts","../src/exclude-models.ts","../src/config.ts","../src/journal.ts","../src/index.ts","../src/partners/registry.ts","../src/partners/tools.ts","../src/spend-control.ts","../src/retry.ts"],"sourcesContent":["export const version = '1.2.3'\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}\nexport function execFallbackSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(fallbackSignatureRegex, 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} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @param structs Struct definitions to include in cache key\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}${structKey}`\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 execFallbackSignature,\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 return parseFunctionSignature(signature, structs)\n\n if (isEventSignature(signature))\n return parseEventSignature(signature, structs)\n\n if (isErrorSignature(signature))\n return parseErrorSignature(signature, structs)\n\n if (isConstructorSignature(signature))\n return parseConstructorSignature(signature, structs)\n\n if (isFallbackSignature(signature)) return parseFallbackSignature(signature)\n\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nexport function parseFunctionSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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\nexport function parseEventSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'event', inputs: abiParameters }\n}\n\nexport function parseErrorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'error', inputs: abiParameters }\n}\n\nexport function parseConstructorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n}\n\nexport function parseFallbackSignature(signature: string) {\n const match = execFallbackSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'fallback' })\n\n return {\n type: 'fallback',\n stateMutability: match.stateMutability ?? 'nonpayable',\n }\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\\spayable)?)(?(?:\\[\\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 if (match.type === 'address payable') {\n type = 'address'\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 structs\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 { Abi } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiItemError } from './errors/abiItem.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signature, 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 item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * type Result = ParseAbiItem<'function balanceOf(address owner) view returns (uint256)'>\n * // ^? type Result = { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * type Result = ParseAbiItem<\n * // ^? type Result = { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * ['function foo(Baz bar) view returns (string)', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n> =\n | (signature extends string\n ? string extends signature\n ? Abi[number]\n : signature extends Signature // Validate signature\n ? ParseSignature\n : never\n : never)\n | (signature extends readonly string[]\n ? string[] extends signature\n ? Abi[number] // Return generic Abi item since type was no inferrable\n : signature extends Signatures // Validate signature\n ? ParseStructs extends infer structs\n ? {\n [key in keyof signature]: ParseSignature<\n signature[key] extends string ? signature[key] : never,\n structs\n >\n } extends infer mapped extends readonly unknown[]\n ? // Filter out `never` since those are structs\n Filter[0] extends infer result\n ? result extends undefined // convert `undefined` to `never` (e.g. `ParseAbiItem<['struct Foo { string name; }']>`)\n ? never\n : result\n : never\n : never\n : never\n : never\n : never)\n\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint256)')\n * // ^? const abiItem: { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * const abiItem = parseAbiItem([\n * // ^? const abiItem: { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * 'function foo(Baz bar) view returns (string)',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n>(\n signature: Narrow &\n (\n | (signature extends string\n ? string extends signature\n ? unknown\n : Signature\n : never)\n | (signature extends readonly string[]\n ? signature extends readonly [] // empty array\n ? Error<'At least one signature required.'>\n : string[] extends signature\n ? unknown\n : Signatures\n : never)\n ),\n): ParseAbiItem {\n let abiItem: ParseAbiItem | undefined\n if (typeof signature === 'string')\n abiItem = parseSignature(signature) as ParseAbiItem\n else {\n const structs = parseStructs(signature as readonly string[])\n const length = signature.length as number\n for (let i = 0; i < length; i++) {\n const signature_ = (signature as readonly string[])[i]!\n if (isStructSignature(signature_)) continue\n abiItem = parseSignature(signature_, structs) as ParseAbiItem\n break\n }\n }\n\n if (!abiItem) throw new InvalidAbiItemError({ signature })\n return abiItem as ParseAbiItem\n}\n","import type { AbiParameter } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiParametersError } from './errors/abiParameter.js'\nimport { isStructSignature, modifiers } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { splitParameters } from './runtime/utils.js'\nimport { parseAbiParameter as parseAbiParameter_ } from './runtime/utils.js'\nimport type { IsStructSignature, Modifier } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { SplitParameters } from './types/utils.js'\nimport type { ParseAbiParameters as ParseAbiParameters_ } from './types/utils.js'\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * type Result = ParseAbiParameters('address from, address to, uint256 amount')\n * // ^? type Result: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * type Result = ParseAbiParameters<\n * // ^? type Result: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * ['Baz bar', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n> =\n | (params extends string\n ? params extends ''\n ? never\n : string extends params\n ? readonly AbiParameter[]\n : ParseAbiParameters_, { modifier: Modifier }>\n : never)\n | (params extends readonly string[]\n ? string[] extends params\n ? AbiParameter // Return generic AbiParameter item since type was no inferrable\n : ParseStructs extends infer structs\n ? {\n [key in keyof params]: params[key] extends string\n ? IsStructSignature extends true\n ? never\n : ParseAbiParameters_<\n SplitParameters,\n { modifier: Modifier; structs: structs }\n >\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends readonly [...infer content]\n ? content['length'] extends 0\n ? never\n : DeepFlatten\n : never\n : never\n : never\n : never)\n\n/**\n * Flatten all members of {@link T}\n *\n * @param T - List of items to flatten\n * @param Acc - The accumulator used while recursing\n * @returns The flattened array\n *\n * @example\n * type Result = DeepFlatten<[['a', 'b'], [['c']]]>\n * // ^? type Result = ['a', 'b', 'c']\n */\ntype DeepFlatten<\n T extends readonly unknown[],\n Acc extends readonly unknown[] = readonly [],\n> = T extends readonly [infer head, ...infer tail]\n ? tail extends undefined\n ? never\n : head extends readonly unknown[]\n ? DeepFlatten]>\n : DeepFlatten\n : Acc\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * const abiParameters = parseAbiParameters('address from, address to, uint256 amount')\n * // ^? const abiParameters: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * const abiParameters = parseAbiParameters([\n * // ^? const abiParameters: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * 'Baz bar',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n>(\n params: Narrow &\n (\n | (params extends string\n ? params extends ''\n ? Error<'Empty string is not allowed.'>\n : unknown\n : never)\n | (params extends readonly string[]\n ? params extends readonly [] // empty array\n ? Error<'At least one parameter required.'>\n : string[] extends params\n ? unknown\n : unknown // TODO: Validate param string\n : never)\n ),\n): ParseAbiParameters {\n const abiParameters: AbiParameter[] = []\n if (typeof params === 'string') {\n const parameters = splitParameters(params)\n const length = parameters.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(parseAbiParameter_(parameters[i]!, { modifiers }))\n }\n } else {\n const structs = parseStructs(params as readonly string[])\n const length = params.length as number\n for (let i = 0; i < length; i++) {\n const signature = (params as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n const parameters = splitParameters(signature)\n const length = parameters.length\n for (let k = 0; k < length; k++) {\n abiParameters.push(\n parseAbiParameter_(parameters[k]!, { modifiers, structs }),\n )\n }\n }\n }\n\n if (abiParameters.length === 0)\n throw new InvalidAbiParametersError({ params })\n\n return abiParameters as ParseAbiParameters\n}\n","export type {\n Abi,\n AbiConstructor,\n AbiError,\n AbiEvent,\n AbiEventParameter,\n AbiFallback,\n AbiFunction,\n AbiInternalType,\n AbiItemType,\n AbiParameter,\n AbiParameterKind,\n AbiReceive,\n AbiStateMutability,\n AbiType,\n Address,\n SolidityAddress,\n SolidityArray,\n SolidityArrayWithoutTuple,\n SolidityArrayWithTuple,\n SolidityBool,\n SolidityBytes,\n SolidityFixedArrayRange,\n SolidityFixedArraySizeLookup,\n SolidityFunction,\n SolidityInt,\n SolidityString,\n SolidityTuple,\n TypedData,\n TypedDataDomain,\n TypedDataParameter,\n TypedDataType,\n} from '../abi.js'\n\n// biome-ignore lint/performance/noBarrelFile: \nexport { BaseError } from '../errors.js'\n\nexport type { Narrow } from '../narrow.js'\nexport { narrow } from '../narrow.js'\n\nexport type {\n Register,\n DefaultRegister,\n ResolvedRegister,\n} from '../register.js'\n\nexport type {\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n AbiTypeToPrimitiveType,\n ExtractAbiError,\n ExtractAbiErrorNames,\n ExtractAbiErrors,\n ExtractAbiEvent,\n ExtractAbiEventNames,\n ExtractAbiEvents,\n ExtractAbiFunction,\n ExtractAbiFunctionNames,\n ExtractAbiFunctions,\n IsAbi,\n IsTypedData,\n TypedDataToPrimitiveTypes,\n} from '../utils.js'\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Human-Readable\n\nexport {\n formatAbi,\n type FormatAbi,\n} from '../human-readable/formatAbi.js'\n\nexport {\n formatAbiItem,\n type FormatAbiItem,\n} from '../human-readable/formatAbiItem.js'\n\nexport {\n formatAbiParameter,\n type FormatAbiParameter,\n} from '../human-readable/formatAbiParameter.js'\n\nexport {\n formatAbiParameters,\n type FormatAbiParameters,\n} from '../human-readable/formatAbiParameters.js'\n\nexport { parseAbi, type ParseAbi } from '../human-readable/parseAbi.js'\n\nexport {\n parseAbiItem,\n type ParseAbiItem,\n} from '../human-readable/parseAbiItem.js'\n\nexport {\n parseAbiParameter,\n type ParseAbiParameter,\n} from '../human-readable/parseAbiParameter.js'\n\nexport {\n parseAbiParameters,\n type ParseAbiParameters,\n} from '../human-readable/parseAbiParameters.js'\n\nexport {\n UnknownTypeError,\n InvalidAbiItemError,\n UnknownSolidityTypeError,\n} from '../human-readable/errors/abiItem.js'\n\nexport {\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n SolidityProtectedKeywordError,\n InvalidParameterError,\n InvalidAbiParametersError,\n InvalidAbiParameterError,\n} from '../human-readable/errors/abiParameter.js'\n\nexport {\n InvalidStructSignatureError,\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../human-readable/errors/signature.js'\n\nexport { InvalidParenthesisError } from '../human-readable/errors/splitParameters.js'\n\nexport { CircularReferenceError } from '../human-readable/errors/struct.js'\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","export const version = '2.46.3'\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 { 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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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 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 IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\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 =\n | HexToBigIntErrorType\n | IntegerOutOfRangeErrorType\n | 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 const value = hexToBigInt(hex, opts)\n const number = Number(value)\n if (!Number.isSafeInteger(number))\n throw new IntegerOutOfRangeError({\n max: `${Number.MAX_SAFE_INTEGER}`,\n min: `${Number.MIN_SAFE_INTEGER}`,\n signed: opts.signed,\n size: opts.size,\n value: `${value}n`,\n })\n return number\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","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * Internal webcrypto alias.\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 * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\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","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\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';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\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\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\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\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 abstract clone(): T;\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\n/** Hash function */\nexport type CHash = ReturnType;\n/** Hash function with output */\nexport type CHashO = ReturnType;\n/** XOF with output */\nexport type CHashXO = ReturnType;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher>(\n hashCons: () => Hash\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash;\n} {\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 createOptHasher, T extends Object>(\n hashCons: (opts?: T) => Hash\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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 createXOFer, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\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 Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\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 IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\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/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\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 clean(B);\n}\n\n/** Keccak sponge function. */\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\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\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(): void {\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): 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(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\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 createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__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 { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.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 { 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 { 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'\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 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 { 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","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","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 AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\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 boolToHex,\n type NumberToHexErrorType,\n numberToHex,\n type StringToHexErrorType,\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, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\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 { 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 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\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 (\n argType === 'object' &&\n isArgOfType(\n Object.values(arg as unknown[] | Record)[\n index\n ],\n component as AbiParameter,\n )\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","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","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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.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 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 { 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 = NegativeOffsetErrorType | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetErrorType | 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 ?? bytes,\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 assertSize,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\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 {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.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 AbiParameterKind,\n true\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 never\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, 10), 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', 10)\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 { AbiParameter } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\nimport { stringify } from '../stringify.js'\n\nexport type FormatAbiItemWithArgsErrorType = ErrorType\n\nexport function formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName = true,\n includeName = false,\n}: {\n abiItem: AbiItem\n args: readonly unknown[]\n includeFunctionName?: boolean | undefined\n includeName?: boolean | undefined\n}) {\n if (!('name' in abiItem)) return\n if (!('inputs' in abiItem)) return\n if (!abiItem.inputs) return\n return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n .map(\n (input: AbiParameter, i: number) =>\n `${includeName && input.name ? `${input.name}: ` : ''}${\n typeof args[i] === 'object' ? stringify(args[i]) : args[i]\n }`,\n )\n .join(', ')})`\n}\n","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 {\n TransactionReceipt,\n TransactionType,\n} 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 TransactionReceiptRevertedErrorType =\n TransactionReceiptRevertedError & {\n name: 'TransactionReceiptRevertedError'\n }\nexport class TransactionReceiptRevertedError extends BaseError {\n receipt: TransactionReceipt\n\n constructor({ receipt }: { receipt: TransactionReceipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n })\n\n this.receipt = receipt\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 raw?: Hex | 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\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://4byte.sourcify.dev/?q=${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.raw = data\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 { 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 url: string\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 this.url = url\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n url: string\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 this.url = url\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n url: string | undefined\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 this.url = url\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n url: string\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 this.url = url\n }\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n | -1\n | -32700 // Parse error\n | -32600 // Invalid request\n | -32601 // Method not found\n | -32602 // Invalid params\n | -32603 // Internal error\n | -32000 // Invalid input\n | -32001 // Resource not found\n | -32002 // Resource unavailable\n | -32003 // Transaction rejected\n | -32004 // Method not supported\n | -32005 // Limit exceeded\n | -32006 // JSON-RPC version not supported\n | -32042 // Method not found\n\ntype RpcErrorOptions = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : (code ?? unknownErrorCode)\n ) as code_\n }\n}\n\nexport type ProviderRpcErrorCode =\n | 4001 // User Rejected Request\n | 4100 // Unauthorized\n | 4200 // Unsupported Method\n | 4900 // Disconnected\n | 4901 // Chain Disconnected\n | 4902 // Chain Not Recognized\n | 5700 // Unsupported non-optional capability\n | 5710 // Unsupported chain id\n | 5720 // Duplicate ID\n | 5730 // Unknown bundle id\n | 5740 // Bundle too large\n | 5750 // Atomic-ready wallet rejected upgrade\n | 5760 // Atomicity not supported\n | 7000 // WalletConnect Session Settlement Failed\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n T = undefined,\n> extends RpcError {\n data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions & {\n data?: T | undefined\n }\n >,\n ) {\n super(cause, options)\n\n this.data = options.data\n }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n code: -32700\n name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage:\n 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n })\n }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n code: -32600\n name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n code: -32601\n name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n code: -32602\n name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n code: -32603\n name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n code: -32000\n name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n code: -32001\n name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n override name = 'ResourceNotFoundRpcError'\n static code = -32001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n })\n }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n code: -32002\n name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n })\n }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n code: -32003\n name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n code: -32004\n name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not supported.`,\n })\n }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n code: -32005\n name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n })\n }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n JsonRpcVersionUnsupportedError & {\n code: -32006\n name: 'JsonRpcVersionUnsupportedError'\n }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n })\n }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n code: 4001\n name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n code: 4100\n name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage:\n 'The requested method and/or account has not been authorized by the user.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n UnsupportedProviderMethodError & {\n code: 4200\n name: 'UnsupportedProviderMethodError'\n }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n code: 4900\n name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n })\n }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n code: 4901\n name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n code: 4902\n name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported non-optional capability\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedNonOptionalCapabilityErrorType =\n UnsupportedNonOptionalCapabilityError & {\n code: 5700\n name: 'UnsupportedNonOptionalCapabilityError'\n }\nexport class UnsupportedNonOptionalCapabilityError extends ProviderRpcError {\n static code = 5700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedNonOptionalCapabilityError.code,\n name: 'UnsupportedNonOptionalCapabilityError',\n shortMessage:\n 'This Wallet does not support a capability that was not marked as optional.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported chain id\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedChainIdErrorType = UnsupportedChainIdError & {\n code: 5710\n name: 'UnsupportedChainIdError'\n}\nexport class UnsupportedChainIdError extends ProviderRpcError {\n static code = 5710 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedChainIdError.code,\n name: 'UnsupportedChainIdError',\n shortMessage: 'This Wallet does not support the requested chain ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Duplicate ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type DuplicateIdErrorType = DuplicateIdError & {\n code: 5720\n name: 'DuplicateIdError'\n}\nexport class DuplicateIdError extends ProviderRpcError {\n static code = 5720 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: DuplicateIdError.code,\n name: 'DuplicateIdError',\n shortMessage: 'There is already a bundle submitted with this ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unknown bundle ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnknownBundleIdErrorType = UnknownBundleIdError & {\n code: 5730\n name: 'UnknownBundleIdError'\n}\nexport class UnknownBundleIdError extends ProviderRpcError {\n static code = 5730 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnknownBundleIdError.code,\n name: 'UnknownBundleIdError',\n shortMessage: 'This bundle id is unknown / has not been submitted',\n })\n }\n}\n\n/**\n * Subclass for an \"Bundle too large\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type BundleTooLargeErrorType = BundleTooLargeError & {\n code: 5740\n name: 'BundleTooLargeError'\n}\nexport class BundleTooLargeError extends ProviderRpcError {\n static code = 5740 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: BundleTooLargeError.code,\n name: 'BundleTooLargeError',\n shortMessage: 'The call bundle is too large for the Wallet to process.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomic-ready wallet rejected upgrade\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicReadyWalletRejectedUpgradeErrorType =\n AtomicReadyWalletRejectedUpgradeError & {\n code: 5750\n name: 'AtomicReadyWalletRejectedUpgradeError'\n }\nexport class AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {\n static code = 5750 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicReadyWalletRejectedUpgradeError.code,\n name: 'AtomicReadyWalletRejectedUpgradeError',\n shortMessage:\n 'The Wallet can support atomicity after an upgrade, but the user rejected the upgrade.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomicity not supported\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicityNotSupportedErrorType = AtomicityNotSupportedError & {\n code: 5760\n name: 'AtomicityNotSupportedError'\n}\nexport class AtomicityNotSupportedError extends ProviderRpcError {\n static code = 5760 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicityNotSupportedError.code,\n name: 'AtomicityNotSupportedError',\n shortMessage:\n 'The wallet does not support atomic execution but the request requires it.',\n })\n }\n}\n\n/**\n * Subclass for a \"Session Settlement Failed\" WalletConnect error.\n *\n * WalletConnect https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n */\nexport type WalletConnectSessionSettlementErrorType =\n WalletConnectSessionSettlementError & {\n code: 7000\n name: 'WalletConnectSessionSettlementError'\n }\nexport class WalletConnectSessionSettlementError extends ProviderRpcError {\n static code = 7000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: WalletConnectSessionSettlementError.code,\n name: 'WalletConnectSessionSettlementError',\n shortMessage: 'WalletConnect session settlement failed.',\n })\n }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\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","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): 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/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\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 protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\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 clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\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(): Uint8Array {\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 clone(): HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC;\n} = (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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * hash-to-curve from RFC 9380.\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\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.ts';\nimport { FpInvertBatch, type IField, mod } from './modular.ts';\nimport type { CHash } from './utils.ts';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.ts';\n\nexport type UnicodeOrBytes = string | Uint8Array;\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 */\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/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\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/**\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 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\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 * [RFC 9380 5.2](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 type XY = (x: T, y: T) => { x: T; y: T };\nexport type XYRatio = [T[], T[], T[], T[]]; // xn/xd, yn/yd\nexport function isogenyMap>(field: F, map: XYRatio): XY {\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 [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\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 };\nexport type HTFMethod = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint;\nexport type MapMethod = (scalars: bigint[]) => H2CPoint;\nexport type Hasher = {\n hashToCurve: HTFMethod;\n encodeToCurve: HTFMethod;\n mapToCurve: MapMethod;\n defaults: Opts & { encodeDST?: UnicodeOrBytes };\n};\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n defaults: Opts & { encodeDST?: UnicodeOrBytes }\n): Hasher {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n function map(num: bigint[]) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial: H2CPoint) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n\n return {\n defaults,\n\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): H2CPoint {\n const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options } as Opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\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): H2CPoint {\n const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options } as Opts);\n return clear(map(u[0]));\n },\n\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]): H2CPoint {\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n };\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\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 { AuthorizationRequest } from '../../types/authorization.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type NumberToHexErrorType, numberToHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters =\n AuthorizationRequest & {\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, nonce, to } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n address,\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 { 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|gas required exceeds allowance/\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 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 { 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 { Prettify } from '../../types/utils.js'\n\nexport type DefineFormatterErrorType = ErrorType\n\nexport function defineFormatter(\n type: type,\n format: (args: parameters, action?: string | undefined) => returnType,\n) {\n return <\n parametersOverride,\n returnTypeOverride,\n exclude extends (keyof parameters | keyof parametersOverride)[] = [],\n >({\n exclude,\n format: overrides,\n }: {\n exclude?: exclude | undefined\n format: (\n args: parametersOverride,\n action?: string | undefined,\n ) => returnTypeOverride\n }) => {\n return {\n exclude,\n format: (args: parametersOverride, action?: string | undefined) => {\n const formatted = format(args as any, action)\n if (exclude) {\n for (const key of exclude) {\n delete (formatted as any)[key]\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n } as Prettify & {\n [_key in exclude[number]]: never\n }\n },\n type,\n }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { AuthorizationList } from '../../types/authorization.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type {\n RpcAuthorizationList,\n RpcTransactionRequest,\n} 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 & { account?: Account | undefined },\n _?: string | undefined,\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 (request.account) rpcRequest.from = request.account.address\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.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : 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","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 type { FeeConflictErrorType } 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 { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = 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\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 } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n /** The account address. */\n address: Address\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [\n address,\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : blockTag,\n ],\n },\n {\n dedupe: Boolean(blockNumber),\n },\n )\n return hexToNumber(count)\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","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\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 {\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 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, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/** @internal */\nexport const version = '0.1.1'\n","import { version } from '../version.js'\n\n/** @internal */\nexport function getUrl(url: string) {\n return url\n}\n\n/** @internal */\nexport function getVersion() {\n return version\n}\n\n/** @internal */\nexport function prettyPrint(args: unknown) {\n if (!args) return ''\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","import { getVersion } from './internal/errors.js'\n\nexport type GlobalErrorType = Error & {\n name: name\n}\n\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError<\n cause extends Error | undefined = undefined,\n> extends Error {\n details: string\n docs?: string | undefined\n docsOrigin?: string | undefined\n docsPath?: string | undefined\n shortMessage: string\n showVersion?: boolean | undefined\n version?: string | undefined\n\n override cause: cause\n override name = 'BaseError'\n\n static defaultStaticOptions = {\n docsOrigin: 'https://oxlib.sh',\n showVersion: false,\n version: `ox@${getVersion()}`,\n } satisfies BaseError.GlobalOptions\n\n static setStaticOptions(options: BaseError.GlobalOptions) {\n BaseError.prototype.docsOrigin = options.docsOrigin\n BaseError.prototype.showVersion = options.showVersion\n BaseError.prototype.version = options.version\n }\n\n static {\n BaseError.setStaticOptions(BaseError.defaultStaticOptions)\n }\n\n constructor(shortMessage: string, options: BaseError.Options = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details) return options.cause.details\n if (options.cause.shortMessage) return options.cause.shortMessage\n }\n if (\n options.cause &&\n 'details' in options.cause &&\n typeof options.cause.details === 'string'\n )\n return options.cause.details\n if (options.cause?.message) return options.cause.message\n return options.details!\n })()\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath\n return options.docsPath\n })()\n\n const docsBaseUrl = options.docsOrigin ?? BaseError.prototype.docsOrigin\n const docs = `${docsBaseUrl}${docsPath ?? ''}`\n const showVersion = Boolean(\n options.version ?? BaseError.prototype.showVersion,\n )\n const version = options.version ?? BaseError.prototype.version\n\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath || showVersion\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n showVersion ? `Version: ${version}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n')\n\n super(message, options.cause ? { cause: options.cause } : undefined)\n\n this.cause = options.cause as any\n this.details = details\n this.docs = docs\n this.docsOrigin = docsBaseUrl\n this.docsPath = docsPath\n this.shortMessage = shortMessage\n this.showVersion = showVersion\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\nexport declare namespace BaseError {\n type Options = {\n /** Cause of the error. */\n cause?: cause | undefined\n /** Details of the error. */\n details?: string | undefined\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Path of the docs. */\n docsPath?: string | undefined\n /** Meta messages to add to the error. */\n metaMessages?: (string | undefined)[] | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n\n type GlobalOptions = {\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Whether to show the version of the library in the error message. */\n showVersion?: boolean | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n}\n\n/** @internal */\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import * as Bytes from '../Bytes.js'\nimport type * as Errors from '../Errors.js'\n\n/** @internal */\nexport function assertSize(bytes: Bytes.Bytes, size_: number): void {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Bytes.size.ErrorType\n | Bytes.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n export type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start\n ) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n })\n }\n}\n\n/** @internal */\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\n/** @internal */\nexport function 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\n/** @internal */\nexport function pad(bytes: Bytes.Bytes, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n if (size === 0) return bytes\n if (bytes.length > size)\n throw new Bytes.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\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Bytes.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Bytes.Bytes,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value\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 return data as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\n\n/** @internal */\nexport function assertSize(hex: Hex.Hex, size_: number): void {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Hex.size.ErrorType\n | Hex.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(value: Hex.Hex, start?: number | undefined) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Hex.Hex,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start\n ) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n })\n }\n}\n\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function pad(hex_: Hex.Hex, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n\n if (size === 0) return hex_\n\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}` as Hex.Hex\n}\n\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n type ErrorType = Hex.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Hex.Hex,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value.replace('0x', '')\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 (data === '0') return '0x'\n if (dir === 'right' && data.length % 2 === 1) return `0x${data}0`\n return `0x${data}` as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Hex.Hex\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from './Errors.js'\n\nconst bigIntSuffix = '#__bigint'\n\n/**\n * Serializes a value to a canonical JSON string as defined by\n * [RFC 8785 (JSON Canonicalization Scheme)](https://www.rfc-editor.org/rfc/rfc8785).\n *\n * - Object keys are sorted recursively by UTF-16 code unit comparison.\n * - Primitives are serialized per ECMAScript rules (no trailing zeros on numbers, etc.).\n * - No whitespace is inserted.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ b: 2, a: 1 })\n * // @log: '{\"a\":1,\"b\":2}'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ z: [3, { y: 1, x: 2 }], a: 'hello' })\n * // @log: '{\"a\":\"hello\",\"z\":[3,{\"x\":2,\"y\":1}]}'\n * ```\n *\n * @param value - The value to canonicalize.\n * @returns The canonical JSON string.\n */\nexport function canonicalize(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'string')\n return JSON.stringify(value)\n if (typeof value === 'number') {\n if (!Number.isFinite(value))\n throw new TypeError('Cannot canonicalize non-finite number')\n return Object.is(value, -0) ? '0' : JSON.stringify(value)\n }\n if (typeof value === 'bigint')\n throw new TypeError('Cannot canonicalize bigint')\n if (Array.isArray(value))\n return `[${value.map((item) => canonicalize(item)).join(',')}]`\n if (typeof value === 'object') {\n const entries = Object.keys(value as Record)\n .sort()\n .reduce((acc, key) => {\n const v = (value as Record)[key]\n if (v !== undefined)\n acc.push(`${JSON.stringify(key)}:${canonicalize(v)}`)\n return acc\n }, [])\n return `{${entries.join(',')}}`\n }\n return undefined as never\n}\n\nexport declare namespace canonicalize {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(\n string: string,\n reviver?: ((this: any, key: string, value: any) => any) | undefined,\n) {\n return JSON.parse(string, (key, value_) => {\n const value = value_\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length))\n return typeof reviver === 'function' ? reviver(key, value) : value\n })\n}\n\nexport declare namespace parse {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(\n value: any,\n replacer?: ((this: any, key: string, value: any) => any) | null | undefined,\n space?: string | number | undefined,\n) {\n return JSON.stringify(\n value,\n (key, value) => {\n if (typeof replacer === 'function') return replacer(key, value)\n if (typeof value === 'bigint') return value.toString() + bigIntSuffix\n return value\n },\n space,\n )\n}\n\nexport declare namespace stringify {\n type ErrorType = Errors.GlobalErrorType\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/bytes.js'\nimport * as internal_hex from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst decoder = /*#__PURE__*/ new TextDecoder()\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/** Root type for a Bytes array. */\nexport type Bytes = Uint8Array\n\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value: unknown): asserts value is Bytes {\n if (value instanceof Uint8Array) return\n if (!value) throw new InvalidBytesTypeError(value)\n if (typeof value !== 'object') throw new InvalidBytesTypeError(value)\n if (!('BYTES_PER_ELEMENT' in value)) throw new InvalidBytesTypeError(value)\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value)\n}\n\nexport declare namespace assert {\n type ErrorType = InvalidBytesTypeError | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values: readonly Bytes[]): Bytes {\n let length = 0\n for (const arr of values) {\n length += arr.length\n }\n const result = new Uint8Array(length)\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i]\n result.set(arr!, index)\n index += arr!.length\n }\n return result\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value: Hex.Hex | Bytes | readonly number[]): Bytes {\n if (value instanceof Uint8Array) return value\n if (typeof value === 'string') return fromHex(value)\n return fromArray(value)\n}\n\nexport declare namespace from {\n type ErrorType =\n | fromHex.ErrorType\n | fromArray.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value: readonly number[] | Uint8Array): Bytes {\n return value instanceof Uint8Array ? value : new Uint8Array(value)\n}\n\nexport declare namespace fromArray {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value: boolean, options: fromBoolean.Options = {}) {\n const { size } = options\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padLeft(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {\n const { size } = options\n\n let hex = value\n if (size) {\n internal_hex.assertSize(value, size)\n hex = Hex.padRight(value, 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 = internal.charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`,\n )\n }\n bytes[index] = (nibbleLeft << 4) | nibbleRight\n }\n return bytes\n}\n\nexport declare namespace fromHex {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_hex.assertSize.ErrorType\n | Hex.padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(\n value: bigint | number,\n options?: fromNumber.Options | undefined,\n) {\n const hex = Hex.fromNumber(value, options)\n return fromHex(hex)\n}\n\nexport declare namespace fromNumber {\n export type Options = Hex.fromNumber.Options\n\n export type ErrorType =\n | Hex.fromNumber.ErrorType\n | fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Bytes {\n const { size } = options\n\n const bytes = encoder.encode(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padRight(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromString {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA: Bytes, bytesB: Bytes) {\n return equalBytes(bytesA, bytesB)\n}\n\nexport declare namespace isEqual {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(\n value: Bytes,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(\n value: Bytes,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length: number): Bytes {\n return crypto.getRandomValues(new Uint8Array(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value: Bytes): number {\n return value.length\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(\n value: Bytes,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Bytes {\n const { strict } = options\n internal.assertStartOffset(value, start)\n const value_ = value.slice(start, end)\n if (strict) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n export type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes: Bytes, options: toBigInt.Options = {}): bigint {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toBigInt(hex, options)\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(\n bytes: Bytes,\n options: toBoolean.Options = {},\n): boolean {\n const { size } = options\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimLeft(bytes_)\n }\n if (bytes_.length > 1 || bytes_[0]! > 1)\n throw new InvalidBytesBooleanError(bytes_)\n return Boolean(bytes_[0])\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes, options: toHex.Options = {}): Hex.Hex {\n return Hex.fromBytes(value, options)\n}\n\nexport declare namespace toHex {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes: Bytes, options: toNumber.Options = {}): number {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toNumber(hex, options)\n}\n\nexport declare namespace toNumber {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes: Bytes, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimRight(bytes_)\n }\n return decoder.decode(bytes_)\n}\n\nexport declare namespace toString {\n export type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n export type ErrorType =\n | internal.assertSize.ErrorType\n | trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n export type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value: unknown): value is Bytes {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesBooleanError'\n\n constructor(bytes: Bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n })\n }\n}\n\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`,\n {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Bytes.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as internal_bytes from './internal/bytes.js'\nimport * as internal from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\n/** Root type for a Hex string. */\nexport type Hex = `0x${string}`\n\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(\n value: unknown,\n options: assert.Options = {},\n): asserts value is Hex {\n const { strict = false } = options\n if (!value) throw new InvalidHexTypeError(value)\n if (typeof value !== 'string') throw new InvalidHexTypeError(value)\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value)) throw new InvalidHexValueError(value)\n }\n if (!value.startsWith('0x')) throw new InvalidHexValueError(value)\n}\n\nexport declare namespace assert {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | InvalidHexTypeError\n | InvalidHexValueError\n | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values: readonly Hex[]): Hex {\n return `0x${(values as Hex[]).reduce((acc, x) => acc + x.replace('0x', ''), '')}`\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value: Hex | Bytes.Bytes | readonly number[]): Hex {\n if (value instanceof Uint8Array) return fromBytes(value)\n if (Array.isArray(value)) return fromBytes(new Uint8Array(value))\n return value as never\n}\n\nexport declare namespace from {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(\n value: boolean,\n options: fromBoolean.Options = {},\n): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padLeft(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(\n value: Bytes.Bytes,\n options: fromBytes.Options = {},\n): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) string += hexes[value[i]!]\n const hex = `0x${string}` as const\n\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padRight(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBytes {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(\n value: number | bigint,\n options: fromNumber.Options = {},\n): Hex {\n const { signed, size } = options\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 stringValue = (\n signed && value_ < 0 ? BigInt.asUintN(size * 8, BigInt(value_)) : value_\n ).toString(16)\n\n const hex = `0x${stringValue}` as Hex\n if (size) return padLeft(hex, size) as Hex\n return hex\n}\n\nexport declare namespace fromNumber {\n type Options =\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\n type ErrorType =\n | IntegerOutOfRangeError\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Hex {\n return fromBytes(encoder.encode(value), options)\n}\n\nexport declare namespace fromString {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA: Hex, hexB: Hex) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB))\n}\n\nexport declare namespace isEqual {\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(\n value: Hex,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(\n value: Hex,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length: number): Hex {\n return fromBytes(Bytes.random(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(\n value: Hex,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Hex {\n const { strict } = options\n internal.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) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value: Hex): number {\n return Math.ceil((value.length - 2) / 2)\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value: Hex): trimLeft.ReturnType {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value: Hex): trimRight.ReturnType {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {\n const { signed } = options\n\n if (options.size) internal.assertSize(hex, options.size)\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n\n const max_signed = max_unsigned >> 1n\n\n if (value <= max_signed) return value\n return value - max_unsigned - 1n\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType = internal.assertSize.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex: Hex, options: toBoolean.Options = {}): boolean {\n if (options.size) internal.assertSize(hex, options.size)\n const hex_ = trimLeft(hex)\n if (hex_ === '0x') return false\n if (hex_ === '0x1') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | InvalidHexBooleanError\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex: Hex, options: toBytes.Options = {}): Bytes.Bytes {\n return Bytes.fromHex(hex, options)\n}\n\nexport declare namespace toBytes {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex: Hex, options: toNumber.Options = {}): number {\n const { signed, size } = options\n if (!signed && !size) return Number(hex)\n return Number(toBigInt(hex, options))\n}\n\nexport declare namespace toNumber {\n type Options = toBigInt.Options\n\n type ErrorType = toBigInt.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex: Hex, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes = Bytes.fromHex(hex)\n if (size) {\n internal_bytes.assertSize(bytes, size)\n bytes = Bytes.trimRight(bytes)\n }\n return new TextDecoder().decode(bytes)\n}\n\nexport declare namespace toString {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_bytes.assertSize.ErrorType\n | Bytes.fromHex.ErrorType\n | Bytes.trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(\n value: unknown,\n options: validate.Options = {},\n): value is Hex {\n const { strict = false } = options\n try {\n assert(value, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n override readonly name = 'Hex.IntegerOutOfRangeError'\n\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` : ''\n }${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`,\n )\n }\n}\n\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexBooleanError'\n\n constructor(hex: Hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`,\n {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexValueError'\n\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidLengthError'\n\n constructor(value: Hex) {\n super(\n `Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`,\n {\n metaMessages: ['It must be an even length.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Hex.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Hex.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Hex.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/** A Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Withdrawal = {\n address: Hex.Hex\n amount: bigintType\n index: numberType\n validatorIndex: numberType\n}\n\n/** An RPC Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Rpc = Withdrawal\n\n/**\n * Converts a {@link ox#Withdrawal.Rpc} to an {@link ox#Withdrawal.Withdrawal}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.fromRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: '0x620323',\n * index: '0x0',\n * validatorIndex: '0x1',\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: 6423331n,\n * // @log: index: 0,\n * // @log: validatorIndex: 1\n * // @log: }\n * ```\n *\n * @param withdrawal - The RPC withdrawal to convert.\n * @returns An instantiated {@link ox#Withdrawal.Withdrawal}.\n */\nexport function fromRpc(withdrawal: Rpc): Withdrawal {\n return {\n ...withdrawal,\n amount: BigInt(withdrawal.amount),\n index: Number(withdrawal.index),\n validatorIndex: Number(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace fromRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Withdrawal.Withdrawal} to an {@link ox#Withdrawal.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.toRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: 6423331n,\n * index: 0,\n * validatorIndex: 1,\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: '0x620323',\n * // @log: index: '0x0',\n * // @log: validatorIndex: '0x1',\n * // @log: }\n * ```\n *\n * @param withdrawal - The Withdrawal to convert.\n * @returns An RPC Withdrawal.\n */\nexport function toRpc(withdrawal: Withdrawal): Rpc {\n return {\n address: withdrawal.address,\n amount: Hex.fromNumber(withdrawal.amount),\n index: Hex.fromNumber(withdrawal.index),\n validatorIndex: Hex.fromNumber(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace toRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Address from './Address.js'\nimport * as Hex from './Hex.js'\nimport * as Withdrawal from './Withdrawal.js'\n\n/**\n * Block overrides.\n */\nexport type BlockOverrides = {\n /** Base fee per gas. */\n baseFeePerGas?: bigintType | undefined\n /** Blob base fee. */\n blobBaseFee?: bigintType | undefined\n /** Fee recipient (also known as coinbase). */\n feeRecipient?: Address.Address | undefined\n /** Gas limit. */\n gasLimit?: bigintType | undefined\n /** Block number. */\n number?: bigintType | undefined\n /** The previous value of randomness beacon. */\n prevRandao?: bigintType | undefined\n /** Block timestamp. */\n time?: bigintType | undefined\n /** Withdrawals made by validators. */\n withdrawals?: Withdrawal.Withdrawal[] | undefined\n}\n\n/**\n * RPC block overrides.\n */\nexport type Rpc = BlockOverrides\n\n/**\n * Converts an {@link ox#BlockOverrides.Rpc} to an {@link ox#BlockOverrides.BlockOverrides}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.fromRpc({\n * baseFeePerGas: '0x1',\n * blobBaseFee: '0x2',\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: '0x4',\n * number: '0x5',\n * prevRandao: '0x6',\n * time: '0x1234567890',\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: '0x1',\n * index: '0x0',\n * validatorIndex: '0x1',\n * },\n * ],\n * })\n * ```\n *\n * @param rpcBlockOverrides - The RPC block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.BlockOverrides}.\n */\nexport function fromRpc(rpcBlockOverrides: Rpc): BlockOverrides {\n return {\n ...(rpcBlockOverrides.baseFeePerGas && {\n baseFeePerGas: BigInt(rpcBlockOverrides.baseFeePerGas),\n }),\n ...(rpcBlockOverrides.blobBaseFee && {\n blobBaseFee: BigInt(rpcBlockOverrides.blobBaseFee),\n }),\n ...(rpcBlockOverrides.feeRecipient && {\n feeRecipient: rpcBlockOverrides.feeRecipient,\n }),\n ...(rpcBlockOverrides.gasLimit && {\n gasLimit: BigInt(rpcBlockOverrides.gasLimit),\n }),\n ...(rpcBlockOverrides.number && {\n number: BigInt(rpcBlockOverrides.number),\n }),\n ...(rpcBlockOverrides.prevRandao && {\n prevRandao: BigInt(rpcBlockOverrides.prevRandao),\n }),\n ...(rpcBlockOverrides.time && {\n time: BigInt(rpcBlockOverrides.time),\n }),\n ...(rpcBlockOverrides.withdrawals && {\n withdrawals: rpcBlockOverrides.withdrawals.map(Withdrawal.fromRpc),\n }),\n }\n}\n\n/**\n * Converts an {@link ox#BlockOverrides.BlockOverrides} to an {@link ox#BlockOverrides.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.toRpc({\n * baseFeePerGas: 1n,\n * blobBaseFee: 2n,\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: 4n,\n * number: 5n,\n * prevRandao: 6n,\n * time: 78187493520n,\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: 1n,\n * index: 0,\n * validatorIndex: 1,\n * },\n * ],\n * })\n * ```\n *\n * @param blockOverrides - The block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.Rpc}.\n */\nexport function toRpc(blockOverrides: BlockOverrides): Rpc {\n return {\n ...(typeof blockOverrides.baseFeePerGas === 'bigint' && {\n baseFeePerGas: Hex.fromNumber(blockOverrides.baseFeePerGas),\n }),\n ...(typeof blockOverrides.blobBaseFee === 'bigint' && {\n blobBaseFee: Hex.fromNumber(blockOverrides.blobBaseFee),\n }),\n ...(typeof blockOverrides.feeRecipient === 'string' && {\n feeRecipient: blockOverrides.feeRecipient,\n }),\n ...(typeof blockOverrides.gasLimit === 'bigint' && {\n gasLimit: Hex.fromNumber(blockOverrides.gasLimit),\n }),\n ...(typeof blockOverrides.number === 'bigint' && {\n number: Hex.fromNumber(blockOverrides.number),\n }),\n ...(typeof blockOverrides.prevRandao === 'bigint' && {\n prevRandao: Hex.fromNumber(blockOverrides.prevRandao),\n }),\n ...(typeof blockOverrides.time === 'bigint' && {\n time: Hex.fromNumber(blockOverrides.time),\n }),\n ...(blockOverrides.withdrawals && {\n withdrawals: blockOverrides.withdrawals.map(Withdrawal.toRpc),\n }),\n }\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 {\n inputs: [\n {\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n\nexport const batchGatewayAbi = [\n {\n name: 'query',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n type: 'tuple[]',\n name: 'queries',\n components: [\n {\n type: 'address',\n name: 'sender',\n },\n {\n type: 'string[]',\n name: 'urls',\n },\n {\n type: 'bytes',\n name: 'data',\n },\n ],\n },\n ],\n outputs: [\n {\n type: 'bool[]',\n name: 'failures',\n },\n {\n type: 'bytes[]',\n name: 'responses',\n },\n ],\n },\n {\n name: 'HttpError',\n type: 'error',\n inputs: [\n {\n type: 'uint16',\n name: 'status',\n },\n {\n type: 'string',\n name: 'message',\n },\n ],\n },\n] as const\n\nconst universalResolverErrors = [\n {\n inputs: [\n {\n name: 'dns',\n type: 'bytes',\n },\n ],\n name: 'DNSDecodingFailed',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'ens',\n type: 'string',\n },\n ],\n name: 'DNSEncodingFailed',\n type: 'error',\n },\n {\n inputs: [],\n name: 'EmptyAddress',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'HttpError',\n type: 'error',\n },\n {\n inputs: [],\n name: 'InvalidBatchGatewayResponse',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'errorData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n {\n name: 'resolver',\n type: 'address',\n },\n ],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n ],\n name: 'ResolverNotFound',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'primary',\n type: 'string',\n },\n {\n name: 'primaryAddress',\n type: 'bytes',\n },\n ],\n name: 'ReverseAddressMismatch',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'selector',\n type: 'bytes4',\n },\n ],\n name: 'UnsupportedResolverProfile',\n type: 'error',\n },\n] as const\n\nexport const universalResolverResolveAbi = [\n ...universalResolverErrors,\n {\n name: 'resolveWithGateways',\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: 'reverseWithGateways',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'uint256', name: 'coinType' },\n { type: 'string[]', name: 'gateways' },\n ],\n outputs: [\n { type: 'string', name: 'resolvedName' },\n { type: 'address', name: 'resolver' },\n { type: 'address', name: 'reverseResolver' },\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 erc1271Abi = [\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 erc6492SignatureValidatorAbi = [\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-1155 Multi Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-1155) */\nexport const erc1155Abi = [\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'needed',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InsufficientBalance',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'approver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidApprover',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: 'idsLength',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'valuesLength',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InvalidArrayLength',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidOperator',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidReceiver',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidSender',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'ERC1155MissingApprovalForAll',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n ],\n name: 'TransferBatch',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'TransferSingle',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'string',\n name: 'value',\n type: 'string',\n },\n {\n indexed: true,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'URI',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address[]',\n name: 'accounts',\n type: 'address[]',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n ],\n name: 'balanceOfBatch',\n outputs: [\n {\n internalType: 'uint256[]',\n name: '',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'isApprovedForAll',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'interfaceId',\n type: 'bytes4',\n },\n ],\n name: 'supportsInterface',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'uri',\n outputs: [\n {\n internalType: 'string',\n name: '',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\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: 'tokenId',\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 erc6492SignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\nexport const multicall3Bytecode =\n '0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033'\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 { 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 {\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 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","/** @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 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 { Abi, AbiStateMutability } from 'abitype'\n\nimport { AbiFunctionSignatureNotFoundError } from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type SliceErrorType, 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 DecodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = {\n abi: abi\n data: Hex\n}\n\nexport type DecodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allFunctionNames extends\n ContractFunctionName = ContractFunctionName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [functionName in allFunctionNames]: {\n args: ContractFunctionArgs\n functionName: functionName\n }\n }[allFunctionNames]\n >\n : {\n args: readonly unknown[] | undefined\n functionName: string\n }\n\nexport type DecodeFunctionDataErrorType =\n | AbiFunctionSignatureNotFoundError\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | SliceErrorType\n | ErrorType\n\nexport function decodeFunctionData(\n parameters: DecodeFunctionDataParameters,\n) {\n const { abi, data } = parameters as DecodeFunctionDataParameters\n const signature = slice(data, 0, 4)\n const description = abi.find(\n (x) =>\n x.type === 'function' &&\n signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!description)\n throw new AbiFunctionSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeFunctionData',\n })\n return {\n functionName: (description as { name: string }).name,\n args: ('inputs' in description &&\n description.inputs &&\n description.inputs.length > 0\n ? decodeAbiParameters(description.inputs, slice(data, 4))\n : undefined) as readonly unknown[] | undefined,\n } as DecodeFunctionDataReturnType\n}\n","import type { Abi, ExtractAbiErrors } from 'abitype'\n\nimport {\n AbiErrorInputsNotFoundError,\n AbiErrorNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\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 { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeErrorResult'\n\nexport type EncodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n errorName extends ContractErrorName | undefined = ContractErrorName,\n ///\n hasErrors = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiErrors] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractErrorArgs<\n abi,\n errorName extends ContractErrorName\n ? errorName\n : ContractErrorName\n >,\n allErrorNames = ContractErrorName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { errorName?: errorName | allErrorNames | undefined }\n : { errorName: errorName | allErrorNames }\n : { errorName?: errorName | allErrorNames | undefined }\n> &\n (hasErrors extends true ? unknown : never)\n\nexport type EncodeErrorResultReturnType = Hex\n\nexport type EncodeErrorResultErrorType =\n | GetAbiItemErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | EncodeAbiParametersErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function encodeErrorResult<\n const abi extends Abi | readonly unknown[],\n errorName extends ContractErrorName | undefined = undefined,\n>(\n parameters: EncodeErrorResultParameters,\n): EncodeErrorResultReturnType {\n const { abi, errorName, args } = parameters as EncodeErrorResultParameters\n\n let abiItem = abi[0]\n if (errorName) {\n const item = getAbiItem({ abi, args, name: errorName })\n if (!item) throw new AbiErrorNotFoundError(errorName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'error')\n throw new AbiErrorNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toFunctionSelector(definition)\n\n let data: Hex = '0x'\n if (args && args.length > 0) {\n if (!abiItem.inputs)\n throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath })\n data = encodeAbiParameters(abiItem.inputs, args)\n }\n return concatHex([signature, data])\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n AbiFunctionOutputsNotFoundError,\n InvalidArrayError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionName,\n ContractFunctionReturnType,\n} from '../../types/contract.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 GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionResult'\n\nexport type EncodeFunctionResultParameters<\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 allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n result?:\n | ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n never // allow all args. required for overloads to work.\n >\n | undefined\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 (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionResultReturnType = Hex\n\nexport type EncodeFunctionResultErrorType =\n | AbiFunctionOutputsNotFoundError\n | AbiFunctionNotFoundError\n | EncodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function encodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionResultParameters,\n): EncodeFunctionResultReturnType {\n const { abi, functionName, result } =\n parameters as EncodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, 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\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath })\n\n const values = (() => {\n if (abiItem.outputs.length === 0) return []\n if (abiItem.outputs.length === 1) return [result]\n if (Array.isArray(result)) return result\n throw new InvalidArrayError(result)\n })()\n\n return encodeAbiParameters(abiItem.outputs, values)\n}\n","import { batchGatewayAbi } from '../../constants/abis.js'\nimport { solidityError } from '../../constants/solidity.js'\nimport type { Hex } from '../../types/misc.js'\nimport { decodeFunctionData } from '../abi/decodeFunctionData.js'\nimport { encodeErrorResult } from '../abi/encodeErrorResult.js'\nimport { encodeFunctionResult } from '../abi/encodeFunctionResult.js'\nimport type {\n CcipRequestErrorType,\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../ccip.js'\n\nexport const localBatchGatewayUrl = 'x-batch-gateway:true'\n\nexport async function localBatchGatewayRequest(parameters: {\n data: Hex\n ccipRequest: (\n parameters: CcipRequestParameters,\n ) => Promise\n}): Promise {\n const { data, ccipRequest } = parameters\n\n const {\n args: [queries],\n } = decodeFunctionData({ abi: batchGatewayAbi, data })\n\n const failures: boolean[] = []\n const responses: Hex[] = []\n await Promise.all(\n queries.map(async (query, i) => {\n try {\n responses[i] = query.urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({ data: query.data, ccipRequest })\n : await ccipRequest(query)\n failures[i] = false\n } catch (err) {\n failures[i] = true\n responses[i] = encodeError(err as CcipRequestErrorType)\n }\n }),\n )\n\n return encodeFunctionResult({\n abi: batchGatewayAbi,\n functionName: 'query',\n result: [failures, responses],\n })\n}\n\nfunction encodeError(error: CcipRequestErrorType): Hex {\n if (error.name === 'HttpRequestError' && error.status)\n return encodeErrorResult({\n abi: batchGatewayAbi,\n errorName: 'HttpError',\n args: [error.status, error.shortMessage],\n })\n return encodeErrorResult({\n abi: [solidityError],\n errorName: 'Error',\n args: ['shortMessage' in error ? error.shortMessage : error.message],\n })\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Client } from '../clients/createClient.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 { ErrorType } from '../errors/utils.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.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 {\n localBatchGatewayRequest,\n localBatchGatewayUrl,\n} from './ens/localBatchGatewayRequest.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 = urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({\n data: callData,\n ccipRequest: ccipRequest_,\n })\n : 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.toLowerCase()).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","import { type Address, parseAbi } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\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 multicall3Bytecode,\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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } 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 /** Block overrides for the call. */\n blockOverrides?: BlockOverrides.BlockOverrides | 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 authorizationList,\n batch = Boolean(client.batch?.multicall),\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n accessList,\n blobs,\n blockOverrides,\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 =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcBlockOverrides = blockOverrides\n ? BlockOverrides.toRpc(blockOverrides)\n : undefined\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 {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\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,\n 'call',\n ) as TransactionRequest\n\n if (\n batch &&\n shouldPerformMulticall({ request }) &&\n !rpcStateOverride &&\n !rpcBlockOverrides\n ) {\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 params = (() => {\n const base = [\n request as ExactPartial,\n block,\n ] as const\n if (rpcStateOverride && rpcBlockOverrides)\n return [...base, rpcStateOverride, rpcBlockOverrides] as const\n if (rpcStateOverride) return [...base, rpcStateOverride] as const\n if (rpcBlockOverrides) return [...base, {}, rpcBlockOverrides] as const\n return base\n })()\n\n const response = await client.request({\n method: 'eth_call',\n params,\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 {\n batchSize = 1024,\n deployless = false,\n wait = 0,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n data,\n to,\n } = args\n\n const multicallAddress = (() => {\n if (deployless) return null\n if (args.multicallAddress) return args.multicallAddress\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new ClientChainNotConfiguredError()\n })()\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? 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 ...(multicallAddress === null\n ? {\n data: toDeploylessCallViaBytecodeData({\n code: multicall3Bytecode,\n data: calldata,\n }),\n }\n : { to: multicallAddress, data: calldata }),\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: { code: Hex; data: Hex }) {\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 { 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 { chainId } = authorization\n const address = authorization.address\n if (!isAddress(address)) throw new InvalidAddressError({ address })\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 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 { MaybePromise, OneOf } from '../../types/utils.js'\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../authorization/serializeAuthorizationList.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 {\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\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> = (\n transaction: OneOf,\n signature?: Signature | undefined,\n) => MaybePromise<\n SerializedTransactionReturnType<\n OneOf,\n _transactionType\n >\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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(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 ? numberToHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return numberToHex(1)\n\n return v === 27n ? '0x' : numberToHex(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 {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../../types/authorization.js'\nimport { toHex } from '../encoding/toHex.js'\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.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 { chainId, nonce, ...signature } = authorization\n const contractAddress = authorization.address\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","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 bytesToHex,\n type StringToHexErrorType,\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 { 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_, 10) / 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_, 10))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_, 10),\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}: {\n domain?: TypedDataDomain | undefined\n}): 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 typeof domain?.chainId === 'bigint') && {\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: domain as never,\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 } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from '../../types/typedData.js'\nimport type { UnionOmit } from '../../types/utils.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 getTypesForEIP712Domain,\n type ValidateTypedDataErrorType,\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 const typedData extends TypedData | Record = TypedData,\n>({\n domain,\n types,\n}: UnionOmit, 'primaryType'>) {\n return hashStruct({\n data: domain as Record,\n primaryType: 'EIP712Domain',\n types: types as Record,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>({\n data,\n primaryType,\n types,\n}: MessageDefinition) {\n const encoded = encodeData({\n data: data as Record,\n primaryType,\n types: types as Record,\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') return [{ type: 'bytes32' }, keccak256(value)]\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 { 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","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: Hash,\n PRFSalt: Hash,\n DK: Uint8Array,\n prfW: Hash,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/**\n * Audited & minimal JS implementation of\n * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).\n * @module\n * @example\n```js\nimport * as bip39 from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nconst mn = bip39.generateMnemonic(wordlist);\nconsole.log(mn);\nconst ent = bip39.mnemonicToEntropy(mn, wordlist)\nbip39.entropyToMnemonic(ent, wordlist);\nbip39.validateMnemonic(mn, wordlist);\nawait bip39.mnemonicToSeed(mn, 'password');\nbip39.mnemonicToSeedSync(mn, 'password');\n\n// Wordlists\nimport { wordlist as czech } from '@scure/bip39/wordlists/czech';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { wordlist as french } from '@scure/bip39/wordlists/french';\nimport { wordlist as italian } from '@scure/bip39/wordlists/italian';\nimport { wordlist as japanese } from '@scure/bip39/wordlists/japanese';\nimport { wordlist as korean } from '@scure/bip39/wordlists/korean';\nimport { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';\nimport { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';\nimport { wordlist as spanish } from '@scure/bip39/wordlists/spanish';\nimport { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';\n```\n */\n/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n abytes(ent, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\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 type { ErrorType } from '../errors/utils.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.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 signAuthorization: source.signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\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 { type IsHexErrorType, isHex } from '../../utils/data/isHex.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 { 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 =\n | HexToBytesErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | 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 {\n lowS: true,\n extraEntropy: isHex(extraEntropy, { strict: false })\n ? hexToBytes(extraEntropy)\n : extraEntropy,\n },\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 type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../utils/authorization/hashAuthorization.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 AuthorizationRequest & {\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 signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const { chainId, nonce, privateKey, to = 'object' } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n address,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\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 { 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(await serializer(signableTransaction)),\n privateKey,\n })\n return (await serializer(\n transaction,\n signature,\n )) as SignTransactionReturnType\n}\n","import type { TypedData } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\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'\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 [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):\n * `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(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'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.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 { 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 signAuthorization(authorization) {\n return 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","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport { HDKey } from '@scure/bip32'\nexport type { Address } from 'abitype'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from '../utils/nonceManager.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from '../utils/signature/serializeSignature.js'\nexport {\n type GenerateMnemonicErrorType,\n generateMnemonic,\n} from './generateMnemonic.js'\nexport {\n type GeneratePrivateKeyErrorType,\n generatePrivateKey,\n} from './generatePrivateKey.js'\nexport {\n type HDKeyToAccountErrorType,\n type HDKeyToAccountOptions,\n hdKeyToAccount,\n} from './hdKeyToAccount.js'\nexport {\n type MnemonicToAccountErrorType,\n type MnemonicToAccountOptions,\n mnemonicToAccount,\n} from './mnemonicToAccount.js'\nexport {\n type PrivateKeyToAccountErrorType,\n type PrivateKeyToAccountOptions,\n privateKeyToAccount,\n} from './privateKeyToAccount.js'\nexport { type ToAccountErrorType, toAccount } from './toAccount.js'\nexport type {\n Account,\n AccountSource,\n CustomSource,\n HDAccount,\n HDOptions,\n JsonRpcAccount,\n LocalAccount,\n PrivateKeyAccount,\n} from './types.js'\nexport {\n type ParseAccountErrorType,\n parseAccount,\n} from './utils/parseAccount.js'\nexport {\n type PrivateKeyToAddressErrorType,\n privateKeyToAddress,\n} from './utils/privateKeyToAddress.js'\nexport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nexport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n setSignEntropy,\n sign,\n} from './utils/sign.js'\nexport {\n type SignAuthorizationErrorType,\n type SignAuthorizationParameters,\n type SignAuthorizationReturnType,\n signAuthorization,\n} from './utils/signAuthorization.js'\nexport {\n type SignMessageErrorType,\n type SignMessageParameters,\n type SignMessageReturnType,\n signMessage,\n} from './utils/signMessage.js'\nexport {\n type SignTransactionErrorType,\n type SignTransactionParameters,\n type SignTransactionReturnType,\n signTransaction,\n} from './utils/signTransaction.js'\nexport {\n type SignTypedDataErrorType,\n type SignTypedDataParameters,\n type SignTypedDataReturnType,\n signTypedData,\n} from './utils/signTypedData.js'\nexport {\n czech,\n english,\n french,\n italian,\n japanese,\n korean,\n portuguese,\n simplifiedChinese,\n spanish,\n traditionalChinese,\n} from './wordlists.js'\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(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// 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 return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\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(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\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, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\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 = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, 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++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\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\nexport function validateObject(\n object: Record,\n fields: Record = {},\n optFields: Record = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _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 */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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\nfunction assertIsSquare(Fp: IField, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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 assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): (Fp: IField, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return (Fp: IField, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // 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): boolean =>\n (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 isLE: boolean;\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 isValidNot0: (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 invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): 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): IField {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security 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're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 * 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.Point.Fn.ORDER)\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 abytes(key);\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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons

> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns Fp type from Point (P_F

== P.F) */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns Fp type from PointCons (PC_F == PC.P.F) */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P == PC.P) */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper = (i: T[]) => T[];\n\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport function normalizeZ

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\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\n/** Internal wNAF opts for specific W and scalarBits */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = 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 point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\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 * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\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 const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\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 acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, 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 createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 than 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 secret keys / bigints)\n */\nexport function pippenger

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\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 const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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 P;\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

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\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 const fieldN = c.Fn;\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 = bitMask(windowSize);\n const tables = points.map((p: P) => {\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[]): P => {\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\nexport type ValidCurveParams = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: IField, isLE?: boolean): IField {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField;\n }\n}\nexport type FpFn = { Fp: IField; Fn: IField };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: Partial> = {},\n FpFnLE?: boolean\n): FpFn & { CURVE: ValidCurveParams } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abool,\n abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n memoized,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * https://paulmillr.com/posts/deterministic-signatures/\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates sigs with increased security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): Required {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n CURVE(): WeierstrassOpts;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\nexport type WeierstrassExtraOpts = Partial<{\n Fp: IField;\n Fn: IField;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n fromBytes: (bytes: Uint8Array) => AffinePoint;\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: (key: Uint8Array, message: Uint8Array) => Uint8Array;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed?: boolean\n ) => Uint8Array;\n Point: WeierstrassPointCons;\n utils: {\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Uint8Array, secretKey: Uint8Array, opts?: ECDSASignOpts) => Uint8Array;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(data);\n },\n },\n toSig(bytes: Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\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\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\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 { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: 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 x = Fp.mul(X, iz);\n const y = 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, y };\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 (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) 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 if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) 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 function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\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 WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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 // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\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 *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\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) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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(): boolean {\n return this.equals(Point.ZERO);\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 } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n hasHighS(): boolean;\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n}\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASignatureFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\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, 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, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, 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, 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, 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: IField, Fn: IField) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: Uint8Array) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey: Uint8Array, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(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: Uint8Array): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item)) return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey) return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed = true\n ): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor(): void {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: Uint8Array,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\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 toBytes(format: ECDSASignatureFormat = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\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 ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\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 *\n * Warning: we cannot assume here that message 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 */\n function prepSig(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\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 function k2sig(kBytes: Uint8Array): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\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 = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts = {}): Uint8Array {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n }) satisfies Signer;\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\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 = secp256k1_CURVE.p;\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(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\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\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(asciiToBytes(tag));\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.toBytes(true).slice(1);\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: Uint8Array) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { 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 const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\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 Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Uint8Array): Uint8Array {\n return schnorrGetExtPubKey(secretKey).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: Uint8Array,\n secretKey: Uint8Array,\n auxRand: Uint8Array = randomBytes(32)\n): Uint8Array {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(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 // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\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(Fn.toBytes(Fn.create(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: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\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 (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!Fn.isValidNot0(s)) return false;\n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\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 }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\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 ))();\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl } from './utils.ts';\n\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\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 }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1: CHash = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\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 this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5: CHash = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * const hdkey1 = HDKey.fromMasterSeed(seed);\n * const hdkey2 = HDKey.fromExtendedKey(base58key);\n * const hdkey3 = HDKey.fromJSON({ xpriv: string });\n *\n * // props\n * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];\n * console.log(hdkey2.privateKey, hdkey2.publicKey);\n * console.log(hdkey3.derive(\"m/0/2147483647'/1\"));\n * const sig = hdkey3.sign(hash);\n * hdkey3.verify(hash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.Point;\nconst { Fn } = Point;\nconst base58check = createBase58check(sha256);\n\nconst MASTER_SECRET = Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n\n/** Network-specific versioning. */\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened offset from Bitcoin, default */\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number): Uint8Array => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array;\n}\n\n/**\n * HDKey from BIP32\n * @example\n```js\nconst hdkey1 = HDKey.fromMasterSeed(seed);\nconst hdkey2 = HDKey.fromExtendedKey(base58key);\nconst hdkey3 = HDKey.fromJSON({ xpriv: string });\n```\n */\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this._privateKey || null;\n }\n get publicKey(): Uint8Array | null {\n return this._publicKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n\n static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n\n static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n readonly versions: Versions;\n readonly depth: number = 0;\n readonly index: number = 0;\n readonly chainCode: Uint8Array | null = null;\n readonly parentFingerprint: number = 0;\n private _privateKey?: Uint8Array;\n private _publicKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key');\n this._privateKey = opt.privateKey;\n this._publicKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n\n derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n deriveChild(index: number): HDKey {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = I.slice(0, 32);\n const chainCode = I.slice(32);\n if (!secp.utils.isValidSecretKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n const ctweak = Fn.fromBytes(childTweak);\n try {\n // Private parent key -> private child key\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n } else {\n const added = Point.fromBytes(this._publicKey).add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n sign(hash: Uint8Array): Uint8Array {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n\n verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n\n wipePrivateData(): this {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA384 as SHA384n,\n sha384 as sha384n,\n sha512_224 as sha512_224n,\n SHA512_224 as SHA512_224n,\n sha512_256 as sha512_256n,\n SHA512_256 as SHA512_256n,\n SHA512 as SHA512n,\n sha512 as sha512n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512: typeof SHA512n = SHA512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512: typeof sha512n = sha512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA384: typeof SHA384n = SHA384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha384: typeof sha384n = sha384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_224: typeof SHA512_224n = SHA512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_224: typeof sha512_224n = sha512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_256: typeof SHA512_256n = SHA512_256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_256: typeof sha512_256n = sha512_256n;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @module\n * @privateRemarks\n * WARNING:\n * - Don't remove error codes\n * - Don't change or reorder error codes.\n *\n * Good naming conventions:\n * - Prefixing common errors — e.g. under the same package — can be a good way to namespace them. E.g. All codec-related errors start with `SOLANA_ERROR__CODECS__`.\n * - Use consistent names — e.g. choose `PDA` or `PROGRAM_DERIVED_ADDRESS` and stick with it. Ensure your names are consistent with existing error codes. The decision might have been made for you.\n * - Recommended prefixes and suffixes:\n * - `MALFORMED_`: Some input was not constructed properly. E.g. `MALFORMED_BASE58_ENCODED_ADDRESS`.\n * - `INVALID_`: Some input is invalid (other than because it was MALFORMED). E.g. `INVALID_NUMBER_OF_BYTES`.\n * - `EXPECTED_`: Some input was different than expected, no need to specify the \"GOT\" part unless necessary. E.g. `EXPECTED_DECODED_ACCOUNT`.\n * - `_CANNOT_`: Some operation cannot be performed or some input cannot be used due to some condition. E.g. `CANNOT_DECODE_EMPTY_BYTE_ARRAY` or `PDA_CANNOT_END_WITH_PDA_MARKER`.\n * - `_MUST_BE_`: Some condition must be true. E.g. `NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE`.\n * - `_FAILED_TO_`: Tried to perform some operation and failed. E.g. `FAILED_TO_DECODE_ACCOUNT`.\n * - `_NOT_FOUND`: Some operation lead to not finding something. E.g. `ACCOUNT_NOT_FOUND`.\n * - `_OUT_OF_RANGE`: Some value is out of range. E.g. `ENUM_DISCRIMINATOR_OUT_OF_RANGE`.\n * - `_EXCEEDED`: Some limit was exceeded. E.g. `PDA_MAX_SEED_LENGTH_EXCEEDED`.\n * - `_MISMATCH`: Some elements do not match. E.g. `ENCODER_DECODER_FIXED_SIZE_MISMATCH`.\n * - `_MISSING`: Some required input is missing. E.g. `TRANSACTION_FEE_PAYER_MISSING`.\n * - `_UNIMPLEMENTED`: Some required component is not available in the environment. E.g. `SUBTLE_CRYPTO_VERIFY_FUNCTION_UNIMPLEMENTED`.\n */\nexport const SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nexport const SOLANA_ERROR__INVALID_NONCE = 2;\nexport const SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nexport const SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nexport const SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nexport const SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nexport const SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nexport const SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nexport const SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nexport const SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\n\n// JSON-RPC-related errors.\n// Reserve error codes in the range [-32768, -32000]\n// Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs\nexport const SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nexport const SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nexport const SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nexport const SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\n\n// Addresses-related errors.\n// Reserve error codes in the range [2800000-2800999].\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 2800000;\nexport const SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nexport const SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nexport const SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nexport const SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nexport const SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nexport const SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nexport const SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\n\n// Account-related errors.\n// Reserve error codes in the range [3230000-3230999].\nexport const SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 3230000;\nexport const SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nexport const SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\n\n// Subtle-Crypto-related errors.\n// Reserve error codes in the range [3610000-3610999].\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 3610000;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\n\n// Crypto-related errors.\n// Reserve error codes in the range [3611000-3611050].\nexport const SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611000;\n\n// Key-related errors.\n// Reserve error codes in the range [3704000-3704999].\nexport const SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704000;\nexport const SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nexport const SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nexport const SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nexport const SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\n\n// Instruction-related errors.\n// Reserve error codes in the range [4128000-4128999].\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128000;\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nexport const SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\n\n// Instruction errors.\n// Reserve error codes starting with [4615000-4615999] for the Rust enum `InstructionError`.\n// Error names here are dictated by the RPC (see ./instruction-error.ts).\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615000;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\n\n// Signer-related errors.\n// Reserve error codes in the range [5508000-5508999].\nexport const SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508000;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nexport const SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\n\n// Offchain-message-related errors.\n// Reserve error codes in the range [5607000-5607999].\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED = 5607000;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE = 5607001;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE = 5607002;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH = 5607003;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH = 5607004;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO = 5607005;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED = 5607006;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH = 5607007;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH = 5607008;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY = 5607009;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO = 5607010;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING = 5607011;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH = 5607012;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE = 5607013;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION = 5607014;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED = 5607015;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE = 5607016;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE = 5607017;\n\n// Transaction-related errors.\n// Reserve error codes in the range [5663000-5663999].\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663000;\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nexport const SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nexport const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nexport const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nexport const SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;\nexport const SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;\n\n// Transaction errors.\n// Reserve error codes starting with [7050000-7050999] for the Rust enum `TransactionError`.\n// Error names here are dictated by the RPC (see ./transaction-error.ts).\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 7050000;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\n// `InstructionError` intentionally omitted.\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\n\n// Instruction plan related errors.\n// Reserve error codes in the range [7618000-7618999].\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618000;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED = 7618004;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND = 7618005;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN = 7618006;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN = 7618007;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT = 7618008;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT = 7618009;\n\n// Codec-related errors.\n// Reserve error codes in the range [8078000-8078999].\nexport const SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078000;\nexport const SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nexport const SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nexport const SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nexport const SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nexport const SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nexport const SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nexport const SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nexport const SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nexport const SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nexport const SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nexport const SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nexport const SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nexport const SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nexport const SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nexport const SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nexport const SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nexport const SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nexport const SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nexport const SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nexport const SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;\n\n// RPC-related errors.\n// Reserve error codes in the range [8100000-8100999].\nexport const SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 8100000;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nexport const SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\n\n// RPC-Subscriptions-related errors.\n// Reserve error codes in the range [8190000-8190999].\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 8190000;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\n\n// Invariant violation errors.\n// Reserve error codes in the range [9900000-9900999].\n// These errors should only be thrown when there is a bug with the\n// library itself and should, in theory, never reach the end user.\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 9900000;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;\n\n/**\n * A union of every Solana error code\n *\n * @privateRemarks\n * You might be wondering why this is not a TypeScript enum or const enum.\n *\n * One of the goals of this library is to enable people to use some or none of it without having to\n * bundle all of it.\n *\n * If we made the set of error codes an enum then anyone who imported it (even if to only use a\n * single error code) would be forced to bundle every code and its label.\n *\n * Const enums appear to solve this problem by letting the compiler inline only the codes that are\n * actually used. Unfortunately exporting ambient (const) enums from a library like `@solana/errors`\n * is not safe, for a variety of reasons covered here: https://stackoverflow.com/a/28818850\n */\nexport type SolanaErrorCode =\n | typeof SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND\n | typeof SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE\n | typeof SOLANA_ERROR__ADDRESSES__MALFORMED_PDA\n | typeof SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE\n | typeof SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER\n | typeof SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED\n | typeof SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS\n | typeof SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE\n | typeof SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__INVALID_CONSTANT\n | typeof SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS\n | typeof SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE\n | typeof SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES\n | typeof SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA\n | typeof SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH\n | typeof SOLANA_ERROR__INVALID_NONCE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE\n | typeof SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_PARAMS\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_REQUEST\n | typeof SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND\n | typeof SOLANA_ERROR__JSON_RPC__PARSE_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SCAN_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION\n | typeof SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY\n | typeof SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE\n | typeof SOLANA_ERROR__MALFORMED_BIGINT_STRING\n | typeof SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR\n | typeof SOLANA_ERROR__MALFORMED_NUMBER_STRING\n | typeof SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD\n | typeof SOLANA_ERROR__RPC__INTEGER_OVERFLOW\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID\n | typeof SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING\n | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES\n | typeof SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE\n | typeof SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE\n | typeof SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT;\n\n/**\n * Errors of this type are understood to have an optional {@link SolanaError} nested inside as\n * `cause`.\n */\nexport type SolanaErrorCodeWithCause = typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE;\n\n/**\n * Errors of this type have a deprecated `cause` property. Consumers should use the error's\n * `context` instead to access relevant error information.\n */\nexport type SolanaErrorCodeWithDeprecatedCause =\n typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @privateRemarks\n * WARNING:\n * - Don't change or remove members of an error's context.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SolanaErrorCode,\n} from './codes';\nimport { RpcSimulateTransactionResult } from './json-rpc-error';\n\ntype BasicInstructionErrorContext = { [P in T]: { index: number } };\n\ntype DefaultUnspecifiedErrorContextToUndefined = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype ReadonlyContextValue = {\n [P in keyof T]: Readonly;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit {\n readonly [n: number]: number;\n}\n\n/** A amount of bytes. */\ntype Bytes = number;\n\n/**\n * A map of every {@link SolanaError} code to the type of its `context` property.\n */\nexport type SolanaErrorContext = ReadonlyContextValue<\n DefaultUnspecifiedErrorContextToUndefined<\n BasicInstructionErrorContext<\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n > & {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: {\n putativeAddress: string;\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: {\n actual: number;\n maxSeeds: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: {\n actual: number;\n index: number;\n maxSeedLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: {\n bump: number;\n };\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: {\n currentBlockHeight: bigint;\n lastValidBlockHeight: bigint;\n };\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: {\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: {\n stringValues: readonly string[];\n };\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: {\n encodedBytes: ReadonlyUint8Array;\n hexEncodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: {\n decoderFixedSize: number;\n encoderFixedSize: number;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: {\n decoderMaxSize: number | undefined;\n encoderMaxSize: number | undefined;\n };\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n formattedValidDiscriminators: string;\n validDiscriminators: readonly number[];\n };\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: {\n expectedLength: number;\n numExcessBytes: number;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: {\n codecDescription: string;\n expectedSize: number;\n hexZeroValue: string;\n zeroValue: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n expected: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: {\n constant: ReadonlyUint8Array;\n data: ReadonlyUint8Array;\n hexConstant: string;\n hexData: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: {\n formattedNumericalValues: string;\n numericalValues: readonly number[];\n stringValues: readonly string[];\n variant: number | string | symbol;\n };\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: {\n actual: bigint | number;\n codecDescription: string;\n expected: bigint | number;\n };\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: {\n alphabet: string;\n base: number;\n value: string;\n };\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n maxRange: number;\n minRange: number;\n };\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: {\n codecDescription: string;\n max: bigint | number;\n min: bigint | number;\n value: bigint | number;\n };\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: {\n bytesLength: number;\n codecDescription: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: {\n decodedBytes: ReadonlyUint8Array;\n hexDecodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: {\n maxRange: number;\n minRange: number;\n variant: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: {\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: {\n code: number;\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: {\n errorName: string;\n index: number;\n instructionErrorContext?: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: {\n numBytesRequired: number;\n numFreeBytes: number;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n instructionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n transactionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]: {\n actualKind: string;\n expectedKind: string;\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: {\n data?: ReadonlyUint8Array;\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: {\n accountAddresses?: readonly string[];\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: {\n actualProgramAddress: string;\n expectedProgramAddress: string;\n };\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__INVALID_NONCE]: {\n actualNonceValue: string;\n expectedNonceValue: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: {\n cacheKey: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: {\n channelName: string;\n supportedChannelNames: readonly string[];\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: {\n unexpectedValue: unknown;\n };\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: {\n currentBlockHeight: bigint;\n rewardsCompleteBlockHeight: bigint;\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: {\n contextSlot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: {\n numSlotsBehind?: number;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: Omit<\n RpcSimulateTransactionResult,\n 'err'\n >;\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: {\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: {\n byteLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: {\n error: unknown;\n message: string;\n };\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: {\n nonceAccountAddress: string;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]: {\n missingRequiredSigners: readonly string[];\n unexpectedSigners: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]: {\n actualBytes: number;\n maxBytes: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]: {\n actualMessageFormat: number;\n expectedMessageFormat: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]: {\n actualLength: number;\n specifiedLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signatoryAddresses: readonly string[];\n signaturesLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]: {\n signatoriesWithInvalidSignatures: readonly string[];\n signatoriesWithMissingSignatures: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]: {\n actualVersion: number;\n expectedVersion: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: {\n notificationName: string;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: {\n errorEvent: Event;\n };\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: {\n method: string;\n params: readonly unknown[];\n };\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: {\n argumentLabel: string;\n keyPath: readonly (number | string | symbol)[];\n methodName: string;\n optionalPathLabel: string;\n path?: string;\n value: bigint;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: {\n headers: Headers;\n message: string;\n statusCode: number;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: {\n headers: readonly string[];\n };\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: {\n key: CryptoKey;\n };\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: {\n value: bigint;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: {\n errorName: string;\n transactionErrorContext?: unknown;\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: {\n transactionSize: Bytes;\n transactionSizeLimit: Bytes;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: {\n lookupTableAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: {\n highestKnownIndex: number;\n highestRequestedIndex: number;\n lookupTableAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: {\n unitsConsumed: number;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signaturesLength: number;\n signerAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: {\n nonce: string;\n };\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: {\n actualVersion: number;\n };\n }\n >\n>;\n\nexport function decodeEncodedContext(encodedContext: string): object {\n const decodedUrlString = __NODEJS__ ? Buffer.from(encodedContext, 'base64').toString('utf8') : atob(encodedContext);\n return Object.fromEntries(new URLSearchParams(decodedUrlString).entries());\n}\n\nfunction encodeValue(value: unknown): string {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join('%2C%20' /* \", \" */);\n return '%5B' /* \"[\" */ + commaSeparatedValues + /* \"]\" */ '%5D';\n } else if (typeof value === 'bigint') {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null\n ? // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...(value as object) }\n : value,\n ),\n );\n }\n}\n\nfunction encodeObjectContextEntry([key, value]: [string, unknown]): `${typeof key}=${string}` {\n return `${key}=${encodeValue(value)}`;\n}\n\nexport function encodeContextObject(context: object): string {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join('&');\n return __NODEJS__ ? Buffer.from(searchParamsString, 'utf8').toString('base64') : btoa(searchParamsString);\n}\n","/* eslint-disable sort-keys-fix/sort-keys-fix */\n/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors#adding-a-new-error\n *\n * WARNING:\n * - Don't change the meaning of an error message.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,\n SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,\n SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,\n SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,\n SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,\n SolanaErrorCode,\n} from './codes';\n\n/**\n * A map of every {@link SolanaError} code to the error message shown to developers in development\n * mode.\n */\nexport const SolanaErrorMessages: Readonly<{\n // This type makes this data structure exhaustive with respect to `SolanaErrorCode`.\n // TypeScript will fail to build this project if add an error code without a message.\n [P in SolanaErrorCode]: string;\n}> = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: 'Account not found at address: $address',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:\n 'Not all accounts were decoded. Encoded accounts found at addresses: $addresses.',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: 'Expected decoded account at address: $address',\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: 'Failed to decode account data at address: $address',\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: 'Accounts not found at addresses: $addresses',\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:\n 'Unable to find a viable program address bump seed.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: '$putativeAddress is not a base58-encoded address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:\n 'Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: 'The `CryptoKey` must be an `Ed25519` public key.',\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:\n '$putativeOffCurveAddress is not a base58-encoded off-curve address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: 'Invalid seeds; point must fall off the Ed25519 curve.',\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:\n 'Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].',\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:\n 'A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.',\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:\n 'The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.',\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:\n 'Expected program derived address bump to be in the range [0, 255], got: $bump.',\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: 'Program address cannot end with PDA marker.',\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:\n 'The network has progressed past the last block for which this transaction could have been committed.',\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:\n 'Codec [$codecDescription] cannot decode empty byte arrays.',\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:\n 'Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.',\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:\n 'Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:\n 'Encoder and decoder must either both be fixed-size or variable-size.',\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.',\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: 'Expected a fixed-size codec, got a variable-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected a positive byte length, got $bytesLength.',\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: 'Expected a variable-size codec, got a fixed-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:\n 'Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].',\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected $expected bytes, got $bytesLength.',\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]:\n 'Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].',\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:\n 'Invalid discriminated union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:\n 'Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.',\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:\n 'Invalid literal union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:\n 'Expected [$codecDescription] to have $expected items, got $actual.',\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: 'Invalid value $value for base $base with alphabet $alphabet.',\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.',\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.',\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.',\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:\n 'Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].',\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:\n 'Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.',\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:\n 'This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?',\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: 'No random values implementation could be found.',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: 'instruction requires an uninitialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:\n 'instruction tries to borrow reference for an account which is already borrowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'instruction left account with an outstanding borrowed reference',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:\n \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: 'account data too small for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: 'instruction expected an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:\n 'An account does not have enough lamports to be rent-exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: 'Program arithmetic overflowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: 'Failed to serialize or deserialize account data: $encodedData',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:\n 'Builtin programs must consume compute units',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: 'Cross-program invocation call depth too deep',\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: 'Computational budget exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: 'custom program error: #$code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: 'instruction contains duplicate accounts',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:\n 'instruction modifications of multiply-passed account differ',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: 'executable accounts must be rent exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: 'instruction changed executable accounts data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:\n 'instruction changed the balance of an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: 'instruction changed executable bit of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:\n 'instruction modified data of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:\n 'instruction spent from the balance of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: 'generic instruction error',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: 'Provided owner is not allowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: 'Account is immutable',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: 'Incorrect authority provided',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: 'incorrect program id for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: 'insufficient funds for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: 'invalid account data for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: 'Invalid account owner',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: 'invalid program argument',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: 'program returned invalid error code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: 'invalid instruction data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: 'Failed to reallocate account data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: 'Provided seeds do not result in a valid address',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:\n 'Accounts data allocations exceeded the maximum allowed per transaction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: 'Max accounts exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: 'Max instruction trace length exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:\n 'Length of the seed is too long for address generation',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: 'An account required by the instruction is missing',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: 'missing required signature for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:\n 'instruction illegally modified the program id of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: 'insufficient account keys for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:\n 'Cross-program invocation with unauthorized signer or writable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:\n 'Failed to create program execution environment',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: 'Program failed to compile',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: 'Program failed to complete',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: 'instruction modified data of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:\n 'instruction changed the balance of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:\n 'Cross-program invocation reentrancy not allowed for this instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: 'instruction modified rent epoch of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:\n 'sum of account balances before and after instruction do not match',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: 'instruction requires an initialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: '',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: 'Unsupported program id',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: 'Unsupported sysvar',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: 'Invalid instruction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: 'The provided instruction plan is empty.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]:\n 'No failed transaction plan result was found in the provided transaction plan result.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]:\n 'This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved — e.g. by targetting RPCs that support transaction bundles.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:\n 'The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:\n 'The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: 'Invalid transaction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:\n 'No more instructions to pack; the message packer has completed the instruction plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]:\n 'Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]:\n 'Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]:\n 'Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]:\n 'Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: 'The instruction does not have any accounts.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: 'The instruction does not have any data.',\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:\n 'Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.',\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:\n 'Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__INVALID_NONCE]:\n 'The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`',\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:\n 'Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It ' +\n 'should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:\n 'Invariant violation: This data publisher does not publish to the channel named ' +\n '`$channelName`. Supported channels include $supportedChannelNames.',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:\n 'Invariant violation: WebSocket message iterator state is corrupt; iterated without first ' +\n 'resolving existing message promise. It should be impossible to hit this error; please ' +\n 'file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:\n 'Invariant violation: WebSocket message iterator is missing state storage. It should be ' +\n 'impossible to hit this error; please file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:\n 'Invariant violation: Switch statement non-exhaustive. Received unexpected value ' +\n '`$unexpectedValue`. It should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: 'JSON-RPC error: Internal JSON-RPC error ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: 'JSON-RPC error: Invalid method parameter(s) ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:\n 'JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:\n 'JSON-RPC error: The method does not exist / is not available ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:\n 'JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:\n 'Epoch rewards period still active at slot $slot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:\n 'Failed to query long-term storage; please try again',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: 'Minimum context slot has not been reached',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: 'Node is unhealthy; behind by $numSlotsBehind slots',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: 'No snapshot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: 'Transaction simulation failed',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:\n \"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:\n 'Transaction history is not available from this node',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: 'Transaction signature length mismatch',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:\n 'Transaction signature verification failure',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: '$__serverMessage',\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: 'Key pair bytes must be of length 64, got $byteLength.',\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:\n 'Expected private key bytes with length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:\n 'Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:\n 'The provided private key does not match the provided public key.',\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.',\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: 'Lamports value must be in the range [0, 2e64-1]',\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: '`$value` cannot be parsed as a `BigInt`',\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: '$message',\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: '`$value` cannot be parsed as a `Number`',\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: 'No nonce account could be found at address `$nonceAccountAddress`',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]:\n 'Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]:\n 'Attempted to sign an offchain message with an address that is not a signer for it',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]:\n 'The signer addresses in this offchain message envelope do not match the list of ' +\n 'required signers in the message preamble. These unexpected signers were present in the ' +\n 'envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope ' +\n '`[$missingSigners]`.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]:\n 'The message body provided has a byte-length of $actualBytes. The maximum allowable ' +\n 'byte-length is $maxBytes',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]:\n 'Expected message format $expectedMessageFormat, got $actualMessageFormat',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]:\n 'The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]: 'Offchain message content must be non-empty',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]:\n 'Offchain message must specify the address of at least one required signer',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]:\n 'Offchain message envelope must reserve space for at least one signature',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]:\n 'The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]:\n 'The signatories of this offchain message must be listed in lexicographical order',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]:\n 'An address must be listed no more than once among the signatories of an offchain message',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]:\n 'Offchain message is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]:\n 'Offchain message signature verification failed. Signature mismatch for required ' +\n 'signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories ' +\n '[$signatoriesWithMissingSignatures]',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]:\n 'The message body provided contains characters whose codes fall outside the allowed ' +\n 'range. In order to ensure clear-signing compatiblity with hardware wallets, the message ' +\n 'may only contain line feeds and characters in the range [\\\\x20-\\\\x7e].',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]:\n 'Expected offchain message version $expectedVersion. Got $actualVersion.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding offchain messages with version ' +\n '$unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:\n \"The notification name must end in 'Notifications' and the API must supply a \" +\n \"subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:\n 'WebSocket was closed before payload could be added to the send buffer',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: 'WebSocket connection closed',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: 'WebSocket failed to connect',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:\n 'Failed to obtain a subscription id from the server',\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: 'Could not find an API plan for RPC method: `$method`',\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:\n 'The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was ' +\n '`$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: 'HTTP error ($statusCode): $message',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:\n 'HTTP header(s) forbidden: $headers. Learn more at ' +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.',\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:\n 'Multiple distinct signers were identified for address `$address`. Please ensure that ' +\n 'you are using the same signer instance for each address.',\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:\n 'The provided value does not implement the `KeyPairSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:\n 'The provided value does not implement the `MessageModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:\n 'The provided value does not implement the `MessagePartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:\n 'The provided value does not implement any of the `MessageSigner` interfaces',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:\n 'The provided value does not implement the `TransactionModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:\n 'The provided value does not implement the `TransactionPartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:\n 'The provided value does not implement the `TransactionSendingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:\n 'The provided value does not implement any of the `TransactionSigner` interfaces',\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:\n 'More than one `TransactionSendingSigner` was identified.',\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:\n 'No `TransactionSendingSigner` was identified. Please provide a valid ' +\n '`TransactionWithSingleSendingSigner` transaction.',\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:\n 'Wallet account signers do not support signing multiple messages/transactions in a single operation',\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: 'Cannot export a non-extractable key.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: 'No digest implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall ' +\n '@solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]:\n 'No signature verification implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: 'No key generation implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: 'No signing implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: 'No key export implementation could be found.',\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]:\n 'Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'Transaction processing left an account with an outstanding borrowed reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: 'Account in use',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: 'Account loaded twice',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]:\n 'Attempt to debit an account but found no record of a prior credit.',\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]:\n \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: 'This transaction has already been processed',\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: 'Blockhash not found',\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: 'Loader call chain is too deep',\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]:\n 'Transactions are currently disabled due to cluster maintenance',\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]:\n 'Transaction contains a duplicate instruction ($index) that is not allowed',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: 'Insufficient funds for fee',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]:\n 'Transaction results in an account ($accountIndex) with insufficient funds for rent',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: 'This account may not be used to pay transaction fees',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: 'Transaction contains an invalid account reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]:\n 'Transaction loads an address table account with invalid data',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]:\n 'Transaction address table lookup uses an invalid index',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]:\n 'Transaction loads an address table account with an invalid owner',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]:\n 'LoadedAccountsDataSizeLimit set for transaction must be greater than 0.',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]:\n 'This program may not be used for executing instructions',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]:\n 'Transaction leaves an account with a lower balance than rent-exempt minimum',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]:\n 'Transaction loads a writable account that cannot be written',\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]:\n 'Transaction exceeded max loaded accounts data size cap',\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]:\n 'Transaction requires a fee but has no signature present',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: 'Attempt to load a program that does not exist',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]:\n 'Execution of the program referenced by account at index $accountIndex is temporarily restricted.',\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: 'ResanitizationNeeded',\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: 'Transaction failed to sanitize accounts offsets correctly',\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: 'Transaction did not pass signature verification',\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: 'Transaction locked too many accounts',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]:\n 'Sum of account balances before and after transaction do not match',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: 'The transaction failed with the error `$errorName`',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: 'Transaction version is unsupported',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]:\n 'Transaction would exceed account data limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]:\n 'Transaction would exceed total account data limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]:\n 'Transaction would exceed max account limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]:\n 'Transaction would exceed max Block Cost Limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: 'Transaction would exceed max Vote Cost Limit',\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]:\n 'Attempted to sign a transaction with an address that is not a signer for it',\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: 'Transaction is missing an address at index: $index.',\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]:\n 'Transaction has no expected signers therefore it cannot be encoded',\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]:\n 'Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: 'Transaction does not have a blockhash lifetime',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: 'Transaction is not a durable nonce transaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]:\n 'Contents of these address lookup tables unknown: $lookupTableAddresses',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]:\n 'Lookup of address at index $highestRequestedIndex failed for lookup table ' +\n '`$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table ' +\n 'may have been extended since its contents were retrieved',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: 'No fee payer set in CompiledTransaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]:\n 'Could not find program address at index $index',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Failed to estimate the compute unit consumption for this transaction message. This is ' +\n 'likely because simulating the transaction failed. Inspect the `cause` property of this ' +\n 'error to learn more',\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Transaction failed when it was simulated in order to estimate the compute unit consumption. ' +\n 'The compute unit estimate provided is for a transaction that failed when simulated and may not ' +\n 'be representative of the compute units this transaction would consume if successful. Inspect the ' +\n '`cause` property of this error to learn more',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: 'Transaction is missing a fee payer.',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]:\n \"Could not determine this transaction's signature. Make sure that the transaction has \" +\n 'been signed by its fee payer.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]:\n 'Transaction first instruction is not advance nonce account instruction.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]:\n 'Transaction with no instructions cannot be durable nonce transaction.',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]:\n 'This transaction includes an address (`$programAddress`) which is both ' +\n 'invoked and set as the fee payer. Program addresses may not pay fees',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]:\n 'This transaction includes an address (`$programAddress`) which is both invoked and ' +\n 'marked writable. Program addresses may not be writable',\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]:\n 'The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.',\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: 'Transaction is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]:\n 'Transaction version must be in the range [0, 127]. `$actualVersion` given',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]:\n 'The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction.',\n};\n","import { SolanaErrorCode } from './codes';\nimport { encodeContextObject } from './context';\nimport { SolanaErrorMessages } from './messages';\n\nconst enum StateType {\n EscapeSequence,\n Text,\n Variable,\n}\ntype State = Readonly<{\n [START_INDEX]: number;\n [TYPE]: StateType;\n}>;\nconst START_INDEX = 'i';\nconst TYPE = 't';\n\nexport function getHumanReadableErrorMessage(\n code: TErrorCode,\n context: object = {},\n): string {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return '';\n }\n let state: State;\n function commitStateUpTo(endIndex?: number) {\n if (state[TYPE] === StateType.Variable) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n\n fragments.push(\n variableName in context\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName as keyof typeof context]}`\n : `$${variableName}`,\n );\n } else if (state[TYPE] === StateType.Text) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments: string[] = [];\n messageFormatString.split('').forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]:\n messageFormatString[0] === '\\\\'\n ? StateType.EscapeSequence\n : messageFormatString[0] === '$'\n ? StateType.Variable\n : StateType.Text,\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case StateType.EscapeSequence:\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n break;\n case StateType.Text:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n }\n break;\n case StateType.Variable:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join('');\n}\n\nexport function getErrorMessage(\n code: TErrorCode,\n context: Record = {},\n): string {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n /**\n * DANGER: Be sure that the shell command is escaped in such a way that makes it\n * impossible for someone to craft malicious context values that would result in\n * an exploit against anyone who bindly copy/pastes it into their terminal.\n */\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n","import { SolanaErrorCode, SolanaErrorCodeWithCause, SolanaErrorCodeWithDeprecatedCause } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { getErrorMessage } from './message-formatter';\n\n/**\n * A variant of {@link SolanaError} where the `cause` property is deprecated.\n *\n * This type is returned by {@link isSolanaError} when checking for error codes in\n * {@link SolanaErrorCodeWithDeprecatedCause}. Accessing `cause` on these errors will show\n * a deprecation warning in IDEs that support JSDoc `@deprecated` tags.\n */\nexport interface SolanaErrorWithDeprecatedCause<\n TErrorCode extends SolanaErrorCodeWithDeprecatedCause = SolanaErrorCodeWithDeprecatedCause,\n> extends Omit, 'cause'> {\n /**\n * @deprecated The `cause` property is deprecated for this error code.\n * Use the error's `context` property instead to access relevant error information.\n */\n readonly cause?: unknown;\n}\n\n/**\n * A type guard that returns `true` if the input is a {@link SolanaError}, optionally with a\n * particular error code.\n *\n * When the `code` argument is supplied and the input is a {@link SolanaError}, TypeScript will\n * refine the error's {@link SolanaError#context | `context`} property to the type associated with\n * that error code. You can use that context to render useful error messages, or to make\n * context-aware decisions that help your application to recover from the error.\n *\n * @example\n * ```ts\n * import {\n * SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE,\n * SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n * isSolanaError,\n * } from '@solana/errors';\n * import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions';\n *\n * try {\n * const transactionSignature = getSignatureFromTransaction(tx);\n * assertIsFullySignedTransaction(tx);\n * /* ... *\\/\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * displayError(\n * \"We can't send this transaction without signatures for these addresses:\\n- %s\",\n * // The type of the `context` object is now refined to contain `addresses`.\n * e.context.addresses.join('\\n- '),\n * );\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) {\n * if (!tx.feePayer) {\n * displayError('Choose a fee payer for this transaction before sending it');\n * } else {\n * displayError('The fee payer still needs to sign for this transaction');\n * }\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function isSolanaError(\n e: unknown,\n code: TErrorCode,\n): e is SolanaErrorWithDeprecatedCause;\nexport function isSolanaError(\n e: unknown,\n code?: TErrorCode,\n): e is SolanaError;\nexport function isSolanaError(\n e: unknown,\n /**\n * When supplied, this function will require that the input is a {@link SolanaError} _and_ that\n * its error code is exactly this value.\n */\n code?: TErrorCode,\n): e is SolanaError {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError).context.__code === code;\n }\n return true;\n }\n return false;\n}\n\ntype SolanaErrorCodedContext = {\n [P in SolanaErrorCode]: Readonly<{\n __code: P;\n }> &\n (SolanaErrorContext[P] extends undefined ? object : SolanaErrorContext[P]);\n};\n\n/**\n * Encapsulates an error's stacktrace, a Solana-specific numeric code that indicates what went\n * wrong, and optional context if the type of error indicated by the code supports it.\n */\nexport class SolanaError extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n readonly cause?: TErrorCode extends SolanaErrorCodeWithCause ? SolanaError : unknown = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n readonly context: SolanaErrorCodedContext[TErrorCode];\n constructor(\n ...[code, contextAndErrorOptions]: SolanaErrorContext[TErrorCode] extends undefined\n ? [code: TErrorCode, errorOptions?: ErrorOptions | undefined]\n : [code: TErrorCode, contextAndErrorOptions: SolanaErrorContext[TErrorCode] & (ErrorOptions | undefined)]\n ) {\n let context: SolanaErrorContext[TErrorCode] | undefined;\n let errorOptions: ErrorOptions | undefined;\n if (contextAndErrorOptions) {\n Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {\n // If the `ErrorOptions` type ever changes, update this code.\n if (name === 'cause') {\n errorOptions = { cause: descriptor.value };\n } else {\n if (context === undefined) {\n context = {\n __code: code,\n } as unknown as SolanaErrorContext[TErrorCode];\n }\n Object.defineProperty(context, name, descriptor);\n }\n });\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = Object.freeze(\n context === undefined\n ? {\n __code: code,\n }\n : context,\n ) as SolanaErrorCodedContext[TErrorCode];\n // This is necessary so that `isSolanaError()` can identify a `SolanaError` without having\n // to import the class for use in an `instanceof` check.\n this.name = 'SolanaError';\n }\n}\n","export function safeCaptureStackTrace(...args: Parameters): void {\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(...args);\n }\n}\n","import { SolanaErrorCode } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\n\ntype Config = Readonly<{\n /**\n * Oh, hello. You might wonder what in tarnation is going on here. Allow us to explain.\n *\n * One of the goals of `@solana/errors` is to allow errors that are not interesting to your\n * application to shake out of your app bundle in production. This means that we must never\n * export large hardcoded maps of error codes/messages.\n *\n * Unfortunately, where instruction and transaction errors from the RPC are concerned, we have\n * no choice but to keep a map between the RPC `rpcEnumError` enum name and its corresponding\n * `SolanaError` code. In the interest of implementing that map in as few bytes of source code\n * as possible, we do the following:\n *\n * 1. Reserve a block of sequential error codes for the enum in question\n * 2. Hardcode the list of enum names in that same order\n * 3. Match the enum error name from the RPC with its index in that list, and reconstruct the\n * `SolanaError` code by adding the `errorCodeBaseOffset` to that index\n */\n errorCodeBaseOffset: number;\n getErrorContext: (\n errorCode: SolanaErrorCode,\n rpcErrorName: string,\n rpcErrorContext?: unknown,\n ) => SolanaErrorContext[SolanaErrorCode];\n orderedErrorNames: string[];\n rpcEnumError: string | { [key: string]: unknown };\n}>;\n\nexport function getSolanaErrorFromRpcError(\n { errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }: Config,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructorOpt: Function,\n): SolanaError {\n let rpcErrorName;\n let rpcErrorContext;\n if (typeof rpcEnumError === 'string') {\n rpcErrorName = rpcEnumError;\n } else {\n rpcErrorName = Object.keys(rpcEnumError)[0];\n rpcErrorContext = rpcEnumError[rpcErrorName];\n }\n const codeOffset = orderedErrorNames.indexOf(rpcErrorName);\n const errorCode = (errorCodeBaseOffset + codeOffset) as SolanaErrorCode;\n const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);\n const err = new SolanaError(errorCode, errorContext);\n safeCaptureStackTrace(err, constructorOpt);\n return err;\n}\n","import { SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN } from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/solana-sdk/blob/master/instruction-error/src/lib.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'GenericError',\n 'InvalidArgument',\n 'InvalidInstructionData',\n 'InvalidAccountData',\n 'AccountDataTooSmall',\n 'InsufficientFunds',\n 'IncorrectProgramId',\n 'MissingRequiredSignature',\n 'AccountAlreadyInitialized',\n 'UninitializedAccount',\n 'UnbalancedInstruction',\n 'ModifiedProgramId',\n 'ExternalAccountLamportSpend',\n 'ExternalAccountDataModified',\n 'ReadonlyLamportChange',\n 'ReadonlyDataModified',\n 'DuplicateAccountIndex',\n 'ExecutableModified',\n 'RentEpochModified',\n 'NotEnoughAccountKeys',\n 'AccountDataSizeChanged',\n 'AccountNotExecutable',\n 'AccountBorrowFailed',\n 'AccountBorrowOutstanding',\n 'DuplicateAccountOutOfSync',\n 'Custom',\n 'InvalidError',\n 'ExecutableDataModified',\n 'ExecutableLamportChange',\n 'ExecutableAccountNotRentExempt',\n 'UnsupportedProgramId',\n 'CallDepth',\n 'MissingAccount',\n 'ReentrancyNotAllowed',\n 'MaxSeedLengthExceeded',\n 'InvalidSeeds',\n 'InvalidRealloc',\n 'ComputationalBudgetExceeded',\n 'PrivilegeEscalation',\n 'ProgramEnvironmentSetupFailure',\n 'ProgramFailedToComplete',\n 'ProgramFailedToCompile',\n 'Immutable',\n 'IncorrectAuthority',\n 'BorshIoError',\n 'AccountNotRentExempt',\n 'InvalidAccountOwner',\n 'ArithmeticOverflow',\n 'UnsupportedSysvar',\n 'IllegalOwner',\n 'MaxAccountsDataAllocationsExceeded',\n 'MaxAccountsExceeded',\n 'MaxInstructionTraceLengthExceeded',\n 'BuiltinProgramsMustConsumeComputeUnits',\n];\n\nexport function getSolanaErrorFromInstructionError(\n /**\n * The index of the instruction inside the transaction.\n */\n index: bigint | number,\n instructionError: string | { [key: string]: unknown },\n): SolanaError {\n const numberIndex = Number(index);\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 4615001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n index: numberIndex,\n ...(rpcErrorContext !== undefined ? { instructionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {\n return {\n code: Number(rpcErrorContext as bigint | number),\n index: numberIndex,\n };\n }\n return { index: numberIndex };\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: instructionError,\n },\n getSolanaErrorFromInstructionError,\n );\n}\n","import {\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n} from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromInstructionError } from './instruction-error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\n/**\n * How to add an error when an entry is added to the RPC `TransactionError` enum:\n *\n * 1. Follow the instructions in `./codes.ts` to add a corresponding Solana error code\n * 2. Add the `TransactionError` enum name in the same order as it appears in `./codes.ts`\n * 3. Add the new error name/code mapping to `./__tests__/transaction-error-test.ts`\n */\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'AccountInUse',\n 'AccountLoadedTwice',\n 'AccountNotFound',\n 'ProgramAccountNotFound',\n 'InsufficientFundsForFee',\n 'InvalidAccountForFee',\n 'AlreadyProcessed',\n 'BlockhashNotFound',\n // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`\n 'CallChainTooDeep',\n 'MissingSignatureForFee',\n 'InvalidAccountIndex',\n 'SignatureFailure',\n 'InvalidProgramForExecution',\n 'SanitizeFailure',\n 'ClusterMaintenance',\n 'AccountBorrowOutstanding',\n 'WouldExceedMaxBlockCostLimit',\n 'UnsupportedVersion',\n 'InvalidWritableAccount',\n 'WouldExceedMaxAccountCostLimit',\n 'WouldExceedAccountDataBlockLimit',\n 'TooManyAccountLocks',\n 'AddressLookupTableNotFound',\n 'InvalidAddressLookupTableOwner',\n 'InvalidAddressLookupTableData',\n 'InvalidAddressLookupTableIndex',\n 'InvalidRentPayingAccount',\n 'WouldExceedMaxVoteCostLimit',\n 'WouldExceedAccountDataTotalLimit',\n 'DuplicateInstruction',\n 'InsufficientFundsForRent',\n 'MaxLoadedAccountsDataSizeExceeded',\n 'InvalidLoadedAccountsDataSizeLimit',\n 'ResanitizationNeeded',\n 'ProgramExecutionTemporarilyRestricted',\n 'UnbalancedTransaction',\n];\n\nexport function getSolanaErrorFromTransactionError(transactionError: string | { [key: string]: unknown }): SolanaError {\n if (typeof transactionError === 'object' && 'InstructionError' in transactionError) {\n return getSolanaErrorFromInstructionError(\n ...(transactionError.InstructionError as Parameters),\n );\n }\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 7050001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n ...(rpcErrorContext !== undefined ? { transactionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {\n return {\n index: Number(rpcErrorContext as bigint | number),\n };\n } else if (\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT ||\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n ) {\n return {\n accountIndex: Number((rpcErrorContext as { account_index: bigint | number }).account_index),\n };\n }\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: transactionError,\n },\n getSolanaErrorFromTransactionError,\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SolanaErrorCode,\n} from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\nimport { getSolanaErrorFromTransactionError } from './transaction-error';\n\ninterface RpcErrorResponse {\n code: bigint | number;\n data?: unknown;\n message: string;\n}\n\ntype TransactionError = string | { [key: string]: unknown };\n\n/**\n * Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-types/src/response.rs\n * @hidden\n */\nexport interface RpcSimulateTransactionResult {\n accounts:\n | ({\n data:\n | string // LegacyBinary\n | {\n // Json\n parsed: unknown;\n program: string;\n space: bigint;\n }\n // Binary\n | [encodedBytes: string, encoding: 'base58' | 'base64' | 'base64+zstd' | 'binary' | 'jsonParsed'];\n executable: boolean;\n lamports: bigint;\n owner: string;\n rentEpoch: bigint;\n space?: bigint;\n } | null)[]\n | null;\n err: TransactionError | null;\n // Enabled by `enable_cpi_recording`\n innerInstructions?:\n | {\n index: number;\n instructions: (\n | {\n // Compiled\n accounts: number[];\n data: string;\n programIdIndex: number;\n stackHeight?: number;\n }\n | {\n // Parsed\n parsed: unknown;\n program: string;\n programId: string;\n stackHeight?: number;\n }\n | {\n // PartiallyDecoded\n accounts: string[];\n data: string;\n programId: string;\n stackHeight?: number;\n }\n )[];\n }[]\n | null;\n loadedAccountsDataSize: number | null;\n logs: string[] | null;\n replacementBlockhash: string | null;\n returnData: {\n data: [string, 'base64'];\n programId: string;\n } | null;\n unitsConsumed: bigint | null;\n}\n\nexport function getSolanaErrorFromJsonRpcError(putativeErrorResponse: unknown): SolanaError {\n let out: SolanaError;\n if (isRpcErrorResponse(putativeErrorResponse)) {\n const { code: rawCode, data, message } = putativeErrorResponse;\n const code = Number(rawCode);\n if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {\n const { err, ...preflightErrorContext } = data as RpcSimulateTransactionResult;\n const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;\n out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {\n ...preflightErrorContext,\n ...causeObject,\n });\n } else {\n let errorContext;\n switch (code) {\n case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:\n case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:\n case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:\n case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:\n case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:\n case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:\n // The server supplies no structured data, but rather a pre-formatted message. Put\n // the server message in `context` so as not to completely lose the data. The long\n // term fix for this is to add data to the server responses and modify the\n // messages in `@solana/errors` to be actual format strings.\n errorContext = { __serverMessage: message };\n break;\n default:\n if (typeof data === 'object' && !Array.isArray(data)) {\n errorContext = data;\n }\n }\n out = new SolanaError(code as SolanaErrorCode, errorContext as SolanaErrorContext[SolanaErrorCode]);\n }\n } else {\n const message =\n typeof putativeErrorResponse === 'object' &&\n putativeErrorResponse !== null &&\n 'message' in putativeErrorResponse &&\n typeof putativeErrorResponse.message === 'string'\n ? putativeErrorResponse.message\n : 'Malformed JSON-RPC error with no message attribute';\n out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });\n }\n safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);\n return out;\n}\n\nfunction isRpcErrorResponse(value: unknown): value is RpcErrorResponse {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'code' in value &&\n 'message' in value &&\n (typeof value.code === 'number' || typeof value.code === 'bigint') &&\n typeof value.message === 'string'\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaErrorCode,\n} from './codes';\nimport { isSolanaError } from './error';\n\n/**\n * Extracts the underlying cause from a simulation-related error.\n *\n * When a transaction simulation fails, the error is often wrapped in a\n * simulation-specific {@link SolanaError}. This function unwraps such errors\n * by returning the `cause` property, giving you access to the actual error\n * that triggered the simulation failure.\n *\n * If the provided error is not a simulation-related error, it is returned unchanged.\n *\n * The following error codes are considered simulation errors:\n * - {@link SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE}\n * - {@link SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT}\n *\n * @param error - The error to unwrap.\n * @return The underlying cause if the error is a simulation error, otherwise the original error.\n *\n * @example\n * Unwrapping a preflight failure to access the root cause.\n * ```ts\n * import { unwrapSimulationError } from '@solana/errors';\n *\n * try {\n * await sendTransaction(signedTransaction);\n * } catch (e) {\n * const cause = unwrapSimulationError(e);\n * console.log('Send transaction failed due to:', cause);\n * }\n * ```\n */\nexport function unwrapSimulationError(error: unknown): unknown {\n const simulationCodes: SolanaErrorCode[] = [\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n ];\n if (isSolanaError(error) && !!error.cause && simulationCodes.includes(error.context.__code)) {\n return error.cause;\n }\n return error;\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n *\n * @param byteArrays - The array of byte arrays to concatenate.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02]);\n * const bytes2 = new Uint8Array([]);\n * const bytes3 = new Uint8Array([0x03, 0x04]);\n * const bytes = mergeBytes([bytes1, bytes2, bytes3]);\n * // ^ [0x01, 0x02, 0x03, 0x04]\n * ```\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n *\n * @param bytes - The byte array to pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 2);\n * // bytes === paddedBytes\n * ```\n */\nexport function padBytes(bytes: Uint8Array, length: number): Uint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n}\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n *\n * @param bytes - The byte array to truncate or pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Truncates the byte array to the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // ^ [0x01, 0x02]\n * ```\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // bytes === fixedBytes\n * ```\n */\nexport const fixBytes = (bytes: ReadonlyUint8Array | Uint8Array, length: number): ReadonlyUint8Array | Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n\n/**\n * Returns true if and only if the provided `data` byte array contains\n * the provided `bytes` byte array at the specified `offset`.\n *\n * @param data - The byte sequence to search for.\n * @param bytes - The byte array in which to search for `data`.\n * @param offset - The position in `bytes` where the search begins.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const data = new Uint8Array([0x02, 0x03]);\n * containsBytes(bytes, data, 1); // true\n * containsBytes(bytes, data, 2); // false\n * ```\n */\nexport function containsBytes(\n data: ReadonlyUint8Array | Uint8Array,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset: number,\n): boolean {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n return bytesEqual(slice, bytes);\n}\n\n/**\n * Returns true if and only if the provided `bytes1` and `bytes2` byte arrays are equal.\n *\n * @param bytes1 - The first byte array to compare.\n * @param bytes2 - The second byte array to compare.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const bytes2 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * bytesEqual(bytes1, bytes2); // true\n * ```\n */\nexport function bytesEqual(bytes1: ReadonlyUint8Array | Uint8Array, bytes2: ReadonlyUint8Array | Uint8Array): boolean {\n return bytes1.length === bytes2.length && bytes1.every((value, index) => value === bytes2[index]);\n}\n","import {\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * This is a common interface for {@link FixedSizeEncoder} and {@link VariableSizeEncoder}.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n */\ntype BaseEncoder = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a fixed-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const encoder: FixedSizeEncoder;\n * const bytes = encoder.encode(42);\n * const size = encoder.fixedSize; // 4\n * ```\n *\n * @see {@link Encoder}\n * @see {@link VariableSizeEncoder}\n */\nexport type FixedSizeEncoder = BaseEncoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a variable-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * ```ts\n * const encoder: VariableSizeEncoder;\n * const bytes = encoder.encode('hello');\n * const size = encoder.getSizeFromValue('hello');\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n */\nexport type VariableSizeEncoder = BaseEncoder & {\n /** Returns the size of the encoded value in bytes for a given input. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * An `Encoder` can be either:\n * - A {@link FixedSizeEncoder}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeEncoder}, where encoded values can vary in size.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * Encoding a value into a new byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = encoder.encode('hello');\n * ```\n *\n * @example\n * Writing the encoded value into an existing byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = new Uint8Array(100);\n * const nextOffset = encoder.write('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Encoders` manually using the {@link createEncoder} function but it is more common\n * to compose multiple `Encoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Encoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonEncoder = (): Encoder =>\n * getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * ```\n *\n * Note that composed `Encoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Encoder()` is\n * a fixed-size encoder, while `addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())`\n * is a variable-size encoder. This makes the final `Person` encoder a variable-size encoder.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link createEncoder}\n */\nexport type Encoder = FixedSizeEncoder | VariableSizeEncoder;\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * This is a common interface for {@link FixedSizeDecoder} and {@link VariableSizeDecoder}.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n */\ntype BaseDecoder = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: ReadonlyUint8Array | Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: ReadonlyUint8Array | Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\n/**\n * An object that can decode a fixed-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const decoder: FixedSizeDecoder;\n * const value = decoder.decode(bytes);\n * const size = decoder.fixedSize; // 4\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type FixedSizeDecoder = BaseDecoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can decode a variable-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const decoder: VariableSizeDecoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder = BaseDecoder & {\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * An `Decoder` can be either:\n * - A {@link FixedSizeDecoder}, where all byte arrays have the same fixed size.\n * - A {@link VariableSizeDecoder}, where byte arrays can vary in size.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * Getting the decoded value from a byte array.\n * ```ts\n * const decoder: Decoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @example\n * Reading the decoded value from a byte array at a specific offset\n * and getting the offset of the next byte to read.\n * ```ts\n * const decoder: Decoder;\n * const [value, nextOffset] = decoder.read('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Decoders` manually using the {@link createDecoder} function but it is more common\n * to compose multiple `Decoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Decoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonDecoder = (): Decoder =>\n * getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * ```\n *\n * Note that composed `Decoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Decoder()` is\n * a fixed-size decoder, while `addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())`\n * is a variable-size decoder. This makes the final `Person` decoder a variable-size decoder.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link createDecoder}\n */\nexport type Decoder = FixedSizeDecoder | VariableSizeDecoder;\n\n/**\n * An object that can encode and decode a value to and from a fixed-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const codec: FixedSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.fixedSize; // 8\n * ```\n *\n * @see {@link Codec}\n * @see {@link VariableSizeCodec}\n */\nexport type FixedSizeCodec = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a variable-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec: VariableSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.getSizeFromValue(42);\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n */\nexport type VariableSizeCodec = VariableSizeDecoder & VariableSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a byte array.\n *\n * A `Codec` can be either:\n * - A {@link FixedSizeCodec}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeCodec}, where encoded values can vary in size.\n *\n * @example\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode('hello');\n * const value = codec.decode(bytes); // 'hello'\n * ```\n *\n * @remarks\n * For convenience, codecs can encode looser types than they decode.\n * That is, type {@link TFrom} can be a superset of type {@link TTo}.\n * For instance, a `Codec` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * It is worth noting that codecs are the union of encoders and decoders.\n * This means that a `Codec` can be combined from an `Encoder`\n * and a `Decoder` using the {@link combineCodec} function. This is particularly\n * useful for library authors who want to expose all three types of objects to their users.\n *\n * ```ts\n * const encoder: Encoder;\n * const decoder: Decoder;\n * const codec: Codec = combineCodec(encoder, decoder);\n * ```\n *\n * Aside from combining encoders and decoders, codecs can also be created from scratch using\n * the {@link createCodec} function but it is more common to compose multiple codecs together\n * using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create a `Codec` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonCodec = (): Codec =>\n * getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * ```\n *\n * Note that composed `Codec` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Codec()` is\n * a fixed-size codec, while `addCodecSizePrefix(getUtf8Codec(), getU32Codec())`\n * is a variable-size codec. This makes the final `Person` codec a variable-size codec.\n *\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link combineCodec}\n * @see {@link createCodec}\n */\nexport type Codec = FixedSizeCodec | VariableSizeCodec;\n\n/**\n * Gets the encoded size of a given value in bytes using the provided encoder.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @param value - The value to be encoded.\n * @param encoder - The encoder used to determine the encoded size.\n * @returns The size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const fixedSizeEncoder = { fixedSize: 4 };\n * getEncodedSize(123, fixedSizeEncoder); // Returns 4.\n *\n * const variableSizeEncoder = { getSizeFromValue: (value: string) => value.length };\n * getEncodedSize(\"hello\", variableSizeEncoder); // Returns 5.\n * ```\n *\n * @see {@link Encoder}\n */\nexport function getEncodedSize(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/**\n * Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and\n * either the `fixedSize` property (for {@link FixedSizeEncoder | FixedSizeEncoders}) or\n * the `getSizeFromValue` function (for {@link VariableSizeEncoder | VariableSizeEncoders}).\n *\n * Instead of manually implementing `encode`, this utility leverages the existing `write` function\n * and the size helpers to generate a complete encoder. The provided `encode` method will allocate\n * a new `Uint8Array` of the correct size and use `write` to populate it.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size encoders).\n *\n * @param encoder - An encoder object that implements `write`, but not `encode`.\n * - If the encoder has a `fixedSize` property, it is treated as a {@link FixedSizeEncoder}.\n * - Otherwise, it is treated as a {@link VariableSizeEncoder}.\n *\n * @returns A fully functional `Encoder` with both `write` and `encode` methods.\n *\n * @example\n * Creating a custom fixed-size encoder.\n * ```ts\n * const encoder = createEncoder({\n * fixedSize: 4,\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n * ```\n *\n * @example\n * Creating a custom variable-size encoder:\n * ```ts\n * const encoder = createEncoder({\n * getSizeFromValue: (value: string) => value.length,\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = encoder.encode(\"hello\");\n * // 0x68656c6c6f\n * ```\n *\n * @remarks\n * Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose\n * encoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createEncoder`.\n *\n * ```ts\n * // Fixed-size encoder for unsigned 32-bit integers.\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n *\n * // Variable-size encoder for 32-bytes prefixed UTF-8 strings.\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const bytes = encoder.encode(\"hello\");\n * // 0x0500000068656c6c6f\n *\n * // Variable-size encoder for custom objects.\n * type Person = { name: string; age: number };\n * const encoder: Encoder = getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * const bytes = encoder.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link getStructEncoder}\n * @see {@link getU32Encoder}\n * @see {@link getUtf8Encoder}\n * @see {@link addEncoderSizePrefix}\n */\nexport function createEncoder(\n encoder: Omit, 'encode'>,\n): FixedSizeEncoder;\nexport function createEncoder(encoder: Omit, 'encode'>): VariableSizeEncoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function.\n *\n * Instead of manually implementing `decode`, this utility leverages the existing `read` function\n * and the size properties to generate a complete decoder. The provided `decode` method will read\n * from a `Uint8Array` at the given offset and return the decoded value.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeDecoder} will be created, otherwise\n * a {@link VariableSizeDecoder} will be created.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size decoders).\n *\n * @param decoder - A decoder object that implements `read`, but not `decode`.\n * - If the decoder has a `fixedSize` property, it is treated as a {@link FixedSizeDecoder}.\n * - Otherwise, it is treated as a {@link VariableSizeDecoder}.\n *\n * @returns A fully functional `Decoder` with both `read` and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size decoder.\n * ```ts\n * const decoder = createDecoder({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size decoder:\n * ```ts\n * const decoder = createDecoder({\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111]));\n * // \"hello\"\n * ```\n *\n * @remarks\n * Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose\n * decoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createDecoder`.\n *\n * ```ts\n * // Fixed-size decoder for unsigned 32-bit integers.\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n *\n * // Variable-size decoder for 32-bytes prefixed UTF-8 strings.\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111]));\n * // \"hello\"\n *\n * // Variable-size decoder for custom objects.\n * type Person = { name: string; age: number };\n * const decoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0]));\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Decoder}\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link getStructDecoder}\n * @see {@link getU32Decoder}\n * @see {@link getUtf8Decoder}\n * @see {@link addDecoderSizePrefix}\n */\nexport function createDecoder(\n decoder: Omit, 'decode'>,\n): FixedSizeDecoder;\nexport function createDecoder(decoder: Omit, 'decode'>): VariableSizeDecoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/**\n * Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions.\n *\n * This utility combines the behavior of {@link createEncoder} and {@link createDecoder} to produce a fully functional `Codec`.\n * The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeCodec} will be created, otherwise\n * a {@link VariableSizeCodec} will be created.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param codec - A codec object that implements `write` and `read`, but not `encode` or `decode`.\n * - If the codec has a `fixedSize` property, it is treated as a {@link FixedSizeCodec}.\n * - Otherwise, it is treated as a {@link VariableSizeCodec}.\n *\n * @returns A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size codec.\n * ```ts\n * const codec = createCodec({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size codec:\n * ```ts\n * const codec = createCodec({\n * getSizeFromValue: (value: string) => value.length,\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = codec.encode(\"hello\");\n * // 0x68656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n * ```\n *\n * @remarks\n * This function effectively combines the behavior of {@link createEncoder} and {@link createDecoder}.\n * If you only need to encode or decode (but not both), consider using those functions instead.\n *\n * Here are some alternative examples using codec primitives instead of `createCodec`.\n *\n * ```ts\n * // Fixed-size codec for unsigned 32-bit integers.\n * const codec = getU32Codec();\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n *\n * // Variable-size codec for 32-bytes prefixed UTF-8 strings.\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const bytes = codec.encode(\"hello\");\n * // 0x0500000068656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n *\n * // Variable-size codec for custom objects.\n * type Person = { name: string; age: number };\n * const codec: Codec = getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * const bytes = codec.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * const value = codec.decode(bytes);\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link createEncoder}\n * @see {@link createDecoder}\n * @see {@link getStructCodec}\n * @see {@link getU32Codec}\n * @see {@link getUtf8Codec}\n * @see {@link addCodecSizePrefix}\n */\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): FixedSizeCodec;\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): VariableSizeCodec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is fixed-size.\n *\n * A fixed-size object is identified by the presence of a `fixedSize` property.\n * If this property exists, the object is considered a {@link FixedSizeCodec},\n * {@link FixedSizeEncoder}, or {@link FixedSizeDecoder}.\n * Otherwise, it is assumed to be a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is fixed-size, `false` otherwise.\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isFixedSize(encoder); // true\n * ```\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isFixedSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is commonly used to distinguish between fixed-size and variable-size objects at runtime.\n * If you need to enforce this distinction with type assertions, consider using {@link assertIsFixedSize}.\n *\n * @see {@link assertIsFixedSize}\n */\nexport function isFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): encoder is FixedSizeEncoder;\nexport function isFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): decoder is FixedSizeDecoder;\nexport function isFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): codec is FixedSizeCodec;\nexport function isFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is fixed-size.\n *\n * If the object is not fixed-size (i.e., it lacks a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not fixed-size.\n *\n * @example\n * Asserting a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsFixedSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsFixedSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isFixedSize}.\n * If you only need to check whether an object is fixed-size without throwing an error, use {@link isFixedSize} instead.\n *\n * @see {@link isFixedSize}\n */\nexport function assertIsFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): asserts encoder is FixedSizeEncoder;\nexport function assertIsFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): asserts decoder is FixedSizeDecoder;\nexport function assertIsFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): asserts codec is FixedSizeCodec;\nexport function assertIsFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is variable-size.\n *\n * A variable-size object is identified by the absence of a `fixedSize` property.\n * If this property is missing, the object is considered a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is variable-size, `false` otherwise.\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isVariableSize(encoder); // true\n * ```\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isVariableSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is the inverse of {@link isFixedSize}.\n *\n * @see {@link isFixedSize}\n * @see {@link assertIsVariableSize}\n */\nexport function isVariableSize(encoder: Encoder): encoder is VariableSizeEncoder;\nexport function isVariableSize(decoder: Decoder): decoder is VariableSizeDecoder;\nexport function isVariableSize(\n codec: Codec,\n): codec is VariableSizeCodec;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is variable-size.\n *\n * If the object is not variable-size (i.e., it has a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not variable-size.\n *\n * @example\n * Asserting a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsVariableSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsVariableSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isVariableSize}.\n * If you only need to check whether an object is variable-size without throwing an error, use {@link isVariableSize} instead.\n *\n * Also note that this function is the inverse of {@link assertIsFixedSize}.\n *\n * @see {@link isVariableSize}\n * @see {@link assertIsFixedSize}\n */\nexport function assertIsVariableSize(encoder: Encoder): asserts encoder is VariableSizeEncoder;\nexport function assertIsVariableSize(decoder: Decoder): asserts decoder is VariableSizeDecoder;\nexport function assertIsVariableSize(\n codec: Codec,\n): asserts codec is VariableSizeCodec;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an `Encoder` and a `Decoder` into a `Codec`.\n *\n * That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`.\n *\n * This allows for modular composition by keeping encoding and decoding logic separate\n * while still offering a convenient way to bundle them into a single `Codec`.\n * This is particularly useful for library maintainers who want to expose `Encoders`,\n * `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic.\n *\n * The provided `Encoder` and `Decoder` must be compatible in terms of:\n * - **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value.\n * - **Variable Size:** If either has a `maxSize` attribute, it must match the other.\n *\n * If these conditions are not met, a {@link SolanaError} will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param encoder - The `Encoder` to combine.\n * @param decoder - The `Decoder` to combine.\n * @returns A `Codec` that provides both `encode` and `decode` methods.\n *\n * @throws {SolanaError}\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH`\n * Thrown if the encoder and decoder have mismatched size types (fixed vs. variable).\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH`\n * Thrown if both are fixed-size but have different `fixedSize` values.\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH`\n * Thrown if the `maxSize` attributes do not match.\n *\n * @example\n * Creating a fixed-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = getU32Encoder();\n * const decoder = getU32Decoder();\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(42); // 0x2a000000\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Creating a variable-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(\"hello\"); // 0x0500000068656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec.\n * This allows users to import only what they need, improving tree-shaking efficiency.\n *\n * ```ts\n * type MyType = \\/* ... *\\/;\n * const getMyTypeEncoder = (): Encoder => { \\/* ... *\\/ };\n * const getMyTypeDecoder = (): Decoder => { \\/* ... *\\/ };\n * const getMyTypeCodec = (): Codec =>\n * combineCodec(getMyTypeEncoder(), getMyTypeDecoder());\n * ```\n *\n * @see {@link Codec}\n * @see {@link Encoder}\n * @see {@link Decoder}\n */\nexport function combineCodec(\n encoder: FixedSizeEncoder,\n decoder: FixedSizeDecoder,\n): FixedSizeCodec;\nexport function combineCodec(\n encoder: VariableSizeEncoder,\n decoder: VariableSizeDecoder,\n): VariableSizeCodec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {\n decoderFixedSize: decoder.fixedSize,\n encoderFixedSize: encoder.fixedSize,\n });\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {\n decoderMaxSize: decoder.maxSize,\n encoderMaxSize: encoder.maxSize,\n });\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SolanaError,\n} from '@solana/errors';\n\nimport { containsBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Creates an encoder that writes a `Uint8Array` sentinel after the encoded value.\n * This is useful to delimit the encoded value when being read by a decoder.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addEncoderSentinel(\n encoder: FixedSizeEncoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeEncoder;\nexport function addEncoderSentinel(\n encoder: Encoder,\n sentinel: ReadonlyUint8Array,\n): VariableSizeEncoder;\nexport function addEncoderSentinel(encoder: Encoder, sentinel: ReadonlyUint8Array): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds\n // and to avoid writing the sentinel as part of the encoded value.\n const encoderBytes = encoder.encode(value);\n if (findSentinelIndex(encoderBytes, sentinel) >= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {\n encodedBytes: encoderBytes,\n hexEncodedBytes: hexBytes(encoderBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n bytes.set(encoderBytes, offset);\n offset += encoderBytes.length;\n bytes.set(sentinel, offset);\n offset += sentinel.length;\n return offset;\n }) as Encoder['write'];\n\n if (isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });\n }\n\n return createEncoder({\n ...encoder,\n ...(encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {}),\n getSizeFromValue: value => encoder.getSizeFromValue(value) + sentinel.length,\n write,\n });\n}\n\n/**\n * Creates a decoder that continues reading until\n * a given `Uint8Array` sentinel is found.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addDecoderSentinel(\n decoder: FixedSizeDecoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): VariableSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): Decoder {\n const read = ((bytes, offset) => {\n const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);\n const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);\n if (sentinelIndex === -1) {\n throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {\n decodedBytes: candidateBytes,\n hexDecodedBytes: hexBytes(candidateBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds\n // and ensure that the sentinel is not part of the decoded value.\n return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];\n }) as Decoder['read'];\n\n if (isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });\n }\n\n return createDecoder({\n ...decoder,\n ...(decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {}),\n read,\n });\n}\n\n/**\n * Creates a Codec that writes a given `Uint8Array` sentinel after the encoded\n * value and, when decoding, continues reading until the sentinel is found.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255]));\n * codec.encode('hello');\n * // 0x68656c6c6fffff\n * // | └-- Our sentinel.\n * // └-- Our encoded string.\n * ```\n *\n * @remarks\n * Note that the sentinel _must not_ be present in the encoded data and\n * _must_ be present in the decoded data for this to work.\n * If this is not the case, dedicated errors will be thrown.\n *\n * ```ts\n * const sentinel = new Uint8Array([108, 108]); // 'll'\n * const codec = addCodecSentinel(getUtf8Codec(), sentinel);\n *\n * codec.encode('hello'); // Throws: sentinel is in encoded data.\n * codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data.\n * ```\n *\n * Separate {@link addEncoderSentinel} and {@link addDecoderSentinel} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello');\n * const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSentinel}\n * @see {@link addDecoderSentinel}\n */\nexport function addCodecSentinel(\n codec: FixedSizeCodec,\n sentinel: ReadonlyUint8Array,\n): FixedSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): VariableSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): Codec {\n return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));\n}\n\nfunction findSentinelIndex(bytes: ReadonlyUint8Array, sentinel: ReadonlyUint8Array) {\n return bytes.findIndex((byte, index, arr) => {\n if (sentinel.length === 1) return byte === sentinel[0];\n return containsBytes(arr, sentinel, index);\n });\n}\n\nfunction hexBytes(bytes: ReadonlyUint8Array): string {\n return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n","import {\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Asserts that a given byte array is not empty (after the optional provided offset).\n *\n * Returns void if the byte array is not empty but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n * If provided, the byte array is considered empty if it has no bytes after the offset.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws\n * ```\n */\nexport function assertByteArrayIsNotEmptyForCodec(\n codecDescription: string,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription,\n });\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode\n * (after the optional provided offset).\n *\n * Returns void if the byte array has at least the expected number\n * of bytes but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param expected - The minimum number of bytes expected in the byte array.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws\n * ```\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected,\n });\n }\n}\n\n/**\n * Asserts that a given offset is within the byte array bounds.\n * This range is between 0 and the byte array length and is inclusive.\n * An offset equals to the byte array length is considered a valid offset\n * as it allows the post-offset of codecs to signal the end of the byte array.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param offset - The offset to check.\n * @param bytesLength - The length of the byte array from which the offset should be within bounds.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws\n * ```\n */\nexport function assertByteArrayOffsetIsNotOutOfRange(codecDescription: string, offset: number, bytesLength: number) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset,\n });\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\ntype NumberEncoder = Encoder | Encoder;\ntype FixedSizeNumberEncoder =\n | FixedSizeEncoder\n | FixedSizeEncoder;\ntype NumberDecoder = Decoder | Decoder;\ntype FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\ntype NumberCodec = Codec | Codec;\ntype FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addEncoderSizePrefix(\n encoder: FixedSizeEncoder,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): VariableSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds.\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n }) as Encoder['write'];\n\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : (encoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n\n return createEncoder({\n ...encoder,\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: value => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write,\n });\n}\n\n/**\n * Bounds the size of the nested `decoder` by reading its encoded `prefix`.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addDecoderSizePrefix(\n decoder: FixedSizeDecoder,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): VariableSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): Decoder {\n const read = ((bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n // Slice the byte array to the contained size if necessary.\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec('addDecoderSizePrefix', size, bytes);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds.\n return [decoder.decode(bytes), offset + size];\n }) as Decoder['read'];\n\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : (decoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...(maxSize !== null ? { maxSize } : {}), read });\n}\n\n/**\n * Stores the byte size of any given codec as an encoded number prefix.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n * When encoding, the size of the encoded data is stored before the encoded data itself.\n * When decoding, the size is read first to know how many bytes to read next.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * For example, say we want to bound a variable-size base-58 string using a `u32` size prefix.\n * Here’s how you can use the `addCodecSizePrefix` function to achieve that.\n *\n * ```ts\n * const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());\n *\n * getU32Base58Codec().encode('hello world');\n * // 0x0b00000068656c6c6f20776f726c64\n * // | └-- Our encoded base-58 string.\n * // └-- Our encoded u32 size prefix.\n * ```\n *\n * @remarks\n * Separate {@link addEncoderSizePrefix} and {@link addDecoderSizePrefix} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');\n * const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSizePrefix}\n * @see {@link addDecoderSizePrefix}\n */\nexport function addCodecSizePrefix(\n codec: FixedSizeCodec,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): VariableSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): Codec {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Converts a `Uint8Array` to an `ArrayBuffer`. If the underlying buffer is a `SharedArrayBuffer`,\n * it will be copied to a non-shared buffer, for safety.\n *\n * @remarks\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nexport function toArrayBuffer(bytes: ReadonlyUint8Array | Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n let buffer: ArrayBuffer;\n if (typeof SharedArrayBuffer === 'undefined') {\n buffer = bytes.buffer as ArrayBuffer;\n } else if (bytes.buffer instanceof SharedArrayBuffer) {\n buffer = new ArrayBuffer(bytes.length);\n new Uint8Array(buffer).set(new Uint8Array(bytes));\n } else {\n buffer = bytes.buffer;\n }\n return (bytesOffset === 0 || bytesOffset === -bytes.byteLength) && bytesLength === bytes.byteLength\n ? buffer\n : buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, SolanaError } from '@solana/errors';\n\nimport { createDecoder, Decoder } from './codec';\n\n/**\n * Create a {@link Decoder} that asserts that the bytes provided to `decode` or `read` are fully consumed by the inner decoder\n * @param decoder A decoder to wrap\n * @returns A new decoder that will throw if provided with a byte array that it does not fully consume\n *\n * @typeParam T - The type of the decoder\n *\n * @remarks\n * Note that this compares the offset after encoding to the length of the input byte array\n *\n * The `offset` parameter to `decode` and `read` is still considered, and will affect the new offset that is compared to the byte array length\n *\n * The error that is thrown by the returned decoder is a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY`\n *\n * @example\n * Create a decoder that decodes a `u32` (4 bytes) and ensures the entire byte array is consumed\n * ```ts\n * const decoder = createDecoderThatUsesExactByteArray(getU32Decoder());\n * decoder.decode(new Uint8Array([0, 0, 0, 0])); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0])); // throws\n *\n * // with an offset\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0]), 1); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0, 0]), 1); // throws\n * ```\n */\nexport function createDecoderThatConsumesEntireByteArray(decoder: Decoder): Decoder {\n return createDecoder({\n ...decoder,\n read(bytes, offset) {\n const [value, newOffset] = decoder.read(bytes, offset);\n if (bytes.length > newOffset) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, {\n expectedLength: newOffset,\n numExcessBytes: bytes.length - newOffset,\n });\n }\n return [value, newOffset];\n },\n });\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * The resulting encoder ensures that encoded values always have the specified number of bytes.\n * If the original encoded value is larger than `fixedBytes`, it is truncated.\n * If it is smaller, it is padded with trailing zeroes.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @returns A `FixedSizeEncoder` that ensures a consistent output size.\n *\n * @example\n * ```ts\n * const encoder = fixEncoderSize(getUtf8Encoder(), 4);\n * encoder.encode(\"Hello\"); // 0x48656c6c (truncated)\n * encoder.encode(\"Hi\"); // 0x48690000 (padded)\n * encoder.encode(\"Hiya\"); // 0x48697961 (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixEncoderSize(\n encoder: Encoder,\n fixedBytes: TSize,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * The resulting decoder always reads exactly `fixedBytes` bytes from the input.\n * If the nested decoder is also fixed-size, the bytes are truncated or padded as needed.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @returns A `FixedSizeDecoder` that ensures a consistent input size.\n *\n * @example\n * ```ts\n * const decoder = fixDecoderSize(getUtf8Decoder(), 4);\n * decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // \"Hell\" (truncated)\n * decoder.decode(new Uint8Array([72, 105, 0, 0])); // \"Hi\" (zeroes ignored)\n * decoder.decode(new Uint8Array([72, 105, 121, 97])); // \"Hiya\" (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixEncoderSize}\n */\nexport function fixDecoderSize(\n decoder: Decoder,\n fixedBytes: TSize,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodecSize', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes.\n * When encoding:\n * - If the encoded value is larger than `fixedBytes`, it is truncated.\n * - If it is smaller, it is padded with trailing zeroes.\n * - If it is exactly `fixedBytes`, it remains unchanged.\n *\n * When decoding:\n * - Exactly `fixedBytes` bytes are read from the input.\n * - If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @returns A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size.\n *\n * @example\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 4);\n *\n * const bytes1 = codec.encode(\"Hello\"); // 0x48656c6c (truncated)\n * const value1 = codec.decode(bytes1); // \"Hell\"\n *\n * const bytes2 = codec.encode(\"Hi\"); // 0x48690000 (padded)\n * const value2 = codec.decode(bytes2); // \"Hi\"\n *\n * const bytes3 = codec.encode(\"Hiya\"); // 0x48697961 (same length)\n * const value3 = codec.decode(bytes3); // \"Hiya\"\n * ```\n *\n * @remarks\n * If you only need to enforce a fixed size for encoding, use {@link fixEncoderSize}.\n * If you only need to enforce a fixed size for decoding, use {@link fixDecoderSize}.\n *\n * ```ts\n * const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode(\"Hiya\");\n * const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);\n * ```\n *\n * @see {@link fixEncoderSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixCodecSize(\n codec: Codec,\n fixedBytes: TSize,\n): FixedSizeCodec {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));\n}\n","import { assertByteArrayOffsetIsNotOutOfRange } from './assertions';\nimport { Codec, createDecoder, createEncoder, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Configuration object for modifying the offset of an encoder, decoder, or codec.\n *\n * This type defines optional functions for adjusting the **pre-offset** (before encoding/decoding)\n * and the **post-offset** (after encoding/decoding). These functions allow precise control\n * over where data is written or read within a byte array.\n *\n * @property preOffset - A function that modifies the offset before encoding or decoding.\n * @property postOffset - A function that modifies the offset after encoding or decoding.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * };\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * };\n * ```\n *\n * @example\n * Using both pre-offset and post-offset together.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * postOffset: ({ postOffset }) => postOffset + 4,\n * };\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n * @see {@link offsetCodec}\n */\ntype OffsetConfig = {\n postOffset?: PostOffsetFunction;\n preOffset?: PreOffsetFunction;\n};\n\n/**\n * Scope provided to the `preOffset` and `postOffset` functions,\n * containing contextual information about the current encoding or decoding process.\n *\n * The pre-offset function modifies where encoding or decoding begins,\n * while the post-offset function modifies where the next operation continues.\n *\n * @property bytes - The entire byte array being encoded or decoded.\n * @property preOffset - The original offset before encoding or decoding starts.\n * @property wrapBytes - A helper function that wraps offsets around the byte array length.\n *\n * @example\n * Using `wrapBytes` to wrap a negative offset to the end of the byte array.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves to last 4 bytes\n * };\n * ```\n *\n * @example\n * Adjusting the offset dynamically based on the byte array size.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ bytes }) => bytes.length > 10 ? 4 : 2,\n * };\n * ```\n *\n * @see {@link PreOffsetFunction}\n * @see {@link PostOffsetFunction}\n */\ntype PreOffsetFunctionScope = {\n /** The entire byte array. */\n bytes: ReadonlyUint8Array | Uint8Array;\n /** The original offset prior to encode or decode. */\n preOffset: Offset;\n /** Wraps the offset to the byte array length. */\n wrapBytes: (offset: Offset) => Offset;\n};\n\n/**\n * A function that modifies the pre-offset before encoding or decoding.\n *\n * This function is used to adjust the starting position before writing\n * or reading data in a byte array.\n *\n * @param scope - The current encoding or decoding context.\n * @returns The new offset at which encoding or decoding should start.\n *\n * @example\n * Skipping the first 2 bytes before writing or reading.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ preOffset }) => preOffset + 2;\n * ```\n *\n * @example\n * Wrapping the offset to ensure it stays within bounds.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ wrapBytes, preOffset }) => wrapBytes(preOffset + 10);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PreOffsetFunction = (scope: PreOffsetFunctionScope) => Offset;\n\n/**\n * A function that modifies the post-offset after encoding or decoding.\n *\n * This function adjusts where the next encoder or decoder should start\n * after the current operation has completed.\n *\n * @param scope - The current encoding or decoding context, including the modified pre-offset\n * and the original post-offset.\n * @returns The new offset at which the next operation should begin.\n *\n * @example\n * Moving the post-offset forward by 4 bytes.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset }) => postOffset + 4;\n * ```\n *\n * @example\n * Wrapping the post-offset within the byte array length.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ wrapBytes, postOffset }) => wrapBytes(postOffset);\n * ```\n *\n * @example\n * Ensuring a minimum spacing of 8 bytes between values.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset, newPreOffset }) =>\n * Math.max(postOffset, newPreOffset + 8);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PostOffsetFunction = (\n scope: PreOffsetFunctionScope & {\n /** The modified offset used to encode or decode. */\n newPreOffset: Offset;\n /** The original offset returned by the encoder or decoder. */\n postOffset: Offset;\n },\n) => Offset;\n\n/**\n * Moves the offset of a given encoder before and/or after encoding.\n *\n * This function allows an encoder to write its encoded value at a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before encoding) and post-offset adjustments (after encoding).\n *\n * The pre-offset function determines where encoding should start, while the\n * post-offset function adjusts where the next encoder should continue writing.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new encoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Actually written at offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * const nextOffset = encoder.write(42, bytes, 0); // Next encoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to ensure an offset wraps around the byte array length.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Writes at bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetDecoder}\n */\nexport function offsetEncoder(encoder: TEncoder, config: OffsetConfig): TEncoder {\n return createEncoder({\n ...encoder,\n write: (value, bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPreOffset, bytes.length);\n const postOffset = encoder.write(value, bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPostOffset, bytes.length);\n return newPostOffset;\n },\n }) as TEncoder;\n}\n\n/**\n * Moves the offset of a given decoder before and/or after decoding.\n *\n * This function allows a decoder to read its input from a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before decoding) and post-offset adjustments (after decoding).\n *\n * The pre-offset function determines where decoding should start, while the\n * post-offset function adjusts where the next decoder should continue reading.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new decoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array([0, 0, 42, 0]); // Value starts at offset 2\n * decoder.read(bytes, 0); // Actually reads from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array([42, 0, 0, 0]);\n * const [value, nextOffset] = decoder.read(bytes, 0); // Next decoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to read from the last 4 bytes of an array.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 42]); // Value stored at the last 4 bytes\n * decoder.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetEncoder}\n */\nexport function offsetDecoder(decoder: TDecoder, config: OffsetConfig): TDecoder {\n return createDecoder({\n ...decoder,\n read: (bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPreOffset, bytes.length);\n const [value, postOffset] = decoder.read(bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPostOffset, bytes.length);\n return [value, newPostOffset];\n },\n }) as TDecoder;\n}\n\n/**\n * Moves the offset of a given codec before and/or after encoding and decoding.\n *\n * This function allows a codec to encode and decode values at custom offsets\n * within a byte array. It modifies both the **pre-offset** (where encoding/decoding starts)\n * and the **post-offset** (where the next operation should continue).\n *\n * This is particularly useful when working with structured binary formats\n * that require skipping reserved bytes, inserting padding, or aligning fields at\n * specific locations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new codec with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Actually written at offset 2\n * codec.read(bytes, 0); // Actually read from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0);\n * // Next encoding starts at offset 6 instead of 4\n * codec.read(bytes, 0);\n * // Next decoding starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to loop around negative offsets.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Writes at bytes.length - 4\n * codec.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you only need to adjust offsets for encoding, use {@link offsetEncoder}.\n * If you only need to adjust offsets for decoding, use {@link offsetDecoder}.\n *\n * ```ts\n * const bytes = new Uint8Array(10);\n * offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).write(42, bytes, 0);\n * const [value] = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).read(bytes, 0);\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n */\nexport function offsetCodec(codec: TCodec, config: OffsetConfig): TCodec {\n return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config)) as TCodec;\n}\n\n/** A modulo function that handles negative dividends and zero divisors. */\nfunction modulo(dividend: number, divisor: number) {\n if (divisor === 0) return 0;\n return ((dividend % divisor) + divisor) % divisor;\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Updates the size of a given encoder.\n *\n * This function modifies the size of an encoder using a provided transformation function.\n * For fixed-size encoders, it updates the `fixedSize` property, and for variable-size\n * encoders, it adjusts the size calculation based on the encoded value.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The original fixed size of the encoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param encoder - The encoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new encoder with the updated size.\n *\n * @example\n * Increasing the size of a `u16` encoder by 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU16Encoder(), size => size + 2);\n * encoder.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * ```\n *\n * @example\n * Shrinking a `u32` encoder to only use 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU32Encoder(), () => 2);\n * encoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeDecoder}\n */\nexport function resizeEncoder(\n encoder: FixedSizeEncoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder {\n if (isFixedSize(encoder)) {\n const fixedSize = resize(encoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return createEncoder({ ...encoder, fixedSize }) as TEncoder;\n }\n return createEncoder({\n ...encoder,\n getSizeFromValue: value => {\n const newSize = resize(encoder.getSizeFromValue(value));\n if (newSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: newSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return newSize;\n },\n }) as TEncoder;\n}\n\n/**\n * Updates the size of a given decoder.\n *\n * This function modifies the size of a decoder using a provided transformation function.\n * For fixed-size decoders, it updates the `fixedSize` property to reflect the new size.\n * Variable-size decoders remain unchanged, as their size is determined dynamically.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the decoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param decoder - The decoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new decoder with the updated size.\n *\n * @example\n * Expanding a `u16` decoder to read 4 bytes instead of 2.\n * ```ts\n * const decoder = resizeDecoder(getU16Decoder(), size => size + 2);\n * decoder.fixedSize; // 4\n * ```\n *\n * @example\n * Shrinking a `u32` decoder to only read 2 bytes.\n * ```ts\n * const decoder = resizeDecoder(getU32Decoder(), () => 2);\n * decoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeEncoder}\n */\nexport function resizeDecoder(\n decoder: FixedSizeDecoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder {\n if (isFixedSize(decoder)) {\n const fixedSize = resize(decoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeDecoder',\n });\n }\n return createDecoder({ ...decoder, fixedSize }) as TDecoder;\n }\n return decoder;\n}\n\n/**\n * Updates the size of a given codec.\n *\n * This function modifies the size of both the codec using a provided\n * transformation function. It is useful for adjusting the allocated byte size for\n * encoding and decoding without altering the underlying data structure.\n *\n * If the new size is negative, an error will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the encoded/decoded value (for fixed-size codecs).\n * @typeParam TNewSize - The new fixed size after resizing (for fixed-size codecs).\n *\n * @param codec - The codec whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new codec with the updated size.\n *\n * @example\n * Expanding a `u16` codec from 2 to 4 bytes.\n * ```ts\n * const codec = resizeCodec(getU16Codec(), size => size + 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (reads original two bytes)\n * ```\n *\n * @example\n * Shrinking a `u32` codec to only use 2 bytes.\n * ```ts\n * const codec = resizeCodec(getU32Codec(), () => 2);\n * codec.fixedSize; // 2\n * ```\n *\n * @remarks\n * If you only need to resize an encoder, use {@link resizeEncoder}.\n * If you only need to resize a decoder, use {@link resizeDecoder}.\n *\n * ```ts\n * const bytes = resizeEncoder(getU32Encoder(), (size) => size + 2).encode(0xffff);\n * const value = resizeDecoder(getU32Decoder(), (size) => size + 2).decode(bytes);\n * ```\n *\n * @see {@link resizeEncoder}\n * @see {@link resizeDecoder}\n */\nexport function resizeCodec(\n codec: FixedSizeCodec,\n resize: (size: TSize) => TNewSize,\n): FixedSizeCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec {\n return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize)) as TCodec;\n}\n","import { Codec, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { offsetDecoder, offsetEncoder } from './offset-codec';\nimport { resizeDecoder, resizeEncoder } from './resize-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Adds left padding to the given encoder, shifting the encoded value forward\n * by `offset` bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add before encoding.\n * @returns A new encoder with left padding applied.\n *\n * @example\n * ```ts\n * const encoder = padLeftEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given encoder, extending the encoded value by `offset`\n * bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add after encoding.\n * @returns A new encoder with right padding applied.\n *\n * @example\n * ```ts\n * const encoder = padRightEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0xffff0000 (two extra bytes added at the end)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightDecoder}\n */\nexport function padRightEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given decoder, shifting the decoding position forward\n * by `offset` bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip before decoding.\n * @returns A new decoder with left padding applied.\n *\n * @example\n * ```ts\n * const decoder = padLeftDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0, 0, 0x12, 0x34])); // 0xffff (reads from offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftEncoder}\n */\nexport function padLeftDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given decoder, extending the post-offset by `offset`\n * bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip after decoding.\n * @returns A new decoder with right padding applied.\n *\n * @example\n * ```ts\n * const decoder = padRightDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0x12, 0x34, 0, 0])); // 0xffff (ignores trailing bytes)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightEncoder}\n */\nexport function padRightDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given codec, shifting the encoding and decoding positions\n * forward by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * This ensures that values are read and written at a later position in the byte array,\n * while the padding bytes remain unused.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add before encoding and decoding.\n * @returns A new codec with left padding applied.\n *\n * @example\n * ```ts\n * const codec = padLeftCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * const value = codec.decode(bytes); // 0xffff (reads from offset 2)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padLeftEncoder}.\n * If you only need to apply padding for decoding, use {@link padLeftDecoder}.\n *\n * ```ts\n * const bytes = padLeftEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padLeftDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padLeftEncoder}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset)) as TCodec;\n}\n\n/**\n * Adds right padding to the given codec, extending the encoded and decoded value\n * by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * The extra bytes remain unused, ensuring that the next operation starts further\n * along the byte array.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add after encoding and decoding.\n * @returns A new codec with right padding applied.\n *\n * @example\n * ```ts\n * const codec = padRightCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (ignores padding bytes)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padRightEncoder}.\n * If you only need to apply padding for decoding, use {@link padRightDecoder}.\n *\n * ```ts\n * const bytes = padRightEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padRightDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padRightEncoder}\n * @see {@link padRightDecoder}\n */\nexport function padRightCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset)) as TCodec;\n}\n","import {\n assertIsFixedSize,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\nfunction copySourceToTargetInReverse(\n source: ReadonlyUint8Array,\n target_WILL_MUTATE: Uint8Array,\n sourceOffset: number,\n sourceLength: number,\n targetOffset: number = 0,\n) {\n while (sourceOffset < --sourceLength) {\n const leftValue = source[sourceOffset];\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];\n target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;\n sourceOffset++;\n }\n if (sourceOffset === sourceLength) {\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];\n }\n}\n\n/**\n * Reverses the bytes of a fixed-size encoder.\n *\n * Given a `FixedSizeEncoder`, this function returns a new `FixedSizeEncoder` that\n * reverses the bytes within the fixed-size byte array when encoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The fixed-size encoder to reverse.\n * @returns A new encoder that writes bytes in reverse order.\n *\n * @example\n * Encoding a `u16` value in reverse order.\n * ```ts\n * const encoder = reverseEncoder(getU16Encoder({ endian: Endian.Big }));\n * const bytes = encoder.encode(0x1234); // 0x3412 (bytes are flipped)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseDecoder}\n */\nexport function reverseEncoder(\n encoder: FixedSizeEncoder,\n): FixedSizeEncoder {\n assertIsFixedSize(encoder);\n return createEncoder({\n ...encoder,\n write: (value: TFrom, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n copySourceToTargetInReverse(\n bytes /* source */,\n bytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + encoder.fixedSize /* sourceLength */,\n );\n return newOffset;\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size decoder.\n *\n * Given a `FixedSizeDecoder`, this function returns a new `FixedSizeDecoder` that\n * reverses the bytes within the fixed-size byte array before decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the decoded value in bytes.\n *\n * @param decoder - The fixed-size decoder to reverse.\n * @returns A new decoder that reads bytes in reverse order.\n *\n * @example\n * Decoding a reversed `u16` value.\n * ```ts\n * const decoder = reverseDecoder(getU16Decoder({ endian: Endian.Big }));\n * const value = decoder.decode(new Uint8Array([0x34, 0x12])); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseEncoder}\n */\nexport function reverseDecoder(\n decoder: FixedSizeDecoder,\n): FixedSizeDecoder {\n assertIsFixedSize(decoder);\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reversedBytes = bytes.slice();\n copySourceToTargetInReverse(\n bytes /* source */,\n reversedBytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + decoder.fixedSize /* sourceLength */,\n );\n return decoder.read(reversedBytes, offset);\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size codec.\n *\n * Given a `FixedSizeCodec`, this function returns a new `FixedSizeCodec` that\n * reverses the bytes within the fixed-size byte array during encoding and decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded/decoded value in bytes.\n *\n * @param codec - The fixed-size codec to reverse.\n * @returns A new codec that encodes and decodes bytes in reverse order.\n *\n * @example\n * Reversing a `u16` codec.\n * ```ts\n * const codec = reverseCodec(getU16Codec({ endian: Endian.Big }));\n * const bytes = codec.encode(0x1234); // 0x3412 (bytes are flipped)\n * const value = codec.decode(bytes); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @remarks\n * If you only need to reverse an encoder, use {@link reverseEncoder}.\n * If you only need to reverse a decoder, use {@link reverseDecoder}.\n *\n * ```ts\n * const bytes = reverseEncoder(getU16Encoder()).encode(0x1234);\n * const value = reverseDecoder(getU16Decoder()).decode(bytes);\n * ```\n *\n * @see {@link reverseEncoder}\n * @see {@link reverseDecoder}\n */\nexport function reverseCodec(\n codec: FixedSizeCodec,\n): FixedSizeCodec {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Transforms an encoder by mapping its input values.\n *\n * This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B`\n * to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function.\n *\n * This is useful for handling type conversions, applying default values, or structuring data before encoding.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldFrom - The original type expected by the encoder.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n *\n * @param encoder - The encoder to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @returns A new encoder that accepts `TNewFrom` values and transforms them before encoding.\n *\n * @example\n * Encoding a string by counting its characters and storing the length as a `u32`.\n * ```ts\n * const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length);\n * encoder.encode(\"hello\"); // 0x05000000 (stores length 5)\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformDecoder}\n */\nexport function transformEncoder(\n encoder: FixedSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder;\nexport function transformEncoder(\n encoder: VariableSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Transforms a decoder by mapping its output values.\n *\n * This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A`\n * to be converted into values of type `B` after decoding. The transformation is applied via the `map` function.\n *\n * This is useful for post-processing, type conversions, or enriching decoded data.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldTo - The original type returned by the decoder.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param decoder - The decoder to transform.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding.\n * @returns A new decoder that decodes into `TNewTo`.\n *\n * @example\n * Decoding a stored `u32` length into a string of `'x'` characters.\n * ```ts\n * const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length));\n * decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // \"xxxxx\"\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformEncoder}\n */\nexport function transformDecoder(\n decoder: FixedSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder;\nexport function transformDecoder(\n decoder: VariableSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder {\n return createDecoder({\n ...decoder,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Transforms a codec by mapping its input and output values.\n *\n * This function takes an existing `Codec` and returns a `Codec`, allowing:\n * - Values of type `C` to be transformed into `A` before encoding.\n * - Values of type `B` to be transformed into `D` after decoding.\n *\n * This is useful for adapting codecs to work with different representations, handling default values, or\n * converting between primitive and structured types.\n *\n * @typeParam TOldFrom - The original type expected by the codec.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n * @typeParam TOldTo - The original type returned by the codec.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param codec - The codec to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding (optional).\n * @returns A new codec that encodes `TNewFrom` and decodes into `TNewTo`.\n *\n * @example\n * Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters.\n * ```ts\n * const codec = transformCodec(\n * getU32Codec(),\n * (value: string) => value.length, // Encode string length\n * (length) => 'x'.repeat(length) // Decode length into a string of 'x's\n * );\n *\n * const bytes = codec.encode(\"hello\"); // 0x05000000 (stores length 5)\n * const value = codec.decode(bytes); // \"xxxxx\"\n * ```\n *\n * @remarks\n * If only input transformation is needed, use {@link transformEncoder}.\n * If only output transformation is needed, use {@link transformDecoder}.\n *\n * ```ts\n * const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode(\"hello\");\n * const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes);\n * ```\n *\n * @see {@link transformEncoder}\n * @see {@link transformDecoder}\n */\nexport function transformCodec(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder['read']),\n });\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '0123456789';\n\n/**\n * Returns an encoder for base-10 strings.\n *\n * This encoder serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-10 strings.\n *\n * @example\n * Encoding a base-10 string.\n * ```ts\n * const encoder = getBase10Encoder();\n * const bytes = encoder.encode('1024'); // 0x0400\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-10 strings.\n *\n * This decoder deserializes base-10 encoded strings from a byte array.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-10 strings.\n *\n * @example\n * Decoding a base-10 string.\n * ```ts\n * const decoder = getBase10Decoder();\n * const value = decoder.decode(new Uint8Array([0x04, 0x00])); // \"1024\"\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-10 strings.\n *\n * This codec serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-10 strings.\n *\n * @example\n * Encoding and decoding a base-10 string.\n * ```ts\n * const codec = getBase10Codec();\n * const bytes = codec.encode('1024'); // 0x0400\n * const value = codec.decode(bytes); // \"1024\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-10 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase10Codec(), 5);\n * ```\n *\n * If you need a size-prefixed base-10 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase10Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase10Encoder} and {@link getBase10Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase10Encoder().encode('1024');\n * const value = getBase10Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase10Encoder}\n * @see {@link getBase10Decoder}\n */\nexport const getBase10Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings using bit re-slicing.\n *\n * This encoder serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to an alphabet, and encoding the result into a byte array.\n * This approach is commonly used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeEncoder` for encoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding a base-X string using bit re-slicing.\n * ```ts\n * const encoder = getBaseXResliceEncoder('elho', 2);\n * const bytes = encoder.encode('hellolol'); // 0x4aee\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.floor((value.length * bits) / 8),\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-X encoded strings using bit re-slicing.\n *\n * This decoder deserializes base-X encoded strings by re-slicing the bits of a byte array into\n * custom-sized chunks and mapping them to a specified alphabet.\n * This is typically used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeDecoder` for decoding base-X strings using bit re-slicing.\n *\n * @example\n * Decoding a base-X string using bit re-slicing.\n * ```ts\n * const decoder = getBaseXResliceDecoder('elho', 2);\n * const value = decoder.decode(new Uint8Array([0x4a, 0xee])); // \"hellolol\"\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): VariableSizeDecoder =>\n createDecoder({\n read(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-X strings using bit re-slicing.\n *\n * This codec serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to a given alphabet, and encoding the result into bytes.\n * It is particularly suited for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding and decoding a base-X string using bit re-slicing.\n * ```ts\n * const codec = getBaseXResliceCodec('elho', 2);\n * const bytes = codec.encode('hellolol'); // 0x4aee\n * const value = codec.decode(bytes); // \"hellolol\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXResliceCodec('elho', 2), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXResliceCodec('elho', 2), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXResliceEncoder} and {@link getBaseXResliceDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXResliceEncoder('elho', 2).encode('hellolol');\n * const value = getBaseXResliceDecoder('elho', 2).decode(bytes);\n * ```\n *\n * @see {@link getBaseXResliceEncoder}\n * @see {@link getBaseXResliceDecoder}\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): VariableSizeCodec =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n toArrayBuffer,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Returns an encoder for base-64 strings.\n *\n * This encoder serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-64 strings.\n *\n * @example\n * Encoding a base-64 string.\n * ```ts\n * const encoder = getBase64Encoder();\n * const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Encoder = (): VariableSizeEncoder => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return transformEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/**\n * Returns a decoder for base-64 strings.\n *\n * This decoder deserializes base-64 encoded strings from a byte array.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-64 strings.\n *\n * @example\n * Decoding a base-64 string.\n * ```ts\n * const decoder = getBase64Decoder();\n * const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // \"hello+world\"\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Decoder = (): VariableSizeDecoder => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(toArrayBuffer(bytes), offset).toString('base64'), bytes.length],\n });\n }\n\n return transformDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/**\n * Returns a codec for encoding and decoding base-64 strings.\n *\n * This codec serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-64 strings.\n *\n * @example\n * Encoding and decoding a base-64 string.\n * ```ts\n * const codec = getBase64Codec();\n * const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57\n * const value = codec.decode(bytes); // \"hello+world\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-64 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase64Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-64 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase64Encoder} and {@link getBase64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase64Encoder().encode('hello+world');\n * const value = getBase64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase64Encoder}\n * @see {@link getBase64Decoder}\n */\nexport const getBase64Codec = (): VariableSizeCodec => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**\n * Removes all null characters (`\\u0000`) from a string.\n *\n * This function cleans a string by stripping out any null characters,\n * which are often used as padding in fixed-size string encodings.\n *\n * @param value - The string to process.\n * @returns The input string with all null characters removed.\n *\n * @example\n * Removing null characters from a string.\n * ```ts\n * removeNullCharacters('hello\\u0000\\u0000'); // \"hello\"\n * ```\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters (`\\u0000`) at the end to reach a fixed length.\n *\n * If the input string is shorter than the specified length, it is padded with null characters\n * until it reaches the desired size. If it is already long enough, it remains unchanged.\n *\n * @param value - The string to pad.\n * @param chars - The total length of the resulting string, including padding.\n * @returns The input string padded with null characters up to the specified length.\n *\n * @example\n * Padding a string with null characters.\n * ```ts\n * padNullCharacters('hello', 8); // \"hello\\u0000\\u0000\\u0000\"\n * ```\n */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from '@solana/text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/**\n * Returns an encoder for UTF-8 strings.\n *\n * This encoder serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding UTF-8 strings.\n *\n * @example\n * Encoding a UTF-8 string.\n * ```ts\n * const encoder = getUtf8Encoder();\n * const bytes = encoder.encode('hello'); // 0x68656c6c6f\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Encoder = (): VariableSizeEncoder => {\n let textEncoder: TextEncoder;\n return createEncoder({\n getSizeFromValue: value => (textEncoder ||= new TextEncoder()).encode(value).length,\n write: (value: string, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new TextEncoder()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for UTF-8 strings.\n *\n * This decoder deserializes UTF-8 encoded strings from a byte array.\n * It reads all available bytes starting from the given offset.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding UTF-8 strings.\n *\n * @example\n * Decoding a UTF-8 string.\n * ```ts\n * const decoder = getUtf8Decoder();\n * const value = decoder.decode(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // \"hello\"\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Decoder = (): VariableSizeDecoder => {\n let textDecoder: TextDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding UTF-8 strings.\n *\n * This codec serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding UTF-8 strings.\n *\n * @example\n * Encoding and decoding a UTF-8 string.\n * ```ts\n * const codec = getUtf8Codec();\n * const bytes = codec.encode('hello'); // 0x68656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size UTF-8 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 5);\n * ```\n *\n * If you need a size-prefixed UTF-8 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getUtf8Encoder} and {@link getUtf8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getUtf8Encoder().encode('hello');\n * const value = getUtf8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getUtf8Encoder}\n * @see {@link getUtf8Decoder}\n */\nexport const getUtf8Codec = (): VariableSizeCodec => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","import type { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport type { Lamports } from '@solana/rpc-types';\n\n/**\n * The number of bytes required to store the {@link BaseAccount} information without its data.\n *\n * @example\n * ```ts\n * const myTotalAccountSize = myAccountDataSize + BASE_ACCOUNT_SIZE;\n * ```\n */\nexport const BASE_ACCOUNT_SIZE = 128;\n\n/**\n * Defines the attributes common to all Solana accounts. Namely, it contains everything stored\n * on-chain except the account data itself.\n *\n * @interface\n *\n * @example\n * ```ts\n * const BaseAccount: BaseAccount = {\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type BaseAccount = {\n readonly executable: boolean;\n readonly lamports: Lamports;\n readonly programAddress: Address;\n readonly space: bigint;\n};\n\n/**\n * Contains all the information relevant to a Solana account. It includes the account's address and\n * data, as well as the properties of {@link BaseAccount}.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Encoded\n * const myEncodedAccount: Account = {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n *\n * // Decoded\n * type MyAccountData = { name: string; age: number };\n * const myDecodedAccount: Account = {\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type Account = BaseAccount & {\n readonly address: Address;\n readonly data: TData;\n};\n\n/**\n * Represents an encoded account and is equivalent to an {@link Account} with `Uint8Array` account\n * data.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * } satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport type EncodedAccount = Account;\n","import type { Decoder, ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SolanaError,\n} from '@solana/errors';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/**\n * Transforms an {@link EncodedAccount} into an {@link Account} (or a {@link MaybeEncodedAccount}\n * into a {@link MaybeAccount}) by decoding the account data using the provided {@link Decoder}\n * instance.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: EncodedAccount<'1234..5678'>;\n * const myDecoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n *\n * const myDecodedAccount = decodeAccount(myAccount, myDecoder);\n * myDecodedAccount satisfies Account;\n * ```\n */\nexport function decodeAccount(\n encodedAccount: EncodedAccount,\n decoder: Decoder,\n): Account;\nexport function decodeAccount(\n encodedAccount: MaybeEncodedAccount,\n decoder: Decoder,\n): MaybeAccount;\nexport function decodeAccount(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n decoder: Decoder,\n): Account | MaybeAccount {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, {\n address: encodedAccount.address,\n });\n }\n}\n\nfunction accountExists(account: Account | MaybeAccount): account is Account {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/**\n * Asserts that an account stores decoded data, ie. not a `Uint8Array`.\n *\n * Note that it does not check the shape of the data matches the decoded type, only that it is not a\n * `Uint8Array`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: Account;\n * assertAccountDecoded(myAccount);\n *\n * // now the account data can be used as MyAccountData\n * account.data satisfies MyAccountData;\n * ```\n *\n * This is particularly useful for narrowing the result of fetching a JSON parsed account.\n *\n * ```ts\n * const account: MaybeAccount = await fetchJsonParsedAccount(\n * rpc,\n * '1234..5678' as Address,\n * );\n *\n * assertAccountDecoded(account);\n * // now we have a MaybeAccount\n * account satisfies MaybeAccount;\n * ```\n */\nexport function assertAccountDecoded(\n account: Account,\n): asserts account is Account;\nexport function assertAccountDecoded(\n account: MaybeAccount,\n): asserts account is MaybeAccount;\nexport function assertAccountDecoded(\n account: Account | MaybeAccount,\n): asserts account is Account | MaybeAccount {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, {\n address: account.address,\n });\n }\n}\n\n/**\n * Asserts that all input accounts store decoded data, ie. not a `Uint8Array`.\n *\n * As with {@link assertAccountDecoded} it does not check the shape of the data matches the decoded\n * type, only that it is not a `Uint8Array`.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccounts: Account[];\n * assertAccountsDecoded(myAccounts);\n *\n * // now the account data can be used as MyAccountData\n * for (const a of account) {\n * account.data satisfies MyAccountData;\n * }\n * ```\n */\nexport function assertAccountsDecoded(\n accounts: Account[],\n): asserts accounts is Account[];\nexport function assertAccountsDecoded(\n accounts: MaybeAccount[],\n): asserts accounts is MaybeAccount[];\nexport function assertAccountsDecoded(\n accounts: (Account | MaybeAccount)[],\n): asserts accounts is (Account | MaybeAccount)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, {\n addresses: encodedAddresses,\n });\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n} from '@solana/rpc-types';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type { JsonParsedDataResponse } from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/**\n * Parses a base64-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/**\n * Parses a base58-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse };\ntype ParsedAccountMeta = { program: string; type?: string };\ntype JsonParsedAccountData = TData & { parsedAccountMeta?: ParsedAccountMeta };\n\n/**\n * Parses an arbitrary `jsonParsed` account provided by the RPC client into an {@link Account} type\n * or a {@link MaybeAccount} type if the raw data can be set to `null`.\n *\n * The expected data type should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * const myAccount: Account = parseJsonRpcAccount(myJsonRpcAccount);\n * ```\n */\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount,\n): Account, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account, TAddress> | MaybeAccount, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = (rpcAccount.data.parsed.info || {}) as TData;\n\n if (rpcAccount.data.program || rpcAccount.data.parsed.type) {\n (data as JsonParsedAccountData).parsedAccountMeta = {\n program: rpcAccount.data.program,\n type: rpcAccount.data.parsed.type,\n };\n }\n\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n space: rpcAccount.space,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Rpc } from '@solana/rpc-spec';\nimport type { Commitment, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/**\n * Optional configuration for fetching a singular account.\n *\n * @interface\n */\nexport type FetchAccountConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the account as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches a {@link MaybeEncodedAccount} from the provided RPC client and address.\n *\n * It uses the {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} RPC method under the hood\n * with base64 encoding and an additional configuration object can be provided to customize the\n * behavior of the RPC call.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress);\n *\n * // With custom configuration.\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/**\n * Fetches a {@link MaybeAccount} from the provided RPC client and address by using\n * {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} under the hood with the `jsonParsed`\n * encoding.\n *\n * It may also return a {@link MaybeEncodedAccount} if the RPC client does not know how to parse the\n * account at the requested address. In any case, the expected data type should be explicitly\n * provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress);\n * myAccount satisfies MaybeAccount | MaybeEncodedAccount;\n *\n * // With custom configuration.\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchJsonParsedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise<\n | MaybeAccount\n | MaybeEncodedAccount\n> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(address, account as Parameters[1])\n : parseBase64RpcAccount(address, account as Parameters[1]);\n}\n\n/**\n * Optional configuration for fetching multiple accounts.\n *\n * @interface\n */\nexport type FetchAccountsConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the accounts as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches an array of {@link MaybeEncodedAccount | MaybeEncodedAccounts} from the provided RPC\n * client and an array of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with base64 encodings and an additional configuration object can be provided to\n * customize the behavior of the RPC call.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n *\n * @example\n * ```ts\n * const myAddressA = address('1234..5678');\n * const myAddressB = address('8765..4321');\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeEncodedAccount<'1234..5678'>;\n * myAccountB satisfies MaybeEncodedAccount<'8765..4321'>;\n *\n * // With custom configuration.\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount;\n };\n}\n\n/**\n * Fetches an array of {@link MaybeAccount | MaybeAccounts} from a provided RPC client and an array\n * of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with the `jsonParsed` encoding. It may also return a\n * {@link MaybeEncodedAccount} instead of the expected {@link MaybeAccount} if the RPC client does\n * not know how to parse some of the requested accounts. In any case, the array of expected data\n * types should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n * @typeParam TData - The expected types of these accounts' data.\n \n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * type MintData = { supply: bigint };\n * const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeAccount | MaybeEncodedAccount;\n * myAccountB satisfies MaybeAccount | MaybeEncodedAccount;\n * ```\n */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters[1]);\n }) as {\n [P in keyof TAddresses]:\n | MaybeAccount<\n TData[P & keyof TData] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P]\n >\n | MaybeEncodedAccount;\n } & {\n [P in keyof TData]:\n | MaybeAccount<\n TData[P] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P & keyof TAddresses]\n >\n | MaybeEncodedAccount;\n };\n}\n","import { Address } from '@solana/addresses';\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\n\nimport { Account } from './account';\n\n/**\n * Represents an account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type with an additional `exists`\n * attribute set to `true`. When it does not exist, it is represented by an object containing only\n * the address of the account and an `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Account exists\n * const myExistingAccount: MaybeAccount = {\n * exists: true,\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * // ...\n * };\n *\n * // Account does not exist\n * const myMissingAccount: MaybeAccount = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeAccount =\n | { readonly address: Address; readonly exists: false }\n | (Account & { readonly exists: true });\n\n/**\n * Represents an encoded account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type having its `TData` type\n * parameter set to `Uint8Array` with an additional `exists` attribute set to `true`. When it does\n * not exist, it is represented by an object containing only the address of the account and an\n * `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * // Encoded account exists\n * const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = {\n * exists: true,\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * // ...\n * };\n *\n * // Encoded account does not exist\n * const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeEncodedAccount = MaybeAccount;\n\n/**\n * Given a {@link MaybeAccount}, asserts that the account exists and allows it to be used as an\n * {@link Account} type going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccount: MaybeEncodedAccount<'1234..5678'>;\n * assertAccountExists(myAccount);\n *\n * // Now we can use myAccount as an `EncodedAccount`\n * myAccount satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport function assertAccountExists(\n account: MaybeAccount,\n): asserts account is Account & { exists: true } {\n if (!account.exists) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, { address: account.address });\n }\n}\n\n/**\n * Given an array of {@link MaybeAccount | MaybeAccounts}, asserts that all the accounts exist and\n * allows them to be used as an array of {@link Account | Accounts} going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccounts: MaybeEncodedAccount

[];\n * assertAccountsExist(myAccounts);\n *\n * // Now we can use them as an array of `EncodedAccounts`\n * for (const a of myAccounts) {\n * a satisfies EncodedAccount
;\n * }\n * ```\n */\nexport function assertAccountsExist(\n accounts: MaybeAccount[],\n): asserts accounts is (Account & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, { addresses: missingAddresses });\n }\n}\n","import { SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SolanaError } from '@solana/errors';\n\n/**\n * Throws an exception unless {@link Crypto#getRandomValues | `crypto.getRandomValues()`} is\n * available in the current JavaScript environment.\n */\nexport function assertPRNGIsAvailable() {\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.getRandomValues !== 'function') {\n throw new SolanaError(SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SolanaError,\n} from '@solana/errors';\n\nfunction assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT);\n }\n}\n\nlet cachedEd25519Decision: PromiseLike | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .then(() => {\n resolve((cachedEd25519Decision = true));\n })\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#digest | `crypto.subtle.digest()`} is available in\n * the current JavaScript environment.\n */\nexport function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#generateKey | `crypto.subtle.generateKey()`} is\n * available in the current JavaScript environment and has support for the Ed25519 curve.\n */\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED);\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#exportKey | `crypto.subtle.exportKey()`} is\n * available in the current JavaScript environment.\n */\nexport function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#sign | `crypto.subtle.sign()`} is available in the\n * current JavaScript environment.\n */\nexport function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);\n }\n}\n/**\n * Throws an exception unless {@link SubtleCrypto#verify | `crypto.subtle.verify()`} is available in\n * the current JavaScript environment.\n */\nexport function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n combineCodec,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * Represents a string that validates as a Solana address. Functions that require well-formed\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an arbitrary string as a base58-encoded address, use the\n * {@link address}, {@link assertIsAddress}, or {@link isAddress} functions in this package.\n */\nexport type Address = Brand, 'Address'>;\n\nlet memoizedBase58Encoder: Encoder | undefined;\nlet memoizedBase58Decoder: Decoder | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Address} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAddress } from '@solana/addresses';\n *\n * if (isAddress(ownerAddress)) {\n * // At this point, `ownerAddress` has been refined to a\n * // `Address` that can be used with the RPC.\n * const { value: lamports } = await rpc.getBalance(ownerAddress).send();\n * setBalanceLamports(lamports);\n * } else {\n * setError(`${ownerAddress} is not an address`);\n * }\n * ```\n */\nexport function isAddress(putativeAddress: string): putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n try {\n return base58Encoder.encode(putativeAddress).byteLength === 32;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an address or public\n * key, from an untrusted network API or user input. Use this function to assert that such an\n * arbitrary string is a base58-encoded address.\n *\n * @example\n * ```ts\n * import { assertIsAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // At this point, `address` is an `Address` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out not to be a base58-encoded address\n * }\n * }\n * ```\n */\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * Combines _asserting_ that a string is an address with _coercing_ it to the {@link Address} type.\n * It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good address as a string, it's more efficient to typecast it rather\n * than to use the {@link address} helper, because the helper unconditionally performs validation on\n * its input.\n * >\n * > ```ts\n * > import { Address } from '@solana/addresses';\n * >\n * > const MEMO_PROGRAM_ADDRESS =\n * > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;\n * > ```\n */\nexport function address(putativeAddress: TAddress): Address {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded address to a byte array.\n *\n * @example\n * ```ts\n * import { getAddressEncoder } from '@solana/addresses';\n *\n * const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;\n * const addressEncoder = getAddressEncoder();\n * const addressBytes = addressEncoder.encode(address);\n * // Uint8Array(32) [\n * // 150, 183, 190, 48, 171, 8, 39, 156,\n * // 122, 213, 172, 108, 193, 95, 26, 158,\n * // 149, 243, 115, 254, 20, 200, 36, 30,\n * // 248, 179, 178, 232, 220, 89, 53, 127\n * // ]\n * ```\n */\nexport function getAddressEncoder(): FixedSizeEncoder {\n return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), putativeAddress =>\n address(putativeAddress),\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an address to the\n * base58-encoded representation of that address.\n *\n * @example\n * ```ts\n * import { getAddressDecoder } from '@solana/addresses';\n *\n * const addressBytes = new Uint8Array([\n * 150, 183, 190, 48, 171, 8, 39, 156,\n * 122, 213, 172, 108, 193, 95, 26, 158,\n * 149, 243, 115, 254, 20, 200, 36, 30,\n * 248, 179, 178, 232, 220, 89, 53, 127\n * ]);\n * const addressDecoder = getAddressDecoder();\n * const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka\n * ```\n */\nexport function getAddressDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded address.\n *\n * @see {@link getAddressDecoder}\n * @see {@link getAddressEncoder}\n */\nexport function getAddressCodec(): FixedSizeCodec {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\n\nimport { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: ReadonlyUint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport function compressedPointBytesAreOnCurve(bytes: ReadonlyUint8Array): boolean {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SolanaError } from '@solana/errors';\nimport type { AffinePoint } from '@solana/nominal-types';\n\nimport { type Address, getAddressCodec } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * Represents an {@link Address} that validates as being off-curve. Functions that require off-curve\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an address as being off-curve, use the {@link offCurveAddress},\n * {@link assertIsOffCurveAddress}, or {@link isOffCurveAddress} functions in this package.\n */\nexport type OffCurveAddress = AffinePoint, 'invalid'>;\n\n/**\n * A type guard that returns `true` if the input address conforms to the {@link OffCurveAddress}\n * type, and refines its type for use in your application.\n *\n * @example\n * ```ts\n * import { isOffCurveAddress } from '@solana/addresses';\n *\n * if (isOffCurveAddress(accountAddress)) {\n * // At this point, `accountAddress` has been refined to a\n * // `OffCurveAddress` that can be used within your business logic.\n * const { value: account } = await rpc.getAccountInfo(accountAddress).send();\n * } else {\n * setError(`${accountAddress} is not off-curve`);\n * }\n * ```\n */\nexport function isOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): putativeOffCurveAddress is OffCurveAddress {\n const addressBytes = getAddressCodec().encode(putativeOffCurveAddress);\n return compressedPointBytesAreOnCurve(addressBytes) === false;\n}\n\n/**\n * From time to time you might acquire an {@link Address}, that you expect to validate as an\n * off-curve address, from an untrusted source. Use this function to assert that such an address is\n * off-curve.\n *\n * @example\n * ```ts\n * import { assertIsOffCurveAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that the input conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `OffCurveAddress`.\n * assertIsOffCurveAddress(address);\n * // At this point, `address` is an `OffCurveAddress` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out to NOT be a base58-encoded off-curve address\n * }\n * }\n * ```\n */\nexport function assertIsOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): asserts putativeOffCurveAddress is OffCurveAddress {\n if (!isOffCurveAddress(putativeOffCurveAddress)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS);\n }\n}\n\n/**\n * Combines _asserting_ that an {@link Address} is off-curve with _coercing_ it to the\n * {@link OffCurveAddress} type. It's most useful with untrusted input.\n */\nexport function offCurveAddress(\n putativeOffCurveAddress: TAddress,\n): OffCurveAddress {\n assertIsOffCurveAddress(putativeOffCurveAddress);\n return putativeOffCurveAddress;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\nimport { bytesEqual, type ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nimport { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * A tuple representing a program derived address (derived from the address of some program and a\n * set of seeds) and the associated bump seed used to ensure that the address, as derived, does not\n * fall on the Ed25519 curve.\n *\n * Whenever you need to validate an arbitrary tuple as one that represents a program derived\n * address, use the {@link assertIsProgramDerivedAddress} or {@link isProgramDerivedAddress}\n * functions in this package.\n */\nexport type ProgramDerivedAddress = Readonly<\n [Address, ProgramDerivedAddressBump]\n>;\n\n/**\n * Represents an integer in the range [0,255] used in the derivation of a program derived address to\n * ensure that it does not fall on the Ed25519 curve.\n */\nexport type ProgramDerivedAddressBump = Brand;\n\n/**\n * A type guard that returns `true` if the input tuple conforms to the {@link ProgramDerivedAddress}\n * type, and refines its type for use in your program.\n *\n * @see The {@link isAddress} function for an example of how to use a type guard.\n */\nexport function isProgramDerivedAddress(\n value: unknown,\n): value is ProgramDerivedAddress {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * In the event that you receive an address/bump-seed tuple from some untrusted source, use this\n * function to assert that it conforms to the {@link ProgramDerivedAddress} interface.\n *\n * @see The {@link assertIsAddress} function for an example of how to use an assertion function.\n */\nexport function assertIsProgramDerivedAddress(\n value: unknown,\n): asserts value is ProgramDerivedAddress {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {\n bump: value[1],\n });\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = ReadonlyUint8Array | string;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise
{\n assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {\n actual: seeds.length,\n maxSeeds: MAX_SEEDS,\n });\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: bytes.byteLength,\n index: ii,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (compressedPointBytesAreOnCurve(addressBytes)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\n\n/**\n * Given a program's {@link Address} and up to 16 {@link Seed | Seeds}, this method will return the\n * program derived address (PDA) associated with each.\n *\n * @example\n * ```ts\n * import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses';\n *\n * const addressEncoder = getAddressEncoder();\n * const [pda, bumpSeed] = await getProgramDerivedAddress({\n * programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address,\n * seeds: [\n * // Owner\n * addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address),\n * // Token program\n * addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address),\n * // Mint\n * addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address),\n * ],\n * });\n * ```\n */\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);\n}\n\n/**\n * Returns a base58-encoded address derived from some base address, some program address, and a seed\n * string or byte array.\n *\n * @example\n * ```ts\n * import { createAddressWithSeed } from '@solana/addresses';\n *\n * const derivedAddress = await createAddressWithSeed({\n * // The private key associated with this address will be able to sign for `derivedAddress`.\n * baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address,\n * // Only this program will be able to write data to this account.\n * programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address,\n * seed: 'data-account',\n * });\n * ```\n */\nexport async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise
{\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: seedBytes.byteLength,\n index: 0,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES.length), new Uint8Array(PDA_MARKER_BYTES))\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';\n\nimport { Address, getAddressDecoder, getAddressEncoder } from './address';\n\n/**\n * Given a public {@link CryptoKey}, this method will return its associated {@link Address}.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const address = await getAddressFromPublicKey(publicKey);\n * ```\n */\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise
{\n assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\n/**\n * Given an {@link Address}, return a {@link CryptoKey} that can be used to verify signatures.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const publicKey = await getPublicKeyFromAddress(address);\n * ```\n */\nexport async function getPublicKeyFromAddress(address: Address) {\n const addressBytes = getAddressEncoder().encode(address);\n return await crypto.subtle.importKey('raw', addressBytes, { name: 'Ed25519' }, true /* extractable */, ['verify']);\n}\n","import { SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\n/**\n * Ensures that a given number falls within a specified range.\n *\n * If the number is outside the allowed range, an error is thrown.\n * This function is primarily used to validate values before encoding them in a codec.\n *\n * @param codecDescription - A string describing the codec that is performing the validation.\n * @param min - The minimum allowed value (inclusive).\n * @param max - The maximum allowed value (inclusive).\n * @param value - The number to validate.\n *\n * @throws {@link SolanaError} if the value is out of range.\n *\n * @example\n * Validating a number within range.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 42); // Passes\n * ```\n *\n * @example\n * Throwing an error for an out-of-range value.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 300); // Throws\n * ```\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: bigint | number,\n max: bigint | number,\n value: bigint | number,\n) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value,\n });\n }\n}\n","import { Codec, Decoder, Encoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n/**\n * Represents an encoder for numbers and bigints.\n *\n * This type allows encoding values that are either `number` or `bigint`.\n * Depending on the specific implementation, the encoded output may have a fixed or variable size.\n *\n * @see {@link FixedSizeNumberEncoder}\n */\nexport type NumberEncoder = Encoder;\n\n/**\n * Represents a fixed-size encoder for numbers and bigints.\n *\n * This encoder serializes values using an exact number of bytes, defined by `TSize`.\n *\n * @typeParam TSize - The number of bytes used for encoding.\n *\n * @see {@link NumberEncoder}\n */\nexport type FixedSizeNumberEncoder = FixedSizeEncoder;\n\n/**\n * Represents a decoder for numbers and bigints.\n *\n * This type supports decoding values as either `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberDecoder}\n */\nexport type NumberDecoder = Decoder | Decoder;\n\n/**\n * Represents a fixed-size decoder for numbers and bigints.\n *\n * This decoder reads a fixed number of bytes (`TSize`) and converts them into a `number` or `bigint`.\n *\n * @typeParam TSize - The number of bytes expected for decoding.\n *\n * @see {@link NumberDecoder}\n */\nexport type FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\n\n/**\n * Represents a codec for encoding and decoding numbers and bigints.\n *\n * - The encoded value can be either a `number` or a `bigint`.\n * - The decoded value will always be either a `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberCodec}\n */\nexport type NumberCodec = Codec | Codec;\n\n/**\n * Represents a fixed-size codec for encoding and decoding numbers and bigints.\n *\n * This codec uses a specific number of bytes (`TSize`) for serialization.\n * The encoded value can be either a `number` or `bigint`, but the decoded value will always be a `number` or `bigint`,\n * depending on the implementation.\n *\n * @typeParam TSize - The number of bytes used for encoding and decoding.\n *\n * @see {@link NumberCodec}\n */\nexport type FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Configuration options for number codecs that use more than one byte.\n *\n * This configuration applies to all number codecs except `u8` and `i8`,\n * allowing the user to specify the endianness of serialization.\n */\nexport type NumberCodecConfig = {\n /**\n * Specifies whether numbers should be encoded in little-endian or big-endian format.\n *\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the byte order used for number serialization.\n *\n * - `Little`: The least significant byte is stored first.\n * - `Big`: The most significant byte is stored first.\n */\nexport enum Endian {\n Little,\n Big,\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n toArrayBuffer,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n config?: NumberCodecConfig;\n name: string;\n size: TSize;\n};\n\ntype NumberFactoryEncoderInput = NumberFactorySharedInput & {\n range?: [bigint | number, bigint | number];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.Big ? false : true;\n}\n\nexport function numberEncoderFactory(\n input: NumberFactoryEncoderInput,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory(\n input: NumberFactoryDecoderInput,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\n });\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit floating-point numbers (`f32`).\n *\n * This encoder serializes `f32` values using 4 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f32` values.\n *\n * @example\n * Encoding an `f32` value.\n * ```ts\n * const encoder = getF32Encoder();\n * const bytes = encoder.encode(-1.5); // 0x0000c0bf\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit floating-point numbers (`f32`).\n *\n * This decoder deserializes `f32` values from 4 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f32` values.\n *\n * @example\n * Decoding an `f32` value.\n * ```ts\n * const decoder = getF32Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`).\n *\n * This codec serializes `f32` values using 4 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f32` values.\n *\n * @example\n * Encoding and decoding an `f32` value.\n * ```ts\n * const codec = getF32Codec();\n * const bytes = codec.encode(-1.5); // 0x0000c0bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbfc00000\n * ```\n *\n * @remarks\n * `f32` values follow the IEEE 754 single-precision floating-point standard.\n * Precision loss may occur for certain values.\n *\n * - If you need higher precision, consider using {@link getF64Codec}.\n * - If you need integer values, consider using {@link getI32Codec} or {@link getU32Codec}.\n *\n * Separate {@link getF32Encoder} and {@link getF32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF32Encoder().encode(-1.5);\n * const value = getF32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF32Encoder}\n * @see {@link getF32Decoder}\n */\nexport const getF32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit floating-point numbers (`f64`).\n *\n * This encoder serializes `f64` values using 8 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f64` values.\n *\n * @example\n * Encoding an `f64` value.\n * ```ts\n * const encoder = getF64Encoder();\n * const bytes = encoder.encode(-1.5); // 0x000000000000f8bf\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f64',\n set: (view, value, le) => view.setFloat64(0, Number(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit floating-point numbers (`f64`).\n *\n * This decoder deserializes `f64` values from 8 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f64` values.\n *\n * @example\n * Decoding an `f64` value.\n * ```ts\n * const decoder = getF64Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: 'f64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`).\n *\n * This codec serializes `f64` values using 8 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f64` values.\n *\n * @example\n * Encoding and decoding an `f64` value.\n * ```ts\n * const codec = getF64Codec();\n * const bytes = codec.encode(-1.5); // 0x000000000000f8bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbff8000000000000\n * ```\n *\n * @remarks\n * `f64` values follow the IEEE 754 double-precision floating-point standard.\n * Precision loss may still occur but is significantly lower than `f32`.\n *\n * - If you need smaller floating-point values, consider using {@link getF32Codec}.\n * - If you need integer values, consider using {@link getI64Codec} or {@link getU64Codec}.\n *\n * Separate {@link getF64Encoder} and {@link getF64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF64Encoder().encode(-1.5);\n * const value = getF64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF64Encoder}\n * @see {@link getF64Decoder}\n */\nexport const getF64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF64Encoder(config), getF64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit signed integers (`i128`).\n *\n * This encoder serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i128` values.\n *\n * @example\n * Encoding an `i128` value.\n * ```ts\n * const encoder = getI128Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i128',\n range: [-BigInt('0x7fffffffffffffffffffffffffffffff') - 1n, BigInt('0x7fffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit signed integers (`i128`).\n *\n * This decoder deserializes `i128` values from 16 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i128` values.\n *\n * @example\n * Decoding an `i128` value.\n * ```ts\n * const decoder = getI128Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n * 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'i128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit signed integers (`i128`).\n *\n * This codec serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i128` values.\n *\n * @example\n * Encoding and decoding an `i128` value.\n * ```ts\n * const codec = getI128Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^127` and `2^127 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI64Codec} or {@link getI32Codec}.\n * - If you need a larger signed integer, consider using a custom codec.\n * - If you need unsigned integers, consider using {@link getU128Codec}.\n *\n * Separate {@link getI128Encoder} and {@link getI128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI128Encoder().encode(-42);\n * const value = getI128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI128Encoder}\n * @see {@link getI128Decoder}\n */\nexport const getI128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI128Encoder(config), getI128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit signed integers (`i16`).\n *\n * This encoder serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i16` values.\n *\n * @example\n * Encoding an `i16` value.\n * ```ts\n * const encoder = getI16Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ff\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i16',\n range: [-Number('0x7fff') - 1, Number('0x7fff')],\n set: (view, value, le) => view.setInt16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit signed integers (`i16`).\n *\n * This decoder deserializes `i16` values from 2 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i16` values.\n *\n * @example\n * Decoding an `i16` value.\n * ```ts\n * const decoder = getI16Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff])); // -42\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: 'i16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit signed integers (`i16`).\n *\n * This codec serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i16` values.\n *\n * @example\n * Encoding and decoding an `i16` value.\n * ```ts\n * const codec = getI16Codec();\n * const bytes = codec.encode(-42); // 0xd6ff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^15` (`-32,768`) and `2^15 - 1` (`32,767`).\n *\n * - If you need a smaller signed integer, consider using {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI32Codec}.\n * - If you need unsigned integers, consider using {@link getU16Codec}.\n *\n * Separate {@link getI16Encoder} and {@link getI16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI16Encoder().encode(-42);\n * const value = getI16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI16Encoder}\n * @see {@link getI16Decoder}\n */\nexport const getI16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI16Encoder(config), getI16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit signed integers (`i32`).\n *\n * This encoder serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i32` values.\n *\n * @example\n * Encoding an `i32` value.\n * ```ts\n * const encoder = getI32Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ffffff\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i32',\n range: [-Number('0x7fffffff') - 1, Number('0x7fffffff')],\n set: (view, value, le) => view.setInt32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit signed integers (`i32`).\n *\n * This decoder deserializes `i32` values from 4 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i32` values.\n *\n * @example\n * Decoding an `i32` value.\n * ```ts\n * const decoder = getI32Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff, 0xff, 0xff])); // -42\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: 'i32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit signed integers (`i32`).\n *\n * This codec serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i32` values.\n *\n * @example\n * Encoding and decoding an `i32` value.\n * ```ts\n * const codec = getI32Codec();\n * const bytes = codec.encode(-42); // 0xd6ffffff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^31` (`-2,147,483,648`) and `2^31 - 1` (`2,147,483,647`).\n *\n * - If you need a smaller signed integer, consider using {@link getI16Codec} or {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI64Codec}.\n * - If you need unsigned integers, consider using {@link getU32Codec}.\n *\n * Separate {@link getI32Encoder} and {@link getI32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI32Encoder().encode(-42);\n * const value = getI32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI32Encoder}\n * @see {@link getI32Decoder}\n */\nexport const getI32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI32Encoder(config), getI32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit signed integers (`i64`).\n *\n * This encoder serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i64` values.\n *\n * @example\n * Encoding an `i64` value.\n * ```ts\n * const encoder = getI64Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffff\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit signed integers (`i64`).\n *\n * This decoder deserializes `i64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i64` values.\n *\n * @example\n * Decoding an `i64` value.\n * ```ts\n * const decoder = getI64Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit signed integers (`i64`).\n *\n * This codec serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i64` values.\n *\n * @example\n * Encoding and decoding an `i64` value.\n * ```ts\n * const codec = getI64Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^63` and `2^63 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI32Codec} or {@link getI16Codec}.\n * - If you need a larger signed integer, consider using {@link getI128Codec}.\n * - If you need unsigned integers, consider using {@link getU64Codec}.\n *\n * Separate {@link getI64Encoder} and {@link getI64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI64Encoder().encode(-42);\n * const value = getI64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI64Encoder}\n * @see {@link getI64Decoder}\n */\nexport const getI64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit signed integers (`i8`).\n *\n * This encoder serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `i8` values.\n *\n * @example\n * Encoding an `i8` value.\n * ```ts\n * const encoder = getI8Encoder();\n * const bytes = encoder.encode(-42); // 0xd6\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit signed integers (`i8`).\n *\n * This decoder deserializes `i8` values from 1 byte.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `i8` values.\n *\n * @example\n * Decoding an `i8` value.\n * ```ts\n * const decoder = getI8Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6])); // -42\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit signed integers (`i8`).\n *\n * This codec serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `i8` values.\n *\n * @example\n * Encoding and decoding an `i8` value.\n * ```ts\n * const codec = getI8Codec();\n * const bytes = codec.encode(-42); // 0xd6\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @remarks\n * This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`).\n *\n * - If you need a larger signed integer, consider using {@link getI16Codec}.\n * - If you need an unsigned integer, consider using {@link getU8Codec}.\n *\n * Separate {@link getI8Encoder} and {@link getI8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI8Encoder().encode(-42);\n * const value = getI8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI8Encoder}\n * @see {@link getI8Decoder}\n */\nexport const getI8Codec = (): FixedSizeCodec =>\n combineCodec(getI8Encoder(), getI8Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n Offset,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Returns an encoder for `shortU16` values.\n *\n * This encoder serializes `shortU16` values using **1 to 3 bytes**.\n * Smaller values use fewer bytes, while larger values take up more space.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding `shortU16` values.\n *\n * @example\n * Encoding a `shortU16` value.\n * ```ts\n * const encoder = getShortU16Encoder();\n * encoder.encode(42); // 0x2a\n * encoder.encode(128); // 0x8001\n * encoder.encode(16384); // 0x808001\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: bigint | number): number => {\n if (value <= 0b01111111) return 1;\n if (value <= 0b0011111111111111) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value: bigint | number, bytes: Uint8Array, offset: Offset): Offset => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = Number(value) >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n shortU16Bytes[ii - 1] |= 0b10000000;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n },\n });\n\n/**\n * Returns a decoder for `shortU16` values.\n *\n * This decoder deserializes `shortU16` values from **1 to 3 bytes**.\n * The number of bytes used depends on the encoded value.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding `shortU16` values.\n *\n * @example\n * Decoding a `shortU16` value.\n * ```ts\n * const decoder = getShortU16Decoder();\n * decoder.decode(new Uint8Array([0x2a])); // 42\n * decoder.decode(new Uint8Array([0x80, 0x01])); // 128\n * decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n maxSize: 3,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset): [number, Offset] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding `shortU16` values.\n *\n * It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.\n * The larger the value, the more bytes it uses.\n *\n * - If the value is `<= 0x7f` (127), it is stored in a **single byte**\n * and the first bit is set to `0` to indicate the end of the value.\n * - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.\n * - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.\n *\n * In other words, the encoding scheme follows this structure:\n *\n * ```txt\n * 0XXXXXXX <- Values 0 to 127 (1 byte)\n * 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)\n * 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)\n * ```\n *\n * @returns A `VariableSizeCodec` for encoding and decoding `shortU16` values.\n *\n * @example\n * Encoding and decoding `shortU16` values.\n * ```ts\n * const codec = getShortU16Codec();\n * const bytes1 = codec.encode(42); // 0x2a\n * const bytes2 = codec.encode(128); // 0x8001\n * const bytes3 = codec.encode(16384); // 0x808001\n *\n * codec.decode(bytes1); // 42\n * codec.decode(bytes2); // 128\n * codec.decode(bytes3); // 16384\n * ```\n *\n * @remarks\n * This codec efficiently stores small numbers, making it useful for transactions and compact representations.\n *\n * If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.\n *\n * Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getShortU16Encoder().encode(42);\n * const value = getShortU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getShortU16Encoder}\n * @see {@link getShortU16Decoder}\n */\nexport const getShortU16Codec = (): VariableSizeCodec =>\n combineCodec(getShortU16Encoder(), getShortU16Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit unsigned integers (`u128`).\n *\n * This encoder serializes `u128` values using sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u128` values.\n *\n * @example\n * Encoding a `u128` value.\n * ```ts\n * const encoder = getU128Encoder();\n * const bytes = encoder.encode(42n); // 0x2a000000000000000000000000000000\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0n, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit unsigned integers (`u128`).\n *\n * This decoder deserializes `u128` values from sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u128` values.\n *\n * @example\n * Decoding a `u128` value.\n * ```ts\n * const decoder = getU128Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit unsigned integers (`u128`).\n *\n * This codec serializes `u128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u128` values.\n *\n * @example\n * Encoding and decoding a `u128` value.\n * ```ts\n * const codec = getU128Codec();\n * const bytes = codec.encode(42); // 0x2a000000000000000000000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000000000000000000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^128 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU64Codec} or {@link getU32Codec}.\n * - If you need signed integers, consider using {@link getI128Codec}.\n *\n * Separate {@link getU128Encoder} and {@link getU128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU128Encoder().encode(42);\n * const value = getU128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU128Encoder}\n * @see {@link getU128Decoder}\n */\nexport const getU128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit unsigned integers (`u16`).\n *\n * This encoder serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u16` values.\n *\n * @example\n * Encoding a `u16` value.\n * ```ts\n * const encoder = getU16Encoder();\n * const bytes = encoder.encode(42); // 0x2a00\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit unsigned integers (`u16`).\n *\n * This decoder deserializes `u16` values from two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u16` values.\n *\n * @example\n * Decoding a `u16` value.\n * ```ts\n * const decoder = getU16Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`).\n *\n * This codec serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u16` values.\n *\n * @example\n * Encoding and decoding a `u16` value.\n * ```ts\n * const codec = getU16Codec();\n * const bytes = codec.encode(42); // 0x2a00 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^16 - 1`.\n * If you need a larger range, consider using {@link getU32Codec} or {@link getU64Codec}.\n * For signed integers, use {@link getI16Codec}.\n *\n * Separate {@link getU16Encoder} and {@link getU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU16Encoder().encode(42);\n * const value = getU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU16Encoder}\n * @see {@link getU16Decoder}\n */\nexport const getU16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit unsigned integers (`u32`).\n *\n * This encoder serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u32` values.\n *\n * @example\n * Encoding a `u32` value.\n * ```ts\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42); // 0x2a000000\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u32',\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit unsigned integers (`u32`).\n *\n * This decoder deserializes `u32` values from four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u32` values.\n *\n * @example\n * Decoding a `u32` value.\n * ```ts\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`).\n *\n * This codec serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u32` values.\n *\n * @example\n * Encoding and decoding a `u32` value.\n * ```ts\n * const codec = getU32Codec();\n * const bytes = codec.encode(42); // 0x2a000000 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000002a\n * ```\n *\n * @remarks\n * This codec only supports values between `0` and `2^32 - 1`.\n * If you need a larger range, consider using {@link getU64Codec} or {@link getU128Codec}.\n * For signed integers, use {@link getI32Codec}.\n *\n * Separate {@link getU32Encoder} and {@link getU32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU32Encoder().encode(42);\n * const value = getU32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU32Encoder}\n * @see {@link getU32Decoder}\n */\nexport const getU32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU32Encoder(config), getU32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit unsigned integers (`u64`).\n *\n * This encoder serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `u64` values.\n *\n * @example\n * Encoding a `u64` value.\n * ```ts\n * const encoder = getU64Encoder();\n * const bytes = encoder.encode(42); // 0x2a00000000000000\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u64',\n range: [0n, BigInt('0xffffffffffffffff')],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit unsigned integers (`u64`).\n *\n * This decoder deserializes `u64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `u64` values.\n *\n * @example\n * Decoding a `u64` value.\n * ```ts\n * const decoder = getU64Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: 'u64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`).\n *\n * This codec serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u64` values.\n *\n * @example\n * Encoding and decoding a `u64` value.\n * ```ts\n * const codec = getU64Codec();\n * const bytes = codec.encode(42); // 0x2a00000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^64 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU32Codec} or {@link getU16Codec}.\n * - If you need a larger unsigned integer, consider using {@link getU128Codec}.\n * - If you need signed integers, consider using {@link getI64Codec}.\n *\n * Separate {@link getU64Encoder} and {@link getU64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU64Encoder().encode(42);\n * const value = getU64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU64Encoder}\n * @see {@link getU64Decoder}\n */\nexport const getU64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU64Encoder(config), getU64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit unsigned integers (`u8`).\n *\n * This encoder serializes `u8` values using a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `u8` values.\n *\n * @example\n * Encoding a `u8` value.\n * ```ts\n * const encoder = getU8Encoder();\n * const bytes = encoder.encode(42); // 0x2a\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'u8',\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit unsigned integers (`u8`).\n *\n * This decoder deserializes `u8` values from a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `u8` values.\n *\n * @example\n * Decoding a `u8` value.\n * ```ts\n * const decoder = getU8Decoder();\n * const value = decoder.decode(new Uint8Array([0xff])); // 255\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getUint8(0),\n name: 'u8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`).\n *\n * This codec serializes `u8` values using a single byte.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `u8` values.\n *\n * @example\n * Encoding and decoding a `u8` value.\n * ```ts\n * const codec = getU8Codec();\n * const bytes = codec.encode(255); // 0xff\n * const value = codec.decode(bytes); // 255\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^8 - 1` (0 to 255).\n * If you need larger integers, consider using {@link getU16Codec}, {@link getU32Codec}, or {@link getU64Codec}.\n * For signed integers, use {@link getI8Codec}.\n *\n * Separate {@link getU8Encoder} and {@link getU8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU8Encoder().encode(42);\n * const value = getU8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU8Encoder}\n * @see {@link getU8Decoder}\n */\nexport const getU8Codec = (): FixedSizeCodec =>\n combineCodec(getU8Encoder(), getU8Decoder());\n","import { SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SolanaError } from '@solana/errors';\n\n/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: bigint | number,\n actual: bigint | number,\n) {\n if (expected !== actual) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {\n actual,\n codecDescription,\n expected,\n });\n }\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\n/**\n * Functionally, this type helper is equivalent to the identity type — i.e. `type Identity = T`.\n * However, wrapping generic object mappings in this type significantly reduces the number\n * of instantiation expressions processed, which increases TypeScript performance and\n * prevents \"Type instantiation is excessively deep and possibly infinite\" errors.\n *\n * This works because TypeScript doesn't create a new level of nesting when encountering conditional generic types.\n * @see https://github.com/microsoft/TypeScript/issues/34933\n * @see https://github.com/kysely-org/kysely/pull/483\n */\nexport type DrainOuterGeneric = [T] extends [unknown] ? T : never;\n\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null,\n );\n}\n\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : (codec.maxSize ?? null);\n}\n","import {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } from './utils';\n\n/**\n * Defines the possible size strategies for array-like codecs (`array`, `map`, and `set`).\n *\n * The size of the collection can be determined using one of the following approaches:\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} to store a size prefix.\n * - A fixed `number` of items, enforcing an exact length.\n * - The string `\"remainder\"`, which infers the number of items by consuming the rest of the available bytes.\n * This option is only available when encoding fixed-size items.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayLikeCodecSize =\n | TPrefix\n | number\n | 'remainder';\n\n/**\n * Defines the configuration options for array codecs.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayCodecConfig = {\n /**\n * Specifies how the size of the array is determined.\n *\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} stores a size prefix before encoding the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length (only for fixed-size items).\n *\n * @defaultValue A `u32` size prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for arrays of values.\n *\n * This encoder serializes arrays by encoding each element using the provided item encoder.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TFrom - The type of the elements in the array.\n *\n * @param item - The encoder for each item in the array.\n * @param config - Optional configuration for the size encoding strategy.\n * @returns A `VariableSizeEncoder` for encoding arrays.\n *\n * @example\n * Encoding an array of `u8` numbers.\n * ```ts\n * const encoder = getArrayEncoder(getU8Encoder());\n * const bytes = encoder.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: FixedSizeEncoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config?: ArrayCodecConfig,\n): VariableSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig = {},\n): Encoder {\n const size = config.size ?? getU32Encoder();\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\n const prefixSize = typeof size === 'object' ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize,\n }),\n write: (array: TFrom[], bytes, offset) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, array.length);\n }\n if (typeof size === 'object') {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach(value => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for arrays of values.\n *\n * This decoder deserializes arrays by decoding each element using the provided item decoder.\n * By default, a `u32` size prefix is expected to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TTo - The type of the decoded elements in the array.\n *\n * @param item - The decoder for each item in the array.\n * @param config - Optional configuration for the size decoding strategy.\n * @returns A `VariableSizeDecoder` for decoding arrays.\n *\n * @example\n * Decoding an array of `u8` numbers.\n * ```ts\n * const decoder = getArrayDecoder(getU8Decoder());\n * const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // [1, 2, 3]\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayDecoder(\n item: Decoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: FixedSizeDecoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: Decoder,\n config?: ArrayCodecConfig,\n): VariableSizeDecoder;\nexport function getArrayDecoder(item: Decoder, config: ArrayCodecConfig = {}): Decoder {\n const size = config.size ?? getU32Decoder();\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n\n if (size === 'remainder') {\n while (offset < bytes.length) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n }\n\n const [resolvedSize, newOffset] = typeof size === 'number' ? [size, offset] : size.read(bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding arrays of values.\n *\n * This codec serializes arrays by encoding each element using the provided item codec.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * @typeParam TFrom - The type of the elements to encode.\n * @typeParam TTo - The type of the decoded elements.\n *\n * @param item - The codec for each item in the array.\n * @param config - Optional configuration for the size encoding/decoding strategy.\n * @returns A `VariableSizeCodec` for encoding and decoding arrays.\n *\n * @example\n * Encoding and decoding an array of `u8` numbers.\n * ```ts\n * const codec = getArrayCodec(getU8Codec());\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n *\n * const array = codec.decode(bytes);\n * // [1, 2, 3]\n * ```\n *\n * @example\n * Using a `u16` size prefix instead of `u32`.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix telling us to read 3 items.\n * ```\n *\n * @example\n * Using a fixed-size array of 3 items.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 3 });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. There must always be 3 items in the array.\n * ```\n *\n * @example\n * Using the `\"remainder\"` size strategy.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 'remainder' });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.\n * ```\n *\n * @remarks\n * The size of the array can be controlled using the `size` option:\n * - A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length.\n *\n * Separate {@link getArrayEncoder} and {@link getArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);\n * const array = getArrayDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getArrayEncoder}\n * @see {@link getArrayDecoder}\n */\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: FixedSizeCodec,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config?: ArrayCodecConfig,\n): VariableSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig = {},\n): Codec {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction computeArrayLikeCodecSize(size: number | object | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Defines the configuration options for bit array codecs.\n *\n * A bit array codec encodes an array of booleans into bits, packing them into bytes.\n * This configuration allows adjusting the bit ordering.\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n * @see {@link getBitArrayCodec}\n */\nexport type BitArrayCodecConfig = {\n /**\n * Determines whether the bits should be read in reverse order.\n *\n * - `false` (default): The first boolean is stored in the most significant bit (MSB-first).\n * - `true`: The first boolean is stored in the least significant bit (LSB-first).\n *\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Returns an encoder that packs an array of booleans into bits.\n *\n * This encoder converts a list of `boolean` values into a compact bit representation,\n * storing 8 booleans per byte.\n *\n * The `backward` config option determines whether the bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding the bit array.\n * @returns A `FixedSizeEncoder` for encoding bit arrays.\n *\n * @example\n * Encoding a bit array.\n * ```ts\n * const encoder = getBitArrayEncoder(1);\n *\n * encoder.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayEncoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeEncoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Returns a decoder that unpacks bits into an array of booleans.\n *\n * This decoder converts a compact bit representation back into a list of `boolean` values.\n * Each byte is expanded into 8 booleans.\n *\n * The `backward` config option determines whether the bits are read in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for decoding the bit array.\n * @returns A `FixedSizeDecoder` for decoding bit arrays.\n *\n * @example\n * Decoding a bit array.\n * ```ts\n * const decoder = getBitArrayDecoder(1);\n *\n * decoder.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayDecoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeDecoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec('bitArray', size, bytes, offset);\n const booleans: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\n slice.forEach(byte => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes boolean arrays as compact bit representations.\n *\n * This codec efficiently stores boolean arrays as bits, packing 8 values per byte.\n * The `backward` config option determines whether bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding and decoding the bit array.\n * @returns A `FixedSizeCodec` for encoding and decoding bit arrays.\n *\n * @example\n * Encoding and decoding a bit array.\n * ```ts\n * const codec = getBitArrayCodec(1);\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n *\n * codec.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @example\n * Encoding and decoding a bit array backwards.\n * ```ts\n * const codec = getBitArrayCodec(1, { backward: true });\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0x05 (0b00000101)\n *\n * codec.decode(new Uint8Array([0x05]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @remarks\n * Separate {@link getBitArrayEncoder} and {@link getBitArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBitArrayEncoder(1).encode([true, false, true, false]);\n * const value = getBitArrayDecoder(1).decode(bytes);\n * ```\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n */\nexport function getBitArrayCodec(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeCodec {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/**\n * Defines the configuration options for boolean codecs.\n *\n * A boolean codec encodes `true` as `1` and `false` as `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * @typeParam TSize - A number codec, encoder, or decoder used for boolean representation.\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n * @see {@link getBooleanCodec}\n */\nexport type BooleanCodecConfig = {\n /**\n * The number codec used to store boolean values.\n *\n * - By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * - A custom number codec can be provided to change the storage size.\n *\n * @defaultValue `u8`\n */\n size?: TSize;\n};\n\n/**\n * Returns an encoder for boolean values.\n *\n * This encoder converts `true` into `1` and `false` into `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for encoding booleans.\n * @returns A `FixedSizeEncoder` where `N` is the size of the number codec.\n *\n * @example\n * Encoding booleans.\n * ```ts\n * const encoder = getBooleanEncoder();\n *\n * encoder.encode(false); // 0x00\n * encoder.encode(true); // 0x01\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanEncoder(): FixedSizeEncoder;\nexport function getBooleanEncoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig): VariableSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig = {}): Encoder {\n return transformEncoder(config.size ?? getU8Encoder(), (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Returns a decoder for boolean values.\n *\n * This decoder reads a number and interprets `1` as `true` and `0` as `false`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for decoding booleans.\n * @returns A `FixedSizeDecoder` where `N` is the size of the number codec.\n *\n * @example\n * Decoding booleans.\n * ```ts\n * const decoder = getBooleanDecoder();\n *\n * decoder.decode(new Uint8Array([0x00])); // false\n * decoder.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanDecoder(): FixedSizeDecoder;\nexport function getBooleanDecoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig): VariableSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig = {}): Decoder {\n return transformDecoder(config.size ?? getU8Decoder(), (value: bigint | number): boolean => Number(value) === 1);\n}\n\n/**\n * Returns a codec for encoding and decoding boolean values.\n *\n * By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * The `size` option allows customizing the number codec used for storage.\n *\n * @param config - Configuration options for encoding and decoding booleans.\n * @returns A `FixedSizeCodec` where `N` is the size of the number codec.\n *\n * @example\n * Encoding and decoding booleans using a `u8` (default).\n * ```ts\n * const codec = getBooleanCodec();\n *\n * codec.encode(false); // 0x00\n * codec.encode(true); // 0x01\n *\n * codec.decode(new Uint8Array([0x00])); // false\n * codec.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @example\n * Encoding and decoding booleans using a custom number codec.\n * ```ts\n * const codec = getBooleanCodec({ size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * ```\n *\n * @remarks\n * Separate {@link getBooleanEncoder} and {@link getBooleanDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBooleanEncoder().encode(true);\n * const value = getBooleanDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n */\nexport function getBooleanCodec(): FixedSizeCodec;\nexport function getBooleanCodec(\n config: BooleanCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig): VariableSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig = {}): Codec {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for raw byte arrays.\n *\n * This encoder writes byte arrays exactly as provided without modification.\n *\n * The size of the encoded byte array is determined by the length of the input.\n * - To enforce a fixed size, consider using {@link fixEncoderSize}.\n * - To add a size prefix, use {@link addEncoderSizePrefix}.\n * - To add a sentinel value, use {@link addEncoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeEncoder`.\n *\n * @example\n * Encoding a byte array as-is.\n * ```ts\n * const encoder = getBytesEncoder();\n *\n * encoder.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * encoder.encode(new Uint8Array([255, 0, 127])); // 0xff007f\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => value.length,\n write: (value, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n },\n });\n}\n\n/**\n * Returns a decoder for raw byte arrays.\n *\n * This decoder reads byte arrays exactly as provided without modification.\n *\n * The decoded byte array extends from the provided offset to the end of the input.\n * - To enforce a fixed size, consider using {@link fixDecoderSize}.\n * - To add a size prefix, use {@link addDecoderSizePrefix}.\n * - To add a sentinel value, use {@link addDecoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeDecoder`.\n *\n * @example\n * Decoding a byte array as-is.\n * ```ts\n * const decoder = getBytesDecoder();\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Uint8Array([1, 2, 3])\n * decoder.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesDecoder(): VariableSizeDecoder {\n return createDecoder({\n read: (bytes, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding raw byte arrays.\n *\n * This codec serializes and deserializes byte arrays without modification.\n *\n * The size of the encoded and decoded byte array is determined dynamically.\n * This means, when reading, the codec will consume all remaining bytes in the input.\n * - To enforce a fixed size, consider using {@link fixCodecSize}.\n * - To add a size prefix, use {@link addCodecSizePrefix}.\n * - To add a sentinel value, use {@link addCodecSentinel}.\n *\n * @returns A `VariableSizeCodec`.\n *\n * @example\n * Encoding and decoding a byte array.\n * ```ts\n * const codec = getBytesCodec();\n *\n * codec.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * codec.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @remarks\n * Separate {@link getBytesEncoder} and {@link getBytesDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBytesEncoder().encode(new Uint8Array([1, 2, 3]));\n * const value = getBytesDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBytesEncoder}\n * @see {@link getBytesDecoder}\n */\nexport function getBytesCodec(): VariableSizeCodec {\n return combineCodec(getBytesEncoder(), getBytesDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n containsBytes,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getBase16Decoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__CODECS__INVALID_CONSTANT, SolanaError } from '@solana/errors';\n\n/**\n * Returns an encoder that always writes a predefined constant byte sequence.\n *\n * This encoder ensures that encoding always produces the specified byte array,\n * ignoring any input values.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence that will be written during encoding.\n *\n * @param constant - The predefined byte array to encode.\n * @returns A `FixedSizeEncoder` where `N` is the length of the constant.\n *\n * @example\n * Encoding a constant magic number.\n * ```ts\n * const encoder = getConstantEncoder(new Uint8Array([1, 2, 3, 4]));\n *\n * const bytes = encoder.encode();\n * // 0x01020304\n * // └──────┘ The predefined 4-byte constant.\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantEncoder(\n constant: TConstant,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: constant.length,\n write: (_, bytes, offset) => {\n bytes.set(constant, offset);\n return offset + constant.length;\n },\n });\n}\n\n/**\n * Returns a decoder that verifies a predefined constant byte sequence.\n *\n * This decoder reads the next bytes and checks that they match the provided constant.\n * If the bytes differ, it throws an error.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence expected during decoding.\n *\n * @param constant - The predefined byte array to verify.\n * @returns A `FixedSizeDecoder` where `N` is the length of the constant.\n *\n * @example\n * Decoding a constant magic number.\n * ```ts\n * const decoder = getConstantDecoder(new Uint8Array([1, 2, 3]));\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Passes\n * decoder.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantDecoder(\n constant: TConstant,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: constant.length,\n read: (bytes, offset) => {\n const base16 = getBase16Decoder();\n if (!containsBytes(bytes, constant, offset)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {\n constant,\n data: bytes,\n hexConstant: base16.decode(constant),\n hexData: base16.decode(bytes),\n offset,\n });\n }\n return [undefined, offset + constant.length];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes a predefined constant byte sequence.\n *\n * - **Encoding:** Always writes the specified byte array.\n * - **Decoding:** Asserts that the next bytes match the constant, throwing an error if they do not.\n *\n * This is useful for encoding fixed byte patterns required in a binary format or to use in\n * conjunction with other codecs such as {@link getHiddenPrefixCodec} or {@link getHiddenSuffixCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence to encode and verify during decoding.\n *\n * @param constant - The predefined byte array to encode and assert during decoding.\n * @returns A `FixedSizeCodec` where `N` is the length of the constant.\n *\n * @example\n * Encoding and decoding a constant magic number.\n * ```ts\n * const codec = getConstantCodec(new Uint8Array([1, 2, 3]));\n *\n * codec.encode(); // 0x010203\n * codec.decode(new Uint8Array([1, 2, 3])); // Passes\n * codec.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @remarks\n * Separate {@link getConstantEncoder} and {@link getConstantDecoder} functions are available.\n *\n * ```ts\n * const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode();\n * getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes);\n * ```\n *\n * @see {@link getConstantEncoder}\n * @see {@link getConstantDecoder}\n */\nexport function getConstantCodec(\n constant: TConstant,\n): FixedSizeCodec {\n return combineCodec(getConstantEncoder(constant), getConstantDecoder(constant));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for a tuple that can be encoded using a tuple codec.\n *\n * This type maps each provided item encoder to its corresponding value type.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n */\ntype GetEncoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for a tuple that can be decoded using a tuple codec.\n *\n * This type maps each provided item decoder to its corresponding value type.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n */\ntype GetDecoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for tuples.\n *\n * This encoder serializes a fixed-size array (tuple) by encoding its items\n * sequentially using the provided item encoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n *\n * @param items - The encoders for each item in the tuple.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples.\n *\n * @example\n * Encoding a tuple with 2 items.\n * ```ts\n * const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]);\n *\n * const bytes = encoder.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleEncoder[]>(\n items: TItems,\n): FixedSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): VariableSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): Encoder> {\n type TFrom = GetEncoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (value: TFrom, bytes, offset) => {\n assertValidNumberOfItemsForCodec('tuple', items.length, value.length);\n items.forEach((item, index) => {\n offset = item.write(value[index], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for tuples.\n *\n * This decoder deserializes a fixed-size array (tuple) by decoding its items\n * sequentially using the provided item decoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n *\n * @param items - The decoders for each item in the tuple.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples.\n *\n * @example\n * Decoding a tuple with 2 items.\n * ```ts\n * const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]);\n *\n * const tuple = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // ['Alice', 42]\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleDecoder[]>(\n items: TItems,\n): FixedSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): VariableSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): Decoder> {\n type TTo = GetDecoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const values = [] as Array & TTo;\n items.forEach(item => {\n const [newValue, newOffset] = item.read(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding tuples.\n *\n * This codec serializes tuples by encoding and decoding each item sequentially.\n *\n * Unlike the {@link getArrayCodec} codec, each item in the tuple has its own codec\n * and, therefore, can be of a different type.\n *\n * @typeParam TItems - An array of codecs, each corresponding to a tuple element.\n *\n * @param items - The codecs for each item in the tuple.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples.\n *\n * @example\n * Encoding and decoding a tuple with 2 items.\n * ```ts\n * const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]);\n *\n * const bytes = codec.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n *\n * const tuple = codec.decode(bytes);\n * // ['Alice', 42]\n * ```\n *\n * @remarks\n * Separate {@link getTupleEncoder} and {@link getTupleDecoder} functions are available.\n *\n * ```ts\n * const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()])\n * .encode(['Alice', 42]);\n *\n * const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()])\n * .decode(bytes);\n * ```\n *\n * @see {@link getTupleEncoder}\n * @see {@link getTupleDecoder}\n */\nexport function getTupleCodec[]>(\n items: TItems,\n): FixedSizeCodec, GetDecoderTypeFromItems & GetEncoderTypeFromItems>;\nexport function getTupleCodec[]>(\n items: TItems,\n): VariableSizeCodec<\n GetEncoderTypeFromItems,\n GetDecoderTypeFromItems & GetEncoderTypeFromItems\n>;\nexport function getTupleCodec[]>(\n items: TItems,\n): Codec, GetDecoderTypeFromItems & GetEncoderTypeFromItems> {\n return combineCodec(\n getTupleEncoder(items),\n getTupleDecoder(items) as Decoder & GetEncoderTypeFromItems>,\n );\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n Offset,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\nimport { DrainOuterGeneric, getMaxSize, maxCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for values that can be encoded using a union codec.\n *\n * This type maps the provided variant encoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n */\ntype GetEncoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Encoder ? TFrom : never;\n}>[number];\n\n/**\n * Infers the TypeScript type for values that can be decoded using a union codec.\n *\n * This type maps the provided variant decoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n */\ntype GetDecoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Decoder ? TFrom : never;\n}>[number];\n\ntype UnionEncoder[]> = TVariants extends readonly FixedSizeEncoder[]\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder[]> = TVariants extends readonly FixedSizeDecoder[]\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec[]> = TVariants extends readonly FixedSizeCodec[]\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for union types.\n *\n * This encoder serializes values by selecting the correct variant encoder\n * based on the `getIndexFromValue` function.\n *\n * Unlike other codecs, this encoder does not store the variant index.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n *\n * @param variants - The encoders for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @returns An `Encoder` for encoding union values.\n *\n * @example\n * Encoding a union of numbers and booleans.\n * ```ts\n * const encoder = getUnionEncoder(\n * [getU16Encoder(), getBooleanEncoder()],\n * value => (typeof value === 'number' ? 0 : 1)\n * );\n *\n * encoder.encode(42);\n * // 0x2a00\n * // └── Encoded number (42) as `u16`\n *\n * encoder.encode(true);\n * // 0x01\n * // └── Encoded boolean (`true`) as `u8`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionEncoder[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const write: Encoder['write'] = (variant, bytes, offset) => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return variants[index].write(variant, bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createEncoder({ fixedSize, write }) as UnionEncoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createEncoder({\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: variant => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return getEncodedSize(variant, variants[index]);\n },\n write,\n }) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for union types.\n *\n * This decoder deserializes values by selecting the correct variant decoder\n * based on the `getIndexFromBytes` function.\n *\n * Unlike other codecs, this decoder does not assume a stored discriminator.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n *\n * @param variants - The decoders for each variant of the union.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Decoder` for decoding union values.\n *\n * @example\n * Decoding a union of numbers and booleans.\n * ```ts\n * const decoder = getUnionDecoder(\n * [getU16Decoder(), getBooleanDecoder()],\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * decoder.decode(new Uint8Array([0x01])); // true\n * // Type is inferred as `number | boolean`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionDecoder[]>(\n variants: TVariants,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionDecoder {\n type TTo = GetDecoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const read: Decoder['read'] = (bytes, offset) => {\n const index = getIndexFromBytes(bytes, offset);\n assertValidVariantIndex(variants, index);\n return variants[index].read(bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createDecoder({ fixedSize, read }) as UnionDecoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createDecoder({ ...(maxSize !== null ? { maxSize } : {}), read }) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding union types.\n *\n * This codec serializes and deserializes union values by selecting the correct variant\n * based on the provided index functions.\n *\n * Unlike the {@link getDiscriminatedUnionCodec}, this codec does not assume a stored\n * discriminator and must be used with an explicit mechanism for managing discriminators.\n *\n * @typeParam TVariants - An array of codecs, each corresponding to a union variant.\n *\n * @param variants - The codecs for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Codec` for encoding and decoding union values.\n *\n * @example\n * Encoding and decoding a union of numbers and booleans.\n * ```ts\n * const codec = getUnionCodec(\n * [getU16Codec(), getBooleanCodec()],\n * value => (typeof value === 'number' ? 0 : 1),\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * const bytes1 = codec.encode(42); // 0x2a00\n * const value1: number | boolean = codec.decode(bytes1); // 42\n *\n * const bytes2 = codec.encode(true); // 0x01\n * const value2: number | boolean = codec.decode(bytes2); // true\n * ```\n *\n * @remarks\n * If you need a codec that includes a stored discriminator,\n * consider using {@link getDiscriminatedUnionCodec}.\n *\n * Separate {@link getUnionEncoder} and {@link getUnionDecoder} functions are also available.\n *\n * ```ts\n * const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42);\n * const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes);\n * ```\n *\n * @see {@link getUnionEncoder}\n * @see {@link getUnionDecoder}\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getUnionCodec[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionCodec {\n return combineCodec(\n getUnionEncoder(variants, getIndexFromValue),\n getUnionDecoder(variants as readonly Decoder[], getIndexFromBytes) as Decoder<\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction assertValidVariantIndex(variants: readonly unknown[], index: number) {\n if (typeof variants[index] === 'undefined') {\n throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {\n maxRange: variants.length - 1,\n minRange: 0,\n variant: index,\n });\n }\n}\n\nfunction getUnionFixedSize | Encoder)[]>(variants: TVariants) {\n if (variants.length === 0) return 0;\n if (!isFixedSize(variants[0])) return null;\n const variantSize = variants[0].fixedSize;\n const sameSizedVariants = variants.every(variant => isFixedSize(variant) && variant.fixedSize === variantSize);\n return sameSizedVariants ? variantSize : null;\n}\n\nfunction getUnionMaxSize | Encoder)[]>(variants: TVariants) {\n return maxCodecSizes(variants.map(variant => getMaxSize(variant)));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SolanaError } from '@solana/errors';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { DrainOuterGeneric } from './utils';\n\n/**\n * Represents a discriminated union using a specific discriminator property.\n *\n * A discriminated union is a TypeScript-friendly way to represent Rust-like enums.\n * Each variant in the union is distinguished by a shared discriminator property.\n *\n * @typeParam TDiscriminatorProperty - The name of the discriminator property.\n * @typeParam TDiscriminatorValue - The type of the discriminator value.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant\n * | { __kind: 'Write'; fields: [string] } // Tuple variant\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant\n * ```\n */\nexport type DiscriminatedUnion<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorValue extends string = string,\n> = {\n [P in TDiscriminatorProperty]: TDiscriminatorValue;\n};\n\n/**\n * Extracts a variant from a discriminated union based on its discriminator value.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type ClickEvent = GetDiscriminatedUnionVariant;\n * // -> { __kind: 'Move'; x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariant<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Extract>;\n\n/**\n * Extracts a variant from a discriminated union without its discriminator property.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type MoveContent = GetDiscriminatedUnionVariantContent;\n * // -> { x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariantContent<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Omit, TDiscriminatorProperty>;\n\n/**\n * Defines the configuration for discriminated union codecs.\n *\n * This configuration controls how the discriminator is stored and named.\n *\n * @typeParam TDiscriminatorProperty - The property name of the discriminator.\n * @typeParam TDiscriminatorSize - The codec used for the discriminator prefix.\n */\nexport type DiscriminatedUnionCodecConfig<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorSize = NumberCodec | NumberDecoder | NumberEncoder,\n> = {\n /**\n * The property name of the discriminator.\n * @defaultValue `__kind`\n */\n discriminator?: TDiscriminatorProperty;\n /**\n * The codec used to encode/decode the discriminator prefix.\n * @defaultValue `u8` prefix\n */\n size?: TDiscriminatorSize;\n};\n\ntype DiscriminatorValue = bigint | boolean | number | string | null | undefined;\ntype Variants = readonly (readonly [DiscriminatorValue, T])[];\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\ntype GetEncoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Encoder\n ? TFrom extends object\n ? TFrom\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype GetDecoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Decoder\n ? TTo extends object\n ? TTo\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype UnionEncoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for discriminated unions.\n *\n * This encoder serializes objects that follow the discriminated union pattern\n * by prefixing them with a numerical discriminator that represents their variant.\n *\n * Unlike {@link getUnionEncoder}, this encoder automatically extracts and processes\n * the discriminator property (default: `__kind`) from each variant.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant encoders as `[discriminator, encoder]` pairs.\n * @param config - Configuration options for encoding.\n * @returns An `Encoder` for encoding discriminated union objects.\n *\n * @example\n * Encoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageEncoder = getDiscriminatedUnionEncoder([\n * ['Quit', getUnitEncoder()],\n * ['Write', getStructEncoder([['fields', getTupleEncoder([addCodecSizePrefix(getUtf8Encoder(), getU32Encoder())])]])],\n * ['Move', getStructEncoder([['x', getI32Encoder()], ['y', getI32Encoder()]])]\n * ]);\n *\n * messageEncoder.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionEncoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const discriminatorProperty = (config.discriminator ?? '__kind') as TDiscriminatorProperty;\n const prefix = config.size ?? getU8Encoder();\n return getUnionEncoder(\n variants.map(([, variant], index) =>\n transformEncoder(getTupleEncoder([prefix, variant]), (value: TFrom): [number, TFrom] => [index, value]),\n ),\n value => getVariantDiscriminator(variants, value[discriminatorProperty]),\n ) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for discriminated unions.\n *\n * This decoder deserializes objects that follow the discriminated union pattern\n * by **reading a numerical discriminator** and mapping it to the corresponding variant.\n *\n * Unlike {@link getUnionDecoder}, this decoder automatically inserts the discriminator\n * property (default: `__kind`) into the decoded object.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant decoders as `[discriminator, decoder]` pairs.\n * @param config - Configuration options for decoding.\n * @returns A `Decoder` for decoding discriminated union objects.\n *\n * @example\n * Decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageDecoder = getDiscriminatedUnionDecoder([\n * ['Quit', getUnitDecoder()],\n * ['Write', getStructDecoder([['fields', getTupleDecoder([addCodecSizePrefix(getUtf8Decoder(), getU32Decoder())])]])],\n * ['Move', getStructDecoder([['x', getI32Decoder()], ['y', getI32Decoder()]])]\n * ]);\n *\n * messageDecoder.decode(new Uint8Array([0x02,0x05,0x00,0x00,0x00,0x06,0x00,0x00,0x00]));\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionDecoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionDecoder {\n const discriminatorProperty = config.discriminator ?? '__kind';\n const prefix = config.size ?? getU8Decoder();\n return getUnionDecoder(\n variants.map(([discriminator, variant]) =>\n transformDecoder(getTupleDecoder([prefix, variant]), ([, value]) => ({\n [discriminatorProperty]: discriminator,\n ...value,\n })),\n ),\n (bytes, offset) => Number(prefix.read(bytes, offset)[0]),\n ) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding {@link DiscriminatedUnion}.\n *\n * A {@link DiscriminatedUnion} is a TypeScript representation of Rust-like enums, where\n * each variant is distinguished by a discriminator field (default: `__kind`).\n *\n * This codec inserts a numerical prefix to represent the variant index.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant codecs as `[discriminator, codec]` pairs.\n * @param config - Configuration options for encoding/decoding.\n * @returns A `Codec` for encoding and decoding discriminated union objects.\n *\n * @example\n * Encoding and decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Quit', getUnitCodec()],\n * ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],\n * ['Move', getStructCodec([['x', getI32Codec()], ['y', getI32Codec()]])]\n * ]);\n *\n * messageCodec.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n *\n * const value = messageCodec.decode(bytes);\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @example\n * Using a `u32` discriminator instead of `u8`.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { size: getU32Codec() });\n *\n * codec.encode({ __kind: 'Quit' });\n * // 0x00000000\n * // └------┘ 4-byte discriminator (Index 0)\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00]));\n * // { __kind: 'Quit' }\n * ```\n *\n * @example\n * Customizing the discriminator property.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { discriminator: 'message' });\n *\n * codec.encode({ message: 'Quit' }); // 0x00\n * codec.decode(new Uint8Array([0x00])); // { message: 'Quit' }\n * ```\n *\n * @remarks\n * Separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available.\n *\n * ```ts\n * const bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' });\n * const message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes);\n * ```\n *\n * @see {@link getDiscriminatedUnionEncoder}\n * @see {@link getDiscriminatedUnionDecoder}\n */\nexport function getDiscriminatedUnionCodec<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionCodec {\n return combineCodec(\n getDiscriminatedUnionEncoder(variants, config) as Encoder<\n GetEncoderTypeFromVariants\n >,\n getDiscriminatedUnionDecoder(variants, config) as Decoder<\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction getVariantDiscriminator | Encoder>>(\n variants: TVariants,\n discriminatorValue: DiscriminatorValue,\n) {\n const discriminator = variants.findIndex(([key]) => discriminatorValue === key);\n if (discriminator < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, {\n value: discriminatorValue,\n variants: variants.map(([key]) => key),\n });\n }\n return discriminator;\n}\n","/**\n * Defines the \"lookup object\" of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * ```\n */\nexport type EnumLookupObject = { [key: string]: number | string };\n\n/**\n * Returns the allowed input for an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionInput = GetEnumFrom; // \"Left\" | \"Right\" | 0 | 1\n * ```\n */\nexport type GetEnumFrom = TEnum[keyof TEnum] | keyof TEnum;\n\n/**\n * Returns all the available variants of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionOutput = GetEnumTo; // 0 | 1\n * ```\n */\nexport type GetEnumTo = TEnum[keyof TEnum];\n\nexport function getEnumStats(constructor: EnumLookupObject) {\n const numericalValues = [...new Set(Object.values(constructor).filter(v => typeof v === 'number'))].sort();\n const enumRecord = Object.fromEntries(Object.entries(constructor).slice(numericalValues.length)) as Record<\n string,\n number | string\n >;\n const enumKeys = Object.keys(enumRecord);\n const enumValues = Object.values(enumRecord);\n const stringValues: string[] = [\n ...new Set([...enumKeys, ...enumValues.filter((v): v is string => typeof v === 'string')]),\n ];\n\n return { enumKeys, enumRecord, enumValues, numericalValues, stringValues };\n}\n\nexport function getEnumIndexFromVariant({\n enumKeys,\n enumValues,\n variant,\n}: {\n enumKeys: string[];\n enumValues: (number | string)[];\n variant: number | string | symbol;\n}): number {\n const valueIndex = findLastIndex(enumValues, value => value === variant);\n if (valueIndex >= 0) return valueIndex;\n return enumKeys.findIndex(key => key === variant);\n}\n\nexport function getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n}: {\n discriminator: number;\n enumKeys: string[];\n enumValues: (number | string)[];\n useValuesAsDiscriminators: boolean;\n}): number {\n if (!useValuesAsDiscriminators) {\n return discriminator >= 0 && discriminator < enumKeys.length ? discriminator : -1;\n }\n return findLastIndex(enumValues, value => value === discriminator);\n}\n\nfunction findLastIndex(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): number {\n let l = array.length;\n while (l--) {\n if (predicate(array[l], l, array)) return l;\n }\n return -1;\n}\n\nexport function formatNumericalValues(values: number[]): string {\n if (values.length === 0) return '';\n let range: [number, number] = [values[0], values[0]];\n const ranges: string[] = [];\n for (let index = 1; index < values.length; index++) {\n const value = values[index];\n if (range[1] + 1 === value) {\n range[1] = value;\n } else {\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n range = [value, value];\n }\n }\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n return ranges.join(', ');\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n EnumLookupObject,\n formatNumericalValues,\n GetEnumFrom,\n getEnumIndexFromDiscriminator,\n getEnumIndexFromVariant,\n getEnumStats,\n GetEnumTo,\n} from './enum-helpers';\n\n/**\n * Defines the configuration options for enum codecs.\n *\n * The `size` option determines the numerical encoding used for the enum's discriminant.\n * By default, enums are stored as a `u8` (1 byte).\n *\n * The `useValuesAsDiscriminators` option allows mapping the actual enum values\n * as discriminators instead of using their positional index.\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type EnumCodecConfig = {\n /**\n * The codec used to encode/decode the enum discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n\n /**\n * If set to `true`, the enum values themselves will be used as discriminators.\n * This is only valid for numerical enum values.\n *\n * @defaultValue `false`\n */\n useValuesAsDiscriminators?: boolean;\n};\n\n/**\n * Returns an encoder for enums.\n *\n * This encoder serializes enums as a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding the enum.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums.\n *\n * @example\n * Encoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const encoder = getEnumEncoder(Direction);\n *\n * encoder.encode(Direction.Up); // 0x00\n * encoder.encode(Direction.Down); // 0x01\n * encoder.encode(Direction.Left); // 0x02\n * encoder.encode(Direction.Right); // 0x03\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeEncoder, 1>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeEncoder>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Encoder> {\n const prefix = config.size ?? getU8Encoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues, stringValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformEncoder(prefix, (variant: GetEnumFrom): number => {\n const index = getEnumIndexFromVariant({ enumKeys, enumValues, variant });\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, {\n formattedNumericalValues: formatNumericalValues(numericalValues),\n numericalValues,\n stringValues,\n variant,\n });\n }\n return useValuesAsDiscriminators ? (enumValues[index] as number) : index;\n });\n}\n\n/**\n * Returns a decoder for enums.\n *\n * This decoder deserializes enums from a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for decoding the enum.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums.\n *\n * @example\n * Decoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const decoder = getEnumDecoder(Direction);\n *\n * decoder.decode(new Uint8Array([0x00])); // Direction.Up\n * decoder.decode(new Uint8Array([0x01])); // Direction.Down\n * decoder.decode(new Uint8Array([0x02])); // Direction.Left\n * decoder.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeDecoder, 1>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeDecoder>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Decoder> {\n const prefix = config.size ?? getU8Decoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformDecoder(prefix, (value: bigint | number): GetEnumTo => {\n const discriminator = Number(value);\n const index = getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n });\n if (index < 0) {\n const validDiscriminators = useValuesAsDiscriminators\n ? numericalValues\n : [...Array(enumKeys.length).keys()];\n throw new SolanaError(SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator,\n formattedValidDiscriminators: formatNumericalValues(validDiscriminators),\n validDiscriminators,\n });\n }\n return enumValues[index] as GetEnumTo;\n });\n}\n\n/**\n * Returns a codec for encoding and decoding enums.\n *\n * This codec serializes enums as a numerical discriminator, allowing them\n * to be efficiently stored and reconstructed from binary data.\n *\n * By default, the discriminator is derived from the positional index\n * of the enum variant, but it can be configured to use the enum's numeric values instead.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding and decoding the enum.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums.\n *\n * @example\n * Encoding and decoding enums using positional indexes.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const codec = getEnumCodec(Direction);\n *\n * codec.encode(Direction.Up); // 0x00\n * codec.encode(Direction.Down); // 0x01\n * codec.encode(Direction.Left); // 0x02\n * codec.encode(Direction.Right); // 0x03\n *\n * codec.decode(new Uint8Array([0x00])); // Direction.Up\n * codec.decode(new Uint8Array([0x01])); // Direction.Down\n * codec.decode(new Uint8Array([0x02])); // Direction.Left\n * codec.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @example\n * Encoding and decoding enums using their numeric values.\n * ```ts\n * enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 }\n * const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true });\n *\n * codec.encode(GameDifficulty.Easy); // 0x01\n * codec.encode(GameDifficulty.Normal); // 0x04\n * codec.encode(GameDifficulty.Hard); // 0x07\n * codec.encode(GameDifficulty.Expert); // 0x09\n *\n * codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy\n * codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal\n * codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard\n * codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert\n * ```\n *\n * Note that, when using values as discriminators, the enum values must be numerical.\n * Otherwise, an error will be thrown.\n *\n * ```ts\n * enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' }\n * getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error.\n * ```\n *\n * @example\n * Using a custom discriminator size.\n * ```ts\n * enum Status { Pending, Approved, Rejected }\n * const codec = getEnumCodec(Status, { size: getU16Codec() });\n *\n * codec.encode(Status.Pending); // 0x0000\n * codec.encode(Status.Approved); // 0x0100\n * codec.encode(Status.Rejected); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending\n * codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved\n * codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected\n * ```\n *\n * @remarks\n * Separate {@link getEnumEncoder} and {@link getEnumDecoder} functions are available.\n *\n * ```ts\n * const bytes = getEnumEncoder(Direction).encode(Direction.Up);\n * const value = getEnumDecoder(Direction).decode(bytes);\n * ```\n *\n * @see {@link getEnumEncoder}\n * @see {@link getEnumDecoder}\n */\nexport function getEnumCodec(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeCodec, GetEnumTo, 1>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetEnumTo, TSize>;\nexport function getEnumCodec(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeCodec, GetEnumTo>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Codec, GetEnumTo> {\n return combineCodec(getEnumEncoder(constructor, config), getEnumDecoder(constructor, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that prefixes encoded values with hidden data.\n *\n * This encoder applies a list of void encoders before encoding the main value.\n * The prefixed data is encoded before the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param prefixedEncoders - A list of void encoders that produce the hidden prefix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden prefix.\n *\n * @example\n * Prefixing a value with constants.\n * ```ts\n * const encoder = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixEncoder(\n encoder: FixedSizeEncoder,\n prefixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([...prefixedEncoders, encoder]) as Encoder,\n (value: TFrom) => [...prefixedEncoders.map(() => undefined), value] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden prefixed data before decoding the main value.\n *\n * This decoder applies a list of void decoders before decoding the main value.\n * The prefixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param prefixedDecoders - A list of void decoders that produce the hidden prefix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden prefix.\n *\n * @example\n * Decoding a value with prefixed constants.\n * ```ts\n * const decoder = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 0x48, 0x65, 0x6C, 0x6C, 0x6F]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixDecoder(\n decoder: FixedSizeDecoder,\n prefixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([...prefixedDecoders, decoder]) as Decoder,\n tuple => tuple[tuple.length - 1] as TTo,\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden prefix.\n *\n * - **Encoding:** Prefixes the value with hidden data before encoding.\n * - **Decoding:** Skips the hidden prefix before decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param prefixedCodecs - A list of void codecs that produce the hidden prefix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden prefix.\n *\n * @example\n * Encoding and decoding a value with prefixed constants.\n * ```ts\n * const codec = getHiddenPrefixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes before a value, consider using {@link padLeftCodec} instead.\n *\n * Separate {@link getHiddenPrefixEncoder} and {@link getHiddenPrefixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenPrefixEncoder}\n * @see {@link getHiddenPrefixDecoder}\n */\nexport function getHiddenPrefixCodec(\n codec: FixedSizeCodec,\n prefixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenPrefixEncoder(codec, prefixedCodecs), getHiddenPrefixDecoder(codec, prefixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that appends hidden data after the encoded value.\n *\n * This encoder applies a list of void encoders after encoding the main value.\n * The suffixed data is encoded after the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param suffixedEncoders - A list of void encoders that produce the hidden suffix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden suffix.\n *\n * @example\n * Suffixing a value with constants.\n * ```ts\n * const encoder = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixEncoder(\n encoder: FixedSizeEncoder,\n suffixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([encoder, ...suffixedEncoders]) as Encoder,\n (value: TFrom) => [value, ...suffixedEncoders.map(() => undefined)] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden suffixed data after decoding the main value.\n *\n * This decoder applies a list of void decoders after decoding the main value.\n * The suffixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param suffixedDecoders - A list of void decoders that produce the hidden suffix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden suffix.\n *\n * @example\n * Decoding a value with suffixed constants.\n * ```ts\n * const decoder = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F, 1, 2, 3, 4, 5, 6]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixDecoder(\n decoder: FixedSizeDecoder,\n suffixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([decoder, ...suffixedDecoders]) as Decoder,\n tuple => tuple[0],\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden suffix.\n *\n * - **Encoding:** Appends hidden data after encoding the main value.\n * - **Decoding:** Skips the hidden suffix after decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param suffixedCodecs - A list of void codecs that produce the hidden suffix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden suffix.\n *\n * @example\n * Encoding and decoding a value with suffixed constants.\n * ```ts\n * const codec = getHiddenSuffixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes after a value, consider using {@link padRightCodec} instead.\n *\n * Separate {@link getHiddenSuffixEncoder} and {@link getHiddenSuffixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenSuffixEncoder}\n * @see {@link getHiddenSuffixDecoder}\n */\nexport function getHiddenSuffixCodec(\n codec: FixedSizeCodec,\n suffixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenSuffixEncoder(codec, suffixedCodecs), getHiddenSuffixDecoder(codec, suffixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\n/**\n * Defines the configuration options for literal union codecs.\n *\n * A literal union codec encodes values from a predefined set of literals.\n * The `size` option determines the numerical encoding used for the discriminant.\n * By default, literals are stored as a `u8` (1 byte).\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type LiteralUnionCodecConfig = {\n /**\n * The codec used to encode/decode the discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n};\n\ntype Variant = bigint | boolean | number | string | null | undefined;\ntype GetTypeFromVariants = TVariants[number];\n\n/**\n * Returns an encoder for literal unions.\n *\n * This encoder serializes a value from a predefined set of literals\n * as a numerical index representing its position in the `variants` array.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding the literal union.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions.\n *\n * @example\n * Encoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']);\n *\n * sizeEncoder.encode('small'); // 0x00\n * sizeEncoder.encode('medium'); // 0x01\n * sizeEncoder.encode('large'); // 0x02\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n): FixedSizeEncoder, 1>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeEncoder>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Encoder> {\n const discriminator = config.size ?? getU8Encoder();\n return transformEncoder(discriminator, variant => {\n const index = variants.indexOf(variant);\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, {\n value: variant,\n variants,\n });\n }\n return index;\n });\n}\n\n/**\n * Returns a decoder for literal unions.\n *\n * This decoder deserializes a numerical index into a corresponding\n * value from a predefined set of literals.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for decoding the literal union.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions.\n *\n * @example\n * Decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']);\n *\n * sizeDecoder.decode(new Uint8Array([0x00])); // 'small'\n * sizeDecoder.decode(new Uint8Array([0x01])); // 'medium'\n * sizeDecoder.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n): FixedSizeDecoder, 1>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeDecoder>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Decoder> {\n const discriminator = config.size ?? getU8Decoder();\n return transformDecoder(discriminator, (index: bigint | number) => {\n if (index < 0 || index >= variants.length) {\n throw new SolanaError(SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator: index,\n maxRange: variants.length - 1,\n minRange: 0,\n });\n }\n return variants[Number(index)];\n });\n}\n\n/**\n * Returns a codec for encoding and decoding literal unions.\n *\n * A literal union codec serializes and deserializes values\n * from a predefined set of literals, using a numerical index\n * to represent each value in the `variants` array.\n *\n * This allows efficient storage and retrieval of common\n * predefined values such as enum-like structures in TypeScript.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding and decoding the literal union.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions.\n *\n * @example\n * Encoding and decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']);\n *\n * sizeCodec.encode('small'); // 0x00\n * sizeCodec.encode('medium'); // 0x01\n * sizeCodec.encode('large'); // 0x02\n *\n * sizeCodec.decode(new Uint8Array([0x00])); // 'small'\n * sizeCodec.decode(new Uint8Array([0x01])); // 'medium'\n * sizeCodec.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @example\n * Encoding and decoding a union of number literals.\n * ```ts\n * type Level = 10 | 20 | 30;\n * const levelCodec = getLiteralUnionCodec([10, 20, 30]);\n *\n * levelCodec.encode(10); // 0x00\n * levelCodec.encode(20); // 0x01\n * levelCodec.encode(30); // 0x02\n *\n * levelCodec.decode(new Uint8Array([0x00])); // 10\n * levelCodec.decode(new Uint8Array([0x01])); // 20\n * levelCodec.decode(new Uint8Array([0x02])); // 30\n * ```\n *\n * @example\n * Using a custom discriminator size with different variant types.\n * ```ts\n * type MaybeBoolean = false | true | \"either\";\n * const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n * codec.encode('either'); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * codec.decode(new Uint8Array([0x02, 0x00])); // 'either'\n * ```\n *\n * @remarks\n * Separate {@link getLiteralUnionEncoder} and {@link getLiteralUnionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green');\n * const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes);\n * ```\n *\n * @see {@link getLiteralUnionEncoder}\n * @see {@link getLiteralUnionDecoder}\n */\nexport function getLiteralUnionCodec(\n variants: TVariants,\n): FixedSizeCodec, GetTypeFromVariants, 1>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetTypeFromVariants, TSize>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeCodec>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Codec> {\n return combineCodec(getLiteralUnionEncoder(variants, config), getLiteralUnionDecoder(variants, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Defines the configuration options for map codecs.\n *\n * The `size` option determines how the number of entries in the map is stored.\n * It can be:\n * - A {@link NumberCodec} to prefix the map with its size.\n * - A fixed number of entries.\n * - `'remainder'`, which infers the number of entries based on the remaining bytes.\n * This option is only available for fixed-size keys and values.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used for the size prefix.\n */\nexport type MapCodecConfig = {\n /**\n * The size of the map.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for maps.\n *\n * This encoder serializes maps where the keys and values are encoded\n * using the provided key and value encoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n *\n * @param key - The encoder for the map's keys.\n * @param value - The encoder for the map's values.\n * @param config - Configuration options for encoding the map.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps.\n *\n * @example\n * Encoding a map with a `u32` size prefix.\n * ```ts\n * const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder());\n * const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getMapEncoder(\n key: FixedSizeEncoder,\n value: FixedSizeEncoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config?: MapCodecConfig,\n): VariableSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig = {},\n): Encoder> {\n return transformEncoder(\n getArrayEncoder(getTupleEncoder([key, value]), config as object),\n (map: Map): [TFromKey, TFromValue][] => [...map.entries()],\n );\n}\n\n/**\n * Returns a decoder for maps.\n *\n * This decoder deserializes maps where the keys and values are decoded\n * using the provided key and value decoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The decoder for the map's keys.\n * @param value - The decoder for the map's values.\n * @param config - Configuration options for decoding the map.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps.\n *\n * @example\n * Decoding a map with a `u32` size prefix.\n * ```ts\n * const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder());\n * const map = decoder.decode(new Uint8Array([\n * 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05\n * ]));\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getMapDecoder(\n key: FixedSizeDecoder,\n value: FixedSizeDecoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config?: MapCodecConfig,\n): VariableSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig = {},\n): Decoder> {\n return transformDecoder(\n getArrayDecoder(getTupleDecoder([key, value]), config as object) as Decoder<[TToKey, TToValue][]>,\n (entries: [TToKey, TToValue][]): Map => new Map(entries),\n );\n}\n\n/**\n * Returns a codec for encoding and decoding maps.\n *\n * This codec serializes maps where the key/value pairs are encoded\n * and decoded one after another using the provided key and value codecs.\n * The number of entries is determined by the `size` configuration and\n * defaults to a `u32` size prefix.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The codec for the map's keys.\n * @param value - The codec for the map's values.\n * @param config - Configuration options for encoding and decoding the map.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps.\n *\n * @example\n * Encoding and decoding a map with a `u32` size prefix (default).\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec());\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with a `u16` size prefix.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x0200616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 2-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a fixed-size map.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with remainder size.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n * // No size prefix, the size is inferred from the remaining bytes.\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @remarks\n * Separate {@link getMapEncoder} and {@link getMapDecoder} functions are available.\n * ```ts\n * const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]]));\n * const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getMapEncoder}\n * @see {@link getMapDecoder}\n */\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeCodec, Map, 0>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: FixedSizeCodec,\n value: FixedSizeCodec,\n config: MapCodecConfig & { size: number },\n): FixedSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config?: MapCodecConfig,\n): VariableSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig = {},\n): Codec, Map> {\n return combineCodec(getMapEncoder(key, value, config as object), getMapDecoder(key, value, config as object));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for `void` values.\n *\n * This encoder writes nothing to the byte array and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op encoder,\n * such as empty variants in {@link getDiscriminatedUnionEncoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeEncoder`, representing an empty encoder.\n *\n * @example\n * Encoding a `void` value.\n * ```ts\n * getUnitEncoder().encode(undefined); // Produces an empty byte array.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitEncoder(): FixedSizeEncoder {\n return createEncoder({\n fixedSize: 0,\n write: (_value, _bytes, offset) => offset,\n });\n}\n\n/**\n * Returns a decoder for `void` values.\n *\n * This decoder always returns `undefined` and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op decoder,\n * such as empty variants in {@link getDiscriminatedUnionDecoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeDecoder`, representing an empty decoder.\n *\n * @example\n * Decoding a `void` value.\n * ```ts\n * getUnitDecoder().decode(anyBytes); // Returns `undefined`.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitDecoder(): FixedSizeDecoder {\n return createDecoder({\n fixedSize: 0,\n read: (_bytes: ReadonlyUint8Array | Uint8Array, offset) => [undefined, offset],\n });\n}\n\n/**\n * Returns a codec for `void` values.\n *\n * This codec does nothing when encoding or decoding and has a fixed size of 0 bytes.\n * Namely, it always returns `undefined` when decoding and produces an empty byte array when encoding.\n *\n * This can be useful when working with structures that require a no-op codec,\n * such as empty variants in {@link getDiscriminatedUnionCodec}.\n *\n * @returns A `FixedSizeCodec`, representing an empty codec.\n *\n * @example\n * Encoding and decoding a `void` value.\n * ```ts\n * const codec = getUnitCodec();\n *\n * codec.encode(undefined); // Produces an empty byte array.\n * codec.decode(new Uint8Array([])); // Returns `undefined`.\n * ```\n *\n * @example\n * Using unit codecs as empty variants in a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Enter' }\n * | { __kind: 'Leave' }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Enter', getUnitCodec()], // <- No-op codec for empty data\n * ['Leave', getUnitCodec()], // <- No-op codec for empty data\n * ['Move', getStructCodec([...])]\n * ]);\n * ```\n *\n * @remarks\n * Separate {@link getUnitEncoder} and {@link getUnitDecoder} functions are available.\n *\n * ```ts\n * const bytes = getUnitEncoder().encode();\n * const value = getUnitDecoder().decode(bytes);\n * ```\n *\n * @see {@link getUnitEncoder}\n * @see {@link getUnitDecoder}\n */\nexport function getUnitCodec(): FixedSizeCodec {\n return combineCodec(getUnitEncoder(), getUnitDecoder());\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getBooleanDecoder, getBooleanEncoder } from './boolean';\nimport { getConstantDecoder, getConstantEncoder } from './constant';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { getUnitDecoder, getUnitEncoder } from './unit';\n\n/**\n * Defines the configuration options for nullable codecs.\n *\n * This configuration controls how nullable values are encoded and decoded.\n *\n * By default, nullable values are prefixed with a `u8` (0 = `null`, 1 = present).\n * The `noneValue` and `prefix` options allow customizing this behavior.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n * @see {@link getNullableCodec}\n */\nexport type NullableCodecConfig = {\n /**\n * Specifies how `null` values are represented in the encoded data.\n *\n * - By default, `null` values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec.\n * - Custom byte array: `null` values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; `null` values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between `null` and present values.\n *\n * - By default, a `u8` prefix is used (`0 = null`, `1 = present`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines `null`.\n * If no `noneValue` is set, `null` is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values, allowing `null` values to be encoded.\n *\n * This encoder serializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are replaced with the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values.\n *\n * @example\n * Encoding an optional number.\n * ```ts\n * const encoder = getNullableEncoder(getU32Encoder());\n *\n * encoder.encode(null); // 0x00\n * encoder.encode(42); // 0x012a000000\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config: NullableCodecConfig = {},\n): Encoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: TFrom): [boolean, TFrom] => [true, value]),\n ],\n variant => Number(variant !== null),\n );\n}\n\n/**\n * Returns a decoder for optional values, allowing `null` values to be recognized.\n *\n * This decoder deserializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes.\n * - If `noneValue` is a byte array, `null` values match the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values.\n *\n * @example\n * Decoding an optional number.\n * ```ts\n * const decoder = getNullableDecoder(getU32Decoder());\n *\n * decoder.decode(new Uint8Array([0x00])); // null\n * decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config: NullableCodecConfig = {},\n): Decoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => null),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]): TTo => value),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values, allowing `null` values to be handled.\n *\n * This codec serializes and deserializes optional values using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present).\n * This can be customized using a custom number codec or even disabled by setting\n * the `prefix` to `null`.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are represented by the provided constant.\n *\n * For more details on the configuration options, see {@link NullableCodecConfig}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding optional values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values.\n *\n * @example\n * Encoding and decoding an optional number using a `u8` prefix (default).\n * ```ts\n * const codec = getNullableCodec(getU32Codec());\n *\n * codec.encode(null); // 0x00\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' });\n *\n * codec.encode(null); // 0x0000000000\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with zeroes and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), {\n * noneValue: 'zeroes',\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0x00000000\n * codec.encode(42); // 0x2a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0xffff\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([0xff, 0xff])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @example\n * Identifying `null` values by the absence of bytes.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), { prefix: null });\n *\n * codec.encode(null); // Empty bytes\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @remarks\n * Separate {@link getNullableEncoder} and {@link getNullableDecoder} functions are available.\n *\n * ```ts\n * const bytes = getNullableEncoder(getU32Encoder()).encode(42);\n * const value = getNullableDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n */\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config: NullableCodecConfig = {},\n): Codec {\n type ConfigCast = NullableCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getNullableEncoder(item, config as ConfigCast),\n getNullableDecoder(item, config as ConfigCast),\n );\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\n\n/**\n * Defines the configuration options for set codecs.\n *\n * This configuration allows specifying how the size of the set is encoded.\n * The `size` option can be:\n *\n * - A {@link NumberCodec}, {@link NumberEncoder}, or {@link NumberDecoder} to store the size as a prefix.\n * - A fixed number of items, enforcing a strict length.\n * - The string `'remainder'` to infer the set size from the remaining bytes (only for fixed-size items).\n *\n * @typeParam TPrefix - The type used for encoding the size of the set.\n */\nexport type SetCodecConfig = {\n /**\n * The size encoding strategy for the set.\n * @defaultValue Uses a `u32` prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for sets of items.\n *\n * This encoder serializes `Set` values by encoding each item using the provided item encoder.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n *\n * @param item - The encoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns An `Encoder>` for encoding sets of items.\n *\n * @example\n * Encoding a set of `u8` numbers.\n * ```ts\n * const encoder = getSetEncoder(getU8Encoder());\n * const bytes = encoder.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getSetEncoder(\n item: FixedSizeEncoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config?: SetCodecConfig,\n): VariableSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig = {},\n): Encoder> {\n return transformEncoder(getArrayEncoder(item, config as object), (set: Set): TFrom[] => [...set]);\n}\n\n/**\n * Returns a decoder for sets of items.\n *\n * This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder.\n * The number of items is determined by a `u32` size prefix by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The decoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Decoder>` for decoding sets of items.\n *\n * @example\n * Decoding a set of `u8` numbers.\n * ```ts\n * const decoder = getSetDecoder(getU8Decoder());\n * const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // new Set([1, 2, 3])\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetDecoder(\n item: Decoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getSetDecoder(\n item: FixedSizeDecoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getSetDecoder(\n item: Decoder,\n config?: SetCodecConfig,\n): VariableSizeDecoder>;\nexport function getSetDecoder(item: Decoder, config: SetCodecConfig = {}): Decoder> {\n return transformDecoder(getArrayDecoder(item, config as object), (entries: TTo[]): Set => new Set(entries));\n}\n\n/**\n * Returns a codec for encoding and decoding sets of items.\n *\n * This codec serializes `Set` values by encoding each item using the provided item codec.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The codec to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Codec, Set>` for encoding and decoding sets.\n *\n * @example\n * Encoding and decoding a set of `u8` numbers.\n * ```ts\n * const codec = getSetCodec(getU8Codec());\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n *\n * const value = codec.decode(bytes);\n * // new Set([1, 2, 3])\n * ```\n *\n * @example\n * Using a `u16` prefix for size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix indicating 3 items.\n * ```\n *\n * @example\n * Using a fixed-size set.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 3 });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- Exactly 3 items of 1 byte each.\n * ```\n *\n * @example\n * Using remainder to infer set size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remaining bytes.\n * ```\n *\n * @remarks\n * Separate {@link getSetEncoder} and {@link getSetDecoder} functions are available.\n *\n * ```ts\n * const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3]));\n * const value = getSetDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getSetEncoder}\n * @see {@link getSetDecoder}\n */\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeCodec, Set, 0>;\nexport function getSetCodec(\n item: FixedSizeCodec,\n config: SetCodecConfig & { size: number },\n): FixedSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config?: SetCodecConfig,\n): VariableSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig = {},\n): Codec, Set> {\n return combineCodec(getSetEncoder(item, config as object), getSetDecoder(item, config as object));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Represents a collection of named fields used in struct codecs.\n *\n * Each field is defined as a tuple containing:\n * - A string key representing the field name.\n * - A codec used to encode and decode the field's value.\n *\n * @typeParam T - The codec type used for each field.\n */\ntype Fields = readonly (readonly [string, T])[];\n\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\n/**\n * Infers the TypeScript type for an object that can be encoded using a struct codec.\n *\n * This type maps the provided field encoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n */\ntype GetEncoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for an object that can be decoded using a struct codec.\n *\n * This type maps the provided field decoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n */\ntype GetDecoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for custom objects.\n *\n * This encoder serializes an object by encoding its fields sequentially,\n * using the provided field encoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n *\n * @param fields - The name and encoder of each field.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects.\n *\n * @example\n * Encoding a custom struct.\n * ```ts\n * const encoder = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]);\n *\n * const bytes = encoder.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructEncoder>>(\n fields: TFields,\n): FixedSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): VariableSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): Encoder> {\n type TFrom = GetEncoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n fields\n .map(([key, codec]) => getEncodedSize(value[key as keyof TFrom], codec))\n .reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (struct: TFrom, bytes, offset) => {\n fields.forEach(([key, codec]) => {\n offset = codec.write(struct[key as keyof TFrom], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for custom objects.\n *\n * This decoder deserializes an object by decoding its fields sequentially,\n * using the provided field decoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n *\n * @param fields - The name and decoder of each field.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects.\n *\n * @example\n * Decoding a custom struct.\n * ```ts\n * const decoder = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]);\n *\n * const struct = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructDecoder>>(\n fields: TFields,\n): FixedSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): VariableSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): Decoder> {\n type TTo = GetDecoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const struct = {} as TTo;\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.read(bytes, offset);\n offset = newOffset;\n struct[key as keyof TTo] = value;\n });\n return [struct, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding custom objects.\n *\n * This codec serializes objects by encoding and decoding each field sequentially.\n *\n * @typeParam TFields - The fields of the struct, each paired with a codec.\n *\n * @param fields - The name and codec of each field.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects.\n *\n * @example\n * Encoding and decoding a custom struct.\n * ```ts\n * const codec = getStructCodec([\n * ['name', fixCodecSize(getUtf8Codec(), 5)],\n * ['age', getU8Codec()]\n * ]);\n *\n * const bytes = codec.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n *\n * const struct = codec.decode(bytes);\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @remarks\n * Separate {@link getStructEncoder} and {@link getStructDecoder} functions are available.\n *\n * ```ts\n * const bytes = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]).encode({ name: 'Alice', age: 42 });\n *\n * const struct = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getStructEncoder}\n * @see {@link getStructDecoder}\n */\nexport function getStructCodec>>(\n fields: TFields,\n): FixedSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): VariableSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): Codec, GetDecoderTypeFromFields & GetEncoderTypeFromFields> {\n return combineCodec(\n getStructEncoder(fields),\n getStructDecoder(fields) as Decoder & GetEncoderTypeFromFields>,\n );\n}\n","/**\n * An implementation of the Rust `Option` type in JavaScript.\n *\n * In Rust, optional values are represented using `Option`, which can be either:\n * - `Some(T)`, indicating a present value.\n * - `None`, indicating the absence of a value.\n *\n * In JavaScript, this is typically represented as `T | null`. However, this approach fails with nested options.\n * For example, `Option>` in Rust would translate to `T | null | null` in JavaScript, which is equivalent to `T | null`.\n * This means there is no way to differentiate between `Some(None)` and `None`, making nested options impossible.\n *\n * This `Option` type helps solve this by mirroring Rust’s `Option` type.\n *\n * ```ts\n * type Option = Some | None;\n * type Some = { __option: 'Some'; value: T };\n * type None = { __option: 'None' };\n * ```\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Here's how you can create `Option` values.\n *\n * To improve developer experience, helper functions are available.\n * TypeScript can infer the type of `T` or it can be explicitly provided.\n *\n * ```ts\n * // Create an option with a value.\n * some('Hello World');\n * some(123);\n *\n * // Create an empty option.\n * none();\n * none();\n * ```\n *\n * @see {@link Some}\n * @see {@link None}\n * @see {@link some}\n * @see {@link none}\n */\nexport type Option = None | Some;\n\n/**\n * A flexible type that allows working with {@link Option} values or nullable values.\n *\n * It defines a looser type that can be used when encoding {@link Option | Options}.\n * This allows us to pass `null` or the nested value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Accepting both `Option` and `T | null` as input.\n * ```ts\n * function double(value: OptionOrNullable) {\n * const option = isOption(value) ? value : wrapNullable(value);\n * return isSome(option) ? option.value * 2 : 'No value';\n * }\n *\n * double(42); // 84\n * double(some(21)); // 42\n * double(none()); // \"No value\"\n * double(null); // \"No value\"\n * ```\n *\n * @see {@link Option}\n * @see {@link isOption}\n * @see {@link wrapNullable}\n */\nexport type OptionOrNullable = Option | T | null;\n\n/**\n * Represents an {@link Option} that contains a value.\n *\n * This type mirrors Rust’s `Some(T)`, indicating that a value is present.\n *\n * For more details, see {@link Option}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Creating a `Some` value.\n * ```ts\n * const value = some(42);\n * isSome(value); // true\n * isNone(value); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link some}\n * @see {@link isSome}\n */\nexport type Some = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an {@link Option} that contains no value.\n *\n * This type mirrors Rust’s `None`, indicating the absence of a value.\n *\n * For more details, see {@link Option}.\n *\n * @example\n * Creating a `None` value.\n * ```ts\n * const empty = none();\n * isNone(empty); // true\n * isSome(empty); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link none}\n * @see {@link isNone}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} that contains a value.\n *\n * This function explicitly wraps a value in an {@link Option} type.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param value - The value to wrap in an {@link Option}.\n * @returns An {@link Option} containing the provided value.\n *\n * @example\n * Wrapping a value in an `Option`.\n * ```ts\n * const option = some('Hello');\n * option.value; // \"Hello\"\n * isOption(option); // true\n * isSome(option); // true\n * isNone(option); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const some = (value: T): Option => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} that contains no value.\n *\n * This function explicitly represents an absent value.\n *\n * @typeParam T - The type of the expected absent value.\n *\n * @returns An {@link Option} containing no value.\n *\n * @example\n * Creating an empty `Option`.\n * ```ts\n * const empty = none();\n * isOption(empty); // true\n * isSome(empty); // false\n * isNone(empty); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const none = (): Option => ({ __option: 'None' });\n\n/**\n * Checks whether the given value is an {@link Option}.\n *\n * This function determines whether an input follows the `Option` structure.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param input - The value to check.\n * @returns `true` if the value is an {@link Option}, `false` otherwise.\n *\n * @example\n * Checking for `Option` values.\n * ```ts\n * isOption(some(42)); // true\n * isOption(none()); // true\n * isOption(42); // false\n * isOption(null); // false\n * isOption(\"anything else\"); // false\n * ```\n *\n * @see {@link Option}\n */\nexport const isOption = (input: unknown): input is Option =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Checks whether the given {@link Option} contains a value.\n *\n * This function acts as a type guard, ensuring the value is a {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link Some}, `false` otherwise.\n *\n * @example\n * Checking for `Some` values.\n * ```ts\n * isSome(some(42)); // true\n * isSome(none()); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const isSome = (option: Option): option is Some => option.__option === 'Some';\n\n/**\n * Checks whether the given {@link Option} contains no value.\n *\n * This function acts as a type guard, ensuring the value is a {@link None}.\n *\n * @typeParam T - The type of the expected value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link None}, `false` otherwise.\n *\n * @example\n * Checking for `None` values.\n * ```ts\n * isNone(some(42)); // false\n * isNone(none()); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const isNone = (option: Option): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option}, returning its contained value or a fallback.\n *\n * This function extracts the value `T` from an `Option` type.\n * - If the option is {@link Some}, it returns the contained value `T`.\n * - If the option is {@link None}, it returns the fallback value `U`, which defaults to `null`.\n *\n * @typeParam T - The type of the contained value.\n * @typeParam U - The type of the fallback value (defaults to `null`).\n *\n * @param option - The {@link Option} to unwrap.\n * @param fallback - A function that provides a fallback value if the option is {@link None}.\n * @returns The contained value if {@link Some}, otherwise the fallback value.\n *\n * @example\n * Unwrapping an `Option` with no fallback.\n * ```ts\n * unwrapOption(some('Hello World')); // \"Hello World\"\n * unwrapOption(none()); // null\n * ```\n *\n * @example\n * Providing a custom fallback value.\n * ```ts\n * unwrapOption(some('Hello World'), () => 'Default'); // \"Hello World\"\n * unwrapOption(none(), () => 'Default'); // \"Default\"\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport function unwrapOption(option: Option): T | null;\nexport function unwrapOption(option: Option, fallback: () => U): T | U;\nexport function unwrapOption(option: Option, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n *\n * - If the input value is `null`, this function returns {@link None}.\n * - Otherwise, it wraps the value in {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param nullable - The nullable value to wrap.\n * @returns An {@link Option} wrapping the value.\n *\n * @example\n * Wrapping nullable values.\n * ```ts\n * wrapNullable('Hello World'); // Option (Some)\n * wrapNullable(null); // Option (None)\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport const wrapNullable = (nullable: T | null): Option => (nullable !== null ? some(nullable) : none());\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getUnionDecoder,\n getUnionEncoder,\n getUnitDecoder,\n getUnitEncoder,\n} from '@solana/codecs-data-structures';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, None, none, Option, OptionOrNullable, Some, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/**\n * Defines the configuration options for {@link Option} codecs.\n *\n * The `getOptionCodec` function behaves similarly to {@link getNullableCodec}\n * but encodes `Option` types instead of `T | null` types.\n *\n * This configuration controls how {@link None} values are encoded and how presence\n * is determined when decoding.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n * @see {@link getOptionCodec}\n */\nexport type OptionCodecConfig = {\n /**\n * Specifies how {@link None} values are represented in the encoded data.\n *\n * - By default, {@link None} values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec for the item.\n * - Custom byte array: {@link None} values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; {@link None} values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between {@link None} and present values.\n *\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines {@link None}.\n * If no `noneValue` is set, {@link None} is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values using the {@link Option} type.\n *\n * This encoder serializes an {@link OptionOrNullable} value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, {@link None} values are encoded as zeroes.\n * - If `noneValue` is a byte array, {@link None} values are replaced with the provided constant.\n *\n * Unlike {@link getNullableEncoder}, this encoder accepts both {@link Option} and {@link Nullable} values.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values.\n *\n * @example\n * Encoding an optional string.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const encoder = getOptionEncoder(stringCodec);\n *\n * encoder.encode(some('Hi'));\n * encoder.encode('Hi');\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * encoder.encode(none());\n * encoder.encode(null);\n * // 0x00\n * // └-- 1-byte prefix (None).\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder, TSize>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config: OptionCodecConfig = {},\n): Encoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: None | null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: Some | TFrom): [boolean, TFrom] => [\n true,\n isOption(value) && isSome(value) ? value.value : value,\n ]),\n ],\n variant => {\n const option = isOption(variant) ? variant : wrapNullable(variant);\n return Number(isSome(option));\n },\n );\n}\n\n/**\n * Returns a decoder for optional values using the {@link Option} type.\n *\n * This decoder deserializes an `Option` value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes.\n * - If `noneValue` is a byte array, `None` values match the provided constant.\n *\n * Unlike {@link getNullableDecoder}, this decoder always outputs an {@link Option} type.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values.\n *\n * @example\n * Decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const decoder = getOptionDecoder(stringCodec);\n *\n * decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69]));\n * // some('Hi')\n *\n * decoder.decode(new Uint8Array([0x00]));\n * // none()\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder, TSize>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config: OptionCodecConfig = {},\n): Decoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => none()),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value)),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values using the {@link Option} type.\n *\n * This codec serializes and deserializes `Option` values using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `None` values are represented by the provided constant.\n * - If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes.\n *\n * For more details on the configuration options, see {@link OptionCodecConfig}.\n *\n * Note that this behaves similarly to {@link getNullableCodec}, except it\n * encodes {@link OptionOrNullable} values and decodes {@link Option} values.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding option values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values.\n *\n * @example\n * Encoding and decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode(some('Hi'));\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * const noneBytes = codec.encode(none());\n * // 0x00\n * // └-- 1-byte prefix (None).\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding nullable values.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode('Hi'); // 0x01020000004869\n * const noneBytes = codec.encode(null); // 0x00\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding an optional number with a fixed size.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' });\n *\n * const someBytes = codec.encode(some(42)); // 0x012a00\n * const noneBytes = codec.encode(none()); // 0x000000\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding {@link None} values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // 0xffff\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Identifying {@link None} values by the absence of bytes.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { prefix: null });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // new Uint8Array(0)\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @remarks\n * Separate {@link getOptionEncoder} and {@link getOptionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getOptionEncoder(getU32Encoder()).encode(some(42));\n * const value = getOptionDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n */\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec, Option, TSize>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec, Option>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config: OptionCodecConfig = {},\n): Codec, Option> {\n type ConfigCast = OptionCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getOptionEncoder(item, config as ConfigCast),\n getOptionDecoder(item, config as ConfigCast),\n );\n}\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Defines types that should not be recursively unwrapped.\n *\n * These types are preserved as-is when using {@link unwrapOptionRecursively}.\n *\n * @see {@link unwrapOptionRecursively}\n */\ntype UnUnwrappables =\n | Date\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | bigint\n | boolean\n | number\n | string\n | symbol\n | null\n | undefined;\n\n/**\n * A type that recursively unwraps nested {@link Option} types.\n *\n * This type resolves all nested {@link Option} values, ensuring\n * that deeply wrapped values are properly extracted.\n *\n * - If `T` is an {@link Option}, it resolves to the contained value.\n * - If `T` is a known primitive or immutable type, it remains unchanged.\n * - If `T` is an object or array, it recursively unwraps any options found.\n *\n * The fallback type `U` (default: `null`) is used in place of `None` values.\n *\n * @typeParam T - The type to be unwrapped.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @example\n * Resolving nested `Option` types.\n * ```ts\n * UnwrappedOption>>; // string\n * UnwrappedOption; // null\n * ```\n *\n * @example\n * Resolving options inside objects and arrays.\n * ```ts\n * UnwrappedOption<{ a: Some; b: None }>; // { a: number; b: null }\n * UnwrappedOption<[Some, None]>; // [number, null]\n * ```\n *\n * @see {@link unwrapOptionRecursively}\n */\nexport type UnwrappedOption =\n T extends Some\n ? UnwrappedOption\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption }\n : T extends Array\n ? Array>\n : T;\n\n/**\n * Recursively unwraps all nested {@link Option} types within a value.\n *\n * This function traverses a given value and removes all instances\n * of {@link Option}, replacing them with their contained values.\n *\n * - If an {@link Option} is encountered, its value is extracted.\n * - If an array or object is encountered, its elements are traversed recursively.\n * - If `None` is encountered, it is replaced with the fallback value (default: `null`).\n *\n * @typeParam T - The type of the input value.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @param input - The value to unwrap.\n * @param fallback - A function that provides a fallback value for `None` options.\n * @returns The recursively unwrapped value.\n *\n * @example\n * Recursively unwrapping nested options.\n * ```ts\n * unwrapOptionRecursively(some(some('Hello World'))); // \"Hello World\"\n * unwrapOptionRecursively(some(none())); // null\n * ```\n *\n * @example\n * Recursively unwrapping options inside objects and arrays.\n * ```ts\n * unwrapOptionRecursively({\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * });\n * // { a: \"hello\", b: null, c: [{ c1: 42 }, { c2: null }] }\n * ```\n *\n * @example\n * Using a fallback value for `None` options.\n * ```ts\n * unwrapOptionRecursively(\n * {\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * },\n * () => 'Default',\n * );\n * // { a: \"hello\", b: \"Default\", c: [{ c1: 42 }, { c2: \"Default\" }] }\n * ```\n *\n * @remarks\n * This function does not mutate objects or arrays.\n *\n * @see {@link Option}\n * @see {@link UnwrappedOption}\n */\nexport function unwrapOptionRecursively(input: T): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback: () => U): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback?: () => U): UnwrappedOption {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption;\n }\n\n const next = (x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption;\n return (fallback ? fallback() : null) as UnwrappedOption;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption;\n }\n return input as UnwrappedOption;\n}\n","export * from '@solana/codecs-core';\nexport * from '@solana/codecs-data-structures';\nexport * from '@solana/codecs-numbers';\nexport * from '@solana/codecs-strings';\nexport * from '@solana/options';\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","/**\n * A pipeline is a solution that allows you to perform successive transforms of a value using functions. This is useful when building up a transaction message.\n *\n * Until the [pipeline operator](https://github.com/tc39/proposal-pipeline-operator) becomes part of JavaScript you can use this utility to create pipelines.\n *\n * Following common implementations of pipe functions that use TypeScript, this function supports a maximum arity of 10 for type safety.\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```ts\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n *\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * @example Basic\n * ```ts\n * const add = (a, b) => a + b;\n * const add10 = x => add(x, 10);\n * const add100 = x => add(x, 100);\n * const sum = pipe(1, add10, add100);\n * sum === 111; // true\n * ```\n *\n * @example Building a Solana transaction message\n * ```ts\n * const transferTransactionMessage = pipe(\n * // The result of the first expression...\n * createTransactionMessage({ version: 0 }),\n * // ...gets passed as the sole argument to the next function in the pipeline.\n * tx => setTransactionMessageFeePayer(myAddress, tx),\n * // The return value of that function gets passed to the next...\n * tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n * // ...and so on.\n * tx => appendTransactionMessageInstruction(createTransferInstruction(myAddress, toAddress, amountInLamports), tx),\n * );\n * ```\n *\n * @returns The initial value\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n): TInitial;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n): R1;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n): R2;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n): R3;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n): R4;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n): R5;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n): R6;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n): R7;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n): R8;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n): R9;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n /** The function with which to transform the return value of the prior function */\n r9_r10: (r9: R9) => R10,\n): R10;\nexport function pipe(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { AccountLookupMeta, AccountMeta } from './accounts';\n\n/**\n * An instruction destined for a given program.\n *\n * @example\n * ```ts\n * type StakeProgramInstruction = Instruction<'StakeConfig11111111111111111111111111111111'>;\n * ```\n */\nexport interface Instruction<\n TProgramAddress extends string = string,\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n> {\n readonly accounts?: TAccounts;\n readonly data?: ReadonlyUint8Array;\n readonly programAddress: Address;\n}\n\n/**\n * An instruction that loads certain accounts.\n *\n * @example\n * ```ts\n * type InstructionWithTwoAccounts = InstructionWithAccounts<\n * [\n * WritableAccount, // First account\n * RentSysvar, // Second account\n * ]\n * >;\n * ```\n */\nexport interface InstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[],\n> extends Instruction {\n readonly accounts: TAccounts;\n}\n\nexport function isInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): instruction is TInstruction & { programAddress: Address } {\n return instruction.programAddress === programAddress;\n}\n\nexport function assertIsInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): asserts instruction is TInstruction & { programAddress: Address } {\n if (instruction.programAddress !== programAddress) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, {\n actualProgramAddress: instruction.programAddress,\n expectedProgramAddress: programAddress,\n });\n }\n}\n\nexport function isInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithAccounts & TInstruction {\n return instruction.accounts !== undefined;\n}\n\nexport function assertIsInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithAccounts & TInstruction {\n if (instruction.accounts === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, {\n data: instruction.data,\n programAddress: instruction.programAddress,\n });\n }\n}\n\n/**\n * An instruction whose data conforms to a certain type.\n *\n * This is most useful when you have a branded `Uint8Array` that represents a particular\n * instruction's data.\n *\n * @example A type for the \\`AdvanceNonce\\` instruction of the System program\n * ```ts\n * type AdvanceNonceAccountInstruction<\n * TNonceAccountAddress extends string = string,\n * TNonceAuthorityAddress extends string = string,\n * > = Instruction<'11111111111111111111111111111111'> &\n * InstructionWithAccounts<\n * [\n * WritableAccount,\n * ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n * ReadonlySignerAccount,\n * ]\n * > &\n * InstructionWithData;\n * ```\n */\nexport interface InstructionWithData extends Instruction {\n readonly data: TData;\n}\n\nexport function isInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithData & TInstruction {\n return instruction.data !== undefined;\n}\n\nexport function assertIsInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithData & TInstruction {\n if (instruction.data === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, {\n accountAddresses: instruction.accounts?.map(a => a.address),\n programAddress: instruction.programAddress,\n });\n }\n}\n","/**\n * Describes the purpose for which an account participates in a transaction.\n *\n * Every account that participates in a transaction can be read from, but only ones that you mark as\n * writable may be written to, and only ones that you indicate must sign the transaction will gain\n * the privileges associated with signers at runtime.\n *\n * | | `isSigner` | `isWritable` |\n * | ----------------------------- | ---------- | ------------ |\n * | `AccountRole.READONLY` | ❌ | ❌ |\n * | `AccountRole.WRITABLE` | ❌ | ✅ |\n * | `AccountRole.READONLY_SIGNER` | ✅ | ❌ |\n * | `AccountRole.WRITABLE_SIGNER` | ✅ | ✅ |\n */\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\n// Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\n/**\n * @returns An {@link AccountRole} representing the non-signer variant of the supplied role.\n */\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the read-only variant of the supplied role.\n */\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a signer. Also refines the\n * TypeScript type of the supplied role.\n */\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a writable account. Also\n * refines the TypeScript type of the supplied role.\n */\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\n/**\n * Given two {@link AccountRole | AccountRoles}, will return the {@link AccountRole} that grants the\n * highest privileges of both.\n *\n * @example\n * ```ts\n * // Returns `AccountRole.WRITABLE_SIGNER`\n * mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE);\n * ```\n */\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\n/**\n * @returns An {@link AccountRole} representing the signer variant of the supplied role.\n */\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the writable variant of the supplied role.\n */\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { Address, assertIsAddress, getAddressDecoder, getAddressEncoder, isAddress } from '@solana/addresses';\nimport { combineCodec, createEncoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nexport type Blockhash = Brand, 'Blockhash'>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Blockhash} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isBlockhash } from '@solana/rpc-types';\n *\n * if (isBlockhash(blockhash)) {\n * // At this point, `blockhash` has been refined to a\n * // `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsFresh(isValid);\n * } else {\n * setError(`${blockhash} is not a blockhash`);\n * }\n * ```\n */\nexport function isBlockhash(putativeBlockhash: string): putativeBlockhash is Blockhash {\n return isAddress(putativeBlockhash);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as a blockhash, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string is\n * a base58-encoded blockhash.\n *\n * @example\n * ```ts\n * import { assertIsBlockhash } from '@solana/rpc-types';\n *\n * // Imagine a function that determines whether a blockhash is fresh when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const blockhash: string = blockhashInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `blockhash` to `Blockhash`.\n * assertIsBlockhash(blockhash);\n * // At this point, `blockhash` is a `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `blockhash` turned out not to be a base58-encoded blockhash\n * }\n * }\n * ```\n */\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n assertIsAddress(putativeBlockhash);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, error.context);\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, error.context);\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is a blockhash with _coercing_ it to the {@link Blockhash}\n * type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { blockhash } from '@solana/rpc-types';\n *\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash(blockhashFromUserInput)).send();\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good blockhash as a string, it's more efficient to typecast it\n * rather than to use the {@link blockhash} helper, because the helper unconditionally performs\n * validation on its input.\n * >\n * > ```ts\n * > import { Blockhash } from '@solana/rpc-types';\n * >\n * > const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * > ```\n */\nexport function blockhash(putativeBlockhash: string): Blockhash {\n assertIsBlockhash(putativeBlockhash);\n return putativeBlockhash;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded blockhash to a byte array.\n *\n * @example\n * ```ts\n * import { getBlockhashEncoder } from '@solana/rpc-types';\n *\n * const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * const blockhashEncoder = getBlockhashEncoder();\n * const blockhashBytes = blockhashEncoder.encode(blockhash);\n * // Uint8Array(32) [\n * // 136, 123, 44, 249, 43, 19, 60, 14,\n * // 144, 16, 168, 241, 121, 111, 70, 232,\n * // 186, 26, 140, 202, 213, 64, 231, 82,\n * // 179, 66, 103, 237, 52, 117, 217, 93\n * // ]\n * ```\n */\nexport function getBlockhashEncoder(): FixedSizeEncoder {\n const addressEncoder = getAddressEncoder();\n return createEncoder({\n fixedSize: 32,\n write: (value: string, bytes, offset) => {\n assertIsBlockhash(value);\n return addressEncoder.write(value as string as Address, bytes, offset);\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing a blockhash to\n * the base58-encoded representation of that blockhash.\n *\n * @example\n * ```ts\n * import { getBlockhashDecoder } from '@solana/rpc-types';\n *\n * const blockhashBytes = new Uint8Array([\n * 136, 123, 44, 249, 43, 19, 60, 14,\n * 144, 16, 168, 241, 121, 111, 70, 232,\n * 186, 26, 140, 202, 213, 64, 231, 82,\n * 179, 66, 103, 237, 52, 117, 217, 93\n * ]);\n * const blockhashDecoder = getBlockhashDecoder();\n * const blockhash = blockhashDecoder.decode(blockhashBytes); // ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48\n * ```\n */\nexport function getBlockhashDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded blockhash.\n *\n * @see {@link getBlockhashDecoder}\n * @see {@link getBlockhashEncoder}\n */\nexport function getBlockhashCodec(): FixedSizeCodec {\n return combineCodec(getBlockhashEncoder(), getBlockhashDecoder());\n}\n\nexport function getBlockhashComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","export type MainnetUrl = string & { '~cluster': 'mainnet' };\nexport type DevnetUrl = string & { '~cluster': 'devnet' };\nexport type TestnetUrl = string & { '~cluster': 'testnet' };\nexport type ClusterUrl = DevnetUrl | MainnetUrl | TestnetUrl | string;\n\n/** Given a URL casts it to a type that is only accepted where mainnet URLs are expected. */\nexport function mainnet(putativeString: string): MainnetUrl {\n return putativeString as MainnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where devnet URLs are expected. */\nexport function devnet(putativeString: string): DevnetUrl {\n return putativeString as DevnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where testnet URLs are expected. */\nexport function testnet(putativeString: string): TestnetUrl {\n return putativeString as TestnetUrl;\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\n\n/**\n * A union of all possible commitment statuses -- each a measure of the network confirmation and\n * stake levels on a particular block.\n *\n * Read more about the statuses themselves, [here](https://docs.solana.com/cluster/commitments).\n */\nexport type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: commitment satisfies never,\n });\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n} from '@solana/codecs-core';\nimport { getU64Decoder, getU64Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * Represents an integer value denominated in Lamports (ie. $1 \\times 10^{-9}$ ◎).\n *\n * It is represented as a `bigint` in client code and an `u64` in server code.\n */\nexport type Lamports = Brand;\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nlet memoizedU64Encoder: FixedSizeEncoder | undefined;\nlet memoizedU64Decoder: FixedSizeDecoder | undefined;\n\nfunction getMemoizedU64Encoder(): FixedSizeEncoder {\n if (!memoizedU64Encoder) memoizedU64Encoder = getU64Encoder();\n return memoizedU64Encoder;\n}\n\nfunction getMemoizedU64Decoder(): FixedSizeDecoder {\n if (!memoizedU64Decoder) memoizedU64Decoder = getU64Decoder();\n return memoizedU64Decoder;\n}\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link Lamports} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isLamports } from '@solana/rpc-types';\n *\n * if (isLamports(lamports)) {\n * // At this point, `lamports` has been refined to a\n * // `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } else {\n * setError(`${lamports} is not a quantity of Lamports`);\n * }\n * ```\n */\nexport function isLamports(putativeLamports: bigint): putativeLamports is Lamports {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\n/**\n * Lamport values returned from the RPC API conform to the type {@link Lamports}. You can use a\n * value of that type wherever a quantity of Lamports is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a quantity of Lamports, from\n * an untrusted network API or user input. To assert that such an arbitrary number is usable as a\n * quantity of Lamports, use this function.\n *\n * ```ts\n * import { assertIsLamports } from '@solana/rpc-types';\n *\n * // Imagine a function that creates a transfer instruction when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `number` type.\n * const lamports: number = parseInt(quantityInput.value, 10);\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `lamports` to `Lamports`.\n * assertIsLamports(lamports);\n * // At this point, `lamports` is a `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } catch (e) {\n * // `lamports` turned out not to validate as a quantity of Lamports.\n * }\n * }\n * ```\n */\nexport function assertIsLamports(putativeLamports: bigint): asserts putativeLamports is Lamports {\n if (putativeLamports < 0 || putativeLamports > maxU64Value) {\n throw new SolanaError(SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE);\n }\n}\n\n/**\n * This helper combines _asserting_ that a number is a possible number of {@link Lamports} with\n * _coercing_ it to the {@link Lamports} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { lamports } from '@solana/rpc-types';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n */\nexport function lamports(putativeLamports: bigint): Lamports {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n\ntype ExtractAdditionalProps = Omit;\n\n/**\n * Returns an encoder that you can use to encode a 64-bit {@link Lamports} value to 8 bytes in\n * little endian order.\n */\nexport function getDefaultLamportsEncoder(): FixedSizeEncoder {\n return getLamportsEncoder(getMemoizedU64Encoder());\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link Lamports} value to a byte array.\n *\n * You must supply a number decoder that will determine how encode the numeric value.\n *\n * @example\n * ```ts\n * import { getLamportsEncoder } from '@solana/rpc-types';\n * import { getU16Encoder } from '@solana/codecs-numbers';\n *\n * const lamports = lamports(256n);\n * const lamportsEncoder = getLamportsEncoder(getU16Encoder());\n * const lamportsBytes = lamportsEncoder.encode(lamports);\n * // Uint8Array(2) [ 0, 1 ]\n * ```\n */\nexport function getLamportsEncoder(\n innerEncoder: TEncoder,\n): Encoder & ExtractAdditionalProps {\n return innerEncoder;\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a 64-bit little endian\n * number to a {@link Lamports} value.\n */\nexport function getDefaultLamportsDecoder(): FixedSizeDecoder {\n return getLamportsDecoder(getMemoizedU64Decoder());\n}\n\n/**\n * Returns a decoder that you can use to convert an array of bytes representing a number to a\n * {@link Lamports} value.\n *\n * You must supply a number decoder that will determine how many bits to use to decode the numeric\n * value.\n *\n * @example\n * ```ts\n * import { getLamportsDecoder } from '@solana/rpc-types';\n * import { getU16Decoder } from '@solana/codecs-numbers';\n *\n * const lamportsBytes = new Uint8Array([ 0, 1 ]);\n * const lamportsDecoder = getLamportsDecoder(getU16Decoder());\n * const lamports = lamportsDecoder.decode(lamportsBytes); // lamports(256n)\n * ```\n */\nexport function getLamportsDecoder(\n innerDecoder: TDecoder,\n): Decoder & ExtractAdditionalProps {\n return transformDecoder(innerDecoder, value =>\n lamports(typeof value === 'bigint' ? value : BigInt(value)),\n ) as Decoder & ExtractAdditionalProps;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a 64-bit {@link Lamports} value.\n *\n * @see {@link getDefaultLamportsDecoder}\n * @see {@link getDefaultLamportsEncoder}\n */\nexport function getDefaultLamportsCodec(): FixedSizeCodec {\n return combineCodec(getDefaultLamportsEncoder(), getDefaultLamportsDecoder());\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link Lamports} value.\n *\n * @see {@link getLamportsDecoder}\n * @see {@link getLamportsEncoder}\n */\nexport function getLamportsCodec(\n innerCodec: TCodec,\n): Codec & ExtractAdditionalProps {\n return combineCodec(getLamportsEncoder(innerCodec), getLamportsDecoder(innerCodec)) as Codec &\n ExtractAdditionalProps;\n}\n","import { SOLANA_ERROR__MALFORMED_BIGINT_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a `bigint` which has been encoded as a string for transit over a transport\n * that does not support `bigint` values natively. The JSON-RPC is such a transport.\n */\nexport type StringifiedBigInt = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `BigInt`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedBigInt } from '@solana/rpc-types';\n *\n * if (isStringifiedBigInt(bigintString)) {\n * // At this point, `bigintString` has been refined to a `StringifiedBigInt`\n * bigintString satisfies StringifiedBigInt; // OK\n * } else {\n * setError(`${bigintString} does not represent a BigInt`);\n * }\n * ```\n */\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `BigInt`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `BigInt`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedBigInt } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents the supply of some token.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `supplyString` to `StringifiedBigInt`.\n * assertIsStringifiedBigInt(supplyString);\n * // At this point, `supplyString` is a `StringifiedBigInt`.\n * supplyString satisfies StringifiedBigInt;\n * } catch (e) {\n * // `supplyString` turned out not to parse as a `BigInt`\n * }\n * ```\n */\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_BIGINT_STRING, {\n value: putativeBigInt,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `BigInt` with _coercing_ it to the\n * {@link StringifiedBigInt} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedBigInt } from '@solana/rpc-types';\n *\n * const supplyString = stringifiedBigInt('1000000000');\n * ```\n */\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","import { SOLANA_ERROR__MALFORMED_NUMBER_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a number which has been encoded as a string for transit over a transport\n * where loss of precision when using the native number type is a concern. The JSON-RPC is such a\n * transport.\n */\nexport type StringifiedNumber = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `Number`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedNumber } from '@solana/rpc-types';\n *\n * if (isStringifiedNumber(numericString)) {\n * // At this point, `numericString` has been refined to a `StringifiedNumber`\n * numericString satisfies StringifiedNumber; // OK\n * } else {\n * setError(`${numericString} does not represent a number`);\n * }\n * ```\n */\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `Number`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `Number`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedNumber } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents some decimal number.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `decimalNumberString` to `StringifiedNumber`.\n * assertIsStringifiedNumber(decimalNumberString);\n * // At this point, `decimalNumberString` is a `StringifiedNumber`.\n * decimalNumberString satisfies StringifiedNumber;\n * } catch (e) {\n * // `decimalNumberString` turned out not to parse as a number.\n * }\n * ```\n */\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_NUMBER_STRING, {\n value: putativeNumber,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `Number` with _coercing_ it to the\n * {@link StringifiedNumber} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedNumber } from '@solana/rpc-types';\n *\n * const decimalNumberString = stringifiedNumber('-42.1');\n * ```\n */\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","import { SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a Unix timestamp in _seconds_.\n *\n * It is represented as a `bigint` in client code and an `i64` in server code.\n */\nexport type UnixTimestamp = Brand;\n\n// Largest possible value to be represented by an i64\nconst maxI64Value = 9223372036854775807n; // 2n ** 63n - 1n\nconst minI64Value = -9223372036854775808n; // -(2n ** 63n)\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link UnixTimestamp} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isUnixTimestamp } from '@solana/rpc-types';\n *\n * if (isUnixTimestamp(timestamp)) {\n * // At this point, `timestamp` has been refined to a\n * // `UnixTimestamp` that can be used anywhere timestamps are expected.\n * timestamp satisfies UnixTimestamp;\n * } else {\n * setError(`${timestamp} is not a Unix timestamp`);\n * }\n * ```\n */\n\nexport function isUnixTimestamp(putativeTimestamp: bigint): putativeTimestamp is UnixTimestamp {\n return putativeTimestamp >= minI64Value && putativeTimestamp <= maxI64Value;\n}\n\n/**\n * Timestamp values returned from the RPC API conform to the type {@link UnixTimestamp}. You can use\n * a value of that type wherever a timestamp is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a timestamp, from an untrusted\n * network API or user input. To assert that such an arbitrary number is usable as a Unix timestamp,\n * use this function.\n *\n * ```ts\n * import { assertIsUnixTimestamp } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents a timestamp.\n * // At this point we know only that it conforms to the `bigint` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `timestamp` to `UnixTimestamp`.\n * assertIsUnixTimestamp(timestamp);\n * // At this point, `timestamp` is a `UnixTimestamp`.\n * timestamp satisfies UnixTimestamp;\n * } catch (e) {\n * // `timestamp` turned out not to be a valid Unix timestamp\n * }\n * ```\n */\nexport function assertIsUnixTimestamp(putativeTimestamp: bigint): asserts putativeTimestamp is UnixTimestamp {\n if (putativeTimestamp < minI64Value || putativeTimestamp > maxI64Value) {\n throw new SolanaError(SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, {\n value: putativeTimestamp,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a `bigint` represents a Unix timestamp with _coercing_ it\n * to the {@link UnixTimestamp} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { unixTimestamp } from '@solana/rpc-types';\n *\n * const timestamp = unixTimestamp(-42n); // Wednesday, December 31, 1969 3:59:18 PM GMT-08:00\n * ```\n */\nexport function unixTimestamp(putativeTimestamp: bigint): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SolanaError } from '@solana/errors';\nimport { type Blockhash, isBlockhash } from '@solana/rpc-types';\n\nimport { ExcludeTransactionMessageLifetime, TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network. The transaction message will continue to be eligible to land\n * until the network considers the `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type BlockhashLifetimeConstraint = Readonly<{\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction message will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction message eligible to land.\n */\n lastValidBlockHeight: bigint;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the age of the blockhash it\n * includes.\n *\n * Such a transaction can only be landed on the network if the current block height of the network\n * is less than or equal to the value of\n * `TransactionMessageWithBlockhashLifetime['lifetimeConstraint']['lastValidBlockHeight']`.\n */\nexport interface TransactionMessageWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * if (isTransactionMessageWithBlockhashLifetime(message)) {\n * // At this point, `message` has been refined to a `TransactionMessageWithBlockhashLifetime`.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.blockhash === 'string' &&\n typeof transactionMessage.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transactionMessage.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * blockhash-based lifetime, from an untrusted network API or user input. Use this function to\n * assert that such a transaction message actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithBlockhashLifetime`.\n * assertIsTransactionMessageWithBlockhashLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `message` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n if (!isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * Given a blockhash and the last block height at which that blockhash is considered usable to land\n * transactions, this method will return a new transaction message having the same type as the one\n * supplied plus the `TransactionMessageWithBlockhashLifetime` type.\n *\n * @example\n * ```ts\n * import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages';\n *\n * const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n * const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, txMessage);\n * ```\n */\nexport function setTransactionMessageLifetimeUsingBlockhash<\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime {\n type ReturnType = ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime;\n\n if (\n 'lifetimeConstraint' in transactionMessage &&\n transactionMessage.lifetimeConstraint &&\n 'blockhash' in transactionMessage.lifetimeConstraint &&\n transactionMessage.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transactionMessage.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transactionMessage as ReturnType;\n }\n\n return Object.freeze({\n ...transactionMessage,\n lifetimeConstraint: Object.freeze(blockhashLifetimeConstraint),\n }) as ReturnType;\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n type Encoder,\n type VariableSizeCodec,\n type VariableSizeDecoder,\n type VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\n\ntype AddressTableLookup = ReturnType[number];\n\nlet memoizedAddressTableLookupEncoder: VariableSizeEncoder | undefined;\nexport function getAddressTableLookupEncoder(): VariableSizeEncoder {\n if (!memoizedAddressTableLookupEncoder) {\n const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<\n readonly number[]\n >;\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder {\n if (!memoizedAddressTableLookupDecoder) {\n const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): VariableSizeCodec {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile/header';\n\ntype MessageHeader = ReturnType;\n\nlet memoizedU8Encoder: FixedSizeEncoder | undefined;\nfunction getMemoizedU8Encoder(): FixedSizeEncoder {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nlet memoizedU8Decoder: FixedSizeDecoder | undefined;\nfunction getMemoizedU8Decoder(): FixedSizeDecoder {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nlet memoizedU8Codec: FixedSizeCodec | undefined;\nfunction getMemoizedU8Codec(): FixedSizeCodec {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nexport function getMessageHeaderEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['numSignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Encoder()],\n ]) as FixedSizeEncoder;\n}\n\nexport function getMessageHeaderDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['numSignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Decoder()],\n ]) as FixedSizeDecoder;\n}\n\nexport function getMessageHeaderCodec(): FixedSizeCodec {\n return getStructCodec([\n ['numSignerAccounts', getMemoizedU8Codec()],\n ['numReadonlySignerAccounts', getMemoizedU8Codec()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Codec()],\n ]) as FixedSizeCodec;\n}\n","import {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile/instructions';\n\ntype Instruction = ReturnType[number];\n\nlet memoizedGetInstructionEncoder: VariableSizeEncoder | undefined;\nexport function getInstructionEncoder(): VariableSizeEncoder {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = transformEncoder, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', addEncoderSizePrefix(getBytesEncoder(), getShortU16Encoder())],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required;\n },\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: VariableSizeDecoder | undefined;\nexport function getInstructionDecoder(): VariableSizeDecoder {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = transformDecoder, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\n 'data',\n addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder()) as VariableSizeDecoder,\n ],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n },\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): VariableSizeCodec {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { AccountMeta, Instruction } from '@solana/instructions';\n\n/**\n * @deprecated Use `TransactionMessage` instead.\n */\n// TODO(#1147) Stop exporting this in a future major version.\nexport type BaseTransactionMessage<\n TVersion extends TransactionVersion = TransactionVersion,\n TInstruction extends Instruction = Instruction,\n> = Readonly<{\n instructions: readonly TInstruction[];\n version: TVersion;\n}>;\n\nexport const MAX_SUPPORTED_TRANSACTION_VERSION = 0;\n\ntype LegacyInstruction = Instruction;\ntype LegacyTransactionMessage = BaseTransactionMessage<'legacy', LegacyInstruction>;\ntype V0TransactionMessage = BaseTransactionMessage<0, Instruction>;\n\nexport type TransactionMessage = LegacyTransactionMessage | V0TransactionMessage;\nexport type TransactionVersion = 'legacy' | 0;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { MAX_SUPPORTED_TRANSACTION_VERSION, TransactionVersion } from '../transaction-message';\n\nconst VERSION_FLAG_MASK = 0x80;\n\n/**\n * Returns an encoder that you can use to encode a {@link TransactionVersion} to a byte array.\n *\n * Legacy messages will produce an empty array and will not advance the offset. Versioned messages\n * will produce an array with a single byte.\n */\nexport function getTransactionVersionEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => (value === 'legacy' ? 0 : 1),\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === 'legacy') {\n return offset;\n }\n if (value < 0 || value > 127) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {\n actualVersion: value,\n });\n }\n\n if (value > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: value,\n });\n }\n bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link TransactionVersion}.\n *\n * When the byte at the current offset is determined to represent a legacy transaction, this decoder\n * will return `'legacy'` and will not advance the offset.\n */\nexport function getTransactionVersionDecoder(): VariableSizeDecoder {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n if (version > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n return [version as TransactionVersion, offset + 1];\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link TransactionVersion}\n *\n * @see {@link getTransactionVersionDecoder}\n * @see {@link getTransactionVersionEncoder}\n */\nexport function getTransactionVersionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n createEncoder,\n Decoder,\n fixDecoderSize,\n fixEncoderSize,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getConstantEncoder,\n getStructDecoder,\n getStructEncoder,\n getUnionEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from '../compile/message';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nfunction getCompiledMessageLegacyEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return getStructEncoder(getPreludeStructEncoderTuple()) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >;\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return transformEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ]) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >,\n value => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n };\n },\n );\n}\n\nfunction getPreludeStructEncoderTuple() {\n const lifetimeTokenEncoder = getUnionEncoder(\n [\n // Use a 32-byte constant encoder for a missing lifetime token (index 0).\n getConstantEncoder(new Uint8Array(32)),\n // Use a 32-byte base58 encoder for a valid lifetime token (index 1).\n fixEncoderSize(getBase58Encoder(), 32),\n ],\n value => (value === undefined ? 0 : 1),\n );\n\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', lifetimeTokenEncoder],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\n ] as const;\n}\n\nfunction getPreludeStructDecoderTuple() {\n return [\n ['version', getTransactionVersionDecoder() as Decoder],\n ['header', getMessageHeaderDecoder()],\n ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', fixDecoderSize(getBase58Decoder(), 32)],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ] as const;\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link CompiledTransactionMessage} to a byte\n * array.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. The byte array produced by this encoder is the message part.\n */\nexport function getCompiledTransactionMessageEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return createEncoder({\n getSizeFromValue: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link CompiledTransactionMessage}.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. You can use this decoder to decode the message part.\n */\nexport function getCompiledTransactionMessageDecoder(): VariableSizeDecoder<\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return transformDecoder(\n getStructDecoder(getPreludeStructDecoderTuple()) as VariableSizeDecoder<\n CompiledTransactionMessage &\n CompiledTransactionMessageWithLifetime & {\n addressTableLookups?: ReturnType;\n }\n >,\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups };\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link CompiledTransactionMessage}\n *\n * @see {@link getCompiledTransactionMessageDecoder}\n * @see {@link getCompiledTransactionMessageEncoder}\n */\nexport function getCompiledTransactionMessageCodec(): VariableSizeCodec<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime),\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return combineCodec(getCompiledTransactionMessageEncoder(), getCompiledTransactionMessageDecoder());\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SolanaError,\n} from '@solana/errors';\nimport {\n AccountLookupMeta,\n AccountMeta,\n AccountRole,\n Instruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = Brand<(AccountLookupMeta | AccountMeta)[], 'OrderedAccounts'>;\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | Record | StaticAccountEntry,\n ) => AddressMap[Address],\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(feePayer: Address, instructions: readonly Instruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set
();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {\n programAddress: instruction.programAddress,\n });\n default:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {\n programAddress: instruction.programAddress,\n });\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress,\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n {\n programAddress: account.address,\n },\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType;\n const orderedAccounts: (AccountLookupMeta | AccountMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Address,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype AddressTableLookup = Readonly<{\n /** The address of the address lookup table account. */\n lookupTableAddress: Address;\n /** Indexes of accounts in a lookup table to load as read-only. */\n readonlyIndexes: readonly number[];\n /** Indexes of accounts in a lookup table to load as writable. */\n writableIndexes: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Address,\n Readonly<{\n [K in keyof Omit]: number[];\n }>\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readonlyIndexes: [],\n writableIndexes: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndexes.push(account.addressIndex);\n } else {\n entry.readonlyIndexes.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype MessageHeader = Readonly<{\n /**\n * The number of accounts in the static accounts list that are neither writable nor\n * signers.\n *\n * Adding this number to `numSignerAccounts` yields the index of the first read-only non-signer\n * account in the static accounts list.\n */\n numReadonlyNonSignerAccounts: number;\n /**\n * The number of read-only accounts in the static accounts list that must sign this\n * transaction.\n *\n * Subtracting this number from `numSignerAccounts` yields the index of the first read-only\n * signer account in the static accounts list.\n */\n numReadonlySignerAccounts: number;\n /**\n * The number of accounts in the static accounts list that must sign this transaction.\n *\n * Subtracting `numReadonlySignerAccounts` from this number yields the number of\n * writable signer accounts in the static accounts list. Writable signer accounts always\n * begin at index zero in the static accounts list.\n *\n * This number itself is the index of the first non-signer account in the static\n * accounts list.\n */\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { Instruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n /**\n * An ordered list of indices that indicate which accounts in the transaction message's\n * accounts list are loaded by this instruction.\n */\n accountIndices?: number[];\n /** The input to the invoked program */\n data?: ReadonlyUint8Array;\n /**\n * The index of the address in the transaction message's accounts list associated with the\n * program to invoke.\n */\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly Instruction[],\n orderedAccounts: OrderedAccounts,\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { TransactionMessageWithBlockhashLifetime, TransactionMessageWithDurableNonceLifetime } from '../index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (\n | TransactionMessageWithBlockhashLifetime\n | TransactionMessageWithDurableNonceLifetime\n )['lifetimeConstraint'],\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { TransactionMessageWithFeePayer } from '../fee-payer';\nimport { TransactionMessageWithLifetime } from '../lifetime';\nimport { BaseTransactionMessage } from '../transaction-message';\nimport { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { getCompiledAddressTableLookups } from './address-table-lookups';\nimport { getCompiledMessageHeader } from './header';\nimport { getCompiledInstructions } from './instructions';\nimport { getCompiledLifetimeToken } from './lifetime-token';\nimport { getCompiledStaticAccounts } from './static-accounts';\n\ntype BaseCompiledTransactionMessage = Readonly<{\n /**\n * Information about the version of the transaction message and the role of the accounts it\n * loads.\n */\n header: ReturnType;\n instructions: ReturnType;\n /** A list of addresses indicating which accounts to load */\n staticAccounts: ReturnType;\n}>;\n\n/**\n * A transaction message in a form suitable for encoding for execution on the network.\n *\n * You can not fully reconstruct a source message from a compiled message without extra information.\n * In particular, supporting details about the lifetime constraint and the concrete addresses of\n * accounts sourced from account lookup tables are lost to compilation.\n */\nexport type CompiledTransactionMessage = LegacyCompiledTransactionMessage | VersionedCompiledTransactionMessage;\n\nexport type CompiledTransactionMessageWithLifetime = Readonly<{\n /**\n * 32 bytes of data observed by the transaction proposed that makes a transaction eligible to\n * land on the network.\n *\n * In the case of a transaction message with a nonce lifetime constraint, this will be the value\n * of the nonce itself. In all other cases this will be a recent blockhash.\n */\n lifetimeToken: ReturnType;\n}>;\n\ntype LegacyCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n /** A list of address tables and the accounts that this transaction loads from them */\n addressTableLookups?: ReturnType;\n version: 0;\n }>;\n\n/**\n * Converts the type of transaction message data structure that you create in your application to\n * the type of transaction message data structure that can be encoded for execution on the network.\n *\n * This is a lossy process; you can not fully reconstruct a source message from a compiled message\n * without extra information. In particular, supporting details about the lifetime constraint and\n * the concrete addresses of accounts sourced from account lookup tables will be lost to\n * compilation.\n *\n * @see {@link decompileTransactionMessage}\n */\nexport function compileTransactionMessage<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): CompiledTransactionMessageFromTransactionMessage {\n type ReturnType = CompiledTransactionMessageFromTransactionMessage;\n\n const addressMap = getAddressMapFromInstructions(\n transactionMessage.feePayer.address,\n transactionMessage.instructions,\n );\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n const lifetimeConstraint = (transactionMessage as Partial).lifetimeConstraint;\n\n return {\n ...(transactionMessage.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n ...(lifetimeConstraint ? { lifetimeToken: getCompiledLifetimeToken(lifetimeConstraint) } : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transactionMessage.instructions, orderedAccounts),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transactionMessage.version,\n } as ReturnType;\n}\n\ntype CompiledTransactionMessageFromTransactionMessage =\n ForwardTransactionMessageLifetime, TTransactionMessage>;\n\ntype ForwardTransactionMessageVersion =\n TTransactionMessage extends Readonly<{ version: 'legacy' }>\n ? LegacyCompiledTransactionMessage\n : VersionedCompiledTransactionMessage;\n\ntype ForwardTransactionMessageLifetime<\n TCompiledTransactionMessage extends CompiledTransactionMessage,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithLifetime\n ? CompiledTransactionMessageWithLifetime & TCompiledTransactionMessage\n : TCompiledTransactionMessage;\n","import { Address } from '@solana/addresses';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction, isSignerRole } from '@solana/instructions';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BaseTransactionMessage, TransactionMessage } from './transaction-message';\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n// Look up the address in lookup tables, return a lookup meta if it is found in any of them\nfunction findAddressInLookupTables(\n address: Address,\n role: AccountRole.READONLY | AccountRole.WRITABLE,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta | undefined {\n for (const [lookupTableAddress, addresses] of Object.entries(addressesByLookupTableAddress)) {\n for (let i = 0; i < addresses.length; i++) {\n if (address === addresses[i]) {\n return {\n address,\n addressIndex: i,\n lookupTableAddress: lookupTableAddress as Address,\n role,\n };\n }\n }\n }\n}\n\ntype TransactionMessageNotLegacy = Exclude;\n\n// Each account can be AccountLookupMeta | AccountMeta\ntype WidenInstructionAccounts =\n TInstruction extends Instruction\n ? Instruction<\n TProgramAddress,\n {\n [K in keyof TAccounts]: TAccounts[K] extends AccountMeta\n ? AccountLookupMeta | AccountMeta\n : TAccounts[K];\n }\n >\n : TInstruction;\n\ntype ExtractAdditionalProps = Omit;\n\ntype WidenTransactionMessageInstructions =\n TTransactionMessage extends BaseTransactionMessage\n ? BaseTransactionMessage> &\n ExtractAdditionalProps<\n TTransactionMessage,\n BaseTransactionMessage>\n >\n : TTransactionMessage;\n\n/**\n * Given a transaction message and a mapping of lookup tables to the addresses stored in them, this\n * function will return a new transaction message with the same instructions but with all non-signer\n * accounts that are found in the given lookup tables represented by an {@link AccountLookupMeta}\n * instead of an {@link AccountMeta}.\n *\n * This means that these accounts will take up less space in the compiled transaction message. This\n * size reduction is most significant when the transaction includes many accounts from the same\n * lookup table.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import {\n * AddressesByLookupTableAddress,\n * compressTransactionMessageUsingAddressLookupTables,\n * } from '@solana/transaction-messages';\n * import { fetchAddressLookupTable } from '@solana-program/address-lookup-table';\n *\n * const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW');\n * const {\n * data: { addresses },\n * } = await fetchAddressLookupTable(rpc, lookupTableAddress);\n * const addressesByAddressLookupTable: AddressesByLookupTableAddress = {\n * [lookupTableAddress]: addresses,\n * };\n *\n * const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables(\n * transactionMessage,\n * addressesByAddressLookupTable,\n * );\n * ```\n */\nexport function compressTransactionMessageUsingAddressLookupTables<\n TTransactionMessage extends TransactionMessageNotLegacy = TransactionMessageNotLegacy,\n>(\n transactionMessage: TTransactionMessage,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): TTransactionMessage | WidenTransactionMessageInstructions {\n const programAddresses = new Set(transactionMessage.instructions.map(ix => ix.programAddress));\n const eligibleLookupAddresses = new Set(\n Object.values(addressesByLookupTableAddress)\n .flatMap(a => a)\n .filter(address => !programAddresses.has(address)),\n );\n const newInstructions: Instruction[] = [];\n let updatedAnyInstructions = false;\n for (const instruction of transactionMessage.instructions) {\n if (!instruction.accounts) {\n newInstructions.push(instruction);\n continue;\n }\n\n const newAccounts: Mutable> = [];\n let updatedAnyAccounts = false;\n for (const account of instruction.accounts) {\n // If the address is already a lookup, is not in any lookup tables, or is a signer role, return as-is\n if (\n 'lookupTableAddress' in account ||\n !eligibleLookupAddresses.has(account.address) ||\n isSignerRole(account.role)\n ) {\n newAccounts.push(account);\n continue;\n }\n\n // We already checked it's in one of the lookup tables\n const lookupMetaAccount = findAddressInLookupTables(\n account.address,\n account.role,\n addressesByLookupTableAddress,\n )!;\n newAccounts.push(Object.freeze(lookupMetaAccount));\n updatedAnyAccounts = true;\n updatedAnyInstructions = true;\n }\n\n newInstructions.push(\n Object.freeze(updatedAnyAccounts ? { ...instruction, accounts: newAccounts } : instruction),\n );\n }\n\n return Object.freeze(\n updatedAnyInstructions ? { ...transactionMessage, instructions: newInstructions } : transactionMessage,\n );\n}\n","import { TransactionMessage, TransactionVersion } from './transaction-message';\nimport { TransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype TransactionConfig = Readonly<{\n version: TVersion;\n}>;\n\ntype EmptyTransactionMessage = Omit<\n Extract,\n 'instructions'\n> &\n TransactionMessageWithinSizeLimit & { instructions: readonly [] };\n\n/**\n * Given a {@link TransactionVersion} this method will return an empty transaction having the\n * capabilities of that version.\n *\n * @example\n * ```ts\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const message = createTransactionMessage({ version: 0 });\n * ```\n */\nexport function createTransactionMessage(\n config: TransactionConfig,\n): EmptyTransactionMessage {\n return Object.freeze({\n instructions: Object.freeze([]),\n version: config.version,\n }) as EmptyTransactionMessage;\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n AccountRole,\n Instruction,\n InstructionWithAccounts,\n InstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport type AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n> = Instruction<'11111111111111111111111111111111'> &\n InstructionWithAccounts<\n readonly [\n WritableAccount,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount | WritableSignerAccount,\n ]\n > &\n InstructionWithData;\n\ntype AdvanceNonceAccountInstructionData = Brand;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\n/**\n * Creates an instruction for the System program to advance a nonce.\n *\n * This instruction is a prerequisite for a transaction with a nonce-based lifetime to be landed on\n * the network. In order to be considered valid, the transaction must meet all of these criteria.\n *\n * 1. Its lifetime constraint must be a {@link NonceLifetimeConstraint}.\n * 2. The value contained in the on-chain account at the address `nonceAccountAddress` must be equal\n * to {@link NonceLifetimeConstraint.nonce} at the time the transaction is landed.\n * 3. The first instruction in that transaction message must be the one returned by this function.\n *\n * You could also use the `getAdvanceNonceAccountInstruction` method of `@solana-program/system`.\n */\nexport function createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n>(\n nonceAccountAddress: Address,\n nonceAuthorityAddress: Address,\n): AdvanceNonceAccountInstruction {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\n/**\n * A type guard that returns `true` if the instruction conforms to the\n * {@link AdvanceNonceAccountInstruction} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAdvanceNonceAccountInstruction } from '@solana/transaction-messages';\n *\n * if (isAdvanceNonceAccountInstruction(message.instructions[0])) {\n * // At this point, the first instruction in the message has been refined to a\n * // `AdvanceNonceAccountInstruction`.\n * setNonceAccountAddress(message.instructions[0].accounts[0].address);\n * } else {\n * setError('The first instruction is not an `AdvanceNonce` instruction');\n * }\n * ```\n */\nexport function isAdvanceNonceAccountInstruction(\n instruction: Instruction,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SolanaError } from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nimport {\n AdvanceNonceAccountInstruction,\n createAdvanceNonceAccountInstruction,\n isAdvanceNonceAccountInstruction,\n} from './durable-nonce-instruction';\nimport { ExcludeTransactionMessageLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = Readonly<{\n readonly nonce: Nonce;\n readonly nonceAccountAddress: Address;\n readonly nonceAuthorityAddress: Address;\n}>;\n\n/** Represents a string that is particularly known to be the base58-encoded value of a nonce. */\nexport type Nonce = Brand;\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network.\n *\n * The transaction message will continue to be eligible to land until the network considers the\n * `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is\n * destroyed, or the nonce value within changes.\n */\nexport type NonceLifetimeConstraint = Readonly<{\n /**\n * A value contained in the related nonce account at the time the transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the value of a nonce it includes.\n *\n * Such a transaction can only be landed on the network if the nonce is known to the network and has\n * not already been used to land a different transaction.\n */\nexport interface TransactionMessageWithDurableNonceLifetime<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n}\n\n/**\n * A helper type to exclude the durable nonce lifetime constraint from a transaction message.\n */\nexport type ExcludeTransactionMessageDurableNonceLifetime =\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? ExcludeTransactionMessageLifetime\n : TTransactionMessage;\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionMessageWithDurableNonceLifetime(message)) {\n * // At this point, `message` has been refined to a\n * // `TransactionMessageWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.nonce === 'string' &&\n transactionMessage.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transactionMessage.instructions[0])\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * nonce-based lifetime, from an untrusted network API or user input. Use this function to assert\n * that such a transaction message actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithDurableNonceLifetime`.\n * assertIsTransactionMessageWithDurableNonceLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `message` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n if (!isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address,\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\n/**\n * Given a nonce, the account where the value of the nonce is stored, and the address of the account\n * authorized to consume that nonce, this method will return a new transaction having the same type\n * as the one supplied plus the {@link TransactionMessageWithDurableNonceLifetime} type.\n *\n * In particular, this method _prepends_ an instruction to the transaction message designed to\n * consume (or 'advance') the nonce in the same transaction whose lifetime is defined by it.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/transaction-messages';\n * import { fetchNonce } from '@solana-program/system';\n *\n * const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ');\n * const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT');\n *\n * const {\n * data: { blockhash },\n * } = await fetchNonce(rpc, nonceAccountAddress);\n * const nonce = blockhash as string as Nonce;\n *\n * const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce(\n * { nonce, nonceAccountAddress, nonceAuthorityAddress },\n * tx,\n * );\n * ```\n */\nexport function setTransactionMessageLifetimeUsingDurableNonce<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig,\n transactionMessage: TTransactionMessage,\n): SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n> {\n type ReturnType = SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n >;\n\n let newInstructions: [\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n\n const firstInstruction = transactionMessage.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (\n isTransactionMessageWithDurableNonceLifetime(transactionMessage) &&\n transactionMessage.lifetimeConstraint.nonce === nonce\n ) {\n return transactionMessage as unknown as ReturnType;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transactionMessage.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions,\n ];\n }\n\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze(newInstructions),\n lifetimeConstraint: Object.freeze({ nonce }),\n }) as unknown as ReturnType;\n}\n\n/**\n * Helper type that transforms a given transaction message type into a new one that has the\n * `AdvanceNonceAccount` instruction as the first instruction and a lifetime constraint\n * representing the nonce value.\n */\ntype SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = TTransactionMessage extends unknown\n ? Omit<\n // 1. The transaction message only grows in size if it currently has a different (or no) lifetime.\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? TTransactionMessage\n : ExcludeTransactionMessageWithinSizeLimit,\n // 2. Remove the instructions array as we are going to replace it with a new one.\n 'instructions'\n > & {\n // 3. Replace or prepend the first instruction with the advance nonce account instruction.\n readonly instructions: TTransactionMessage['instructions'] extends readonly [\n AdvanceNonceAccountInstruction,\n ...infer TTail extends readonly Instruction[],\n ]\n ? readonly [AdvanceNonceAccountInstruction, ...TTail]\n : readonly [\n AdvanceNonceAccountInstruction,\n ...TTransactionMessage['instructions'],\n ];\n // 4. Set the lifetime constraint to the nonce value.\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n }\n : never;\n","import { Address } from '@solana/addresses';\n\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * Represents a transaction message for which a fee payer has been declared. A transaction must\n * conform to this type to be compiled and landed on the network.\n */\nexport interface TransactionMessageWithFeePayer {\n readonly feePayer: Readonly<{ address: Address }>;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Given a base58-encoded address of a system account, this method will return a new transaction\n * message having the same type as the one supplied plus the {@link TransactionMessageWithFeePayer}\n * type.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const myAddress = address('mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu');\n * const txPaidByMe = setTransactionMessageFeePayer(myAddress, tx);\n * ```\n */\nexport function setTransactionMessageFeePayer<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n feePayer: Address,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayer {\n if (\n 'feePayer' in transactionMessage &&\n feePayer === transactionMessage.feePayer?.address &&\n isAddressOnlyFeePayer(transactionMessage.feePayer)\n ) {\n return transactionMessage as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n }\n const out = {\n ...transactionMessage,\n feePayer: Object.freeze({ address: feePayer }),\n };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n}\n\nfunction isAddressOnlyFeePayer(\n feePayer: Partial['feePayer'],\n): feePayer is { address: Address } {\n return (\n !!feePayer &&\n 'address' in feePayer &&\n typeof feePayer.address === 'string' &&\n Object.keys(feePayer).length === 1\n );\n}\n","import { Instruction } from '@solana/instructions';\n\nimport { ExcludeTransactionMessageDurableNonceLifetime } from './durable-nonce';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype AppendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit, 'instructions'> & {\n readonly instructions: readonly [...TTransactionMessage['instructions'], ...TInstructions];\n }\n : never;\n\n/**\n * A helper type to prepend instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype PrependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit<\n ExcludeTransactionMessageWithinSizeLimit>,\n 'instructions'\n > & {\n readonly instructions: readonly [...TInstructions, ...TTransactionMessage['instructions']];\n }\n : never;\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstructions} if you need to append multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { appendTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransactionMessage = appendTransactionMessageInstruction(\n * {\n * data: getUtf8Encoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * transactionMessage,\n * );\n * ```\n */\nexport function appendTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return appendTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstruction} if you only need to append one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { appendTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = appendTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function appendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze([\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ...instructions,\n ] as readonly [...TTransactionMessage['instructions'], ...TInstructions]),\n }) as AppendTransactionMessageInstructions;\n}\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstructions} if you need to prepend multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstruction(\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return prependTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstruction} if you only need to prepend one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return Object.freeze({\n ...(transactionMessage as ExcludeTransactionMessageDurableNonceLifetime),\n instructions: Object.freeze([\n ...instructions,\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ] as readonly [...TInstructions, ...TTransactionMessage['instructions']]),\n }) as unknown as PrependTransactionMessageInstructions;\n}\n","import { Address, assertIsAddress } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\nimport { pipe } from '@solana/functional';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport type { Blockhash } from '@solana/rpc-types';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BlockhashLifetimeConstraint, setTransactionMessageLifetimeUsingBlockhash } from './blockhash';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from './compile';\nimport type { getCompiledAddressTableLookups } from './compile/address-table-lookups';\nimport { createTransactionMessage } from './create-transaction-message';\nimport { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from './durable-nonce';\nimport { isAdvanceNonceAccountInstruction } from './durable-nonce-instruction';\nimport { setTransactionMessageFeePayer, TransactionMessageWithFeePayer } from './fee-payer';\nimport { appendTransactionMessageInstruction } from './instructions';\nimport { TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage, TransactionVersion } from './transaction-message';\n\nfunction getAccountMetas(message: CompiledTransactionMessage): AccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: AccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction getAddressLookupMetas(\n compiledAddressTableLookups: ReturnType,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta[] {\n // check that all message lookups are known\n const compiledAddressTableLookupAddresses = compiledAddressTableLookups.map(l => l.lookupTableAddress);\n const missing = compiledAddressTableLookupAddresses.filter(a => addressesByLookupTableAddress[a] === undefined);\n if (missing.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, {\n lookupTableAddresses: missing,\n });\n }\n\n const readOnlyMetas: AccountLookupMeta[] = [];\n const writableMetas: AccountLookupMeta[] = [];\n\n // we know that for each lookup, knownLookups[lookup.lookupTableAddress] is defined\n for (const lookup of compiledAddressTableLookups) {\n const addresses = addressesByLookupTableAddress[lookup.lookupTableAddress];\n const readonlyIndexes = lookup.readonlyIndexes;\n const writableIndexes = lookup.writableIndexes;\n\n const highestIndex = Math.max(...readonlyIndexes, ...writableIndexes);\n if (highestIndex >= addresses.length) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n {\n highestKnownIndex: addresses.length - 1,\n highestRequestedIndex: highestIndex,\n lookupTableAddress: lookup.lookupTableAddress,\n },\n );\n }\n\n const readOnlyForLookup: AccountLookupMeta[] = readonlyIndexes.map(r => ({\n address: addresses[r],\n addressIndex: r,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.READONLY,\n }));\n readOnlyMetas.push(...readOnlyForLookup);\n\n const writableForLookup: AccountLookupMeta[] = writableIndexes.map(w => ({\n address: addresses[w],\n addressIndex: w,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.WRITABLE,\n }));\n writableMetas.push(...writableForLookup);\n }\n\n return [...writableMetas, ...readOnlyMetas];\n}\n\nfunction convertInstruction(\n instruction: CompiledTransactionMessage['instructions'][0],\n accountMetas: AccountMeta[],\n): Instruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, {\n index: instruction.programAddressIndex,\n });\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return Object.freeze({\n programAddress,\n ...(accounts && accounts.length ? { accounts: Object.freeze(accounts) } : {}),\n ...(data && data.length ? { data } : {}),\n });\n}\n\ntype LifetimeConstraint =\n | BlockhashLifetimeConstraint\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: Instruction,\n lastValidBlockHeight?: bigint,\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts[0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts[2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nexport type DecompileTransactionMessageConfig = {\n /**\n * If the compiled message loads addresses from one or more address lookup tables, you will have\n * to supply a map of those tables to an array of the addresses they contained at the time that\n * the transaction message was constructed.\n *\n * @see {@link decompileTransactionMessageFetchingLookupTables} if you do not already have this.\n */\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n /**\n * If the compiled message has a blockhash-based lifetime constraint, you will have to supply\n * the block height after which that blockhash is no longer valid for use as a lifetime\n * constraint.\n */\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Converts the type of transaction message data structure appropriate for execution on the network\n * to the type of transaction message data structure designed for use in your application.\n *\n * Because compilation is a lossy process, you can not fully reconstruct a source message from a\n * compiled message without extra information. In order to faithfully reconstruct the original\n * source message you will need to supply supporting details about the lifetime constraint and the\n * concrete addresses of any accounts sourced from account lookup tables.\n *\n * @see {@link compileTransactionMessage}\n */\nexport function decompileTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n config?: DecompileTransactionMessageConfig,\n): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime {\n const feePayer = compiledTransactionMessage.staticAccounts[0];\n if (!feePayer) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING);\n }\n\n const accountMetas = getAccountMetas(compiledTransactionMessage);\n const accountLookupMetas =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? getAddressLookupMetas(\n compiledTransactionMessage.addressTableLookups,\n config?.addressesByLookupTableAddress ?? {},\n )\n : [];\n const transactionMetas = [...accountMetas, ...accountLookupMetas];\n\n const instructions: Instruction[] = compiledTransactionMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, transactionMetas),\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledTransactionMessage.lifetimeToken,\n firstInstruction,\n config?.lastValidBlockHeight,\n );\n\n return pipe(\n createTransactionMessage({ version: compiledTransactionMessage.version as TransactionVersion }),\n m => setTransactionMessageFeePayer(feePayer, m),\n m =>\n instructions.reduce(\n (acc, instruction) => appendTransactionMessageInstruction(instruction, acc),\n m as TransactionMessage,\n ),\n m =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionMessageLifetimeUsingBlockhash(lifetimeConstraint, m)\n : setTransactionMessageLifetimeUsingDurableNonce(lifetimeConstraint, m),\n ) as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime;\n}\n","export const ED25519_ALGORITHM_IDENTIFIER =\n // Resist the temptation to convert this to a simple string; As of version 133.0.3, Firefox\n // requires the object form of `AlgorithmIdentifier` and will throw a `DOMException` otherwise.\n Object.freeze({ name: 'Ed25519' });\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\nfunction addPkcs8Header(bytes: ReadonlyUint8Array): ReadonlyUint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 private key for use\n * with other methods in this package that accept\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]));\n * const extractablePrivateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n * ```\n */\nexport async function createPrivateKeyFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const actualLength = bytes.byteLength;\n if (actualLength !== 32) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, {\n actualLength,\n });\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, ED25519_ALGORITHM_IDENTIFIER, extractable, [\n 'sign',\n ]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SolanaError } from '@solana/errors';\n\n/**\n * Given an extractable [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * private key, gets the corresponding public key as a\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey).\n *\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the public\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes, getPublicKeyFromPrivateKey } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n *\n * const publicKey = await getPublicKeyFromPrivateKey(privateKey);\n * const extractablePublicKey = await getPublicKeyFromPrivateKey(privateKey, true);\n * ```\n */\nexport async function getPublicKeyFromPrivateKey(\n privateKey: CryptoKey,\n extractable: boolean = false,\n): Promise {\n assertKeyExporterIsAvailable();\n\n if (privateKey.extractable === false) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, { key: privateKey });\n }\n\n // Export private key.\n const jwk = await crypto.subtle.exportKey('jwk', privateKey);\n\n // Import public key.\n return await crypto.subtle.importKey(\n 'jwk',\n {\n crv /* curve */: 'Ed25519',\n ext /* extractable */: extractable,\n key_ops /* key operations */: ['verify'],\n kty /* key type */: 'OKP' /* octet key pair */,\n x /* public key x-coordinate */: jwk.x,\n },\n 'Ed25519',\n extractable,\n ['verify'],\n );\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder, ReadonlyUint8Array, toArrayBuffer } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\n/**\n * A 64-byte Ed25519 signature as a base58-encoded string.\n */\nexport type Signature = Brand, 'Signature'>;\n/**\n * A 64-byte Ed25519 signature.\n *\n * Whenever you need to verify that a particular signature is, in fact, the one that would have been\n * produced by signing some known bytes using the private key associated with some known public key,\n * use the {@link verifySignature} function in this package.\n */\nexport type SignatureBytes = Brand;\n\nlet base58Encoder: Encoder | undefined;\n\n/**\n * Asserts that an arbitrary string is a base58-encoded Ed25519 signature.\n *\n * Useful when you receive a string from user input or an untrusted network API that you expect to\n * represent an Ed25519 signature (eg. of a transaction).\n *\n * @example\n * ```ts\n * import { assertIsSignature } from '@solana/keys';\n *\n * // Imagine a function that asserts whether a user-supplied signature is valid or not.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const signature: string = signatureInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signature` to `Signature`.\n * assertIsSignature(signature);\n * // At this point, `signature` is a `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * } catch (e) {\n * // `signature` turned out not to be a base58-encoded signature\n * }\n * }\n * ```\n */\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeSignature.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n assertIsSignatureBytes(bytes);\n}\n\n/**\n * Asserts that an arbitrary `ReadonlyUint8Array` is an Ed25519 signature.\n *\n * Useful when you receive a `ReadonlyUint8Array` from an external interface (like the browser wallets' `signMessage` API) that you expect to\n * represent an Ed25519 signature.\n *\n * @example\n * ```ts\n * import { assertIsSignatureBytes } from '@solana/keys';\n *\n * // Imagine a function that verifies a signature.\n * function verifySignature() {\n * // We know only that the input conforms to the `ReadonlyUint8Array` type.\n * const signatureBytes: ReadonlyUint8Array = signatureBytesInput;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signatureBytes` to `SignatureBytes`.\n * assertIsSignatureBytes(signatureBytes);\n * // At this point, `signatureBytes` is a `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } catch (e) {\n * // `signatureBytes` turned out not to be a 64-byte Ed25519 signature\n * }\n * }\n * ```\n */\nexport function assertIsSignatureBytes(\n putativeSignatureBytes: ReadonlyUint8Array,\n): asserts putativeSignatureBytes is SignatureBytes {\n const numBytes = putativeSignatureBytes.byteLength;\n if (numBytes !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * A type guard that accepts a string as input. It will both return `true` if the string conforms to\n * the {@link Signature} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignature } from '@solana/keys';\n *\n * if (isSignature(signature)) {\n * // At this point, `signature` has been refined to a\n * // `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * setSignatureStatus(status);\n * } else {\n * setError(`${signature} is not a transaction signature`);\n * }\n * ```\n */\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n return isSignatureBytes(bytes);\n}\n\n/**\n * A type guard that accepts a `ReadonlyUint8Array` as input. It will both return `true` if the `ReadonlyUint8Array` conforms to\n * the {@link SignatureBytes} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignatureBytes } from '@solana/keys';\n *\n * if (isSignatureBytes(signatureBytes)) {\n * // At this point, `signatureBytes` has been refined to a\n * // `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } else {\n * setError(`${signatureBytes} is not a 64-byte Ed25519 signature`);\n * }\n * ```\n */\nexport function isSignatureBytes(putativeSignatureBytes: ReadonlyUint8Array): putativeSignatureBytes is SignatureBytes {\n return putativeSignatureBytes.byteLength === 64;\n}\n\n/**\n * Given a private [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and a\n * `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a\n * `Uint8Array`.\n *\n * @example\n * ```ts\n * import { signBytes } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * const signature = await signBytes(privateKey, data);\n * ```\n */\nexport async function signBytes(key: CryptoKey, data: ReadonlyUint8Array): Promise {\n assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(data));\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\n/**\n * This helper combines _asserting_ that a string is an Ed25519 signature with _coercing_ it to the\n * {@link Signature} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signature } from '@solana/keys';\n *\n * const signature = signature(userSuppliedSignature);\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * ```\n */\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\n/**\n * This helper combines _asserting_ that a `ReadonlyUint8Array` is an Ed25519 signature with _coercing_ it to the\n * {@link SignatureBytes} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signatureBytes } from '@solana/keys';\n *\n * const signature = signatureBytes(userSuppliedSignatureBytes);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport function signatureBytes(putativeSignatureBytes: ReadonlyUint8Array): SignatureBytes {\n assertIsSignatureBytes(putativeSignatureBytes);\n return putativeSignatureBytes;\n}\n\n/**\n * Given a public [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), some\n * {@link SignatureBytes}, and a `Uint8Array` of data, this method will return `true` if the\n * signature was produced by signing the data using the private key associated with the public key,\n * and `false` otherwise.\n *\n * @example\n * ```ts\n * import { verifySignature } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport async function verifySignature(\n key: CryptoKey,\n signature: SignatureBytes,\n data: ReadonlyUint8Array,\n): Promise {\n assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(signature), toArrayBuffer(data));\n}\n","import { assertKeyGenerationIsAvailable, assertPRNGIsAvailable } from '@solana/assertions';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SolanaError,\n} from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\nimport { createPrivateKeyFromBytes } from './private-key';\nimport { getPublicKeyFromPrivateKey } from './public-key';\nimport { signBytes, verifySignature } from './signatures';\n\n/**\n * Generates an Ed25519 public/private key pair for use with other methods in this package that\n * accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await generateKeyPair();\n * ```\n */\nexport async function generateKeyPair(): Promise {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ ED25519_ALGORITHM_IDENTIFIER, // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify'],\n );\n return keyPair;\n}\n\n/**\n * Given a 64-byte `Uint8Array` secret key, creates an Ed25519 public/private key pair for use with\n * other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 64 bytes, the first 32 of which represent the private key and the last 32 of which\n * represent its associated public key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairFromBytes } from '@solana/keys';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a CryptoKeyPair from the bytes.\n * const { privateKey, publicKey } = await createKeyPairFromBytes(keypairBytes);\n * ```\n */\nexport async function createKeyPairFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n assertPRNGIsAvailable();\n\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), ED25519_ALGORITHM_IDENTIFIER, /* extractable */ true, [\n 'verify',\n ]),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n\n // Verify the key pair\n const randomBytes = new Uint8Array(32);\n crypto.getRandomValues(randomBytes);\n const signedData = await signBytes(privateKey, randomBytes);\n const isValid = await verifySignature(publicKey, signedData, randomBytes);\n if (!isValid) {\n throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);\n }\n\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 public/private key\n * pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await createKeyPairFromPrivateKeyBytes(new Uint8Array([...]));\n * ```\n *\n * This can be useful when you have a private key but not the corresponding public key or when you\n * need to derive key pairs from seeds. For instance, the following code snippet derives a key pair\n * from the hash of a message.\n *\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedKeypair = await createKeyPairFromPrivateKeyBytes(seed);\n * ```\n */\nexport async function createKeyPairFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const privateKeyPromise = createPrivateKeyFromBytes(bytes, extractable);\n\n // Here we need the private key to be extractable in order to export\n // it as a public key. Therefore, if the `extractable` parameter\n // is `false`, we need to create two private keys such that:\n // - The extractable one is used to create the public key and\n // - The non-extractable one is the one we will return.\n const [publicKey, privateKey] = await Promise.all([\n // This nested promise makes things efficient by\n // creating the public key in parallel with the\n // second private key creation, if it is needed.\n (extractable ? privateKeyPromise : createPrivateKeyFromBytes(bytes, true /* extractable */)).then(\n async privateKey => await getPublicKeyFromPrivateKey(privateKey, true /* extractable */),\n ),\n privateKeyPromise,\n ]);\n\n return { privateKey, publicKey };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { SignaturesMap } from '../transaction';\n\nfunction getSignaturesToEncode(signaturesMap: SignaturesMap): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { getAddressDecoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n padRightDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { getTransactionVersionDecoder } from '@solana/transaction-messages';\n\nimport { SignaturesMap, Transaction, TransactionMessageBytes } from '../transaction';\nimport { getSignaturesEncoder } from './signatures-encoder';\n\n/**\n * Returns an encoder that you can use to encode a {@link Transaction} to a byte array in a wire\n * format appropriate for sending to the Solana network for execution.\n */\nexport function getTransactionEncoder(): VariableSizeEncoder {\n return getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['messageBytes', getBytesEncoder()],\n ]);\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana transaction wire format\n * to a {@link Transaction} object.\n *\n * @example\n * ```ts\n * import { getTransactionDecoder } from '@solana/transactions';\n *\n * const transactionDecoder = getTransactionDecoder();\n * const transaction = transactionDecoder.decode(wireTransactionBytes);\n * for (const [address, signature] in Object.entries(transaction.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\n\nexport function getTransactionDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getShortU16Decoder() })],\n ['messageBytes', getBytesDecoder()],\n ]),\n decodePartiallyDecodedTransaction,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a {@link Transaction}\n *\n * @see {@link getTransactionDecoder}\n * @see {@link getTransactionEncoder}\n */\nexport function getTransactionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder());\n}\n\ntype PartiallyDecodedTransaction = {\n messageBytes: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedTransaction(transaction: PartiallyDecodedTransaction): Transaction {\n const { messageBytes, signatures } = transaction;\n\n /*\n Relevant message structure is at the start:\n - transaction version (0 bytes for legacy transactions, 1 byte for versioned transactions)\n - `numRequiredSignatures` (1 byte, we verify this matches the length of signatures)\n - `numReadOnlySignedAccounts` (1 byte, not used here)\n - `numReadOnlyUnsignedAccounts` (1 byte, not used here)\n - static addresses, with signers first. This is an array of addresses, prefixed with a short-u16 length\n */\n\n const signerAddressesDecoder = getTupleDecoder([\n // read transaction version\n getTransactionVersionDecoder(),\n // read first byte of header, `numSignerAccounts`\n // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need\n padRightDecoder(getU8Decoder(), 2),\n // read static addresses\n getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() }),\n ]);\n const [_txVersion, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);\n\n const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);\n\n // signer addresses and signatures must be the same length\n // we encode an all-zero signature when the signature is missing\n if (signerAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, {\n numRequiredSignatures,\n signaturesLength: signatures.length,\n signerAddresses,\n });\n }\n\n // combine the signer addresses + signatures into the signatures map\n const signaturesMap: SignaturesMap = {};\n signerAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return {\n messageBytes: messageBytes as TransactionMessageBytes,\n signatures: Object.freeze(signaturesMap),\n };\n}\n","import { type Address, isAddress } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SolanaError,\n} from '@solana/errors';\nimport { type Blockhash, isBlockhash, type Slot } from '@solana/rpc-types';\nimport type {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n Nonce,\n TransactionMessage,\n TransactionMessageWithBlockhashLifetime,\n TransactionMessageWithDurableNonceLifetime,\n} from '@solana/transaction-messages';\n\nimport type { Transaction } from './transaction';\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network. The transaction will continue to be eligible to land until the network considers the\n * `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type TransactionBlockhashLifetime = {\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction eligible to land.\n */\n lastValidBlockHeight: Slot;\n};\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionDurableNonceLifetime = {\n /**\n * A value contained in the account with address `nonceAccountAddress` at the time the\n * transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n /** The account that contains the `nonce` value */\n nonceAccountAddress: Address;\n};\n\n/**\n * A transaction whose ability to land on the network is determined by some evanescent criteria.\n *\n * This describes a window of time after which a transaction is constructed and before which it will\n * no longer be accepted by the network.\n *\n * No transaction can land on Solana without having a `lifetimeConstraint` set.\n */\nexport type TransactionWithLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime | TransactionDurableNonceLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by the age of a blockhash observed on the network.\n *\n * The transaction will continue to be eligible to land until the network considers the `blockhash`\n * to be expired.\n */\nexport type TransactionWithBlockhashLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by a nonce.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionWithDurableNonceLifetime = {\n readonly lifetimeConstraint: TransactionDurableNonceLifetime;\n};\n\n/**\n * Helper type that sets the lifetime constraint of a transaction to be the same as the\n * lifetime constraint of the provided transaction message.\n *\n * If the transaction message has no explicit lifetime constraint, neither will the transaction.\n */\nexport type SetTransactionLifetimeFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends TransactionMessage,\n> = TTransactionMessage extends { lifetimeConstraint: unknown }\n ? TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithBlockhashLifetime['lifetimeConstraint']\n ? TransactionWithBlockhashLifetime & TTransaction\n : TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithDurableNonceLifetime['lifetimeConstraint']\n ? TransactionWithDurableNonceLifetime & TTransaction\n : TransactionWithLifetime & TTransaction\n : TTransaction;\n\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address;\n\nfunction compiledInstructionIsAdvanceNonceInstruction(\n instruction: CompiledTransactionMessage['instructions'][number],\n staticAddresses: Address[],\n): instruction is typeof instruction & { accountIndices: [number, number, number] } {\n return (\n staticAddresses[instruction.programAddressIndex] === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accountIndices?.length === 3\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): boolean {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\n/**\n * Get the lifetime constraint for a transaction from a compiled transaction message that includes a lifetime token.\n * @param compiledTransactionMessage A compiled transaction message that includes a lifetime token\n * @returns A lifetime constraint for the transaction\n * Note that this is less precise than checking a decompiled instruction, as we can't inspect\n * the address or role of input accounts (which may be in lookup tables). However, this is\n * sufficient for all valid advance durable nonce instructions.\n * Note that the program address must not be in a lookup table, see [this answer on StackExchange](https://solana.stackexchange.com/a/16224/289)\n * @see {@link isAdvanceNonceAccountInstruction}\n * Note that this function is async to allow for future implementations that may fetch `lastValidBlockHeight` using an RPC\n */\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function getTransactionLifetimeConstraintFromCompiledTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n): Promise {\n const firstInstruction = compiledTransactionMessage.instructions[0];\n const { staticAccounts } = compiledTransactionMessage;\n\n // We need to check if the first instruction is an AdvanceNonceAccount instruction\n if (firstInstruction && compiledInstructionIsAdvanceNonceInstruction(firstInstruction, staticAccounts)) {\n const nonceAccountAddress = staticAccounts[firstInstruction.accountIndices[0]];\n if (!nonceAccountAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, {\n nonce: compiledTransactionMessage.lifetimeToken,\n });\n }\n return {\n nonce: compiledTransactionMessage.lifetimeToken as Nonce,\n nonceAccountAddress,\n };\n } else {\n return {\n blockhash: compiledTransactionMessage.lifetimeToken as Blockhash,\n // This is not known from the compiled message, so we set it to the maximum possible value\n lastValidBlockHeight: 0xffffffffffffffffn,\n };\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * if (isTransactionWithBlockhashLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a `TransactionWithBlockhashLifetime`.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'blockhash' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.blockhash === 'string' &&\n typeof transaction.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transaction.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * blockhash-based lifetime, from for example a wallet. Use this function to\n * assert that such a transaction actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithBlockhashLifetime`.\n * assertIsTransactionWithBlockhashLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `transaction` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithBlockhashLifetime {\n if (!isTransactionWithBlockhashLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithDurableNonceLifetime } from '@solana/transactions';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionWithDurableNonceLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a\n * // `TransactionWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'nonce' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n typeof transaction.lifetimeConstraint.nonceAccountAddress === 'string' &&\n isAddress(transaction.lifetimeConstraint.nonceAccountAddress)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * nonce-based lifetime, from for example a wallet. Use this function to assert\n * that such a transaction actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithDurableNonceLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithDurableNonceLifetime`.\n * assertIsTransactionWithDurableNonceLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `transaction` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithDurableNonceLifetime {\n if (!isTransactionWithDurableNonceLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n","import {\n compileTransactionMessage,\n getCompiledTransactionMessageEncoder,\n isTransactionMessageWithBlockhashLifetime,\n isTransactionMessageWithDurableNonceLifetime,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport type { TransactionWithLifetime } from './lifetime';\nimport type { SignaturesMap, TransactionFromTransactionMessage, TransactionMessageBytes } from './transaction';\n\n/**\n * Returns a {@link Transaction} object for a given {@link TransactionMessage}.\n *\n * This includes the compiled bytes of the transaction message, and a map of signatures. This map\n * will have a key for each address that is required to sign the transaction. The transaction will\n * not yet have signatures for any of these addresses.\n *\n * Whether a transaction message is ready to be compiled or not is enforced for you at the type\n * level. In order to be signable, a transaction message must:\n *\n * - have a version and a list of zero or more instructions (ie. conform to\n * {@link TransactionMessage})\n * - have a fee payer set (ie. conform to {@link TransactionMessageWithFeePayer})\n * - have a lifetime specified (ie. conform to {@link TransactionMessageWithBlockhashLifetime} or\n * {@link TransactionMessageWithDurableNonceLifetime})\n */\nexport function compileTransaction(\n transactionMessage: TTransactionMessage,\n): Readonly> {\n type ReturnType = Readonly>;\n\n const compiledMessage = compileTransactionMessage(transactionMessage);\n const messageBytes = getCompiledTransactionMessageEncoder().encode(compiledMessage) as TransactionMessageBytes;\n\n const transactionSigners = compiledMessage.staticAccounts.slice(0, compiledMessage.header.numSignerAccounts);\n const signatures: SignaturesMap = {};\n for (const signerAddress of transactionSigners) {\n signatures[signerAddress] = null;\n }\n\n let lifetimeConstraint: TransactionWithLifetime['lifetimeConstraint'] | undefined;\n if (isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n lifetimeConstraint = {\n blockhash: transactionMessage.lifetimeConstraint.blockhash,\n lastValidBlockHeight: transactionMessage.lifetimeConstraint.lastValidBlockHeight,\n };\n } else if (isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n lifetimeConstraint = {\n nonce: transactionMessage.lifetimeConstraint.nonce,\n nonceAccountAddress: transactionMessage.instructions[0].accounts[0].address,\n };\n }\n\n return Object.freeze({\n ...(lifetimeConstraint ? { lifetimeConstraint } : undefined),\n messageBytes: messageBytes,\n signatures: Object.freeze(signatures),\n }) as ReturnType;\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { bytesEqual, Decoder } from '@solana/codecs-core';\nimport { getBase58Decoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Signature, SignatureBytes, signBytes } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { Transaction } from './transaction';\n\n/**\n * Represents a transaction that is signed by all of its required signers. Being fully signed is a\n * prerequisite of functions designed to land transactions on the network.\n */\nexport type FullySignedTransaction = NominalType<'transactionSignedness', 'fullySigned'>;\n\nlet base58Decoder: Decoder | undefined;\n\n/**\n * Given a transaction signed by its fee payer, this method will return the {@link Signature} that\n * uniquely identifies it. This string can be used to look up transactions at a later date, for\n * example on a Solana block explorer.\n *\n * @example\n * ```ts\n * import { getSignatureFromTransaction } from '@solana/transactions';\n *\n * const signature = getSignatureFromTransaction(tx);\n * console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`);\n * ```\n */\nexport function getSignatureFromTransaction(transaction: Transaction): Signature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n // We have ordered signatures from the compiled message accounts\n // first signature is the fee payer\n const signatureBytes = Object.values(transaction.signatures)[0];\n if (!signatureBytes) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);\n }\n const transactionSignature = base58Decoder.decode(signatureBytes);\n return transactionSignature as Signature;\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link Transaction}.\n *\n * Though the resulting transaction might have every signature it needs to land on the network, this\n * function will not assert that it does. A partially signed transaction cannot be landed on the\n * network, but can be serialized and deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignTransaction } from '@solana/transactions';\n *\n * const partiallySignedTransaction = await partiallySignTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link signTransaction} if you want to assert that the transaction has all of its required\n * signatures after signing.\n */\nexport async function partiallySignTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const existingSignature = transaction.signatures[address];\n\n // Check if the address is expected to sign the transaction\n if (existingSignature === undefined) {\n // address is not an expected signer for this transaction\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);\n\n if (existingSignature !== null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n const expectedSigners = Object.keys(transaction.signatures);\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {\n expectedAddresses: expectedSigners,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return transaction;\n }\n\n return Object.freeze({\n ...transaction,\n signatures: Object.freeze({\n ...transaction.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link FullySignedTransaction}.\n *\n * This function will throw unless the resulting transaction is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signTransaction } from '@solana/transactions';\n *\n * const signedTransaction = await signTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link partiallySignTransaction} if you want to sign the transaction without asserting that\n * the resulting transaction is fully signed.\n */\nexport async function signTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertIsFullySignedTransaction(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * Checks whether a given {@link Transaction} is fully signed.\n *\n * @example\n * ```ts\n * import { isFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isFullySignedTransaction(transaction)) {\n * // At this point we know that the transaction is signed and can be sent to the network.\n * }\n * ```\n */\nexport function isFullySignedTransaction(\n transaction: TTransaction,\n): transaction is FullySignedTransaction & TTransaction {\n return Object.entries(transaction.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link Transaction}, that you expect to be fully signed,\n * from an untrusted network API or user input. Use this function to assert that such a transaction\n * is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `FullySignedTransaction`.\n * assertIsFullySignedTransaction(transaction);\n * // At this point we know that the transaction is signed and can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsFullySignedTransaction(\n transaction: TTransaction,\n): asserts transaction is FullySignedTransaction & TTransaction {\n const missingSigs: Address[] = [];\n Object.entries(transaction.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n","import { getBase64Decoder } from '@solana/codecs-strings';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/** Represents the wire format of a transaction as a base64-encoded string. */\nexport type Base64EncodedWireTransaction = Brand, 'Base64EncodedWireTransaction'>;\n\n/**\n * Given a signed transaction, this method returns the transaction as a string that conforms to the\n * {@link Base64EncodedWireTransaction} type.\n *\n * @example\n * ```ts\n * import { getBase64EncodedWireTransaction, signTransaction } from '@solana/transactions';\n *\n * const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send();\n * ```\n */\nexport function getBase64EncodedWireTransaction(transaction: Transaction): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes) as Base64EncodedWireTransaction;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type { NominalType } from '@solana/nominal-types';\nimport type { BaseTransactionMessage, TransactionMessageWithinSizeLimit } from '@solana/transaction-messages';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/**\n * The maximum size of a transaction packet in bytes.\n */\nexport const TRANSACTION_PACKET_SIZE = 1280;\n\n/**\n * The size of the transaction packet header in bytes.\n * This includes the IPv6 header and the fragment header.\n */\nexport const TRANSACTION_PACKET_HEADER =\n 40 /* 40 bytes is the size of the IPv6 header. */ + 8; /* 8 bytes is the size of the fragment header. */\n\n/**\n * The maximum size of a transaction in bytes.\n *\n * Note that this excludes the transaction packet header.\n * In other words, this is how much content we can fit in a transaction packet.\n */\nexport const TRANSACTION_SIZE_LIMIT = TRANSACTION_PACKET_SIZE - TRANSACTION_PACKET_HEADER;\n\n/**\n * Gets the size of a given transaction in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionSize(transaction);\n * ```\n */\nexport function getTransactionSize(transaction: Transaction): number {\n return getTransactionEncoder().getSizeFromValue(transaction);\n}\n\n/**\n * A type guard that checks if a transaction is within the size limit.\n */\nexport type TransactionWithinSizeLimit = NominalType<'transactionSize', 'withinLimit'>;\n\n/**\n * Helper type that adds the `TransactionWithinSizeLimit` flag to\n * a transaction if and only if the provided transaction message\n * is also within the size limit.\n */\nexport type SetTransactionWithinSizeLimitFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithinSizeLimit\n ? TransactionWithinSizeLimit & TTransaction\n : TTransaction;\n\n/**\n * Checks if a transaction is within the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * if (isTransactionWithinSizeLimit(transaction)) {\n * transaction satisfies TransactionWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionWithinSizeLimit(\n transaction: TTransaction,\n): transaction is TransactionWithinSizeLimit & TTransaction {\n return getTransactionSize(transaction) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction is within the size limit.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction exceeds the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * assertIsTransactionWithinSizeLimit(transaction);\n * transaction satisfies TransactionWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionWithinSizeLimit(\n transaction: TTransaction,\n): asserts transaction is TransactionWithinSizeLimit & TTransaction {\n const transactionSize = getTransactionSize(transaction);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","import { assertIsFullySignedTransaction, FullySignedTransaction, isFullySignedTransaction } from './signatures';\nimport { Transaction } from './transaction';\nimport {\n assertIsTransactionWithinSizeLimit,\n isTransactionWithinSizeLimit,\n TransactionWithinSizeLimit,\n} from './transaction-size';\n\n/**\n * Helper type that includes all transaction types required\n * for the transaction to be sent to the network.\n *\n * @see {@link isSendableTransaction}\n * @see {@link assertIsSendableTransaction}\n */\nexport type SendableTransaction = FullySignedTransaction & TransactionWithinSizeLimit;\n\n/**\n * Checks if a transaction has all the required\n * conditions to be sent to the network.\n *\n * @example\n * ```ts\n * import { isSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isSendableTransaction(transaction)) {\n * // At this point we know that the transaction can be sent to the network.\n * }\n * ```\n *\n * @see {@link assertIsSendableTransaction}\n */\nexport function isSendableTransaction(\n transaction: TTransaction,\n): transaction is SendableTransaction & TTransaction {\n return isFullySignedTransaction(transaction) && isTransactionWithinSizeLimit(transaction);\n}\n\n/**\n * Asserts that a given transaction has all the\n * required conditions to be sent to the network.\n *\n * From time to time you might acquire a {@link Transaction}\n * from an untrusted network API or user input and you are not sure\n * that it has all the required conditions to be sent to the network\n * — such as being fully signed and within the size limit.\n * This function can be used to assert that such a transaction\n * is in fact sendable.\n *\n * @example\n * ```ts\n * import { assertIsSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `SendableTransaction`.\n * assertIsSendableTransaction(transaction);\n * // At this point we know that the transaction can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT)) {\n * setError(`Transaction exceeds size limit of ${e.context.transactionSizeLimit} bytes`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsSendableTransaction(\n transaction: TTransaction,\n): asserts transaction is SendableTransaction & TTransaction {\n assertIsFullySignedTransaction(transaction);\n assertIsTransactionWithinSizeLimit(transaction);\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithinSizeLimit,\n} from '@solana/transaction-messages';\n\nimport { compileTransaction } from './compile-transaction';\nimport { getTransactionSize, TRANSACTION_SIZE_LIMIT } from './transaction-size';\n\n/**\n * Gets the compiled transaction size of a given transaction message in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionMessageSize(transactionMessage);\n * ```\n */\nexport function getTransactionMessageSize(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n): number {\n return getTransactionSize(compileTransaction(transactionMessage));\n}\n\n/**\n * Checks if a transaction message is within the size limit\n * when compiled into a transaction.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * if (isTransactionMessageWithinSizeLimit(transactionMessage)) {\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n return getTransactionMessageSize(transactionMessage) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction message is within the size limit\n * when compiled into a transaction.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction message exceeds the size limit.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * assertIsTransactionMessageWithinSizeLimit(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): asserts transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n const transactionSize = getTransactionMessageSize(transactionMessage);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","/**\n * Forked from https://github.com/digitalloggers/race-as-promised/tree/master\n *\n * Authored by Brian Kim:\n * https://github.com/nodejs/node/issues/17469#issuecomment-685216777\n *\n * Adapted to module structure.\n *\n * This is free and unencumbered software released into the public domain.\n *\n * Anyone is free to copy, modify, publish, use, compile, sell, or\n * distribute this software, either in source code form or as a compiled\n * binary, for any purpose, commercial or non-commercial, and by any\n * means.\n *\n * In jurisdictions that recognize copyright laws, the author or authors\n * of this software dedicate any and all copyright interest in the\n * software to the public domain. We make this dedication for the benefit\n * of the public at large and to the detriment of our heirs and\n * successors. We intend this dedication to be an overt act of\n * relinquishment in perpetuity of all present and future rights to this\n * software under copyright law.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * For more information, please refer to \n */\n\ntype Deferred = Readonly<{\n reject: (reason?: unknown) => void;\n resolve: (value: unknown) => void;\n}>;\n\nfunction isObject(value: unknown): value is object {\n return value !== null && (typeof value === 'object' || typeof value === 'function');\n}\n\nfunction addRaceContender(contender: object) {\n const deferreds = new Set();\n const record = { deferreds, settled: false };\n\n // This call to `then` happens once for the lifetime of the value.\n Promise.resolve(contender).then(\n value => {\n for (const { resolve } of deferreds) {\n resolve(value);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n err => {\n for (const { reject } of deferreds) {\n reject(err);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n );\n return record;\n}\n\n// Keys are the values passed to race, values are a record of data containing a\n// set of deferreds and whether the value has settled.\nconst wm = new WeakMap; settled: boolean }>();\n/**\n * An implementation of [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)\n * that causes all of the losing promises to settle. This allows them to be released and garbage\n * collected, preventing memory leaks.\n *\n * Read more here: https://github.com/nodejs/node/issues/17469\n */\nexport async function safeRace(contenders: T): Promise> {\n let deferred: Deferred;\n const result = new Promise((resolve, reject) => {\n deferred = { reject, resolve };\n for (const contender of contenders) {\n if (!isObject(contender)) {\n // If the contender is a primitive, attempting to use it as a key in the\n // weakmap would throw an error. Luckily, it is safe to call\n // `Promise.resolve(contender).then` on a primitive value multiple times\n // because the promise fulfills immediately.\n Promise.resolve(contender).then(resolve, reject);\n continue;\n }\n\n let record = wm.get(contender);\n if (record === undefined) {\n record = addRaceContender(contender);\n record.deferreds.add(deferred);\n wm.set(contender, record);\n } else if (record.settled) {\n // If the value has settled, it is safe to call\n // `Promise.resolve(contender).then` on it.\n Promise.resolve(contender).then(resolve, reject);\n } else {\n record.deferreds.add(deferred);\n }\n }\n });\n\n // The finally callback executes when any value settles, preventing any of\n // the unresolved values from retaining a reference to the resolved value.\n return await (result.finally(() => {\n for (const contender of contenders) {\n if (isObject(contender)) {\n const record = wm.get(contender)!;\n record.deferreds.delete(deferred);\n }\n }\n }) as Promise>);\n}\n","import { safeRace } from './race';\n\n/**\n * Returns a new promise that will reject if the abort signal fires before the original promise\n * settles. Resolves or rejects with the value of the original promise otherwise.\n *\n * @example\n * ```ts\n * const result = await getAbortablePromise(\n * // Resolves or rejects when `fetch` settles.\n * fetch('https://example.com/json').then(r => r.json()),\n * // ...unless it takes longer than 5 seconds, after which the `AbortSignal` is triggered.\n * AbortSignal.timeout(5000),\n * );\n * ```\n */\nexport function getAbortablePromise(promise: Promise, abortSignal?: AbortSignal): Promise {\n if (!abortSignal) {\n return promise;\n } else {\n return safeRace([\n // This promise only ever rejects if the signal is aborted. Otherwise it idles forever.\n // It's important that this come before the input promise; in the event of an abort, we\n // want to throw even if the input promise's result is ready\n new Promise((_, reject) => {\n if (abortSignal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(abortSignal.reason);\n } else {\n abortSignal.addEventListener('abort', function () {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n });\n }\n }),\n promise,\n ]);\n }\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SolanaError,\n} from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\n/**\n * A set of instructions with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans in order to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely the following plans are supported:\n * - {@link SingleInstructionPlan} - A plan that contains a single instruction.\n * This is a simple instruction wrapper and the simplest leaf in this tree.\n * - {@link ParallelInstructionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialInstructionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that instructions inside it can be split into separate transactions.\n * - {@link MessagePackerInstructionPlan} - A plan that can dynamically pack\n * instructions into transaction messages.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myInstructionPlan: InstructionPlan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * instructionC,\n * instructionD,\n * ]);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link ParallelInstructionPlan}\n * @see {@link SequentialInstructionPlan}\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type InstructionPlan =\n | MessagePackerInstructionPlan\n | ParallelInstructionPlan\n | SequentialInstructionPlan\n | SingleInstructionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the instructions inside them can be split into separate transactions.\n * When `divisible` is `false`, the instructions inside the plan should\n * all be executed atomically — either in a single transaction or in a\n * transaction bundle.\n *\n * You may use the {@link sequentialInstructionPlan} and {@link nonDivisibleSequentialInstructionPlan}\n * helpers to create objects of this type.\n *\n * @example Simple sequential plan with two instructions.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan;\n * ```\n *\n * @example Non-divisible sequential plan with two instructions.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @example Sequential plan with nested parallel plans.\n * Here, instructions A and B can be executed in parallel, but they must both be finalized\n * before instructions C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * parallelInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @see {@link sequentialInstructionPlan}\n * @see {@link nonDivisibleSequentialInstructionPlan}\n */\nexport type SequentialInstructionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without consequence.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialInstructionPlan}.\n *\n * You may use the {@link parallelInstructionPlan} helper to create objects of this type.\n *\n * @example Simple parallel plan with two instructions.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @example Parallel plan with nested sequential plans.\n * Here, instructions A and B must be executed sequentially and so must instructions C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @see {@link parallelInstructionPlan}\n */\nexport type ParallelInstructionPlan = Readonly<{\n kind: 'parallel';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan that contains a single instruction.\n *\n * This is a simple instruction wrapper that transforms an instruction into a plan.\n *\n * You may use the {@link singleInstructionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * plan satisfies SingleInstructionPlan;\n * ```\n *\n * @see {@link singleInstructionPlan}\n */\nexport type SingleInstructionPlan = Readonly<{\n instruction: TInstruction;\n kind: 'single';\n}>;\n\n/**\n * A plan that can dynamically pack instructions into transaction messages.\n *\n * This plan provides a {@link MessagePacker} via the `getMessagePacker`\n * method, which enables instructions to be dynamically packed into the\n * provided transaction message until there are no more instructions to pack.\n * The returned {@link MessagePacker} offers a `packMessageToCapacity(message)`\n * method that packs the provided message — when possible — and a `done()` method\n * that checks whether there are more instructions to pack.\n *\n * Several helper functions are provided to create objects of this type such as\n * {@link getLinearMessagePackerInstructionPlan} or {@link getMessagePackerInstructionPlanFromInstructions}.\n *\n * @example An message packer plan for a write instruction that uses as many bytes as possible.\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example A message packer plan for multiple realloc instructions.\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example Using a message packer plan.\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link getLinearMessagePackerInstructionPlan}\n * @see {@link getMessagePackerInstructionPlanFromInstructions}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport type MessagePackerInstructionPlan = Readonly<{\n getMessagePacker: () => MessagePacker;\n kind: 'messagePacker';\n}>;\n\n/**\n * The message packer returned by the {@link MessagePackerInstructionPlan}.\n *\n * It offers a `packMessageToCapacity(transactionMessage)` method that packs as many instructions\n * as possible into the provided transaction message, while still being able to fit into the\n * transaction size limit. It returns the updated transaction message with the packed instructions\n * or throws an error if the current transaction message cannot accommodate this plan.\n *\n * The `done()` method checks whether there are more instructions to pack into\n * transaction messages.\n *\n * @example\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type MessagePacker = Readonly<{\n /** Checks whether the message packer has more instructions to pack into transaction messages. */\n done: () => boolean;\n /**\n * Packs the provided transaction message with instructions or throws if not possible.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN}\n * if the provided transaction message cannot be used to fill the next instructions.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE}\n * if the message packer is already done and no more instructions can be packed.\n */\n packMessageToCapacity: (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer;\n}>;\n\n/**\n * Creates a {@link ParallelInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = parallelInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n */\nexport function parallelInstructionPlan(plans: (Instruction | InstructionPlan)[]): ParallelInstructionPlan {\n return Object.freeze({\n kind: 'parallel',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function sequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: true } {\n return Object.freeze({\n divisible: true,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a non-divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function nonDivisibleSequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: false } {\n return Object.freeze({\n divisible: false,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a {@link SingleInstructionPlan} from an {@link Instruction} object.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n */\nexport function singleInstructionPlan(instruction: Instruction): SingleInstructionPlan {\n return Object.freeze({ instruction, kind: 'single' });\n}\n\nfunction parseSingleInstructionPlans(plans: (Instruction | InstructionPlan)[]): InstructionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleInstructionPlan(plan)));\n}\n\n/**\n * Checks if the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a single instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * if (isSingleInstructionPlan(plan)) {\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * }\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link assertIsSingleInstructionPlan}\n */\nexport function isSingleInstructionPlan(plan: InstructionPlan): plan is SingleInstructionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a single instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * assertIsSingleInstructionPlan(plan);\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link isSingleInstructionPlan}\n */\nexport function assertIsSingleInstructionPlan(plan: InstructionPlan): asserts plan is SingleInstructionPlan {\n if (!isSingleInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a message packer instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * if (isMessagePackerInstructionPlan(plan)) {\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link assertIsMessagePackerInstructionPlan}\n */\nexport function isMessagePackerInstructionPlan(plan: InstructionPlan): plan is MessagePackerInstructionPlan {\n return plan.kind === 'messagePacker';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a message packer instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * assertIsMessagePackerInstructionPlan(plan);\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link isMessagePackerInstructionPlan}\n */\nexport function assertIsMessagePackerInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is MessagePackerInstructionPlan {\n if (!isMessagePackerInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'messagePacker',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isSequentialInstructionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsSequentialInstructionPlan}\n */\nexport function isSequentialInstructionPlan(plan: InstructionPlan): plan is SequentialInstructionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsSequentialInstructionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isSequentialInstructionPlan}\n */\nexport function assertIsSequentialInstructionPlan(plan: InstructionPlan): asserts plan is SequentialInstructionPlan {\n if (!isSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a non-divisible sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isNonDivisibleSequentialInstructionPlan(plan)) {\n * // All instructions must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsNonDivisibleSequentialInstructionPlan}\n */\nexport function isNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): plan is SequentialInstructionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a non-divisible sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsNonDivisibleSequentialInstructionPlan(plan);\n * // All instructions must be executed atomically.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isNonDivisibleSequentialInstructionPlan}\n */\nexport function assertIsNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is SequentialInstructionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a parallel instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * if (isParallelInstructionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * }\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link assertIsParallelInstructionPlan}\n */\nexport function isParallelInstructionPlan(plan: InstructionPlan): plan is ParallelInstructionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a parallel instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * assertIsParallelInstructionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link isParallelInstructionPlan}\n */\nexport function assertIsParallelInstructionPlan(plan: InstructionPlan): asserts plan is ParallelInstructionPlan {\n if (!isParallelInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Finds the first instruction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the instruction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param instructionPlan - The instruction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @returns The first matching instruction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const nonDivisible = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing instructionC and instructionD.\n * ```\n *\n * @example\n * Finding a specific single instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const found = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.instruction === instructionB,\n * );\n * // Returns the SingleInstructionPlan wrapping instructionB.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function findInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): InstructionPlan | undefined {\n if (predicate(instructionPlan)) {\n return instructionPlan;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return undefined;\n }\n for (const subPlan of instructionPlan.plans) {\n const foundPlan = findInstructionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every instruction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the instruction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param instructionPlan - The instruction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const allDivisible = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single instructions use a specific program.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const allUseSameProgram = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.instruction.programAddress === myProgramAddress,\n * );\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function everyInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): boolean {\n if (!predicate(instructionPlan)) {\n return false;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return true;\n }\n return instructionPlan.plans.every(p => everyInstructionPlan(p, predicate));\n}\n\n/**\n * Transforms an instruction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the instruction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param instructionPlan - The instruction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed instruction plan tree.\n *\n * @example\n * Making all sequential plans non-divisible to ensure atomicity.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' && p.divisible) {\n * return nonDivisibleSequentialInstructionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Filtering out debug instructions before production execution.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, debugInstruction, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' || p.kind === 'parallel') {\n * return { ...p, plans: p.plans.filter((p) => !isDebugInstruction(p)) };\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function transformInstructionPlan(\n instructionPlan: InstructionPlan,\n fn: (plan: InstructionPlan) => InstructionPlan,\n): InstructionPlan {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return Object.freeze(fn(instructionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...instructionPlan,\n plans: instructionPlan.plans.map(p => transformInstructionPlan(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleInstructionPlan} and {@link MessagePackerInstructionPlan}\n * instances from an instruction plan tree.\n *\n * This function recursively traverses any nested structure of instruction plans and extracts\n * all the leaf plans they contain. It's useful when you need to access all the individual\n * instructions or message packers that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param instructionPlan - The instruction plan to extract leaf plans from\n * @returns An array of all single and message packer instruction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * instructionE,\n * ]);\n *\n * const leafPlans = flattenInstructionPlan(plan);\n * // Array of `SingleInstructionPlan` containing:\n * // instructionA, instructionB, instructionC, instructionD and instructionE.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n */\nexport function flattenInstructionPlan(\n instructionPlan: InstructionPlan,\n): (MessagePackerInstructionPlan | SingleInstructionPlan)[] {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return [instructionPlan];\n }\n return instructionPlan.plans.flatMap(flattenInstructionPlan);\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs instructions\n * such that each instruction consumes as many bytes as possible from the given\n * `totalLength` while still being able to fit into the given transaction messages.\n *\n * This is particularly useful for instructions that write data to accounts and must\n * span multiple transactions due to their size limit.\n *\n * This message packer will first call `getInstruction` with a length of zero to\n * determine the base size of the instruction before figuring out how many\n * additional bytes can be packed into the transaction message. That remaining space\n * will then be used to call `getInstruction` again with the appropriate length.\n *\n * @param getInstruction - A function that returns an instruction for a given offset and length.\n * @param totalLength - The total length of the data to write, in bytes.\n *\n * @example\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getLinearMessagePackerInstructionPlan({\n getInstruction,\n totalLength: totalBytes,\n}: {\n getInstruction: (offset: number, length: number) => Instruction;\n totalLength: number;\n}): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let offset = 0;\n return Object.freeze({\n done: () => offset >= totalBytes,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (offset >= totalBytes) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const messageSizeWithBaseInstruction = getTransactionMessageSize(\n appendTransactionMessageInstruction(getInstruction(offset, 0), message),\n );\n const freeSpace =\n TRANSACTION_SIZE_LIMIT -\n messageSizeWithBaseInstruction /* Includes the base instruction (length: 0). */ -\n 1; /* Leeway for shortU16 numbers in transaction headers. */\n\n if (freeSpace <= 0) {\n const messageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n // (+1) We need to pack at least one byte of data otherwise\n // there is no point packing the base instruction alone.\n numBytesRequired: messageSizeWithBaseInstruction - messageSize + 1,\n // (-1) Leeway for shortU16 numbers in transaction headers.\n numFreeBytes: TRANSACTION_SIZE_LIMIT - messageSize - 1,\n });\n }\n\n const length = Math.min(totalBytes - offset, freeSpace);\n const instruction = getInstruction(offset, length);\n offset += length;\n return appendTransactionMessageInstruction(instruction, message);\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} from a list of instructions.\n *\n * This can be useful to prepare a set of instructions that can be iterated over\n * — e.g. to pack a list of instructions that gradually reallocate the size of an account\n * one `REALLOC_LIMIT` (10'240 bytes) at a time.\n *\n * @example\n * ```ts\n * const plan = getMessagePackerInstructionPlanFromInstructions([\n * instructionA,\n * instructionB,\n * instructionC,\n * ]);\n *\n * const messagePacker = plan.getMessagePacker();\n * firstTransactionMessage = messagePacker.packMessageToCapacity(firstTransactionMessage);\n * // Contains instruction A and instruction B.\n * secondTransactionMessage = messagePacker.packMessageToCapacity(secondTransactionMessage);\n * // Contains instruction C.\n * messagePacker.done(); // true\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport function getMessagePackerInstructionPlanFromInstructions(\n instructions: TInstruction[],\n): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let instructionIndex = 0;\n return Object.freeze({\n done: () => instructionIndex >= instructions.length,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (instructionIndex >= instructions.length) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const originalMessageSize = getTransactionMessageSize(message);\n\n for (let index = instructionIndex; index < instructions.length; index++) {\n message = appendTransactionMessageInstruction(instructions[index], message);\n const messageSize = getTransactionMessageSize(message);\n\n if (messageSize > TRANSACTION_SIZE_LIMIT) {\n if (index === instructionIndex) {\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n {\n numBytesRequired: messageSize - originalMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - originalMessageSize,\n },\n );\n }\n instructionIndex = index;\n return message;\n }\n }\n\n instructionIndex = instructions.length;\n return message;\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\nconst REALLOC_LIMIT = 10_240;\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs a list of realloc instructions.\n *\n * That is, it splits instruction by chunks of `REALLOC_LIMIT` (10'240) bytes until\n * the given total size is reached.\n *\n * @example\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getReallocMessagePackerInstructionPlan({\n getInstruction,\n totalSize,\n}: {\n getInstruction: (size: number) => Instruction;\n totalSize: number;\n}): MessagePackerInstructionPlan {\n const numberOfInstructions = Math.ceil(totalSize / REALLOC_LIMIT);\n const lastInstructionSize = totalSize % REALLOC_LIMIT;\n const instructions = new Array(numberOfInstructions)\n .fill(0)\n .map((_, i) => getInstruction(i === numberOfInstructions - 1 ? lastInstructionSize : REALLOC_LIMIT));\n\n return getMessagePackerInstructionPlanFromInstructions(instructions);\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, SolanaError } from '@solana/errors';\nimport { type Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport { flattenInstructionPlan, InstructionPlan } from './instruction-plan';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\n\ntype AppendTransactionMessageInstructions = ReturnType<\n typeof appendTransactionMessageInstructions\n>;\n\n/**\n * Appends all instructions from an instruction plan to a transaction message.\n *\n * This function flattens the instruction plan into its leaf plans and sequentially\n * appends each instruction to the provided transaction message. It handles both\n * single instructions and message packer plans.\n *\n * Note that any {@link MessagePackerInstructionPlan} is assumed to only append\n * instructions. If it modifies other properties of the transaction message, the\n * type of the returned transaction message may not accurately reflect those changes.\n *\n * @typeParam TTransactionMessage - The type of transaction message being modified.\n *\n * @param transactionMessage - The transaction message to append instructions to.\n * @param instructionPlan - The instruction plan containing the instructions to append.\n * @returns The transaction message with all instructions from the plan appended.\n *\n * @example\n * Appending a simple instruction plan to a transaction message.\n * ```ts\n * import { appendTransactionMessageInstructionPlan } from '@solana/instruction-plans';\n * import { createTransactionMessage, setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const message = setTransactionMessageFeePayer(feePayer, createTransactionMessage({ version: 0 }));\n * const plan = singleInstructionPlan(myInstruction);\n *\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @example\n * Appending a sequential instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function appendTransactionMessageInstructionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer,\n>(\n instructionPlan: InstructionPlan,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n type Out = AppendTransactionMessageInstructions;\n\n const leafInstructionPlans = flattenInstructionPlan(instructionPlan);\n\n return leafInstructionPlans.reduce(\n (messageSoFar, plan) => {\n const kind = plan.kind;\n if (kind === 'single') {\n return appendTransactionMessageInstruction(plan.instruction, messageSoFar) as unknown as Out;\n }\n if (kind === 'messagePacker') {\n const messagerPacker = plan.getMessagePacker();\n let nextMessage: Out = messageSoFar;\n while (!messagerPacker.done()) {\n nextMessage = messagerPacker.packMessageToCapacity(nextMessage) as Out;\n }\n return nextMessage;\n }\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, {\n kind,\n });\n },\n transactionMessage as unknown as Out,\n );\n}\n","import { SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, SolanaError } from '@solana/errors';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\n/**\n * A set of transaction messages with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely, the following plans are supported:\n * - {@link SingleTransactionPlan} - A plan that contains a single transaction message.\n * This is the simplest leaf in this tree.\n * - {@link ParallelTransactionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialTransactionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that transaction messages inside it can be split into separate batches.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myTransactionPlan: TransactionPlan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * messageC,\n * ]);\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link ParallelTransactionPlan}\n * @see {@link SequentialTransactionPlan}\n */\nexport type TransactionPlan = ParallelTransactionPlan | SequentialTransactionPlan | SingleTransactionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the transaction messages inside them can be split into separate batches.\n * When `divisible` is `false`, the transaction messages inside the plan should\n * all be executed atomically — usually in a transaction bundle.\n *\n * You may use the {@link sequentialTransactionPlan} and {@link nonDivisibleSequentialTransactionPlan}\n * helpers to create objects of this type.\n *\n * @example\n * Simple sequential plan with two transaction messages.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan;\n * ```\n *\n * @example\n * Non-divisible sequential plan with two transaction messages.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan & { divisible: false };\n * ```\n *\n * @example\n * Sequential plan with nested parallel plans.\n * Here, messages A and B can be executed in parallel, but they must both be finalized\n * before messages C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * parallelTransactionPlan([messageC, messageD]),\n * ]);\n * ```\n *\n * @see {@link sequentialTransactionPlan}\n * @see {@link nonDivisibleSequentialTransactionPlan}\n */\nexport type SequentialTransactionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without causing any side effects.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialTransactionPlan}.\n *\n * You may use the {@link parallelTransactionPlan} helper to create objects of this type.\n *\n * @example\n * Simple parallel plan with two transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @example\n * Parallel plan with nested sequential plans.\n * Here, messages A and B must be executed sequentially and so must messages C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @see {@link parallelTransactionPlan}\n */\nexport type ParallelTransactionPlan = Readonly<{\n kind: 'parallel';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan that contains a single transaction message.\n *\n * This is a simple transaction message wrapper that transforms a message into a plan.\n *\n * You may use the {@link singleTransactionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link singleTransactionPlan}\n */\nexport type SingleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n}>;\n\n/**\n * Creates a {@link ParallelTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = parallelTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n */\nexport function parallelTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): ParallelTransactionPlan {\n return Object.freeze({ kind: 'parallel', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function sequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function nonDivisibleSequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a {@link SingleTransactionPlan} from a {@link TransactionMessage} object.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link SingleTransactionPlan}\n */\nexport function singleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlan {\n return Object.freeze({ kind: 'single', message: transactionMessage });\n}\n\nfunction parseSingleTransactionPlans(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): TransactionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleTransactionPlan(plan)));\n}\n\n/**\n * Checks if the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a single transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * if (isSingleTransactionPlan(plan)) {\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link assertIsSingleTransactionPlan}\n */\nexport function isSingleTransactionPlan(plan: TransactionPlan): plan is SingleTransactionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a single transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * assertIsSingleTransactionPlan(plan);\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link isSingleTransactionPlan}\n */\nexport function assertIsSingleTransactionPlan(plan: TransactionPlan): asserts plan is SingleTransactionPlan {\n if (!isSingleTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * if (isSequentialTransactionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsSequentialTransactionPlan}\n */\nexport function isSequentialTransactionPlan(plan: TransactionPlan): plan is SequentialTransactionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsSequentialTransactionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isSequentialTransactionPlan}\n */\nexport function assertIsSequentialTransactionPlan(plan: TransactionPlan): asserts plan is SequentialTransactionPlan {\n if (!isSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a non-divisible sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * if (isNonDivisibleSequentialTransactionPlan(plan)) {\n * // All transaction messages must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlan}\n */\nexport function isNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): plan is SequentialTransactionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a non-divisible sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlan(plan);\n * // All transaction messages must be executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isNonDivisibleSequentialTransactionPlan}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): asserts plan is SequentialTransactionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a parallel transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * if (isParallelTransactionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link assertIsParallelTransactionPlan}\n */\nexport function isParallelTransactionPlan(plan: TransactionPlan): plan is ParallelTransactionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a parallel transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * assertIsParallelTransactionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link isParallelTransactionPlan}\n */\nexport function assertIsParallelTransactionPlan(plan: TransactionPlan): asserts plan is ParallelTransactionPlan {\n if (!isParallelTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * @deprecated Use {@link flattenTransactionPlan} instead.\n */\nexport const getAllSingleTransactionPlans = flattenTransactionPlan;\n\n/**\n * Retrieves all individual {@link SingleTransactionPlan} instances from a transaction plan tree.\n *\n * This function recursively traverses any nested structure of transaction plans and extracts\n * all the single transaction plans they contain. It's useful when you need to access all\n * the actual transaction messages that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param transactionPlan - The transaction plan to extract single plans from\n * @returns An array of all single transaction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * messageE,\n * ]);\n *\n * const singlePlans = flattenTransactionPlan(plan);\n * // Array of `SingleTransactionPlan` containing:\n * // messageA, messageB, messageC and messageD.\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * ```\n */\nexport function flattenTransactionPlan(transactionPlan: TransactionPlan): SingleTransactionPlan[] {\n if (transactionPlan.kind === 'single') {\n return [transactionPlan];\n }\n return transactionPlan.plans.flatMap(flattenTransactionPlan);\n}\n\n/**\n * Finds the first transaction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param transactionPlan - The transaction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @return The first matching transaction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const nonDivisible = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing messageC and messageD.\n * ```\n *\n * @example\n * Finding a specific single transaction plan.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB, messageC]);\n *\n * const found = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.message === messageB,\n * );\n * // Returns the SingleTransactionPlan wrapping messageB.\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function findTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): TransactionPlan | undefined {\n if (predicate(transactionPlan)) {\n return transactionPlan;\n }\n if (transactionPlan.kind === 'single') {\n return undefined;\n }\n for (const subPlan of transactionPlan.plans) {\n const foundPlan = findTransactionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every transaction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param transactionPlan - The transaction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const allDivisible = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single plans have a specific fee payer.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const allUseSameFeePayer = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.message.feePayer.address === myFeePayer,\n * );\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function everyTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): boolean {\n if (!predicate(transactionPlan)) {\n return false;\n }\n if (transactionPlan.kind === 'single') {\n return true;\n }\n return transactionPlan.plans.every(p => everyTransactionPlan(p, predicate));\n}\n\n/**\n * Transforms a transaction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlan - The transaction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed transaction plan tree.\n *\n * @example\n * Removing parallelism by converting parallel plans to sequential.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'parallel') {\n * return sequentialTransactionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Updating the fee payer on all transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'single') {\n * return singleTransactionPlan({ ...p.message, feePayer: newFeePayer });\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function transformTransactionPlan(\n transactionPlan: TransactionPlan,\n fn: (plan: TransactionPlan) => TransactionPlan,\n): TransactionPlan {\n if (transactionPlan.kind === 'single') {\n return Object.freeze(fn(transactionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlan,\n plans: transactionPlan.plans.map(p => transformTransactionPlan(p, fn)),\n }),\n ),\n );\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { getSignatureFromTransaction, Transaction } from '@solana/transactions';\n\n/**\n * The result of executing a transaction plan.\n *\n * This is structured as a recursive tree of results that mirrors the structure\n * of the original transaction plan, capturing the execution status at each level.\n *\n * Namely, the following result types are supported:\n * - {@link SingleTransactionPlanResult} - A result for a single transaction message\n * containing its execution status.\n * - {@link ParallelTransactionPlanResult} - A result containing other results that\n * were executed in parallel.\n * - {@link SequentialTransactionPlanResult} - A result containing other results that\n * were executed sequentially. It also retains the divisibility property from the\n * original plan.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link TransactionPlanResultStatus}\n */\nexport type TransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = ParallelTransactionPlanResult | SequentialTransactionPlanResult | TSingle;\n\n/**\n * A {@link TransactionPlanResult} where all single transaction results are successful.\n *\n * This type represents a transaction plan result tree where every\n * {@link SingleTransactionPlanResult} has a 'successful' status. It can be used\n * to ensure that an entire execution completed without any failures or cancellations.\n *\n * Note: This is different from {@link SuccessfulSingleTransactionPlanResult} which\n * represents a single successful transaction, whereas this type represents an entire\n * plan result tree (which may contain parallel/sequential structures) where all\n * leaf nodes are successful.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n *\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link SuccessfulSingleTransactionPlanResult}\n */\nexport type SuccessfulTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = TransactionPlanResult>;\n\n/** A context object that may be passed along with successful results. */\nexport type TransactionPlanResultContext = Record;\n\n/**\n * A result for a sequential transaction plan.\n *\n * This represents the execution result of a {@link SequentialTransactionPlan} and\n * contains child results that were executed sequentially. It also retains the\n * divisibility property from the original plan.\n *\n * You may use the {@link sequentialTransactionPlanResult} and\n * {@link nonDivisibleSequentialTransactionPlanResult} helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult;\n * ```\n *\n * @example\n * Non-divisible sequential result.\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link sequentialTransactionPlanResult}\n * @see {@link nonDivisibleSequentialTransactionPlanResult}\n */\nexport type SequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a parallel transaction plan.\n *\n * This represents the execution result of a {@link ParallelTransactionPlan} and\n * contains child results that were executed in parallel.\n *\n * You may use the {@link parallelTransactionPlanResult} helper to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link parallelTransactionPlanResult}\n */\nexport type ParallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n kind: 'parallel';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a single transaction plan.\n *\n * This represents the execution result of a {@link SingleTransactionPlan} and\n * contains the original transaction message along with its execution status.\n *\n * You may use the {@link successfulSingleTransactionPlanResult},\n * {@link failedSingleTransactionPlanResult}, or {@link canceledSingleTransactionPlanResult}\n * helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TTransactionMessage - The type of the transaction message\n *\n * @example\n * Successful result with a transaction and context.\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Failed result with an error.\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError(SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Canceled result.\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link successfulSingleTransactionPlanResult}\n * @see {@link failedSingleTransactionPlanResult}\n * @see {@link canceledSingleTransactionPlanResult}\n */\nexport type SingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n status: TransactionPlanResultStatus;\n}>;\n\n/**\n * The status of a single transaction plan execution.\n *\n * This represents the outcome of executing a single transaction message and can be one of:\n * - `successful` - The transaction was successfully executed. Contains the transaction\n * and an optional context object.\n * - `failed` - The transaction execution failed. Contains the error that caused the failure.\n * - `canceled` - The transaction execution was canceled.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n */\nexport type TransactionPlanResultStatus =\n | Readonly<{ context: TContext; kind: 'successful'; signature: Signature; transaction?: Transaction }>\n | Readonly<{ error: Error; kind: 'failed' }>\n | Readonly<{ kind: 'canceled' }>;\n\n/**\n * Creates a divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `true`,\n * indicating that the nested plans were executed sequentially but could have been\n * split into separate transactions or batches.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: true };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function sequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `false`,\n * indicating that the nested plans were executed sequentially and could not have been\n * split into separate transactions or batches (e.g., they were executed as a transaction bundle).\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function nonDivisibleSequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans });\n}\n\n/**\n * Creates a {@link ParallelTransactionPlanResult} from an array of nested results.\n *\n * This function creates a parallel result indicating that the nested plans\n * were executed in parallel.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed in parallel\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n */\nexport function parallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): ParallelTransactionPlanResult {\n return Object.freeze({ kind: 'parallel', plans });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and transaction.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param transaction - The successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n transaction: Transaction,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({\n context: context ?? ({} as TContext),\n kind: 'successful',\n signature: getSignatureFromTransaction(transaction),\n transaction,\n }),\n });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and signature.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the signature of the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param signature - The signature of the successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * signature\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResultFromSignature<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n signature: Signature,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ context: context ?? ({} as TContext), kind: 'successful', signature }),\n });\n}\n\n/**\n * Creates a failed {@link SingleTransactionPlanResult} from a transaction message and error.\n *\n * This function creates a single result with a 'failed' status, indicating that\n * the transaction execution failed. It includes the original transaction message\n * and the error that caused the failure.\n *\n * @template TContext - The type of the context object (not used in failed results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param error - The error that caused the transaction to fail\n *\n * @example\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError({\n * code: 123,\n * message: 'Transaction simulation failed',\n * }),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function failedSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage, error: Error): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ error, kind: 'failed' }),\n });\n}\n\n/**\n * Creates a canceled {@link SingleTransactionPlanResult} from a transaction message.\n *\n * This function creates a single result with a 'canceled' status, indicating that\n * the transaction execution was canceled. It includes the original transaction message.\n *\n * @template TContext - The type of the context object (not used in canceled results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n *\n * @example\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function canceledSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ kind: 'canceled' }),\n });\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSingleTransactionPlanResult(result)) {\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link assertIsSingleTransactionPlanResult}\n */\nexport function isSingleTransactionPlanResult(plan: TransactionPlanResult): plan is SingleTransactionPlanResult {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSingleTransactionPlanResult(result);\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link isSingleTransactionPlanResult}\n */\nexport function assertIsSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SingleTransactionPlanResult {\n if (!isSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a successful single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSuccessfulSingleTransactionPlanResult(result)) {\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * }\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'successful';\n}\n\n/**\n * Asserts that the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a successful single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSuccessfulSingleTransactionPlanResult(result);\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulSingleTransactionPlanResult {\n if (!isSuccessfulSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'successful single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a failed single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * if (isFailedSingleTransactionPlanResult(result)) {\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * }\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link assertIsFailedSingleTransactionPlanResult}\n */\nexport function isFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is FailedSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'failed';\n}\n\n/**\n * Asserts that the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a failed single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * assertIsFailedSingleTransactionPlanResult(result);\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link isFailedSingleTransactionPlanResult}\n */\nexport function assertIsFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is FailedSingleTransactionPlanResult {\n if (!isFailedSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'failed single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a canceled single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * if (isCanceledSingleTransactionPlanResult(result)) {\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * }\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link assertIsCanceledSingleTransactionPlanResult}\n */\nexport function isCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is CanceledSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'canceled';\n}\n\n/**\n * Asserts that the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a canceled single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * assertIsCanceledSingleTransactionPlanResult(result);\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link isCanceledSingleTransactionPlanResult}\n */\nexport function assertIsCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is CanceledSingleTransactionPlanResult {\n if (!isCanceledSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'canceled single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isSequentialTransactionPlanResult(result)) {\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsSequentialTransactionPlanResult}\n */\nexport function isSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsSequentialTransactionPlanResult(result);\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isSequentialTransactionPlanResult}\n */\nexport function assertIsSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult {\n if (!isSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a non-divisible sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isNonDivisibleSequentialTransactionPlanResult(result)) {\n * // Transactions were executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlanResult}\n */\nexport function isNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a non-divisible sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlanResult(result);\n * // Transactions were executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isNonDivisibleSequentialTransactionPlanResult}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a parallel transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * if (isParallelTransactionPlanResult(result)) {\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link assertIsParallelTransactionPlanResult}\n */\nexport function isParallelTransactionPlanResult(plan: TransactionPlanResult): plan is ParallelTransactionPlanResult {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a parallel transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * assertIsParallelTransactionPlanResult(result);\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link isParallelTransactionPlanResult}\n */\nexport function assertIsParallelTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is ParallelTransactionPlanResult {\n if (!isParallelTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It recursively checks all nested results\n * to ensure every {@link SingleTransactionPlanResult} has a 'successful' status.\n *\n * Note: This is different from {@link isSuccessfulSingleTransactionPlanResult} which\n * checks if a single result is successful. This function checks that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if all single transaction results in the tree are successful, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * if (isSuccessfulTransactionPlanResult(result)) {\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * }\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulTransactionPlanResult {\n return everyTransactionPlanResult(\n plan,\n r => !isSingleTransactionPlanResult(r) || isSuccessfulSingleTransactionPlanResult(r),\n );\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It throws if any {@link SingleTransactionPlanResult}\n * in the tree has a 'failed' or 'canceled' status.\n *\n * Note: This is different from {@link assertIsSuccessfulSingleTransactionPlanResult} which\n * asserts that a single result is successful. This function asserts that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT` if\n * any single transaction result in the tree is not successful.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * assertIsSuccessfulTransactionPlanResult(result);\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulTransactionPlanResult {\n if (!isSuccessfulTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT, {\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Finds the first transaction plan result in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan result tree,\n * returning the first result that satisfies the predicate. It checks the root result\n * first, then recursively searches through nested results.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @param predicate - A function that returns `true` for the result to find.\n * @returns The first matching transaction plan result, or `undefined` if no match is found.\n *\n * @example\n * Finding a failed transaction result.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * ]);\n *\n * const failed = findTransactionPlanResult(\n * result,\n * (r) => r.kind === 'single' && r.status.kind === 'failed',\n * );\n * // Returns the failed single transaction plan result for messageB.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function findTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (result: TransactionPlanResult) => boolean,\n): TransactionPlanResult | undefined {\n if (predicate(transactionPlanResult)) {\n return transactionPlanResult;\n }\n if (transactionPlanResult.kind === 'single') {\n return undefined;\n }\n for (const subResult of transactionPlanResult.plans) {\n const foundResult = findTransactionPlanResult(subResult, predicate);\n if (foundResult) {\n return foundResult;\n }\n }\n return undefined;\n}\n\n/**\n * Retrieves the first failed transaction plan result from a transaction plan result tree.\n *\n * This function searches the transaction plan result tree using a depth-first traversal\n * and returns the first single transaction result with a 'failed' status. If no failed\n * result is found, it throws a {@link SolanaError}.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @return The first failed single transaction plan result.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND` if no\n * failed transaction plan result is found. The error context contains a non-enumerable\n * `transactionPlanResult` property for recovery purposes.\n *\n * @example\n * Retrieving the first failed result from a parallel execution.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * failedSingleTransactionPlanResult(messageC, anotherError),\n * ]);\n *\n * const firstFailed = getFirstFailedSingleTransactionPlanResult(result);\n * // Returns the failed result for messageB.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n */\nexport function getFirstFailedSingleTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n): FailedSingleTransactionPlanResult {\n const result = findTransactionPlanResult(\n transactionPlanResult,\n r => r.kind === 'single' && r.status.kind === 'failed',\n );\n\n if (!result) {\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can recover but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n const context = {};\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n context,\n );\n }\n\n return result as FailedSingleTransactionPlanResult;\n}\n\n/**\n * Checks if every transaction plan result in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan result tree,\n * returning `true` only if the predicate returns `true` for every result in the tree\n * (including the root result and all nested results).\n *\n * @param transactionPlanResult - The transaction plan result tree to check.\n * @param predicate - A function that returns `true` if the result satisfies the condition.\n * @return `true` if every result in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all transactions were successful.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * const allSuccessful = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind === 'successful',\n * );\n * // Returns true because all single results are successful.\n * ```\n *\n * @example\n * Checking if no transactions were canceled.\n * ```ts\n * const result = sequentialTransactionPlanResult([resultA, resultB, resultC]);\n *\n * const noCanceled = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind !== 'canceled',\n * );\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function everyTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (plan: TransactionPlanResult) => boolean,\n): boolean {\n if (!predicate(transactionPlanResult)) {\n return false;\n }\n if (transactionPlanResult.kind === 'single') {\n return true;\n }\n return transactionPlanResult.plans.every(p => everyTransactionPlanResult(p, predicate));\n}\n\n/**\n * Transforms a transaction plan result tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan result tree, applying the\n * transformation function to each result. The transformation is applied bottom-up,\n * meaning nested results are transformed first, then the parent results receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed results are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlanResult - The transaction plan result tree to transform.\n * @param fn - A function that transforms each result and returns a new result.\n * @return A new transformed transaction plan result tree.\n *\n * @example\n * Converting all canceled results to failed results.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * canceledSingleTransactionPlanResult(messageB),\n * ]);\n *\n * const transformed = transformTransactionPlanResult(result, (r) => {\n * if (r.kind === 'single' && r.status.kind === 'canceled') {\n * return failedSingleTransactionPlanResult(r.message, new Error('Execution canceled'));\n * }\n * return r;\n * });\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function transformTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n fn: (plan: TransactionPlanResult) => TransactionPlanResult,\n): TransactionPlanResult {\n if (transactionPlanResult.kind === 'single') {\n return Object.freeze(fn(transactionPlanResult));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlanResult,\n plans: transactionPlanResult.plans.map(p => transformTransactionPlanResult(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleTransactionPlanResult} instances from a transaction plan result tree.\n *\n * This function recursively traverses any nested structure of transaction plan results and extracts\n * all the single results they contain. It's useful when you need to access all the individual\n * transaction results, regardless of their organization in the result tree (parallel or sequential).\n *\n * @param result - The transaction plan result to extract single results from\n * @returns An array of all single transaction plan results contained in the tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * sequentialTransactionPlanResult([resultA, resultB]),\n * nonDivisibleSequentialTransactionPlanResult([resultC, resultD]),\n * resultE,\n * ]);\n *\n * const singleResults = flattenTransactionPlanResult(result);\n * // Array of `SingleTransactionPlanResult` containing:\n * // resultA, resultB, resultC, resultD and resultE.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n */\nexport function flattenTransactionPlanResult(result: TransactionPlanResult): SingleTransactionPlanResult[] {\n if (result.kind === 'single') {\n return [result];\n }\n return result.plans.flatMap(flattenTransactionPlanResult);\n}\n\n/**\n * A {@link SingleTransactionPlanResult} with 'successful' status.\n */\nexport type SuccessfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = SingleTransactionPlanResult & { status: { kind: 'successful' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'failed' status.\n */\nexport type FailedSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'failed' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'canceled' status.\n */\nexport type CanceledSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'canceled' } };\n\n/**\n * A summary of a {@link TransactionPlanResult}, categorizing transactions by their execution status.\n * - `successful`: Indicates whether all transactions were successful (i.e., no failed or canceled transactions).\n * - `successfulTransactions`: An array of successful transactions, each including its signature.\n * - `failedTransactions`: An array of failed transactions, each including the error that caused the failure.\n * - `canceledTransactions`: An array of canceled transactions.\n */\nexport type TransactionPlanResultSummary = Readonly<{\n canceledTransactions: CanceledSingleTransactionPlanResult[];\n failedTransactions: FailedSingleTransactionPlanResult[];\n successful: boolean;\n successfulTransactions: SuccessfulSingleTransactionPlanResult[];\n}>;\n\n/**\n * Summarize a {@link TransactionPlanResult} into a {@link TransactionPlanResultSummary}.\n * @param result The transaction plan result to summarize\n * @returns A summary of the transaction plan result\n */\nexport function summarizeTransactionPlanResult(result: TransactionPlanResult): TransactionPlanResultSummary {\n const successfulTransactions: TransactionPlanResultSummary['successfulTransactions'] = [];\n const failedTransactions: TransactionPlanResultSummary['failedTransactions'] = [];\n const canceledTransactions: TransactionPlanResultSummary['canceledTransactions'] = [];\n\n const flattenedResults = flattenTransactionPlanResult(result);\n\n for (const singleResult of flattenedResults) {\n switch (singleResult.status.kind) {\n case 'successful': {\n successfulTransactions.push(singleResult as SuccessfulSingleTransactionPlanResult);\n break;\n }\n case 'failed': {\n failedTransactions.push(singleResult as FailedSingleTransactionPlanResult);\n break;\n }\n case 'canceled': {\n canceledTransactions.push(singleResult as CanceledSingleTransactionPlanResult);\n break;\n }\n }\n }\n\n return Object.freeze({\n canceledTransactions,\n failedTransactions,\n successful: failedTransactions.length === 0 && canceledTransactions.length === 0,\n successfulTransactions,\n });\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { getAbortablePromise } from '@solana/promises';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { Transaction } from '@solana/transactions';\n\nimport type {\n ParallelTransactionPlan,\n SequentialTransactionPlan,\n SingleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\nimport {\n canceledSingleTransactionPlanResult,\n failedSingleTransactionPlanResult,\n parallelTransactionPlanResult,\n sequentialTransactionPlanResult,\n SingleTransactionPlanResult,\n successfulSingleTransactionPlanResult,\n successfulSingleTransactionPlanResultFromSignature,\n type TransactionPlanResult,\n type TransactionPlanResultContext,\n} from './transaction-plan-result';\n\n/**\n * Executes a transaction plan and returns the execution results.\n *\n * This function traverses the transaction plan tree, executing each transaction\n * message and collecting results that mirror the structure of the original plan.\n *\n * @typeParam TContext - The type of the context object that may be passed along with successful results.\n * @param transactionPlan - The transaction plan to execute.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel execution.\n * @return A promise that resolves to the execution results.\n *\n * @see {@link TransactionPlan}\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutor = (\n transactionPlan: TransactionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\ntype ExecuteResult = {\n context?: TContext;\n} & ({ signature: Signature } | { transaction: Transaction });\n\ntype ExecuteTransactionMessage = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\n/**\n * Configuration object for creating a new transaction plan executor.\n *\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutorConfig = {\n /** Called whenever a transaction message must be sent to the blockchain. */\n executeTransactionMessage: ExecuteTransactionMessage;\n};\n\n/**\n * Creates a new transaction plan executor based on the provided configuration.\n *\n * The executor will traverse the provided `TransactionPlan` sequentially or in parallel,\n * executing each transaction message using the `executeTransactionMessage` function.\n *\n * - If that function is successful, the executor will return a successful `TransactionPlanResult`\n * for that message including the transaction and any custom context.\n * - If that function throws an error, the executor will stop processing and cancel all\n * remaining transaction messages in the plan.\n * - If the `abortSignal` is triggered, the executor will immediately stop processing the plan and\n * return a `TransactionPlanResult` with the status set to `canceled`.\n *\n * @param config - Configuration object containing the transaction message executor function.\n * @return A {@link TransactionPlanExecutor} function that can execute transaction plans.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * if any transaction in the plan fails to execute. The error context contains a\n * `transactionPlanResult` property with the partial results up to the point of failure.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED}\n * if the transaction plan contains non-divisible sequential plans, which are not\n * supported by this executor.\n *\n * @example\n * ```ts\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * const transactionPlanExecutor = createTransactionPlanExecutor({\n * executeTransactionMessage: async (message) => {\n * const transaction = await signTransactionMessageWithSigners(message);\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * return { transaction };\n * }\n * });\n * ```\n *\n * @see {@link TransactionPlanExecutorConfig}\n */\nexport function createTransactionPlanExecutor(config: TransactionPlanExecutorConfig): TransactionPlanExecutor {\n return async (plan, { abortSignal } = {}): Promise => {\n const context: TraverseContext = {\n ...config,\n abortSignal: abortSignal,\n canceled: abortSignal?.aborted ?? false,\n };\n\n // Fail early if there are non-divisible sequential plans in the\n // transaction plan as they are not supported by this executor.\n assertDivisibleSequentialPlansOnly(plan);\n\n const cancelHandler = () => {\n context.canceled = true;\n };\n abortSignal?.addEventListener('abort', cancelHandler);\n const transactionPlanResult = await traverse(plan, context);\n abortSignal?.removeEventListener('abort', cancelHandler);\n\n if (context.canceled) {\n const abortReason = abortSignal?.aborted ? abortSignal.reason : undefined;\n const context = { cause: findErrorFromTransactionPlanResult(transactionPlanResult) ?? abortReason };\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can create recovery plans but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, context);\n }\n\n return transactionPlanResult;\n };\n}\n\ntype TraverseContext = TransactionPlanExecutorConfig & {\n abortSignal?: AbortSignal;\n canceled: boolean;\n};\n\nasync function traverse(transactionPlan: TransactionPlan, context: TraverseContext): Promise {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(transactionPlan, context);\n case 'parallel':\n return await traverseParallel(transactionPlan, context);\n case 'single':\n return await traverseSingle(transactionPlan, context);\n default:\n transactionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n transactionPlan: SequentialTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n\n const results: TransactionPlanResult[] = [];\n\n for (const subPlan of transactionPlan.plans) {\n const result = await traverse(subPlan, context);\n results.push(result);\n }\n\n return sequentialTransactionPlanResult(results);\n}\n\nasync function traverseParallel(\n transactionPlan: ParallelTransactionPlan,\n context: TraverseContext,\n): Promise {\n const results = await Promise.all(transactionPlan.plans.map(plan => traverse(plan, context)));\n return parallelTransactionPlanResult(results);\n}\n\nasync function traverseSingle(\n transactionPlan: SingleTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (context.canceled) {\n return canceledSingleTransactionPlanResult(transactionPlan.message);\n }\n\n try {\n const result = await getAbortablePromise(\n context.executeTransactionMessage(transactionPlan.message, { abortSignal: context.abortSignal }),\n context.abortSignal,\n );\n if ('transaction' in result) {\n return successfulSingleTransactionPlanResult(transactionPlan.message, result.transaction, result.context);\n } else {\n return successfulSingleTransactionPlanResultFromSignature(\n transactionPlan.message,\n result.signature,\n result.context,\n );\n }\n } catch (error) {\n context.canceled = true;\n return failedSingleTransactionPlanResult(transactionPlan.message, error as Error);\n }\n}\n\nfunction findErrorFromTransactionPlanResult(result: TransactionPlanResult): Error | undefined {\n if (result.kind === 'single') {\n return result.status.kind === 'failed' ? result.status.error : undefined;\n }\n for (const plan of result.plans) {\n const error = findErrorFromTransactionPlanResult(plan);\n if (error) {\n return error;\n }\n }\n}\n\nfunction assertDivisibleSequentialPlansOnly(transactionPlan: TransactionPlan): void {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'parallel':\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'single':\n default:\n return;\n }\n}\n\n/**\n * Wraps a transaction plan execution promise to return a\n * {@link TransactionPlanResult} even on execution failure.\n *\n * When a transaction plan executor throws a\n * {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * error, this helper catches it and returns the `TransactionPlanResult`\n * from the error context instead of throwing.\n *\n * This allows us to handle the result of an execution in a single unified way\n * instead of using try/catch and examine the `TransactionPlanResult` in both\n * success and failure cases.\n *\n * Any other errors are re-thrown as normal.\n *\n * @param promise - A promise returned by a transaction plan executor.\n * @return A promise that resolves to the transaction plan result, even if some transactions failed.\n *\n * @example\n * Handling failures using a single result object:\n * ```ts\n * const result = await passthroughFailedTransactionPlanExecution(\n * transactionPlanExecutor(transactionPlan)\n * );\n *\n * const summary = summarizeTransactionPlanResult(result);\n * if (summary.successful) {\n * console.log('All transactions executed successfully');\n * } else {\n * console.log(`${summary.successfulTransactions.length} succeeded`);\n * console.log(`${summary.failedTransactions.length} failed`);\n * console.log(`${summary.canceledTransactions.length} canceled`);\n * }\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n * @see {@link summarizeTransactionPlanResult}\n */\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise {\n try {\n return await promise;\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN)) {\n return error.context.transactionPlanResult as TransactionPlanResult;\n }\n throw error;\n }\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { getAbortablePromise } from '@solana/promises';\nimport {\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\nimport {\n InstructionPlan,\n MessagePackerInstructionPlan,\n ParallelInstructionPlan,\n SequentialInstructionPlan,\n SingleInstructionPlan,\n} from './instruction-plan';\nimport {\n flattenTransactionPlan,\n nonDivisibleSequentialTransactionPlan,\n parallelTransactionPlan,\n sequentialTransactionPlan,\n SingleTransactionPlan,\n singleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\n\n/**\n * Plans one or more transactions according to the provided instruction plan.\n *\n * @param instructionPlan - The instruction plan to be planned and executed.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel the planning process.\n *\n * @see {@link InstructionPlan}\n * @see {@link TransactionPlan}\n */\nexport type TransactionPlanner = (\n instructionPlan: InstructionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise;\n\ntype Mutable = { -readonly [P in keyof T]: T[P] };\n\ntype CreateTransactionMessage = (config?: {\n abortSignal?: AbortSignal;\n}) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\ntype OnTransactionMessageUpdated = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\n/**\n * Configuration object for creating a new transaction planner.\n *\n * @see {@link createTransactionPlanner}\n */\nexport type TransactionPlannerConfig = {\n /** Called whenever a new transaction message is needed. */\n createTransactionMessage: CreateTransactionMessage;\n /**\n * Called whenever a transaction message is updated — e.g. new instructions were added.\n * This function must return the updated transaction message back — even if no changes were made.\n */\n onTransactionMessageUpdated?: OnTransactionMessageUpdated;\n};\n\n/**\n * Creates a new transaction planner based on the provided configuration.\n *\n * At the very least, the `createTransactionMessage` function must be provided.\n * This function is used to create new transaction messages whenever needed.\n *\n * Additionally, the `onTransactionMessageUpdated` function can be provided\n * to update transaction messages during the planning process. This function will\n * be called whenever a transaction message is updated, e.g. when new instructions\n * are added to a transaction message. It accepts the updated transaction message\n * and must return a transaction message back, even if no changes were made.\n *\n * @example\n * ```ts\n * const transactionPlanner = createTransactionPlanner({\n * createTransactionMessage: () => pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(mySigner, message),\n * )\n * });\n * ```\n *\n * @see {@link TransactionPlannerConfig}\n */\nexport function createTransactionPlanner(config: TransactionPlannerConfig): TransactionPlanner {\n return async (instructionPlan, { abortSignal } = {}): Promise => {\n const plan = await traverse(instructionPlan, {\n abortSignal,\n createTransactionMessage: config.createTransactionMessage,\n onTransactionMessageUpdated: config.onTransactionMessageUpdated ?? (msg => msg),\n parent: null,\n parentCandidates: [],\n });\n\n if (!plan) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN);\n }\n\n return freezeTransactionPlan(plan);\n };\n}\n\ntype MutableTransactionPlan = Mutable;\ntype MutableSingleTransactionPlan = Mutable;\n\ntype TraverseContext = {\n abortSignal?: AbortSignal;\n createTransactionMessage: CreateTransactionMessage;\n onTransactionMessageUpdated: OnTransactionMessageUpdated;\n parent: InstructionPlan | null;\n parentCandidates: MutableSingleTransactionPlan[];\n};\n\nasync function traverse(\n instructionPlan: InstructionPlan,\n context: TraverseContext,\n): Promise {\n context.abortSignal?.throwIfAborted();\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(instructionPlan, context);\n case 'parallel':\n return await traverseParallel(instructionPlan, context);\n case 'single':\n return await traverseSingle(instructionPlan, context);\n case 'messagePacker':\n return await traverseMessagePacker(instructionPlan, context);\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n instructionPlan: SequentialInstructionPlan,\n context: TraverseContext,\n): Promise {\n let candidate: MutableSingleTransactionPlan | null = null;\n\n // Check if the sequential plan must fit entirely in its parent candidates\n // due to constraints like being inside a parallel plan or not being divisible.\n const mustEntirelyFitInParentCandidate =\n context.parent && (context.parent.kind === 'parallel' || !instructionPlan.divisible);\n\n // If so, try to fit the entire plan inside one of the parent candidates.\n if (mustEntirelyFitInParentCandidate) {\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, message =>\n fitEntirePlanInsideMessage(instructionPlan, message),\n );\n // If that's possible, we the candidate is mutated and we can return null.\n // Otherwise, we proceed with the normal traversal and no parent candidate.\n if (candidate) {\n return null;\n }\n } else {\n // Otherwise, we can use the first parent candidate, if any,\n // since we know it must be a divisible sequential plan.\n candidate = context.parentCandidates.length > 0 ? context.parentCandidates[0] : null;\n }\n\n const transactionPlans: TransactionPlan[] = [];\n for (const plan of instructionPlan.plans) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidate ? [candidate] : [],\n });\n if (transactionPlan) {\n candidate = getSequentialCandidate(transactionPlan);\n const newPlans =\n transactionPlan.kind === 'sequential' && (transactionPlan.divisible || !instructionPlan.divisible)\n ? transactionPlan.plans\n : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a sequential plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return {\n divisible: instructionPlan.divisible,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nasync function traverseParallel(\n instructionPlan: ParallelInstructionPlan,\n context: TraverseContext,\n): Promise {\n const candidates: MutableSingleTransactionPlan[] = [...context.parentCandidates];\n const transactionPlans: TransactionPlan[] = [];\n\n // Reorder children so message packer plans are last.\n const sortedChildren = Array.from(instructionPlan.plans).sort(\n (a, b) => Number(a.kind === 'messagePacker') - Number(b.kind === 'messagePacker'),\n );\n\n for (const plan of sortedChildren) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidates,\n });\n if (transactionPlan) {\n candidates.push(...getParallelCandidates(transactionPlan));\n const newPlans = transactionPlan.kind === 'parallel' ? transactionPlan.plans : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a parallel plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return { kind: 'parallel', plans: transactionPlans };\n}\n\nasync function traverseSingle(\n instructionPlan: SingleInstructionPlan,\n context: TraverseContext,\n): Promise {\n const predicate = (message: TransactionMessage & TransactionMessageWithFeePayer) =>\n appendTransactionMessageInstructions([instructionPlan.instruction], message);\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, predicate);\n if (candidate) {\n return null;\n }\n const message = await createNewMessage(context, predicate);\n return { kind: 'single', message };\n}\n\nasync function traverseMessagePacker(\n instructionPlan: MessagePackerInstructionPlan,\n context: TraverseContext,\n): Promise {\n const messagePacker = instructionPlan.getMessagePacker();\n const transactionPlans: SingleTransactionPlan[] = [];\n const candidates = [...context.parentCandidates];\n\n while (!messagePacker.done()) {\n const candidate = await selectAndMutateCandidate(context, candidates, messagePacker.packMessageToCapacity);\n if (!candidate) {\n const message = await createNewMessage(context, messagePacker.packMessageToCapacity);\n const newPlan: MutableSingleTransactionPlan = { kind: 'single', message };\n transactionPlans.push(newPlan);\n }\n }\n\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n if (context.parent?.kind === 'parallel') {\n return { kind: 'parallel', plans: transactionPlans };\n }\n return {\n divisible: context.parent?.kind === 'sequential' ? context.parent.divisible : true,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nfunction getSequentialCandidate(latestPlan: MutableTransactionPlan): MutableSingleTransactionPlan | null {\n if (latestPlan.kind === 'single') {\n return latestPlan;\n }\n if (latestPlan.kind === 'sequential' && latestPlan.plans.length > 0) {\n return getSequentialCandidate(latestPlan.plans[latestPlan.plans.length - 1]);\n }\n return null;\n}\n\nfunction getParallelCandidates(latestPlan: TransactionPlan): MutableSingleTransactionPlan[] {\n return flattenTransactionPlan(latestPlan);\n}\n\nasync function selectAndMutateCandidate(\n context: Pick,\n candidates: MutableSingleTransactionPlan[],\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n for (const candidate of candidates) {\n try {\n const message = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(candidate.message), {\n abortSignal: context.abortSignal,\n }),\n ),\n context.abortSignal,\n );\n if (getTransactionMessageSize(message) <= TRANSACTION_SIZE_LIMIT) {\n candidate.message = message;\n return candidate;\n }\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN)) {\n // Try the next candidate.\n } else {\n throw error;\n }\n }\n }\n return null;\n}\n\nasync function createNewMessage(\n context: Pick,\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n const newMessage = await getAbortablePromise(\n Promise.resolve(context.createTransactionMessage({ abortSignal: context.abortSignal })),\n context.abortSignal,\n );\n const updatedMessage = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(newMessage), { abortSignal: context.abortSignal }),\n ),\n context.abortSignal,\n );\n const updatedMessageSize = getTransactionMessageSize(updatedMessage);\n if (updatedMessageSize > TRANSACTION_SIZE_LIMIT) {\n const newMessageSize = getTransactionMessageSize(newMessage);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: updatedMessageSize - newMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - newMessageSize,\n });\n }\n return updatedMessage;\n}\n\nfunction freezeTransactionPlan(plan: MutableTransactionPlan): TransactionPlan {\n const kind = plan.kind;\n switch (kind) {\n case 'single':\n return singleTransactionPlan(plan.message);\n case 'sequential':\n return plan.divisible\n ? sequentialTransactionPlan(plan.plans.map(freezeTransactionPlan))\n : nonDivisibleSequentialTransactionPlan(plan.plans.map(freezeTransactionPlan));\n case 'parallel':\n return parallelTransactionPlan(plan.plans.map(freezeTransactionPlan));\n default:\n plan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nfunction fitEntirePlanInsideMessage(\n instructionPlan: InstructionPlan,\n message: TransactionMessage & TransactionMessageWithFeePayer,\n): TransactionMessage & TransactionMessageWithFeePayer {\n let newMessage: TransactionMessage & TransactionMessageWithFeePayer = message;\n\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n case 'parallel':\n for (const plan of instructionPlan.plans) {\n newMessage = fitEntirePlanInsideMessage(plan, newMessage);\n }\n return newMessage;\n case 'single':\n newMessage = appendTransactionMessageInstructions([instructionPlan.instruction], message);\n // eslint-disable-next-line no-case-declarations\n const newMessageSize = getTransactionMessageSize(newMessage);\n if (newMessageSize > TRANSACTION_SIZE_LIMIT) {\n const baseMessageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: newMessageSize - baseMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - baseMessageSize,\n });\n }\n return newMessage;\n case 'messagePacker':\n // eslint-disable-next-line no-case-declarations\n const messagePacker = instructionPlan.getMessagePacker();\n while (!messagePacker.done()) {\n newMessage = messagePacker.packMessageToCapacity(newMessage);\n }\n return newMessage;\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n","import { assertIsAddress, isAddress } from '@solana/addresses';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * A 32-byte array identifying the application requesting off-chain message signing.\n *\n * This may be any arbitrary bytes. For instance the on-chain address of a program, DAO instance,\n * Candy Machine, et cetera.\n *\n * This field SHOULD be displayed to users as a base58-encoded ASCII string rather than interpreted\n * otherwise.\n */\nexport type OffchainMessageApplicationDomain = Brand<\n EncodedString,\n 'OffchainMessageApplicationDomain'\n>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the\n * {@link OffchainMessageApplicationDomain} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * if (isOffchainMessageApplicationDomain(applicationDomain)) {\n * // At this point, `applicationDomain` has been refined to an\n * // `OffchainMessageApplcationDomain` that can be used to craft a message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } else {\n * setError(`${applicationDomain} is not a valid application domain for an offchain message`);\n * }\n * ```\n */\nexport function isOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): putativeApplicationDomain is OffchainMessageApplicationDomain {\n return isAddress(putativeApplicationDomain);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an offchain message\n * application domain, from an untrusted network API or user input. Use this function to assert that\n * such an arbitrary string is a base58-encoded application domain.\n *\n * @example\n * ```ts\n * import { assertIsOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * // Imagine a function that determines whether an application domain is valid.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const applicationDomain: string = applicationDomainInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `applicationDomain` to `OffchainMessageApplicationDomain`.\n * assertIsOffchainMessageApplicationDomain(applicationDomain);\n * // At this point, `applicationDomain` is a `OffchainMessageApplicationDomain` that can be\n * // used to craft an offchain message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } catch (e) {\n * // `applicationDomain` turned out not to be a base58-encoded application domain\n * }\n * }\n * ```\n */\nexport function assertIsOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): asserts putativeApplicationDomain is OffchainMessageApplicationDomain {\n try {\n assertIsAddress(putativeApplicationDomain);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n error.context,\n );\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n error.context,\n );\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is an offchain message application domain with _coercing_ it\n * to the {@link OffchainMessageApplicationDomain} type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good application domain as a string, it's more efficient to typecast\n * > it rather than to use the {@link offchainMessageApplicationDomain} helper, because the helper\n * > unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageApplicationDomain } from '@solana/offchain-messages';\n * >\n * > const applicationDomain =\n * > 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * > ```\n */\nexport function offchainMessageApplicationDomain(putativeApplicationDomain: string): OffchainMessageApplicationDomain {\n assertIsOffchainMessageApplicationDomain(putativeApplicationDomain);\n return putativeApplicationDomain;\n}\n","import { Address, getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformEncoder,\n} from '@solana/codecs-core';\n\nimport { OffchainMessageApplicationDomain, offchainMessageApplicationDomain } from '../application-domain';\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded offchain message application\n * domain to a byte array.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainEncoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomain =\n * 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * const offchainMessageApplicationDomainEncoder = getOffchainMessageApplicationDomainEncoder();\n * const offchainMessageApplicationDomainBytes =\n * offchainMessageApplicationDomainEncoder.encode(offchainMessageApplicationDomain);\n * // Uint8Array(32) [\n * // 247, 203, 28, 80, 52, 240, 169, 19,\n * // 21, 103, 107, 119, 91, 235, 13, 48,\n * // 194, 169, 148, 160, 78, 105, 235, 37,\n * // 232, 160, 49, 47, 64, 89, 18, 153,\n * // ]\n * ```\n */\nexport function getOffchainMessageApplicationDomainEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getAddressEncoder(),\n putativeApplicationDomain => offchainMessageApplicationDomain(putativeApplicationDomain) as string as Address,\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an offchain\n * message application domain to the base58-encoded representation of that application domain.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomainBytes = new Uint8Array([\n * 247, 203, 28, 80, 52, 240, 169, 19,\n * 21, 103, 107, 119, 91, 235, 13, 48,\n * 194, 169, 148, 160, 78, 105, 235, 37,\n * 232, 160, 49, 47, 64, 89, 18, 153,\n * ]);\n * const offchainMessageApplicationDomainDecoder = getOffchainMessageApplicationDomainDecoder();\n * const offchainMessageApplicationDomain =\n * offchainMessageApplicationDomainDecoder.decode(offchainMessageApplicationDomainBytes);\n * // HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx\n * ```\n */\nexport function getOffchainMessageApplicationDomainDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder<\n OffchainMessageApplicationDomain,\n 32\n >;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded offchain message\n * application domain.\n *\n * @see {@link getOffchainMessageApplicationDomainDecoder}\n * @see {@link getOffchainMessageApplicationDomainEncoder}\n */\nexport function getOffchainMessageApplicationDomainCodec(): FixedSizeCodec<\n OffchainMessageApplicationDomain,\n OffchainMessageApplicationDomain,\n 32\n> {\n return combineCodec(getOffchainMessageApplicationDomainEncoder(), getOffchainMessageApplicationDomainDecoder());\n}\n","import {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getConstantDecoder, getConstantEncoder } from '@solana/codecs-data-structures';\n\n// The string `'\\xffsolana offchain'`\nconst OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES: ReadonlyUint8Array = new Uint8Array([\n 0xff, 0x73, 0x6f, 0x6c, 0x61, 0x6e, 0x61, 0x20, 0x6f, 0x66, 0x66, 0x63, 0x68, 0x61, 0x69, 0x6e,\n]);\n\nexport function getOffchainMessageSigningDomainDecoder(): FixedSizeDecoder {\n return getConstantDecoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeDecoder;\n}\n\nexport function getOffchainMessageSigningDomainEncoder(): FixedSizeEncoder {\n return getConstantEncoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeEncoder;\n}\n\nexport function getOffchainMessageSigningDomainCodec(): FixedSizeCodec {\n return combineCodec(getOffchainMessageSigningDomainEncoder(), getOffchainMessageSigningDomainDecoder());\n}\n","import { Address, getAddressDecoder } from '@solana/addresses';\nimport {\n FixedSizeDecoder,\n FixedSizeEncoder,\n offsetDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageVersion } from '../version';\nimport { getOffchainMessageSigningDomainDecoder, getOffchainMessageSigningDomainEncoder } from './signing-domain';\n\ntype TDecoderFields = Parameters[0];\ntype TEncoderFields = Parameters[0];\n\nfunction getSigningDomainPrefixedDecoder(...fields: T) {\n return getHiddenPrefixDecoder(getStructDecoder(fields), [getOffchainMessageSigningDomainDecoder()]);\n}\n\nfunction getSigningDomainPrefixedEncoder(...fields: T) {\n return getHiddenPrefixEncoder(getStructEncoder(fields), [getOffchainMessageSigningDomainEncoder()]);\n}\n\nfunction getVersionTransformer(fixedVersion?: OffchainMessageVersion) {\n return (version: number) => {\n if (version > 1) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n if (fixedVersion != null && version !== fixedVersion) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION, {\n actualVersion: version,\n expectedVersion: fixedVersion,\n });\n }\n return version;\n };\n}\n\nexport function createOffchainMessagePreambleDecoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TDecoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer(version)) as FixedSizeDecoder],\n ...fields,\n );\n}\n\nexport function createOffchainMessagePreambleEncoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TEncoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedEncoder(\n ['version', transformEncoder(getU8Encoder(), getVersionTransformer(version)) as FixedSizeEncoder],\n ...fields,\n );\n}\n\nexport function decodeRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const { version, bytesAfterVersion } = getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer())],\n ['bytesAfterVersion', getBytesDecoder()],\n ).decode(bytes);\n return offsetDecoder(\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses;\n }),\n {\n preOffset: ({ preOffset }) =>\n preOffset +\n (version === 0\n ? 32 + 1 // skip the application domain and message format of v0 messages\n : 0),\n },\n ).decode(bytesAfterVersion);\n}\n\nexport function getSignatoriesComparator(): (a: ReadonlyUint8Array, b: ReadonlyUint8Array) => -1 | 0 | 1 {\n return (x, y) => {\n if (x.length !== y.length) {\n return x.length < y.length ? -1 : 1;\n }\n for (let ii = 0; ii < x.length; ii++) {\n if (x[ii] === y[ii]) {\n continue;\n } else {\n return x[ii] < y[ii] ? -1 : 1;\n }\n }\n return 0;\n };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\n\nfunction getSignaturesToEncode(signaturesMap: OffchainMessageEnvelope['signatures']): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getU8Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { Address, address } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\nimport { OffchainMessageBytes } from '../message';\nimport { decodeRequiredSignatoryAddresses } from './preamble-common';\nimport { getSignaturesEncoder } from './signatures';\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageEnvelope} to a byte array\n * appropriate for sharing with a third party for validation.\n */\nexport function getOffchainMessageEnvelopeEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['content', getBytesEncoder()],\n ]),\n envelope => {\n const signaturesMapAddresses = Object.keys(envelope.signatures).map(address);\n if (signaturesMapAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(envelope.content);\n const missingRequiredSigners = [];\n const unexpectedSigners = [];\n for (const address of signatoryAddresses) {\n if (!signaturesMapAddresses.includes(address)) {\n missingRequiredSigners.push(address);\n }\n }\n for (const address of signaturesMapAddresses) {\n if (!signatoryAddresses.includes(address)) {\n unexpectedSigners.push(address);\n }\n }\n if (missingRequiredSigners.length || unexpectedSigners.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH, {\n missingRequiredSigners,\n unexpectedSigners,\n });\n }\n const orderedSignatureMap: OffchainMessageEnvelope['signatures'] = {};\n for (const address of signatoryAddresses) {\n orderedSignatureMap[address] = envelope.signatures[address];\n }\n return {\n ...envelope,\n signatures: orderedSignatureMap,\n };\n },\n );\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana offchain message format\n * to a {@link OffchainMessageEnvelope} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageEnvelopeDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelopeDecoder = getOffchainMessageEnvelopeDecoder();\n * const offchainMessageEnvelope = offchainMessageEnvelopeDecoder.decode(offchainMessageEnvelopeBytes);\n * for (const [address, signature] in Object.entries(offchainMessageEnvelope.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\nexport function getOffchainMessageEnvelopeDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getU8Decoder() })],\n ['content', getBytesDecoder()],\n ]),\n decodePartiallyDecodedOffchainMessageEnvelope,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageEnvelope}\n *\n * @see {@link getOffchainMessageEnvelopeDecoder}\n * @see {@link getOffchainMessageEnvelopeEncoder}\n */\nexport function getOffchainMessageEnvelopeCodec() {\n return combineCodec(getOffchainMessageEnvelopeEncoder(), getOffchainMessageEnvelopeDecoder());\n}\n\ntype PartiallyDecodedOffchainMessageEnvelope = {\n content: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedOffchainMessageEnvelope(\n offchainMessageEnvelope: PartiallyDecodedOffchainMessageEnvelope,\n): OffchainMessageEnvelope {\n const { content, signatures } = offchainMessageEnvelope;\n\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(content);\n\n // Signer addresses and signatures must be the same length\n // We encode an all-zero signature when the signature is missing\n if (signatoryAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH, {\n numRequiredSignatures: signatoryAddresses.length,\n signatoryAddresses,\n signaturesLength: signatures.length,\n });\n }\n\n // Combine the signer addresses + signatures into the signatures map\n const signaturesMap: OffchainMessageEnvelope['signatures'] = {};\n signatoryAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return Object.freeze({\n content: content as OffchainMessageBytes,\n signatures: Object.freeze(signaturesMap),\n });\n}\n\nfunction decodeAndValidateRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const signatoryAddresses = decodeRequiredSignatoryAddresses(bytes);\n\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n\n return signatoryAddresses;\n}\n","import { getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nconst MAX_BODY_BYTES =\n // Largest 16-bit unsigned integer\n 0xffff;\nconst MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE =\n // Space remaining in the mininum IPv6 MTU after network header overhead\n 1232;\n\n/**\n * A restriction on what characters the message text can contain and how long it can be.\n *\n * The aim of this restriction is to make a message more likely to be signable by a hardware wallet\n * that imposes limits on message size. In the case of wanting a message to be clear-signable,\n * restricting the character set to ASCII may ensure that certain models of hardware wallet without\n * extended character sets can display it onscreen.\n *\n * @remarks This only applies to v0 messages.\n */\nexport enum OffchainMessageContentFormat {\n RESTRICTED_ASCII_1232_BYTES_MAX = 0,\n UTF8_1232_BYTES_MAX = 1,\n UTF8_65535_BYTES_MAX = 2,\n}\n\n/**\n * Describes message text that is no more than 1232 bytes long and made up of characters with ASCII\n * character codes in the range [0x20, 0x7e].\n *\n * @remarks This type aims to restrict text to that which can be clear-signed by hardware wallets\n * that can only display ASCII characters onscreen.\n */\nexport type OffchainMessageContentRestrictedAsciiOf1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 1232 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 65535 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of65535BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX;\n text: Brand;\n}>;\n\nexport type OffchainMessageContent =\n | OffchainMessageContentRestrictedAsciiOf1232BytesMax\n | OffchainMessageContentUtf8Of1232BytesMax\n | OffchainMessageContentUtf8Of65535BytesMax;\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (isTextRestrictedAscii(putativeContent.text) === false) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX ||\n putativeContent.text.length === 0 ||\n isTextRestrictedAscii(putativeContent.text) === false\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is restricted ASCII with\n * _coercing_ it to the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type. It's most\n * useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageContentRestrictedAsciiOf1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: offchainMessageContentRestrictedAsciiOf1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentRestrictedAsciiOf1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good ASCII content as a string, it's more efficient to typecast it\n * > rather than to use the {@link offchainMessageContentRestrictedAsciiOf1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n * > text: 'Hello world',\n * > } as OffchainMessageContentRestrictedAsciiOf1232BytesMax<'Hello world'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentRestrictedAsciiOf1232BytesMax(\n text: TText,\n): OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n });\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 1232 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of1232BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 1232 bytes, it's more efficient\n * > to typecast it rather than to use the {@link offchainMessageContentUtf8Of1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of1232BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of1232BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of65535BytesMax}\n * type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of65535BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 65535 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of65535BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of65535BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of65535BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of65535BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 65535 bytes, it's more efficient\n * > to typecast it rather than to use the {@link OffchainMessageContentUtf8Of65535BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of65535BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of65535BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of65535BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent);\n return putativeContent;\n}\n\nfunction isTextRestrictedAscii(putativeRestrictedAsciiString: string): boolean {\n return /^[\\x20-\\x7e]+$/.test(putativeRestrictedAsciiString);\n}\n","import {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageContentUtf8Of1232BytesMax,\n assertIsOffchainMessageContentUtf8Of65535BytesMax,\n OffchainMessageContentFormat,\n OffchainMessageContentRestrictedAsciiOf1232BytesMax,\n OffchainMessageContentUtf8Of1232BytesMax,\n OffchainMessageContentUtf8Of65535BytesMax,\n} from './content';\nimport { OffchainMessagePreambleV0 } from './preamble-v0';\nimport { OffchainMessageWithRequiredSignatories } from './signatures';\n\nexport type BaseOffchainMessageV0 = Omit<\n OffchainMessagePreambleV0,\n 'messageFormat' | 'messageLength' | 'requiredSignatories'\n>;\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax}\n */\nexport interface OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent {\n readonly content: OffchainMessageContentRestrictedAsciiOf1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link offchainMessageContentUtf8Of1232BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of1232BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentUtf8Of65535BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of65535BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of65535BytesMax;\n}\n\n/**\n * A union of the formats a v0 message's contents can take.\n *\n * @remarks From v1 and onward, an offchain message has only one format: UTF-8 text of arbitrary\n * length.\n */\nexport type OffchainMessageWithContent =\n | OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent\n | OffchainMessageWithUtf8Of1232BytesMaxContent\n | OffchainMessageWithUtf8Of65535BytesMaxContent;\n\nexport type OffchainMessageV0 = BaseOffchainMessageV0 &\n OffchainMessageWithContent &\n OffchainMessageWithRequiredSignatories;\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }>,\n): asserts putativeMessage is OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link offchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link offchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentUtf8Of65535BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of65535BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of65535BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeMessage.content);\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getEnumDecoder, getEnumEncoder } from '@solana/codecs-data-structures';\n\nimport { OffchainMessageContentFormat } from '../content';\n\nexport function getOffchainMessageContentFormatDecoder(): FixedSizeDecoder {\n return getEnumDecoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatEncoder(): FixedSizeEncoder {\n return getEnumEncoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatCodec(): FixedSizeCodec<\n OffchainMessageContentFormat,\n OffchainMessageContentFormat,\n 1\n> {\n return combineCodec(getOffchainMessageContentFormatEncoder(), getOffchainMessageContentFormatDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder, getU16Decoder, getU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\n\nimport { OffchainMessagePreambleV0 } from '../preamble-v0';\nimport {\n getOffchainMessageApplicationDomainDecoder,\n getOffchainMessageApplicationDomainEncoder,\n} from './application-domain';\nimport { getOffchainMessageContentFormatDecoder, getOffchainMessageContentFormatEncoder } from './content';\nimport { createOffchainMessagePreambleDecoder, createOffchainMessagePreambleEncoder } from './preamble-common';\n\nexport function getOffchainMessageV0PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainDecoder()],\n ['messageFormat', getOffchainMessageContentFormatDecoder()],\n [\n 'requiredSignatories',\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(address => Object.freeze({ address }));\n }),\n ],\n ['messageLength', getU16Decoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainEncoder()],\n ['messageFormat', getOffchainMessageContentFormatEncoder()],\n [\n 'requiredSignatories',\n transformEncoder(\n getArrayEncoder(getAddressEncoder(), { size: getU8Encoder() }),\n (signatoryAddresses: OffchainMessagePreambleV0['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(({ address }) => address);\n },\n ),\n ],\n ['messageLength', getU16Encoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0PreambleEncoder(), getOffchainMessageV0PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageContentFormat } from '../content';\nimport {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageUtf8Of1232BytesMax,\n assertIsOffchainMessageUtf8Of65535BytesMax,\n OffchainMessageV0,\n} from '../message-v0';\nimport { getOffchainMessageV0PreambleDecoder, getOffchainMessageV0PreambleEncoder } from './preamble-v0';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV0} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV0Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV0Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v0 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 0.\n */\nexport function getOffchainMessageV0Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV0PreambleDecoder(), getUtf8Decoder()]),\n ([{ messageLength, messageFormat, requiredSignatories, ...preambleRest }, text]) => {\n const actualLength = getUtf8Encoder().getSizeFromValue(text);\n if (messageLength !== actualLength) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH, {\n actualLength: actualLength,\n specifiedLength: messageLength,\n });\n }\n const offchainMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }> = Object.freeze({\n ...preambleRest,\n content: Object.freeze({\n format: messageFormat,\n text,\n }),\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n switch (messageFormat) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n return offchainMessage;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: messageFormat satisfies never,\n });\n }\n }\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV0} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV0Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV0PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...preamble } = offchainMessage;\n switch (offchainMessage.content.format) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n break;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: offchainMessage.content satisfies never,\n });\n }\n }\n const messageLength = getUtf8Encoder().getSizeFromValue(content.text);\n const compiledPreamble = {\n ...preamble,\n messageFormat: content.format,\n messageLength,\n };\n return [compiledPreamble, content.text] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV0}\n *\n * @see {@link getOffchainMessageV0Decoder}\n * @see {@link getOffchainMessageV0Encoder}\n */\nexport function getOffchainMessageV0Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0Encoder(), getOffchainMessageV0Decoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getBytesDecoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessagePreambleV1 } from '../preamble-v1';\nimport {\n createOffchainMessagePreambleDecoder,\n createOffchainMessagePreambleEncoder,\n getSignatoriesComparator,\n} from './preamble-common';\n\nexport function getOffchainMessageV1PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(/* version */ 1, [\n 'requiredSignatories',\n transformDecoder(\n getArrayDecoder(fixDecoderSize(getBytesDecoder(), 32), { size: getU8Decoder() }),\n signatoryAddressesBytes => {\n if (signatoryAddressesBytes.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const comparator = getSignatoriesComparator();\n for (let ii = 0; ii < signatoryAddressesBytes.length - 1; ii++) {\n switch (comparator(signatoryAddressesBytes[ii], signatoryAddressesBytes[ii + 1])) {\n case 0:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n case 1:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED);\n }\n }\n const addressDecoder = getAddressDecoder();\n return signatoryAddressesBytes.map(addressBytes =>\n Object.freeze({\n address: addressDecoder.decode(addressBytes),\n }),\n );\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(/* version */ 1, [\n 'requiredSignatories',\n transformEncoder(\n transformEncoder(\n getArrayEncoder(getBytesEncoder(), { size: getU8Encoder() }),\n (signatoryAddressesBytes: readonly ReadonlyUint8Array[]) => {\n return signatoryAddressesBytes.toSorted(getSignatoriesComparator());\n },\n ),\n (signatoryAddresses: OffchainMessagePreambleV1['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const seenSignatories = new Set();\n for (const { address } of signatoryAddresses) {\n if (seenSignatories.has(address)) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n }\n seenSignatories.add(address);\n }\n const addressEncoder = getAddressEncoder();\n return signatoryAddresses.map(({ address }) => addressEncoder.encode(address));\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1PreambleEncoder(), getOffchainMessageV1PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY, SolanaError } from '@solana/errors';\n\nimport { OffchainMessageV1 } from '../message-v1';\nimport { getOffchainMessageV1PreambleDecoder, getOffchainMessageV1PreambleEncoder } from './preamble-v1';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV1} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV1Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV1Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v1 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 1.\n */\nexport function getOffchainMessageV1Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV1PreambleDecoder(), getUtf8Decoder()]),\n ([{ requiredSignatories, ...preambleRest }, text]) => {\n if (text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return Object.freeze({\n ...preambleRest,\n content: text,\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV1} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV1Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV1PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...compiledPreamble } = offchainMessage;\n if (content.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return [compiledPreamble, content] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV1}\n *\n * @see {@link getOffchainMessageV1Decoder}\n * @see {@link getOffchainMessageV1Encoder}\n */\nexport function getOffchainMessageV1Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1Encoder(), getOffchainMessageV1Decoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getHiddenPrefixDecoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, SolanaError } from '@solana/errors';\n\nimport { OffchainMessage } from '../message';\nimport { getOffchainMessageV0Decoder, getOffchainMessageV0Encoder } from './message-v0';\nimport { getOffchainMessageV1Decoder, getOffchainMessageV1Encoder } from './message-v1';\nimport { getOffchainMessageSigningDomainDecoder } from './signing-domain';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessage} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageDecoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded an offchain message (version: ${offchainMessage.version}`);\n * ```\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the decoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageDecoder(): VariableSizeDecoder {\n return createDecoder({\n read(bytes, offset): [OffchainMessage, number] {\n const version = getHiddenPrefixDecoder(getU8Decoder(), [\n // Discard the signing domain\n getOffchainMessageSigningDomainDecoder(),\n ]).decode(bytes, offset);\n switch (version) {\n case 0:\n return getOffchainMessageV0Decoder().read(bytes, offset);\n case 1:\n return getOffchainMessageV1Decoder().read(bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n },\n });\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessage} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the encoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: offchainMessage => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().getSizeFromValue(offchainMessage);\n case 1:\n return getOffchainMessageV1Encoder().getSizeFromValue(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n write: (offchainMessage, bytes, offset) => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().write(offchainMessage, bytes, offset);\n case 1:\n return getOffchainMessageV1Encoder().write(offchainMessage, bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessage}\n *\n * @see {@link getOffchainMessageDecoder}\n * @see {@link getOffchainMessageEncoder}\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the codecs specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageEncoder(), getOffchainMessageDecoder());\n}\n","import { VariableSizeEncoder } from '@solana/codecs-core';\n\nimport { OffchainMessageEnvelope } from './envelope';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\nexport function compileOffchainMessageEnvelopeUsingEncoder(\n offchainMessage: T,\n encoder: VariableSizeEncoder,\n) {\n const offchainMessageBytes = encoder.encode(offchainMessage) as OffchainMessageBytes;\n const signatures: OffchainMessageEnvelope['signatures'] = {};\n for (const { address } of offchainMessage.requiredSignatories) {\n signatures[address] = null;\n }\n return Object.freeze({\n content: offchainMessageBytes,\n signatures: Object.freeze(signatures),\n });\n}\n","import { getOffchainMessageV0Encoder } from './codecs/message-v0';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV0 } from './message-v0';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV0}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV0Envelope(offchainMessage: OffchainMessageV0): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV0Encoder());\n}\n","import { getOffchainMessageV1Encoder } from './codecs/message-v1';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV1 } from './message-v1';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV1}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV1Envelope(offchainMessage: OffchainMessageV1): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV1Encoder());\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { compileOffchainMessageV0Envelope } from './envelope-v0';\nimport { compileOffchainMessageV1Envelope } from './envelope-v1';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\ntype OrderedMap = Record;\ntype OffchainMessageSignaturesMap = OrderedMap;\n\nexport interface OffchainMessageEnvelope {\n /** The bytes of the combined offchain message preamble and content */\n readonly content: OffchainMessageBytes;\n /**\n * A map between the addresses of an offchain message's signers, and the 64-byte Ed25519\n * signature of the combined message preamble and message content by the private key associated\n * with each.\n */\n readonly signatures: OffchainMessageSignaturesMap;\n}\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessage}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the compile functions\n * specific to that version so as not to bundle more code than you need.\n */\nexport function compileOffchainMessageEnvelope(offchainMessage: OffchainMessage): OffchainMessageEnvelope {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return compileOffchainMessageV0Envelope(offchainMessage);\n case 1:\n return compileOffchainMessageV1Envelope(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: version satisfies never,\n });\n }\n}\n","import { Address, getAddressFromPublicKey, getPublicKeyFromAddress } from '@solana/addresses';\nimport { bytesEqual } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes, signBytes, verifySignature } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { decodeRequiredSignatoryAddresses } from './codecs/preamble-common';\nimport { OffchainMessageEnvelope } from './envelope';\n\n/**\n * Represents an offchain message envelope that is signed by all of its required signers.\n */\nexport type FullySignedOffchainMessageEnvelope = NominalType<'offchainMessageEnvelopeSignedness', 'fullySigned'>;\n\n/**\n * Represents an address that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatory = Readonly<{\n address: Address;\n}>;\n\n/**\n * An offchain message having a list of accounts that must sign it in order for it to be valid.\n */\nexport interface OffchainMessageWithRequiredSignatories<\n TSignatory extends OffchainMessageSignatory = OffchainMessageSignatory,\n> {\n requiredSignatories: readonly TSignatory[];\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message, this method will return a new signed offchain message\n * envelope of type {@link OffchainMessageEnvelope}.\n *\n * Though the resulting message might be signed by all required signers, this function will not\n * assert that it is. A partially signed message is not complete, but can be serialized and\n * deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const partiallySignedOffchainMessage = await partiallySignOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link signOffchainMessageEnvelope} if you want to assert that the message is signed by all\n * its required signers after signing.\n */\nexport async function partiallySignOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n const requiredSignatoryAddresses = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n\n // Check if the address is expected to sign the message\n if (!requiredSignatoryAddresses.includes(address)) {\n // address is not an expected signer for this message\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const existingSignature = offchainMessageEnvelope.signatures[address];\n const newSignature = await signBytes(keyPair.privateKey, offchainMessageEnvelope.content);\n\n if (existingSignature != null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE, {\n expectedAddresses: requiredSignatoryAddresses,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return offchainMessageEnvelope;\n }\n\n return Object.freeze({\n ...offchainMessageEnvelope,\n signatures: Object.freeze({\n ...offchainMessageEnvelope.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message envelope, this method will return a new signed envelope of\n * type {@link FullySignedOffchainMessageEnvelope}.\n *\n * This function will throw unless the resulting message is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const signedOffchainMessage = await signOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link partiallySignOffchainMessageEnvelope} if you want to sign the message without\n * asserting that the resulting message envelope is fully signed.\n */\nexport async function signOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n const out = await partiallySignOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope);\n assertIsFullySignedOffchainMessageEnvelope(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * A type guard that returns `true` if the input {@link OffchainMessageEnvelope} is fully signed,\n * and refines its type for use in your program, adding the\n * {@link FullySignedOffchainMessageEnvelope} type.\n *\n * @example\n * ```ts\n * import { isFullySignedOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * if (isFullySignedOffchainMessageEnvelope(offchainMessageEnvelope)) {\n * // At this point we know that the offchain message is fully signed.\n * }\n * ```\n */\nexport function isFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n return Object.entries(offchainMessage.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link OffchainMessageEnvelope}, that you expect to be\n * fully signed, from an untrusted network API or user input. Use this function to assert that such\n * an offchain message is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedOffchainMessage } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast\n * // `offchainMessageEnvelope` to `FullySignedOffchainMessageEnvelope`.\n * assertIsFullySignedOffchainMessageEnvelope(offchainMessage);\n * // At this point we know that the offchain message is signed by all required signers.\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function assertIsFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): asserts offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n const missingSigs: Address[] = [];\n Object.entries(offchainMessage.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n\n/**\n * Asserts that there are signatures present for all of an offchain message's required signatories,\n * and that those signatures are valid given the message.\n *\n * @example\n * ```ts\n * import { isSolanaError, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE } from '@solana/errors';\n * import { verifyOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * try {\n * await verifyOffchainMessageEnvelope(offchainMessageEnvelope);\n * // At this point the message is valid and signed by all of the required signatories.\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) {\n * if (e.context.signatoriesWithMissingSignatures.length) {\n * console.error(\n * 'Missing signatures for the following addresses',\n * e.context.signatoriesWithMissingSignatures,\n * );\n * }\n * if (e.context.signatoriesWithInvalidSignatures.length) {\n * console.error(\n * 'Signatures for the following addresses are invalid',\n * e.context.signatoriesWithInvalidSignatures,\n * );\n * }\n * }\n * throw e;\n * }\n */\nexport async function verifyOffchainMessageEnvelope(offchainMessageEnvelope: OffchainMessageEnvelope): Promise {\n let errorContext;\n const requiredSignatories = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n await Promise.all(\n requiredSignatories.map(async address => {\n const signature = offchainMessageEnvelope.signatures[address];\n if (signature == null) {\n errorContext ||= {};\n errorContext.signatoriesWithMissingSignatures ||= [];\n errorContext.signatoriesWithMissingSignatures.push(address);\n } else {\n const publicKey = await getPublicKeyFromAddress(address);\n if (await verifySignature(publicKey, signature, offchainMessageEnvelope.content)) {\n return true;\n } else {\n errorContext ||= {};\n errorContext.signatoriesWithInvalidSignatures ||= [];\n errorContext.signatoriesWithInvalidSignatures.push(address);\n }\n }\n }),\n );\n if (errorContext) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, errorContext);\n }\n}\n","/**\n * Defines a plugin that transforms or extends a client with additional functionality.\n *\n * For instance, plugins may add RPC capabilities, wallet integration, transaction building,\n * or other features necessary for interacting with the Solana blockchain.\n *\n * Plugins are functions that take a client object as input and return a new client object\n * or a promise that resolves to a new client object. This allows for both synchronous\n * and asynchronous transformations and extensions of the client.\n *\n * Plugins are usually applied using the `use` method on a {@link Client} or {@link AsyncClient}\n * instance, which {@link createEmptyClient} provides as a starting point.\n *\n * @typeParam TInput - The input client object type that this plugin accepts.\n * @typeParam TOutput - The output type. Either a new client object or a promise resolving to one.\n *\n * @example Basic RPC plugin\n * Given an RPC endpoint, this plugin adds an `rpc` property to the client.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc } from '@solana/kit';\n *\n * // Define a simple RPC plugin.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n *\n * // Use the plugin.\n * const client = createEmptyClient().use(rpcPlugin('https://api.mainnet-beta.solana.com'));\n * await client.rpc.getLatestBlockhash().send();\n * ```\n *\n * @example Async plugin that generates a payer wallet\n * The following plugin shows how to create an asynchronous plugin that generates a new keypair signer.\n *\n * ```ts\n * import { createEmptyClient, generateKeypairSigner } from '@solana/kit';\n *\n * // Define a plugin that generates a new keypair signer.\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n *\n * // Use the plugin.\n * const client = await createEmptyClient().use(generatedPayerPlugin());\n * console.log(client.payer.address);\n * ```\n *\n * @example Plugins with input requirements\n * A plugin can specify required properties on the input client. The example below requires the\n * client to already have a `payer` signer attached to the client in order to perform an airdrop.\n *\n * ```ts\n * import { createEmptyClient, TransactionSigner, Lamports, lamports } from '@solana/kit';\n *\n * // Define a plugin that airdrops lamports to the payer set on the client.\n * function airdropPayerPlugin(lamports: Lamports) {\n * return async (client: T) => {\n * await myAirdropFunction(client.payer, lamports);\n * return client;\n * };\n * }\n *\n * // Use the plugins.\n * const client = await createEmptyClient()\n * .use(generatedPayerPlugin()) // This is required before using the airdrop plugin.\n * .use(airdropPayerPlugin(lamports(1_000_000_000n)));\n * ```\n *\n * @example Chaining plugins\n * Multiple plugins — asynchronous or not — can be chained together to build up complex clients.\n * The example below demonstrates how to gradually build a client with multiple plugins.\n * Notice how, despite having multiple asynchronous plugins, we only need to `await` the final result.\n * This is because the `use` method on `AsyncClient` returns another `AsyncClient`, allowing for seamless chaining.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc, createSolanaRpcSubscriptions, generateKeypairSigner } from '@solana/kit';\n *\n * // Define multiple plugins.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n * function rpcSubscriptionsPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpcSubscriptions(endpoint) });\n * }\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n * function generatedAuthorityPlugin() {\n * return async (client: T) => ({...client, authority: await generateKeypairSigner() });\n * }\n *\n * // Chain plugins together.\n * const client = await createEmptyClient()\n * .use(rpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(rpcSubscriptionsPlugin('wss://api.mainnet-beta.solana.com'))\n * .use(generatedPayerPlugin())\n * .use(generatedAuthorityPlugin());\n * ```\n */\nexport type ClientPlugin | object> = (input: TInput) => TOutput;\n\n/**\n * A client that can be extended with plugins.\n *\n * The `Client` type represents a client object that can be built up through\n * the application of one or more plugins. It provides a `use` method to\n * apply plugins, either synchronously (returning a new `Client`) or\n * asynchronously (returning an {@link AsyncClient}).\n *\n * @typeParam TSelf - The current shape of the client object including all applied plugins.\n */\nexport type Client = TSelf & {\n /**\n * Applies a plugin to extend or transform the client.\n *\n * @param plugin The plugin function to apply to this client.\n * @returns Either a new `Client` (for sync plugins) or {@link AsyncClient} (for async plugins).\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => TOutput extends Promise ? AsyncClient : Client;\n};\n\n/**\n * An asynchronous wrapper that represents a promise of a client.\n *\n * The `AsyncClient` type is returned when an async plugin is applied to a client.\n * It behaves like a `Promise>` but with an additional `use` method\n * that allows chaining more plugins before the promise resolves.\n *\n * This enables fluent chaining of both synchronous and asynchronous plugins\n * without having to await intermediate promises.\n *\n * @typeParam TSelf - The shape of the client object that this async client will resolve to.\n */\nexport type AsyncClient = Promise> & {\n /**\n * Applies a plugin to the client once it resolves.\n *\n * @param plugin The plugin function to apply to the resolved client.\n * @returns A new `AsyncClient` representing the result of applying the plugin.\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => AsyncClient ? (U extends object ? U : never) : TOutput>;\n};\n\n// TODO(loris): Add examples in this docblock using real plugins once they have been published.\n\n/**\n * Creates a new empty client that can be extended with plugins.\n *\n * This serves as an entry point for building Solana clients.\n * Start with an empty client and chain the `.use()` method\n * to apply plugins that add various functionalities such as RPC\n * connectivity, wallet integration, transaction building, and more.\n *\n * See {@link ClientPlugin} for detailed examples on creating and using plugins.\n *\n * @returns An empty client object with only the `use` method available.\n *\n * @example Basic client setup\n * ```ts\n * import { createEmptyClient } from '@solana/client';\n *\n * const client = createEmptyClient()\n * .use(myRpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(myWalletPlugin());\n * ```\n */\nexport function createEmptyClient(): Client {\n return addUse({});\n}\n\nfunction addUse(value: TSelf): Client {\n return Object.freeze({\n ...value,\n use | object>(plugin: ClientPlugin) {\n const result = plugin(value);\n return result instanceof Promise ? createAsyncClient(result) : addUse(result);\n },\n } as Client);\n}\n\nfunction createAsyncClient(promise: Promise): AsyncClient {\n return Object.freeze({\n catch(onrejected) {\n return promise.then(v => addUse(v)).catch(onrejected);\n },\n finally(onfinally) {\n return promise.then(v => addUse(v)).finally(onfinally);\n },\n then(onfulfilled, onrejected) {\n return promise.then(v => addUse(v)).then(onfulfilled, onrejected);\n },\n use | object>(plugin: ClientPlugin) {\n return createAsyncClient(promise.then(plugin));\n },\n } as AsyncClient);\n}\n","import type { Address } from '@solana/addresses';\nimport { isSolanaError, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SolanaError } from '@solana/errors';\n\n/**\n * Identifies whether an error -- typically caused by a transaction failure -- is a custom program\n * error from the provided program address.\n *\n * @param transactionMessage The transaction message that failed to execute. Since the RPC response\n * only provides the index of the failed instruction, the transaction message is required to\n * determine its program address\n * @param programAddress The address of the program from which the error is expected to have\n * originated\n * @param code The expected error code of the custom program error. When provided, the function will\n * check that the custom program error code matches the given value.\n *\n * @example\n * ```ts\n * try {\n * // Send and confirm your transaction.\n * } catch (error) {\n * if (isProgramError(error, transactionMessage, myProgramAddress, 42)) {\n * // Handle custom program error 42 from this program.\n * } else if (isProgramError(error, transactionMessage, myProgramAddress)) {\n * // Handle all other custom program errors from this program.\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isProgramError(\n error: unknown,\n transactionMessage: { instructions: Record },\n programAddress: Address,\n code?: TProgramErrorCode,\n): error is Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> &\n SolanaError {\n if (!isSolanaError(error, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM)) {\n return false;\n }\n const instructionProgramAddress = transactionMessage.instructions[error.context.index]?.programAddress;\n if (!instructionProgramAddress || instructionProgramAddress !== programAddress) {\n return false;\n }\n return typeof code === 'undefined' || error.context.code === code;\n}\n","/**\n * This function is a replacement for `JSON.parse` that can handle large\n * unsafe integers by parsing them as BigInts. It transforms every\n * numerical value into a BigInt without loss of precision.\n */\nexport function parseJsonWithBigInts(json: string): unknown {\n return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {\n return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;\n });\n}\n\nfunction wrapIntegersInBigIntValueObject(json: string): string {\n const out = [];\n let inQuote = false;\n for (let ii = 0; ii < json.length; ii++) {\n let isEscaped = false;\n if (json[ii] === '\\\\') {\n out.push(json[ii++]);\n isEscaped = !isEscaped;\n }\n if (json[ii] === '\"') {\n out.push(json[ii]);\n if (!isEscaped) {\n inQuote = !inQuote;\n }\n continue;\n }\n if (!inQuote) {\n const consumedNumber = consumeNumber(json, ii);\n if (consumedNumber?.length) {\n ii += consumedNumber.length - 1;\n // Don't wrap numbers that contain a decimal point or a negative exponent.\n if (consumedNumber.match(/\\.|[eE]-/)) {\n out.push(consumedNumber);\n } else {\n out.push(wrapBigIntValueObject(consumedNumber));\n }\n continue;\n }\n }\n out.push(json[ii]);\n }\n\n return out.join('');\n}\n\nfunction consumeNumber(json: string, ii: number): string | null {\n /** @see https://stackoverflow.com/a/13340826/11440277 */\n const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/;\n\n // Stop early if the first character isn't a digit or a minus sign.\n if (!json[ii]?.match(/[-\\d]/)) {\n return null;\n }\n\n // Otherwise, check if the next characters form a valid JSON number.\n const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);\n return numberMatch ? numberMatch[0] : null;\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: string): string {\n return `{\"$n\":\"${value}\"}`;\n}\n\nfunction unwrapBigIntValueObject({ $n }: BigIntValueObject): bigint {\n if ($n.match(/[eE]/)) {\n const [units, exponent] = $n.split(/[eE]/);\n return BigInt(units) * BigInt(10) ** BigInt(exponent);\n }\n return BigInt($n);\n}\n\nfunction isBigIntValueObject(value: unknown): value is BigIntValueObject {\n return !!value && typeof value === 'object' && '$n' in value && typeof value.$n === 'string';\n}\n","import { RpcRequest } from './rpc-request';\n\nlet _nextMessageId = 0n;\nfunction getNextMessageId(): string {\n const id = _nextMessageId;\n _nextMessageId++;\n return id.toString();\n}\n\n/**\n * Returns a spec-compliant JSON RPC 2.0 message, given a method name and some params.\n *\n * Generates a new `id` on each call by incrementing a `bigint` and casting it to a string.\n */\nexport function createRpcMessage(request: RpcRequest) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method: request.methodName,\n params: request.params,\n };\n}\n","/**\n * Transforms a value into a JSON string, whilst rendering bigints as large unsafe integers.\n */\nexport function stringifyJsonWithBigInts(value: unknown, space?: number | string): string {\n return unwrapBigIntValueObject(\n JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? wrapBigIntValueObject(v) : v), space),\n );\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: bigint): BigIntValueObject {\n return { $n: `${value}` };\n}\n\nfunction unwrapBigIntValueObject(value: string): string {\n return value.replace(/\\{\\s*\"\\$n\"\\s*:\\s*\"(-?\\d+)\"\\s*\\}/g, '$1');\n}\n","import { SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\n\nimport { RpcApi, RpcPlan } from './rpc-api';\nimport { RpcTransport } from './rpc-transport';\n\nexport type RpcConfig = Readonly<{\n api: RpcApi;\n transport: TRpcTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcMethods`.\n *\n * Calling each method returns a {@link PendingRpcRequest | PendingRpcRequest} where\n * `TResponse` is that method's response type.\n */\nexport type Rpc = {\n [TMethodName in keyof TRpcMethods]: PendingRpcRequestBuilder>;\n};\n\n/**\n * Pending requests are the result of calling a supported method on a {@link Rpc} object. They\n * encapsulate all of the information necessary to make the request without actually making it.\n *\n * Calling the {@link PendingRpcRequest.send | `send(options)`} method on a\n * {@link PendingRpcRequest | PendingRpcRequest} will trigger the request and return a\n * promise for `TResponse`.\n */\nexport type PendingRpcRequest = {\n send(options?: RpcSendOptions): Promise;\n};\n\nexport type RpcSendOptions = Readonly<{\n /**\n * An optional signal that you can supply when triggering a {@link PendingRpcRequest} that you\n * might later need to abort.\n */\n abortSignal?: AbortSignal;\n}>;\n\ntype PendingRpcRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TMethodImplementations]: PendingRpcRequestReturnTypeMapper;\n }>\n>;\n\ntype PendingRpcRequestReturnTypeMapper =\n // Check that this property of the TRpcMethods interface is, in fact, a function.\n TMethodImplementation extends Callable\n ? (...args: Parameters) => PendingRpcRequest>\n : never;\n\n/**\n * Creates a {@link Rpc} instance given a {@link RpcApi | RpcApi} and a\n * {@link RpcTransport} capable of fulfilling them.\n */\nexport function createRpc(\n rpcConfig: RpcConfig,\n): Rpc {\n return makeProxy(rpcConfig);\n}\n\nfunction makeProxy(\n rpcConfig: RpcConfig,\n): Rpc {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const getApiPlan = Reflect.get(target, methodName, receiver);\n if (!getApiPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {\n method: methodName,\n params: rawParams,\n });\n }\n const apiPlan = getApiPlan(...rawParams);\n return createPendingRpcRequest(rpcConfig, apiPlan);\n };\n },\n }) as Rpc;\n}\n\nfunction createPendingRpcRequest(\n { transport }: RpcConfig,\n plan: RpcPlan,\n): PendingRpcRequest {\n return {\n async send(options?: RpcSendOptions): Promise {\n return await plan.execute({ signal: options?.abortSignal, transport });\n },\n };\n}\n","import {\n Callable,\n createRpcMessage,\n RpcRequestTransformer,\n RpcResponse,\n RpcResponseTransformer,\n} from '@solana/rpc-spec-types';\n\nimport type { RpcTransport } from './rpc-transport';\n\nexport type RpcApiConfig = Readonly<{\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n /**\n * An optional function that transforms the {@link RpcResponse} before it is returned to the\n * caller.\n *\n * Use cases for this include constructing complex data types from serialized data, and throwing\n * exceptions.\n */\n responseTransformer?: RpcResponseTransformer;\n}>;\n\n/**\n * This type allows an {@link RpcApi} to describe how a particular request should be issued to the\n * JSON RPC server.\n *\n * Given a function that was called on a {@link Rpc}, this object exposes an `execute` function that\n * dictates which request will be sent, how the underlying transport will be used, and how the\n * responses will be transformed.\n *\n * This function accepts a {@link RpcTransport} and an `AbortSignal` and asynchronously returns a\n * {@link RpcResponse}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * transport.\n * - call the underlying transport zero, one or multiple times depending on the use-case (e.g.\n * caching or aggregating multiple responses).\n * - transform the response from the JSON RPC server, in case it does not match the `TResponse`\n * specified by the {@link PendingRpcRequest | PendingRpcRequest} returned from that\n * function.\n */\nexport type RpcPlan = {\n execute: (\n config: Readonly<{\n signal?: AbortSignal;\n transport: RpcTransport;\n }>,\n ) => Promise>;\n};\n\n/**\n * For each of `TRpcMethods`, this object exposes a method with the same name that maps between its\n * input arguments and a {@link RpcPlan | RpcPlan} that implements the execution of a\n * JSON RPC request to fetch `TResponse`.\n */\nexport type RpcApi = {\n [MethodName in keyof TRpcMethods]: RpcReturnTypeMapper;\n};\n\ntype RpcReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcApiMethod = (...args: any) => any;\ninterface RpcApiMethods {\n [methodName: string]: RpcApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a {@link RpcPlan} by\n * creating an `execute` function that:\n *\n * - sets the transport payload to a JSON RPC v2 payload object with the requested `methodName` and\n * `params` properties, optionally transformed by {@link RpcApiConfig.requestTransformer}.\n * - transforms the transport's response using the {@link RpcApiConfig.responseTransformer}\n * function, if provided.\n *\n * @example\n * ```ts\n * // For example, given this `RpcApi`:\n * const rpcApi = createJsonRpcApi({\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * responseTransformer: response => response.result,\n * });\n *\n * // ...the following function call:\n * rpcApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Returns the \"result\" property of the RPC response.\n * ```\n */\nexport function createJsonRpcApi(config?: RpcApiConfig): RpcApi {\n return new Proxy({} as RpcApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcMethods as string;\n return function (\n ...rawParams: Parameters<\n TRpcMethods[TMethodName] extends CallableFunction ? TRpcMethods[TMethodName] : never\n >\n ): RpcPlan> {\n const rawRequest = Object.freeze({ methodName, params: rawParams });\n const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;\n return Object.freeze(>>{\n execute: async ({ signal, transport }) => {\n const payload = createRpcMessage(request);\n const response = await transport({ payload, signal });\n if (!config?.responseTransformer) {\n return response;\n }\n return config.responseTransformer(response, request);\n },\n });\n };\n },\n });\n}\n","import { RpcResponse } from '@solana/rpc-spec-types';\n\ntype Config = Readonly<{\n /** A value of arbitrary type to be sent to a RPC server */\n payload: unknown;\n /**\n * An optional `AbortSignal` on which the `'abort'` event will be fired if the request should be\n * cancelled.\n */\n signal?: AbortSignal;\n}>;\n\n/**\n * A function that can act as a transport for a {@link Rpc}. It need only return a promise for a\n * response given the supplied config.\n */\nexport type RpcTransport = {\n (config: Config): Promise>;\n};\n\n/**\n * Returns `true` if the given payload is a JSON RPC v2 payload.\n *\n * This means, the payload is an object such that:\n *\n * - It has a `jsonrpc` property with a value of `'2.0'`.\n * - It has a `method` property that is a string.\n * - It has a `params` property of any type.\n *\n * @example\n * ```ts\n * import { isJsonRpcPayload } from '@solana/rpc-spec';\n *\n * if (isJsonRpcPayload(payload)) {\n * const payloadMethod: string = payload.method;\n * const payloadParams: unknown = payload.params;\n * }\n * ```\n */\nexport function isJsonRpcPayload(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: string;\n params: unknown;\n}> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n","export function downcastNodeToNumberIfBigint(value: bigint): number;\nexport function downcastNodeToNumberIfBigint(value: T): T;\nexport function downcastNodeToNumberIfBigint(value: unknown): unknown {\n return typeof value === 'bigint'\n ? // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n Number(value)\n : value;\n}\n","import { RpcRequest, RpcRequestTransformer, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nexport type KeyPathWildcard = { readonly ['__keyPathWildcard:@solana/kit']: unique symbol };\nexport type KeyPath = ReadonlyArray;\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n\ntype NodeVisitor = (value: unknown, state: TState) => unknown;\nexport type TraversalState = Readonly<{\n keyPath: KeyPath;\n}>;\n\nfunction getTreeWalker(visitors: NodeVisitor[]) {\n return function traverse(node: unknown, state: TState): unknown {\n if (Array.isArray(node)) {\n return node.map((element, ii) => {\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, ii],\n };\n return traverse(element, nextState);\n });\n } else if (typeof node === 'object' && node !== null) {\n const out: Record = {};\n for (const propName in node) {\n if (!Object.prototype.hasOwnProperty.call(node, propName)) {\n continue;\n }\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, propName],\n };\n out[propName] = traverse(node[propName as keyof typeof node], nextState);\n }\n return out;\n } else {\n return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);\n }\n };\n}\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided visitors at\n * each node. A custom initial state can be provided but must at least provide `{ keyPath: [] }`.\n *\n * @example\n * ```ts\n * import { getTreeWalkerRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getTreeWalkerRequestTransformer(\n * [\n * // Replaces foo.bar with \"baz\".\n * (node, state) => (state.keyPath === ['foo', 'bar'] ? 'baz' : node),\n * // Increments all numbers by 1.\n * node => (typeof node === number ? node + 1 : node),\n * ],\n * { keyPath: [] },\n * );\n * ```\n */\nexport function getTreeWalkerRequestTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const traverse = getTreeWalker(visitors);\n return Object.freeze({\n ...request,\n params: traverse(request.params, initialState),\n });\n };\n}\n\nexport function getTreeWalkerResponseTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcResponseTransformer {\n return json => getTreeWalker(visitors)(json, initialState);\n}\n","import { downcastNodeToNumberIfBigint } from './request-transformer-bigint-downcast-internal';\nimport { getTreeWalkerRequestTransformer } from './tree-traversal';\n\n/**\n * Creates a transformer that downcasts all `BigInt` values to `Number`.\n *\n * @example\n * ```ts\n * import { getBigIntDowncastRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getBigIntDowncastRequestTransformer();\n * ```\n *\n */\nexport function getBigIntDowncastRequestTransformer() {\n return getTreeWalkerRequestTransformer([downcastNodeToNumberIfBigint], { keyPath: [] });\n}\n","import { Commitment } from '@solana/rpc-types';\n\nexport function applyDefaultCommitment({\n commitmentPropertyName,\n params,\n optionsObjectPositionInParams,\n overrideCommitment,\n}: Readonly<{\n commitmentPropertyName: string;\n optionsObjectPositionInParams: number;\n overrideCommitment?: Commitment;\n params: unknown[];\n}>) {\n const paramInTargetPosition = params[optionsObjectPositionInParams];\n if (\n // There's no config.\n paramInTargetPosition === undefined ||\n // There is a config object.\n (paramInTargetPosition && typeof paramInTargetPosition === 'object' && !Array.isArray(paramInTargetPosition))\n ) {\n if (\n // The config object already has a commitment set.\n paramInTargetPosition &&\n commitmentPropertyName in paramInTargetPosition\n ) {\n if (\n !paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] ||\n paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] === 'finalized'\n ) {\n // Delete the commitment property; `finalized` is already the server default.\n const nextParams = [...params];\n const {\n [commitmentPropertyName as keyof typeof paramInTargetPosition]: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...rest\n } = paramInTargetPosition;\n if (Object.keys(rest).length > 0) {\n nextParams[optionsObjectPositionInParams] = rest;\n } else {\n if (optionsObjectPositionInParams === nextParams.length - 1) {\n nextParams.length--;\n } else {\n nextParams[optionsObjectPositionInParams] = undefined;\n }\n }\n return nextParams;\n }\n } else if (overrideCommitment !== 'finalized') {\n // Apply the default commitment.\n const nextParams = [...params];\n nextParams[optionsObjectPositionInParams] = {\n ...paramInTargetPosition,\n [commitmentPropertyName]: overrideCommitment,\n };\n return nextParams;\n }\n }\n return params;\n}\n","import type { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { applyDefaultCommitment } from './request-transformer-default-commitment-internal';\n\n/**\n * Creates a transformer that adds the provided default commitment to the configuration object of the request when applicable.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getDefaultCommitmentRequestTransformer, OPTIONS_OBJECT_POSITION_BY_METHOD } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultCommitmentRequestTransformer({\n * defaultCommitment: 'confirmed',\n * optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n * });\n */\nexport function getDefaultCommitmentRequestTransformer({\n defaultCommitment,\n optionsObjectPositionByMethod,\n}: Readonly<{\n defaultCommitment?: Commitment;\n optionsObjectPositionByMethod: Record;\n}>): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const { params, methodName } = request;\n\n // We only apply default commitment to array parameters.\n if (!Array.isArray(params)) {\n return request;\n }\n\n // Find the position of the options object in the parameters and abort if not found.\n const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];\n if (optionsObjectPositionInParams == null) {\n return request;\n }\n\n return Object.freeze({\n methodName,\n params: applyDefaultCommitment({\n commitmentPropertyName: methodName === 'sendTransaction' ? 'preflightCommitment' : 'commitment',\n optionsObjectPositionInParams,\n overrideCommitment: defaultCommitment,\n params,\n }),\n });\n };\n}\n","import { KeyPath, TraversalState } from './tree-traversal';\n\nexport function getIntegerOverflowNodeVisitor(onIntegerOverflow: (keyPath: KeyPath, value: bigint) => void) {\n return (value: T, { keyPath }: TraversalState): T => {\n if (typeof value === 'bigint') {\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath as (number | string)[], value);\n }\n }\n return value;\n };\n}\n","import { RpcRequest } from '@solana/rpc-spec-types';\n\nimport { getIntegerOverflowNodeVisitor } from './request-transformer-integer-overflow-internal';\nimport { getTreeWalkerRequestTransformer, KeyPath } from './tree-traversal';\n\nexport type IntegerOverflowHandler = (request: RpcRequest, keyPath: KeyPath, value: bigint) => void;\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided handler\n * when an integer overflow is detected.\n *\n * @example\n * ```ts\n * import { getIntegerOverflowRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getIntegerOverflowRequestTransformer((request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * });\n * ```\n */\nexport function getIntegerOverflowRequestTransformer(onIntegerOverflow: IntegerOverflowHandler) {\n return (request: RpcRequest): RpcRequest => {\n const transformer = getTreeWalkerRequestTransformer(\n [getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))],\n { keyPath: [] },\n );\n return transformer(request);\n };\n}\n","export const OPTIONS_OBJECT_POSITION_BY_METHOD: Record = {\n accountNotifications: 1,\n blockNotifications: 1,\n getAccountInfo: 1,\n getBalance: 1,\n getBlock: 1,\n getBlockHeight: 0,\n getBlockProduction: 0,\n getBlocks: 2,\n getBlocksWithLimit: 2,\n getEpochInfo: 0,\n getFeeForMessage: 1,\n getInflationGovernor: 0,\n getInflationReward: 1,\n getLargestAccounts: 0,\n getLatestBlockhash: 0,\n getLeaderSchedule: 1,\n getMinimumBalanceForRentExemption: 1,\n getMultipleAccounts: 1,\n getProgramAccounts: 1,\n getSignaturesForAddress: 1,\n getSlot: 0,\n getSlotLeader: 0,\n getStakeMinimumDelegation: 0,\n getSupply: 0,\n getTokenAccountBalance: 1,\n getTokenAccountsByDelegate: 2,\n getTokenAccountsByOwner: 2,\n getTokenLargestAccounts: 1,\n getTokenSupply: 1,\n getTransaction: 1,\n getTransactionCount: 0,\n getVoteAccounts: 0,\n isBlockhashValid: 1,\n logsNotifications: 1,\n programNotifications: 1,\n requestAirdrop: 2,\n sendTransaction: 1,\n signatureNotifications: 1,\n simulateTransaction: 1,\n};\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { getBigIntDowncastRequestTransformer } from './request-transformer-bigint-downcast';\nimport { getDefaultCommitmentRequestTransformer } from './request-transformer-default-commitment';\nimport { getIntegerOverflowRequestTransformer, IntegerOverflowHandler } from './request-transformer-integer-overflow';\nimport { OPTIONS_OBJECT_POSITION_BY_METHOD } from './request-transformer-options-object-position-config';\n\nexport type RequestTransformerConfig = Readonly<{\n /**\n * An optional {@link Commitment} value to use as the default when none is supplied by the\n * caller.\n */\n defaultCommitment?: Commitment;\n /**\n * An optional function that will be called whenever a `bigint` input exceeds that which can be\n * expressed using JavaScript numbers.\n *\n * This is used in the default {@link SolanaRpcSubscriptionsApi} to throw an exception rather\n * than to allow truncated values to propagate through a program.\n */\n onIntegerOverflow?: IntegerOverflowHandler;\n}>;\n\n/**\n * Returns the default request transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcRequestTransformer | RpcRequestTransformers} together such as the\n * {@link getDefaultCommitmentTransformer}, the {@link getIntegerOverflowRequestTransformer} and the\n * {@link getBigIntDowncastRequestTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultRequestTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultRequestTransformerForSolanaRpc({\n * defaultCommitment: 'confirmed',\n * onIntegerOverflow: (request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * },\n * });\n * ```\n */\nexport function getDefaultRequestTransformerForSolanaRpc(config?: RequestTransformerConfig): RpcRequestTransformer {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n return (request: RpcRequest): RpcRequest => {\n return pipe(\n request,\n handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : r => r,\n getBigIntDowncastRequestTransformer(),\n getDefaultCommitmentRequestTransformer({\n defaultCommitment: config?.defaultCommitment,\n optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n }),\n );\n };\n}\n","import { KeyPath, KEYPATH_WILDCARD, TraversalState } from './tree-traversal';\n\nexport function getBigIntUpcastVisitor(allowedNumericKeyPaths: readonly KeyPath[]) {\n return function upcastNodeToBigIntIfNumber(value: unknown, { keyPath }: TraversalState) {\n const isInteger = (typeof value === 'number' && Number.isInteger(value)) || typeof value === 'bigint';\n if (!isInteger) return value;\n if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {\n return Number(value);\n } else {\n return BigInt(value);\n }\n };\n}\n\nfunction keyPathIsAllowedToBeNumeric(keyPath: KeyPath, allowedNumericKeyPaths: readonly KeyPath[]) {\n return allowedNumericKeyPaths.some(prohibitedKeyPath => {\n if (prohibitedKeyPath.length !== keyPath.length) {\n return false;\n }\n for (let ii = keyPath.length - 1; ii >= 0; ii--) {\n const keyPathPart = keyPath[ii];\n const prohibitedKeyPathPart = prohibitedKeyPath[ii];\n if (\n prohibitedKeyPathPart !== keyPathPart &&\n (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== 'number')\n ) {\n return false;\n }\n }\n return true;\n });\n}\n","import { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath } from './tree-traversal';\n\n/**\n * Returns a transformer that upcasts all `Number` values to `BigInts` unless they match within the\n * provided {@link KeyPath | KeyPaths}. In other words, the provided {@link KeyPath | KeyPaths} will\n * remain as `Number` values, any other numeric value will be upcasted to a `BigInt`.\n *\n * Note that you can use {@link KEYPATH_WILDCARD} to match any key within a {@link KeyPath}.\n *\n * @example\n * ```ts\n * import { getBigIntUpcastResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getBigIntUpcastResponseTransformer([\n * ['index'],\n * ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n * ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n * ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n * ]);\n * ```\n */\nexport function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths: readonly KeyPath[]) {\n return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });\n}\n","import { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\ntype JsonRpcResponse = { result: unknown };\n\n/**\n * Returns a transformer that extracts the `result` field from the body of the RPC response.\n *\n * For instance, we go from `{ jsonrpc: '2.0', result: 'foo', id: 1 }` to `'foo'`.\n *\n * @example\n * ```ts\n * import { getResultResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getResultResponseTransformer();\n * ```\n */\nexport function getResultResponseTransformer(): RpcResponseTransformer {\n return json => (json as JsonRpcResponse).result;\n}\n","import { KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\nexport type AllowedNumericKeypaths = Partial>;\n\n// Numeric values nested in `jsonParsed` accounts\nexport const jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nexport const jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n];\nexport const innerInstructionsConfigs = [\n ['index'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n];\nexport const messageConfig = [\n ['addressTableLookups', KEYPATH_WILDCARD, 'writableIndexes', KEYPATH_WILDCARD],\n ['addressTableLookups', KEYPATH_WILDCARD, 'readonlyIndexes', KEYPATH_WILDCARD],\n ['header', 'numReadonlySignedAccounts'],\n ['header', 'numReadonlyUnsignedAccounts'],\n ['header', 'numRequiredSignatures'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n] as const;\n","import { getSolanaErrorFromJsonRpcError } from '@solana/errors';\nimport { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { innerInstructionsConfigs, jsonParsedAccountsConfigs } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\ntype JsonRpcResponse = { error: Parameters[0] } | { result: unknown };\n\n// Keypaths for simulateTransaction result that should remain as Number (not BigInt)\n// Note: These are relative to the error.data root, not result.value like in success responses\nfunction getSimulateTransactionAllowedNumericKeypaths(): readonly KeyPath[] {\n return [\n ['loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['innerInstructions', KEYPATH_WILDCARD, ...c]),\n ];\n}\n\n/**\n * Returns a transformer that throws a {@link SolanaError} with the appropriate RPC error code if\n * the body of the RPC response contains an error.\n *\n * @example\n * ```ts\n * import { getThrowSolanaErrorResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getThrowSolanaErrorResponseTransformer();\n * ```\n */\nexport function getThrowSolanaErrorResponseTransformer(): RpcResponseTransformer {\n return (json, request) => {\n const jsonRpcResponse = json as JsonRpcResponse;\n if ('error' in jsonRpcResponse) {\n const { error } = jsonRpcResponse;\n\n // Check if this is a sendTransaction preflight failure (error code -32002)\n // These errors contain RpcSimulateTransactionResult in error.data which needs\n // BigInt values downcast to Number for fields that should be numbers\n const isSendTransactionPreflightFailure =\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n (error.code === -32002 || error.code === -32002n);\n\n if (isSendTransactionPreflightFailure && 'data' in error && error.data) {\n // Apply BigInt downcast transformation to error.data\n const treeWalker = getTreeWalkerResponseTransformer(\n [getBigIntUpcastVisitor(getSimulateTransactionAllowedNumericKeypaths())],\n { keyPath: [] },\n );\n const transformedData = treeWalker(error.data, request);\n\n // Reconstruct error with transformed data\n const transformedError = { ...error, data: transformedData };\n throw getSolanaErrorFromJsonRpcError(transformedError);\n }\n\n throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);\n }\n return jsonRpcResponse;\n };\n}\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcResponse, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { AllowedNumericKeypaths } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastResponseTransformer } from './response-transformer-bigint-upcast';\nimport { getResultResponseTransformer } from './response-transformer-result';\nimport { getThrowSolanaErrorResponseTransformer } from './response-transformer-throw-solana-error';\n\nexport type ResponseTransformerConfig = Readonly<{\n /**\n * An optional map from the name of an API method to an array of {@link KeyPath | KeyPaths}\n * pointing to values in the response that should materialize in the application as `Number`\n * instead of `BigInt`.\n */\n allowedNumericKeyPaths?: AllowedNumericKeypaths;\n}>;\n\n/**\n * Returns the default response transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcResponseTransformer | RpcResponseTransformers} together such as the\n * {@link getThrowSolanaErrorResponseTransformer}, the {@link getResultResponseTransformer} and the\n * {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpc({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpc(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(\n response,\n r => getThrowSolanaErrorResponseTransformer()(r, request),\n r => getResultResponseTransformer()(r, request),\n r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request),\n );\n };\n}\n\n/**\n * Returns the default response transformer for the Solana RPC Subscriptions API.\n *\n * Under the hood, this function composes the {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpcSubscriptions } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpcSubscriptions(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(response, r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));\n };\n}\n","/**\n * This package contains types that describe the [methods](https://solana.com/docs/rpc/http) of the\n * Solana JSON RPC API, and utilities for creating a {@link RpcApi} implementation with sensible\n * defaults. It can be used standalone, but it is also exported as part of Kit\n * [`@solana/kit`](https://github.com/anza-xyz/kit/tree/main/packages/kit).\n *\n * @example\n * Each RPC method is described in terms of a TypeScript type of the following form:\n *\n * ```ts\n * type ExampleApi = {\n * getSomething(address: Address): Something;\n * };\n * ```\n *\n * A {@link RpcApi} that implements `ExampleApi` will ultimately expose its defined methods on any\n * {@link Rpc} that uses it.\n *\n * ```ts\n * const rpc: Rpc = createExampleRpc(/* ... *\\/);\n * const something: Something = await rpc.getSomething(address('95DpK3y3GF7U8s1k4EvZ7xqyeCkhsHeZaE97iZpHUGMN')).send();\n * ```\n *\n * @packageDocumentation\n */\nimport { createJsonRpcApi, RpcApi } from '@solana/rpc-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpc,\n innerInstructionsConfigs,\n jsonParsedAccountsConfigs,\n jsonParsedTokenAccountsConfigs,\n KEYPATH_WILDCARD,\n messageConfig,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype SolanaRpcApiForAllClusters = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n SendTransactionApi &\n SimulateTransactionApi;\ntype SolanaRpcApiForTestClusters = RequestAirdropApi & SolanaRpcApiForAllClusters;\n/**\n * Represents the RPC methods available on test clusters.\n *\n * For instance, the test clusters support the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApi = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the devnet cluster.\n *\n * For instance, the devnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiDevnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the testnet cluster.\n *\n * For instance, the testnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiTestnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the mainnet cluster.\n *\n * For instance, the mainnet cluster does not support the {@link RequestAirdropApi} whereas test\n * clusters do.\n */\nexport type SolanaRpcApiMainnet = SolanaRpcApiForAllClusters;\n\nexport type {\n GetAccountInfoApi,\n GetBalanceApi,\n GetBlockApi,\n GetBlockCommitmentApi,\n GetBlockHeightApi,\n GetBlockProductionApi,\n GetBlocksApi,\n GetBlocksWithLimitApi,\n GetBlockTimeApi,\n GetClusterNodesApi,\n GetEpochInfoApi,\n GetEpochScheduleApi,\n GetFeeForMessageApi,\n GetFirstAvailableBlockApi,\n GetGenesisHashApi,\n GetHealthApi,\n GetHighestSnapshotSlotApi,\n GetIdentityApi,\n GetInflationGovernorApi,\n GetInflationRateApi,\n GetInflationRewardApi,\n GetLargestAccountsApi,\n GetLatestBlockhashApi,\n GetLeaderScheduleApi,\n GetMaxRetransmitSlotApi,\n GetMaxShredInsertSlotApi,\n GetMinimumBalanceForRentExemptionApi,\n GetMultipleAccountsApi,\n GetProgramAccountsApi,\n GetRecentPerformanceSamplesApi,\n GetRecentPrioritizationFeesApi,\n GetSignaturesForAddressApi,\n GetSignatureStatusesApi,\n GetSlotApi,\n GetSlotLeaderApi,\n GetSlotLeadersApi,\n GetStakeMinimumDelegationApi,\n GetSupplyApi,\n GetTokenAccountBalanceApi,\n GetTokenAccountsByDelegateApi,\n GetTokenAccountsByOwnerApi,\n GetTokenLargestAccountsApi,\n GetTokenSupplyApi,\n GetTransactionApi,\n GetTransactionCountApi,\n GetVersionApi,\n GetVoteAccountsApi,\n IsBlockhashValidApi,\n MinimumLedgerSlotApi,\n RequestAirdropApi,\n SendTransactionApi,\n SimulateTransactionApi,\n};\n\ntype Config = RequestTransformerConfig;\n\n/**\n * Creates a {@link RpcApi} implementation of the Solana JSON RPC API with some default behaviours.\n *\n * The default behaviours include:\n * - A transform that converts `bigint` inputs to `number` for compatibility with version 1.0 of the\n * Solana JSON RPC.\n * - A transform that calls the config's {@link Config.onIntegerOverflow | onIntegerOverflow}\n * handler whenever a `bigint` input would overflow a JavaScript IEEE 754 number. See\n * [this](https://github.com/solana-labs/solana-web3.js/issues/1116) GitHub issue for more\n * information.\n * - A transform that applies a default commitment wherever not specified\n */\nexport function createSolanaRpcApi<\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n TRpcMethods extends SolanaRpcApi | SolanaRpcApiDevnet | SolanaRpcApiMainnet | SolanaRpcApiTestnet = SolanaRpcApi,\n>(config?: Config): RpcApi {\n return createJsonRpcApi({\n requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),\n responseTransformer: getDefaultResponseTransformerForSolanaRpc({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n }),\n });\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n ...c,\n ]),\n ...messageConfig.map(c => ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', ...c] as const),\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => ['meta', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ...messageConfig.map(c => ['transaction', 'message', ...c] as const),\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: [\n ['value', 'loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['value', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ],\n };\n }\n return memoizedKeypaths;\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SolanaError } from '@solana/errors';\n\nexport type AllowedHttpRequestHeaders = Readonly<\n {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | Capitalize> // `Foo-bar`\n | K // `Foo-Bar`\n | Lowercase // `foo-bar`\n | Uncapitalize // `foo-Bar`\n // `FOO-BAR`\n | Uppercase]?: never;\n } & { [headerName: string]: string }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n // Though technically forbidden in non-Node environments, we don't have a way to target\n // TypeScript types depending on which platform you are authoring for. `Accept-Encoding` is\n // therefore omitted from the forbidden headers type, but is still a runtime error in dev mode\n // when supplied in a non-Node context.\n // | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n // Similar to `Accept-Encoding`, we don't have a way to target TypeScript types depending on\n // which platform you are authoring for. `Origin` is therefore omitted from the forbidden\n // headers type, but is still a runtime error in dev mode when supplied in a browser context.\n // | 'Origin'\n | 'Permissions-Policy'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via'\n | `Proxy-${string}`\n | `Sec-${string}`;\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record = /* @__PURE__ */ Object.assign(\n {\n 'accept-charset': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n 'permissions-policy': true,\n // Prefix matching is implemented in code, below.\n // 'proxy-': true,\n // 'sec-': true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n },\n __NODEJS__ ? undefined : { 'accept-encoding': true },\n __BROWSER__ ? { origin: true } : undefined,\n);\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record,\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, {\n headers: badHeaders,\n });\n }\n}\n\n// Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n// in the `DisallowedHeaders` type.\nexport function normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError } from '@solana/errors';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\nimport type Dispatcher from 'undici-types/dispatcher';\n\nimport { HttpTransportConfig as Config } from './http-transport-config';\nimport { assertIsAllowedHttpRequestHeaders, normalizeHeaders } from './http-transport-headers';\n\nlet didWarnDispatcherWasSuppliedInNonNodeEnvironment = false;\nfunction warnDispatcherWasSuppliedInNonNodeEnvironment() {\n if (didWarnDispatcherWasSuppliedInNonNodeEnvironment) {\n return;\n }\n didWarnDispatcherWasSuppliedInNonNodeEnvironment = true;\n console.warn(\n 'You have supplied a `Dispatcher` to `createHttpTransport()`. It has been ignored ' +\n 'because Undici dispatchers only work in Node environments. To eliminate this ' +\n 'warning, omit the `dispatcher_NODE_ONLY` property from your config when running in ' +\n 'a non-Node environment.',\n );\n}\n\n/**\n * Creates a function you can use to make `POST` requests with headers suitable for sending JSON\n * data to a server.\n *\n * @example\n * ```ts\n * import { createHttpTransport } from '@solana/rpc-transport-http';\n *\n * const transport = createHttpTransport({ url: 'https://api.mainnet-beta.solana.com' });\n * const response = await transport({\n * payload: { id: 1, jsonrpc: '2.0', method: 'getSlot' },\n * });\n * const data = await response.json();\n * ```\n */\nexport function createHttpTransport(config: Config): RpcTransport {\n if (process.env.NODE_ENV !== \"production\" && !__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n warnDispatcherWasSuppliedInNonNodeEnvironment();\n }\n const { fromJson, headers, toJson, url } = config;\n if (process.env.NODE_ENV !== \"production\" && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n let dispatcherConfig: { dispatcher: Dispatcher | undefined } | undefined;\n if (__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n dispatcherConfig = { dispatcher: config.dispatcher_NODE_ONLY };\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest({\n payload,\n signal,\n }: Parameters[0]): Promise> {\n const body = toJson ? toJson(payload) : JSON.stringify(payload);\n const requestInfo = {\n ...dispatcherConfig,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetch(url, requestInfo);\n if (!response.ok) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {\n headers: response.headers,\n message: response.statusText,\n statusCode: response.status,\n });\n }\n if (fromJson) {\n return fromJson(await response.text(), payload) as TResponse;\n }\n return await response.json();\n };\n}\n","import { isJsonRpcPayload } from '@solana/rpc-spec';\n\nconst SOLANA_RPC_METHODS = [\n 'getAccountInfo',\n 'getBalance',\n 'getBlock',\n 'getBlockCommitment',\n 'getBlockHeight',\n 'getBlockProduction',\n 'getBlocks',\n 'getBlocksWithLimit',\n 'getBlockTime',\n 'getClusterNodes',\n 'getEpochInfo',\n 'getEpochSchedule',\n 'getFeeForMessage',\n 'getFirstAvailableBlock',\n 'getGenesisHash',\n 'getHealth',\n 'getHighestSnapshotSlot',\n 'getIdentity',\n 'getInflationGovernor',\n 'getInflationRate',\n 'getInflationReward',\n 'getLargestAccounts',\n 'getLatestBlockhash',\n 'getLeaderSchedule',\n 'getMaxRetransmitSlot',\n 'getMaxShredInsertSlot',\n 'getMinimumBalanceForRentExemption',\n 'getMultipleAccounts',\n 'getProgramAccounts',\n 'getRecentPerformanceSamples',\n 'getRecentPrioritizationFees',\n 'getSignaturesForAddress',\n 'getSignatureStatuses',\n 'getSlot',\n 'getSlotLeader',\n 'getSlotLeaders',\n 'getStakeMinimumDelegation',\n 'getSupply',\n 'getTokenAccountBalance',\n 'getTokenAccountsByDelegate',\n 'getTokenAccountsByOwner',\n 'getTokenLargestAccounts',\n 'getTokenSupply',\n 'getTransaction',\n 'getTransactionCount',\n 'getVersion',\n 'getVoteAccounts',\n 'index',\n 'isBlockhashValid',\n 'minimumLedgerSlot',\n 'requestAirdrop',\n 'sendTransaction',\n 'simulateTransaction',\n] as const;\n\n/**\n * Helper function that checks if a given `RpcRequest` comes from the Solana RPC API.\n */\nexport function isSolanaRequest(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: (typeof SOLANA_RPC_METHODS)[number];\n params: unknown;\n}> {\n return isJsonRpcPayload(payload) && (SOLANA_RPC_METHODS as readonly string[]).includes(payload.method);\n}\n","import { RpcTransport } from '@solana/rpc-spec';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\n\nimport { createHttpTransport } from './http-transport';\nimport { HttpTransportConfig } from './http-transport-config';\nimport { isSolanaRequest } from './is-solana-request';\n\ntype Config = Pick;\n\n/**\n * Creates a {@link RpcTransport} that uses JSON HTTP requests — much like the\n * {@link createHttpTransport} function - except that it also uses custom `toJson` and `fromJson`\n * functions in order to allow `bigint` values to be serialized and deserialized correctly over the\n * wire.\n *\n * Since this is something specific to the Solana RPC API, these custom JSON functions are only\n * triggered when the request is recognized as a Solana RPC request. Normal RPC APIs should aim to\n * wrap their `bigint` values — e.g. `u64` or `i64` — in special value objects that represent the\n * number as a string to avoid numerical values going above `Number.MAX_SAFE_INTEGER`.\n *\n * It has the same configuration options as {@link createHttpTransport}, but without the `fromJson`\n * and `toJson` options.\n */\nexport function createHttpTransportForSolanaRpc(config: Config): RpcTransport {\n return createHttpTransport({\n ...config,\n fromJson: (rawResponse: string, payload: unknown) =>\n isSolanaRequest(payload) ? parseJsonWithBigInts(rawResponse) : JSON.parse(rawResponse),\n toJson: (payload: unknown) =>\n isSolanaRequest(payload) ? stringifyJsonWithBigInts(payload) : JSON.stringify(payload),\n });\n}\n","/**\n * This project is a fork of [nickyout/fast-stable-stringify](https://github.com/nickyout/fast-stable-stringify)\n *\n * The most popular repository providing this feature is [substack's json-stable-stringify](https://www.npmjs.com/package/json-stable-stringify). The intent of this library is to provide a faster alternative for when performance is more important than features. It assumes you provide basic javascript values without circular references, and returns a non-indented string.\n *\n * Just like substack's, it:\n *\n * - handles all variations of all basic javascript values (number, string, boolean, array, object, null, Date, BigInt)\n * - handles undefined _and_ function in the same way as `JSON.stringify`\n * - **does not support ie8 (and below) with complete certainty**.\n *\n * Unlike substack's, it:\n *\n * - does not implement the 'replacer' or 'space' arguments of the JSON.stringify method\n * - does not check for circular references\n *\n * @example\n * ```js\n * import stringify from '@solana/fast-stable-stringify';\n * stringify({ d: 0, c: 1, a: 2, b: 3, e: 4 }); // '{\"a\":2,\"b\":3,\"c\":1,\"d\":0,\"e\":4}'\n * ```\n *\n * @packageDocumentation\n */\nconst objToString = Object.prototype.toString;\nconst objKeys =\n Object.keys ||\n function (obj) {\n const keys = [];\n for (const name in obj) {\n keys.push(name);\n }\n return keys;\n };\n\nfunction stringify(val: unknown, isArrayProp: boolean) {\n let i, max, str, keys, key, propVal, toStr;\n if (val === true) {\n return 'true';\n }\n if (val === false) {\n return 'false';\n }\n switch (typeof val) {\n case 'object':\n if (val === null) {\n return null;\n } else if ('toJSON' in val && typeof val.toJSON === 'function') {\n return stringify(val.toJSON(), isArrayProp);\n } else {\n toStr = objToString.call(val);\n if (toStr === '[object Array]') {\n str = '[';\n max = (val as unknown[]).length - 1;\n for (i = 0; i < max; i++) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true) + ',';\n }\n if (max > -1) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true);\n }\n return str + ']';\n } else if (toStr === '[object Object]') {\n // only object is left\n keys = objKeys(val).sort();\n max = keys.length;\n str = '';\n i = 0;\n while (i < max) {\n key = keys[i];\n propVal = stringify((val as Record)[key], false);\n if (propVal !== undefined) {\n if (str) {\n str += ',';\n }\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += JSON.stringify(key) + ':' + propVal;\n }\n i++;\n }\n return '{' + str + '}';\n } else {\n return JSON.stringify(val);\n }\n }\n case 'function':\n case 'undefined':\n return isArrayProp ? null : undefined;\n case 'bigint':\n return `${val.toString()}n`;\n case 'string':\n return JSON.stringify(val);\n default:\n return isFinite(val as number) ? val : null;\n }\n}\n\nexport default function (\n val:\n | Function // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n | undefined,\n): undefined;\nexport default function (val: unknown): string;\nexport default function (val: unknown): string | undefined {\n const returnVal = stringify(val, false);\n if (returnVal !== undefined) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n return '' + returnVal;\n }\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcApi } from '@solana/rpc-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\n/**\n * When you create {@link Rpc} instances with custom transports but otherwise the default RPC API\n * behaviours, use this.\n *\n * @example\n * ```ts\n * const myCustomRpc = createRpc({\n * api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n * transport: myCustomTransport,\n * });\n * ```\n */\nexport const DEFAULT_RPC_CONFIG: Partial[0]>> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { AbortController } from '@solana/event-target-impl';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\n// This used to be a `Symbol()`, but there's a bug in Node <21 where the `undici` library passes\n// the `reason` property of the `AbortSignal` straight to `Error.captureStackTrace()` without first\n// typechecking it. `Error.captureStackTrace()` fatals when given a `Symbol`.\n// See https://github.com/nodejs/undici/pull/2597\nlet EXPLICIT_ABORT_TOKEN: ReturnType;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return process.env.NODE_ENV !== \"production\"\n ? {\n EXPLICIT_ABORT_TOKEN:\n 'This object is thrown from the request that underlies a series of coalesced ' +\n 'requests when the last request in that series aborts',\n }\n : {};\n}\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: TTransport,\n getDeduplicationKey: GetDeduplicationKeyFn,\n): TTransport {\n let coalescedRequestsByDeduplicationKey: Record | undefined;\n return async function makeCoalescedHttpRequest(\n request: Parameters[0],\n ): Promise> {\n const { payload, signal } = request;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(request);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n queueMicrotask(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n const responsePromise = (async () => {\n try {\n return await transport({\n ...request,\n signal: abortController.signal,\n });\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n // We triggered this error when the last subscriber aborted. Letting this\n // error bubble up from here would cause runtime fatals where there should\n // be none.\n return;\n }\n throw e;\n }\n })();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise,\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise>;\n return await new Promise>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n queueMicrotask(() => {\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n }\n });\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject((e.target as AbortSignal).reason);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise\n .then(resolve)\n .catch(reject)\n .finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as RpcResponse;\n }\n } as TTransport;\n}\n","import fastStableStringify from '@solana/fast-stable-stringify';\nimport { isJsonRpcPayload } from '@solana/rpc-spec';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport, createHttpTransportForSolanaRpc } from '@solana/rpc-transport-http';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { RpcTransportFromClusterUrl } from './rpc-clusters';\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\ntype RpcTransportConfig = Parameters[0];\ninterface DefaultRpcTransportConfig extends RpcTransportConfig {\n url: TClusterUrl;\n}\n\nfunction normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n // Lowercasing header names makes it easier to override user-supplied headers.\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n\n/**\n * Creates a {@link RpcTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - An automatically-set `Solana-Client` request header, containing the version of `@solana/kit`\n * - Logic that coalesces multiple calls in the same runloop, for the same methods with the same\n * arguments, into a single network request.\n * - [node-only] An automatically-set `Accept-Encoding` request header asking the server to compress\n * responses\n *\n * @param config\n */\nexport function createDefaultRpcTransport(\n config: DefaultRpcTransportConfig,\n): RpcTransportFromClusterUrl {\n return pipe(\n createHttpTransportForSolanaRpc({\n ...config,\n headers: {\n ...(__NODEJS__ &&\n ({\n // Keep these headers lowercase so they will be overridden by any user-supplied headers below.\n 'accept-encoding':\n // Natively supported by Node LTS v20.18.0 and above.\n 'br,gzip,deflate', // Brotli, gzip, and Deflate, in that order.\n } as { [overrideHeader: string]: string })),\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': __VERSION__ ? `js/${__VERSION__}` : 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }) as RpcTransportFromClusterUrl,\n transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey),\n );\n}\n","import { createSolanaRpcApi } from '@solana/rpc-api';\nimport { createRpc, RpcTransport } from '@solana/rpc-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport type { RpcFromTransport, SolanaRpcApiFromTransport } from './rpc-clusters';\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { createDefaultRpcTransport } from './rpc-transport';\n\ntype DefaultRpcTransportConfig = Parameters<\n typeof createDefaultRpcTransport\n>[0];\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given a cluster URL and some\n * optional transport config. See {@link createDefaultRpcTransport} for the shape of the transport\n * config.\n */\nexport function createSolanaRpc(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcFromTransport(createDefaultRpcTransport({ url: clusterUrl, ...config }));\n}\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given the supplied\n * {@link RpcTransport}.\n */\nexport function createSolanaRpcFromTransport(transport: TTransport) {\n return createRpc({\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n transport,\n }) as RpcFromTransport, TTransport>;\n}\n","\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable {\n const iteratorState: Map> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher = Record> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter>(\n eventEmitter: TypedEventEmitter | TypedEventTarget,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\nimport { createAsyncIterableFromDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsApi, RpcSubscriptionsPlan } from './rpc-subscriptions-api';\nimport { PendingRpcSubscriptionsRequest, RpcSubscribeOptions } from './rpc-subscriptions-request';\nimport { RpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsConfig = Readonly<{\n api: RpcSubscriptionsApi;\n transport: RpcSubscriptionsTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcSubscriptionsMethods`.\n *\n * Calling each method returns a\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} where\n * `TNotification` is that method's notification type.\n */\nexport type RpcSubscriptions = {\n [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder<\n OverloadImplementations\n >;\n};\n\ntype PendingRpcSubscriptionsRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TSubscriptionMethodImplementations]: PendingRpcSubscriptionsRequestReturnTypeMapper<\n TSubscriptionMethodImplementations[P]\n >;\n }>\n>;\n\ntype PendingRpcSubscriptionsRequestReturnTypeMapper =\n // Check that this property of the TRpcSubscriptionMethods interface is, in fact, a function.\n TSubscriptionMethodImplementation extends Callable\n ? (\n ...args: Parameters\n ) => PendingRpcSubscriptionsRequest>\n : never;\n\n/**\n * Creates a {@link RpcSubscriptions} instance given a\n * {@link RpcSubscriptionsApi | RpcSubscriptionsApi} and a\n * {@link RpcSubscriptionsTransport} capable of fulfilling them.\n */\nexport function createSubscriptionRpc(\n rpcConfig: RpcSubscriptionsConfig,\n): RpcSubscriptions {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const notificationName = p.toString();\n const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);\n if (!createRpcSubscriptionPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {\n notificationName,\n });\n }\n const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);\n return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);\n };\n },\n }) as RpcSubscriptions;\n}\n\nfunction createPendingRpcSubscription(\n transport: RpcSubscriptionsTransport,\n subscriptionsPlan: RpcSubscriptionsPlan,\n): PendingRpcSubscriptionsRequest {\n return {\n async subscribe({ abortSignal }: RpcSubscribeOptions): Promise> {\n const notificationsDataPublisher = await transport({\n signal: abortSignal,\n ...subscriptionsPlan,\n });\n return createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName: 'notification',\n dataPublisher: notificationsDataPublisher,\n errorChannelName: 'error',\n });\n },\n };\n}\n","import { Callable, RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsTransportDataEvents } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsApiConfig = Readonly<{\n planExecutor: RpcSubscriptionsPlanExecutor>;\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n}>;\n\n/**\n * A function that implements a protocol for subscribing and unsubscribing from notifications given\n * a {@link RpcSubscriptionsChannel}, a {@link RpcRequest}, and an `AbortSignal`.\n *\n * @returns A {@link DataPublisher} that emits {@link RpcSubscriptionsTransportDataEvents}\n */\ntype RpcSubscriptionsPlanExecutor = (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n request: RpcRequest;\n signal: AbortSignal;\n }>,\n) => Promise>>;\n\n/**\n * This type allows an {@link RpcSubscriptionsApi} to describe how a particular subscription should\n * be issued to the JSON RPC server.\n *\n * Given a function that was called on a {@link RpcSubscriptions}, this object exposes an `execute`\n * function that dictates which subscription request will be sent, how the underlying transport will\n * be used, and how the notifications will be transformed.\n *\n * This function accepts a {@link RpcSubscriptionsChannel} and an `AbortSignal` and asynchronously\n * returns a {@link DataPublisher}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * channel.\n * - call the underlying channel zero, one or multiple times depending on the use-case (e.g.\n * caching or coalescing multiple subscriptions).\n * - transform the notification from the JSON RPC server, in case it does not match the\n * `TNotification` specified by the\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} emitted\n * from the publisher returned.\n */\nexport type RpcSubscriptionsPlan = Readonly<{\n /**\n * This method may be called with a newly-opened channel or a pre-established channel.\n */\n execute: (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n signal: AbortSignal;\n }>,\n ) => Promise>>;\n /**\n * This request is used to uniquely identify the subscription.\n * It typically comes from the method name and parameters of the subscription call,\n * after potentially being transformed by the RPC Subscriptions API.\n */\n request: RpcRequest;\n}>;\n\n/**\n * For each of `TRpcSubscriptionsMethods`, this object exposes a method with the same name that maps\n * between its input arguments and a\n * {@link RpcSubscriptionsPlan | RpcSubscriptionsPlan} that implements the execution\n * of a JSON RPC subscription for `TNotifications`.\n */\nexport type RpcSubscriptionsApi = {\n [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper<\n TRpcSubscriptionMethods[MethodName]\n >;\n};\n\ntype RpcSubscriptionsReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcSubscriptionsPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcSubscriptionsApiMethod = (...args: any) => any;\nexport interface RpcSubscriptionsApiMethods {\n [methodName: string]: RpcSubscriptionsApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a\n * {@link RpcSubscriptionsPlan} by creating an `execute` function that:\n *\n * - calls the supplied {@link RpcSubscriptionsApiConfig.planExecutor} with a JSON RPC v2 payload\n * object with the requested `methodName` and `params` properties, optionally transformed by\n * {@link RpcSubscriptionsApiConfig.requestTransformer}.\n *\n * @example\n * ```ts\n * // For example, given this `RpcSubscriptionsApi`:\n * const rpcSubscriptionsApi = createJsonRpcSubscriptionsApi({\n * async planExecutor({ channel, request }) {\n * await channel.send(request);\n * return {\n * ...channel,\n * on(type, listener, options) {\n * if (type !== 'message') {\n * return channel.on(type, listener, options);\n * }\n * return channel.on(\n * 'message',\n * function resultGettingListener(message) {\n * listener(message.result);\n * },\n * options,\n * );\n * }\n * }\n * },\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * });\n *\n * // ...the following function call:\n * rpcSubscriptionsApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcSubscriptionsPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Emits the \"result\" property of each RPC Subscriptions message.\n * ```\n */\nexport function createRpcSubscriptionsApi(\n config: RpcSubscriptionsApiConfig,\n): RpcSubscriptionsApi {\n return new Proxy({} as RpcSubscriptionsApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcSubscriptionsApiMethods as string;\n return function (\n ...params: Parameters<\n TRpcSubscriptionsApiMethods[TNotificationName] extends CallableFunction\n ? TRpcSubscriptionsApiMethods[TNotificationName]\n : never\n >\n ): RpcSubscriptionsPlan> {\n const rawRequest = { methodName, params };\n const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;\n return {\n execute(planConfig) {\n return config.planExecutor({ ...planConfig, request });\n },\n request,\n };\n };\n },\n });\n}\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype RpcSubscriptionsChannelSolanaErrorCode =\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT;\n\nexport type RpcSubscriptionChannelEvents = {\n /**\n * Fires when the channel closes unexpectedly.\n * @eventProperty\n */\n error: SolanaError;\n /**\n * Fires on every message received from the remote end.\n * @eventProperty\n */\n message: TInboundMessage;\n};\n\n/**\n * A {@link DataPublisher} on which you can subscribe to events of type\n * {@link RpcSubscriptionChannelEvents | RpcSubscriptionChannelEvents}.\n * Additionally, you can use this object to send messages of type `TOutboundMessage` back to the\n * remote end by calling its {@link RpcSubscriptionsChannel.send | `send(message)`} method.\n */\nexport interface RpcSubscriptionsChannel extends DataPublisher<\n RpcSubscriptionChannelEvents\n> {\n send(message: TOutboundMessage): Promise;\n}\n\n/**\n * A channel creator is a function that accepts an `AbortSignal`, returns a new\n * {@link RpcSubscriptionsChannel}, and tears down the channel when the abort signal fires.\n */\nexport type RpcSubscriptionsChannelCreator = (\n config: Readonly<{\n abortSignal: AbortSignal;\n }>,\n) => Promise>;\n\n/**\n * Given a channel with inbound messages of type `T` and a function of type `T => U`, returns a new\n * channel with inbound messages of type `U`.\n *\n * Note that this only affects messages of type `\"message\"` and thus, does not affect incoming error\n * messages.\n *\n * @example Parsing incoming JSON messages\n * ```ts\n * const transformedChannel = transformChannelInboundMessages(channel, JSON.parse);\n * ```\n */\nexport function transformChannelInboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TInboundMessage) => TNewInboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n on(type, subscriber, options) {\n if (type !== 'message') {\n return channel.on(\n type,\n subscriber as (data: RpcSubscriptionChannelEvents[typeof type]) => void,\n options,\n );\n }\n return channel.on(\n 'message',\n message => (subscriber as (data: TNewInboundMessage) => void)(transform(message)),\n options,\n );\n },\n });\n}\n\n/**\n * Given a channel with outbound messages of type `T` and a function of type `U => T`, returns a new\n * channel with outbound messages of type `U`.\n *\n * @example Stringifying JSON messages before sending them over the wire\n * ```ts\n * const transformedChannel = transformChannelOutboundMessages(channel, JSON.stringify);\n * ```\n */\nexport function transformChannelOutboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TNewOutboundMessage) => TOutboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n send: message => channel.send(transform(message)),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n getSolanaErrorFromJsonRpcError,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport { createRpcMessage, RpcRequest, RpcResponseData, RpcResponseTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\nimport { demultiplexDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionChannelEvents } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\n\ntype Config = Readonly<{\n channel: RpcSubscriptionsChannel | RpcResponseData>;\n responseTransformer?: RpcResponseTransformer;\n signal: AbortSignal;\n subscribeRequest: RpcRequest;\n unsubscribeMethodName: string;\n}>;\n\ntype RpcNotification = Readonly<{\n method: string;\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\n\ntype RpcSubscriptionId = number;\n\ntype RpcSubscriptionNotificationEvents = Omit, 'message'> & {\n notification: TNotification;\n};\n\nconst subscriberCountBySubscriptionIdByChannel = new WeakMap>();\nfunction decrementSubscriberCountAndReturnNewCount(channel: WeakKey, subscriptionId?: number): number | undefined {\n return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);\n}\nfunction incrementSubscriberCount(channel: WeakKey, subscriptionId?: number): void {\n augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);\n}\nfunction getSubscriberCountBySubscriptionIdForChannel(channel: WeakKey): Record {\n let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);\n if (!subscriberCountBySubscriptionId) {\n subscriberCountBySubscriptionIdByChannel.set(channel, (subscriberCountBySubscriptionId = {}));\n }\n return subscriberCountBySubscriptionId;\n}\nfunction augmentSubscriberCountAndReturnNewCount(\n amount: -1 | 1,\n channel: WeakKey,\n subscriptionId?: number,\n): number | undefined {\n if (subscriptionId === undefined) {\n return;\n }\n const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);\n if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) {\n subscriberCountBySubscriptionId[subscriptionId] = 0;\n }\n const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];\n if (newCount <= 0) {\n delete subscriberCountBySubscriptionId[subscriptionId];\n } else {\n subscriberCountBySubscriptionId[subscriptionId] = newCount;\n }\n return newCount;\n}\n\nconst cache = new WeakMap();\nfunction getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel: RpcSubscriptionsChannel>,\n subscribeRequest: RpcRequest,\n responseTransformer?: RpcResponseTransformer,\n): DataPublisher<{\n [channelName: `notification:${number}`]: TNotification;\n}> {\n let publisherByResponseTransformer = cache.get(channel);\n if (!publisherByResponseTransformer) {\n cache.set(channel, (publisherByResponseTransformer = new WeakMap()));\n }\n const responseTransformerKey = responseTransformer ?? channel;\n let publisher = publisherByResponseTransformer.get(responseTransformerKey);\n if (!publisher) {\n publisherByResponseTransformer.set(\n responseTransformerKey,\n (publisher = demultiplexDataPublisher(channel, 'message', rawMessage => {\n const message = rawMessage as RpcNotification | RpcResponseData;\n if (!('method' in message)) {\n return;\n }\n const transformedNotification = responseTransformer\n ? responseTransformer(message.params.result, subscribeRequest)\n : message.params.result;\n return [`notification:${message.params.subscription}`, transformedNotification];\n })),\n );\n }\n return publisher;\n}\n\n/**\n * Given a channel, this function executes the particular subscription plan required by the Solana\n * JSON RPC Subscriptions API.\n *\n * @param config\n *\n * 1. Calls the `subscribeRequest` on the remote RPC\n * 2. Waits for a response containing the subscription id\n * 3. Returns a {@link DataPublisher} that publishes notifications related to that subscriptions id,\n * filtering out all others\n * 4. Calls the `unsubscribeMethodName` on the remote RPC when the abort signal is fired.\n */\nexport async function executeRpcPubSubSubscriptionPlan({\n channel,\n responseTransformer,\n signal,\n subscribeRequest,\n unsubscribeMethodName,\n}: Config): Promise>> {\n let subscriptionId: number | undefined;\n channel.on(\n 'error',\n () => {\n // An error on the channel indicates that the subscriptions are dead.\n // There is no longer any sense hanging on to subscription ids.\n // Erasing it here will prevent the unsubscribe code from running.\n subscriptionId = undefined;\n subscriberCountBySubscriptionIdByChannel.delete(channel);\n },\n { signal },\n );\n /**\n * STEP 1\n * Create a promise that rejects if this subscription is aborted and sends\n * the unsubscribe message if the subscription is active at that time.\n */\n const abortPromise = new Promise((_, reject) => {\n function handleAbort(this: AbortSignal) {\n /**\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they\n * will be assigned the same subscription id, and will occupy one subscription slot. We\n * must be careful not to send the unsubscribe message until the last subscriber aborts.\n */\n if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {\n const unsubscribePayload = createRpcMessage({\n methodName: unsubscribeMethodName,\n params: [subscriptionId],\n });\n subscriptionId = undefined;\n channel.send(unsubscribePayload).catch(() => {});\n }\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n }\n if (signal.aborted) {\n handleAbort.call(signal);\n } else {\n signal.addEventListener('abort', handleAbort);\n }\n });\n /**\n * STEP 2\n * Send the subscription request.\n */\n const subscribePayload = createRpcMessage(subscribeRequest);\n await channel.send(subscribePayload);\n /**\n * STEP 3\n * Wait for the acknowledgement from the server with the subscription id.\n */\n const subscriptionIdPromise = new Promise((resolve, reject) => {\n const abortController = new AbortController();\n signal.addEventListener('abort', abortController.abort.bind(abortController));\n const options = { signal: abortController.signal } as const;\n channel.on(\n 'error',\n err => {\n abortController.abort();\n reject(err);\n },\n options,\n );\n channel.on(\n 'message',\n message => {\n if (message && typeof message === 'object' && 'id' in message && message.id === subscribePayload.id) {\n abortController.abort();\n if ('error' in message) {\n reject(getSolanaErrorFromJsonRpcError(message.error));\n } else {\n resolve(message.result);\n }\n }\n },\n options,\n );\n });\n subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);\n if (subscriptionId == null) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);\n }\n incrementSubscriberCount(channel, subscriptionId);\n /**\n * STEP 4\n * Filter out notifications unrelated to this subscription.\n */\n const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel,\n subscribeRequest,\n responseTransformer,\n );\n const notificationKey = `notification:${subscriptionId}` as const;\n return {\n on(type, listener, options) {\n switch (type) {\n case 'notification':\n return notificationPublisher.on(\n notificationKey,\n listener as (data: RpcSubscriptionNotificationEvents['notification']) => void,\n options,\n );\n case 'error':\n return channel.on(\n 'error',\n listener as (data: RpcSubscriptionNotificationEvents['error']) => void,\n options,\n );\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {\n channelName: type,\n supportedChannelNames: ['notification', 'error'],\n });\n }\n },\n };\n}\n","import {\n createRpcSubscriptionsApi,\n executeRpcPubSubSubscriptionPlan,\n RpcSubscriptionsApi,\n RpcSubscriptionsApiMethods,\n} from '@solana/rpc-subscriptions-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpcSubscriptions,\n jsonParsedAccountsConfigs,\n KEYPATH_WILDCARD,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\nexport type SolanaRpcSubscriptionsApi = AccountNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsApiUnstable = BlockNotificationsApi &\n SlotsUpdatesNotificationsApi &\n VoteNotificationsApi;\n\nexport type {\n AccountNotificationsApi,\n BlockNotificationsApi,\n LogsNotificationsApi,\n ProgramNotificationsApi,\n RootNotificationsApi,\n SignatureNotificationsApi,\n SlotNotificationsApi,\n SlotsUpdatesNotificationsApi,\n VoteNotificationsApi,\n};\n\ntype Config = RequestTransformerConfig;\n\nfunction createSolanaRpcSubscriptionsApi_INTERNAL(\n config?: Config,\n): RpcSubscriptionsApi {\n const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);\n const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n });\n return createRpcSubscriptionsApi({\n planExecutor({ request, ...rest }) {\n return executeRpcPubSubSubscriptionPlan({\n ...rest,\n responseTransformer,\n subscribeRequest: { ...request, methodName: request.methodName.replace(/Notifications$/, 'Subscribe') },\n unsubscribeMethodName: request.methodName.replace(/Notifications$/, 'Unsubscribe'),\n });\n },\n requestTransformer,\n });\n}\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config,\n): RpcSubscriptionsApi {\n return createSolanaRpcSubscriptionsApi_INTERNAL(config);\n}\n\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(config?: Config) {\n return createSolanaRpcSubscriptionsApi_INTERNAL(\n config,\n );\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths<\n RpcSubscriptionsApi\n>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths<\n RpcSubscriptionsApi\n> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\n }\n return memoizedKeypaths;\n}\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 CLOSE_TIMEOUT: 30000,\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","'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\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\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\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\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 | String)[]} 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 CLOSE_TIMEOUT,\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 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._closeTimeout = options.closeTimeout;\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 {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\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 closeTimeout: CLOSE_TIMEOUT,\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 websocket._closeTimeout = opts.closeTimeout;\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 websocket._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 //\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. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\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","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\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 { 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 { CLOSE_TIMEOUT, 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 {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\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 closeTimeout: CLOSE_TIMEOUT,\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 !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\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 * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\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, headers);\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","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","// When building the browser bundle, this import gets replaced by `globalThis.WebSocket`.\nimport WebSocketImpl from 'ws';\n\nexport default globalThis.WebSocket\n ? globalThis.WebSocket // Use native `WebSocket` in runtimes that support it (eg. Deno)\n : WebSocketImpl;\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { EventTarget } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport { getDataPublisherFromEventEmitter } from '@solana/subscribable';\nimport WebSocket from '@solana/ws-impl';\n\nexport type Config = Readonly<{\n /**\n * The number of bytes to admit into the WebSocket's send buffer before queueing messages on the\n * client.\n *\n * When you call {@link RpcSubscriptionsChannel.send | `send()`} on a `WebSocket` the runtime\n * might add the message to a buffer rather than send it right away. In the event that\n * `socket.bufferedAmount` exceeds the value configured here, messages will be added to a queue\n * in your application code instead of being sent to the WebSocket, until such time as the\n * `bufferedAmount` falls back below the high watermark.\n */\n sendBufferHighWatermark: number;\n /**\n * An `AbortSignal` to fire when you want to explicitly close the `WebSocket`.\n *\n * If the channel is open it will be closed with a normal closure code\n * (https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1) If the channel has not been\n * established yet, firing this signal will result in the `AbortError` being thrown to the\n * caller who was trying to open the channel.\n */\n signal: AbortSignal;\n /**\n * A string representing the target endpoint.\n *\n * In Node, it must be an absolute URL using the `ws` or `wss` protocol.\n */\n url: string;\n}>;\n\ntype WebSocketMessage = ArrayBufferLike | ArrayBufferView | Blob | string;\n\nconst NORMAL_CLOSURE_CODE = 1000; // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n\n/**\n * Creates an object that represents an open channel to a `WebSocket` server.\n *\n * You can use it to send messages by calling its\n * {@link RpcSubscriptionsChannel.send | `send()`} function and you can receive them by subscribing\n * to the {@link RpcSubscriptionChannelEvents} it emits.\n */\nexport function createWebSocketChannel({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise> {\n if (signal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(signal.reason);\n }\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise }> | undefined;\n let hasConnected = false;\n const listenerRemovers = new Set<() => void>();\n function cleanupListeners() {\n listenerRemovers.forEach(r => {\n r();\n });\n listenerRemovers.clear();\n }\n function handleAbort() {\n cleanupListeners();\n if (!hasConnected) {\n rejectOpen(signal.reason);\n }\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(NORMAL_CLOSURE_CODE);\n }\n }\n function handleClose(ev: CloseEvent) {\n cleanupListeners();\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('message', handleMessage);\n webSocket.removeEventListener('open', handleOpen);\n if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) {\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, {\n cause: ev,\n }),\n }),\n );\n }\n }\n function handleError(ev: Event) {\n if (signal.aborted) {\n return;\n }\n if (!hasConnected) {\n const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, {\n errorEvent: ev,\n });\n rejectOpen(failedToConnectError);\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: failedToConnectError,\n }),\n );\n }\n }\n function handleMessage(ev: MessageEvent) {\n if (signal.aborted) {\n return;\n }\n eventTarget.dispatchEvent(new CustomEvent('message', { detail: ev.data }));\n }\n const eventTarget = new EventTarget();\n const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n function handleOpen() {\n hasConnected = true;\n resolveOpen({\n ...dataPublisher,\n async send(message) {\n if (webSocket.readyState !== WebSocket.OPEN) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);\n }\n if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {\n let onCancel!: () => void;\n const promise = new Promise((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n new SolanaError(\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n ),\n );\n };\n });\n bufferDrainWatcher = {\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {\n const TypedArrayConstructor = message.constructor as {\n new (...args: [typeof message]): typeof message;\n };\n // Clone the message to prevent mutation while queued.\n message = new TypedArrayConstructor(message);\n }\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n });\n }\n const webSocket = new WebSocket(url);\n signal.addEventListener('abort', handleAbort);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('message', handleMessage);\n webSocket.addEventListener('open', handleOpen);\n let rejectOpen!: (e: SolanaError) => void;\n let resolveOpen!: (value: RpcSubscriptionsChannel) => void;\n return new Promise>((resolve, reject) => {\n rejectOpen = reject;\n resolveOpen = resolve;\n });\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_SUBSCRIPTIONS_CONFIG: Partial<\n NonNullable[0]>\n> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { isSolanaError, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\ntype Config> = Readonly<{\n abortSignal: AbortSignal;\n channel: TChannel;\n intervalMs: number;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that sends a ping message to\n * the inner channel if a message has not been sent or received in the last `intervalMs`. In web\n * browsers, this implementation sends no ping when the network is down, and sends a ping\n * immediately upon the network coming back up.\n */\nexport function getRpcSubscriptionsChannelWithAutoping>({\n abortSignal: callerAbortSignal,\n channel,\n intervalMs,\n}: Config): TChannel {\n let intervalId: ReturnType | undefined;\n function sendPing() {\n channel.send(PING_PAYLOAD).catch((e: unknown) => {\n if (isSolanaError(e, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED)) {\n pingerAbortController.abort();\n }\n });\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, intervalMs);\n }\n const pingerAbortController = new AbortController();\n pingerAbortController.signal.addEventListener('abort', () => {\n clearInterval(intervalId);\n });\n callerAbortSignal.addEventListener('abort', () => {\n pingerAbortController.abort();\n });\n channel.on(\n 'error',\n () => {\n pingerAbortController.abort();\n },\n { signal: pingerAbortController.signal },\n );\n channel.on('message', restartPingTimer, { signal: pingerAbortController.signal });\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n if (__BROWSER__) {\n globalThis.addEventListener(\n 'offline',\n function handleOffline() {\n clearInterval(intervalId);\n },\n { signal: pingerAbortController.signal },\n );\n globalThis.addEventListener(\n 'online',\n function handleOnline() {\n sendPing();\n restartPingTimer();\n },\n { signal: pingerAbortController.signal },\n );\n }\n return {\n ...channel,\n send(...args) {\n if (!pingerAbortController.signal.aborted) {\n restartPingTimer();\n }\n return channel.send(...args);\n },\n };\n}\n","import { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\nexport type ChannelPoolEntry = {\n channel: PromiseLike> | RpcSubscriptionsChannel;\n readonly dispose: () => void;\n subscriptionCount: number;\n};\n\ntype ChannelPool = { readonly entries: ChannelPoolEntry[]; freeChannelIndex: number };\n\nexport function createChannelPool(): ChannelPool {\n return {\n entries: [],\n freeChannelIndex: -1,\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannelCreator } from '@solana/rpc-subscriptions-spec';\n\nimport { ChannelPoolEntry, createChannelPool } from './rpc-subscriptions-channel-pool-internal';\n\ntype Config = Readonly<{\n maxSubscriptionsPerChannel: number;\n minChannels: number;\n}>;\n\n/**\n * Given a channel creator, will return a new channel creator with the following behavior.\n *\n * 1. When called, returns a {@link RpcSubscriptionsChannel}. Adds that channel to a pool.\n * 2. When called again, creates and returns new\n * {@link RpcSubscriptionChannel | RpcSubscriptionChannels} up to the number specified by\n * `minChannels`.\n * 3. When `minChannels` channels have been created, subsequent calls vend whichever existing\n * channel from the pool has the fewest subscribers, or the next one in rotation in the event of\n * a tie.\n * 4. Once all channels carry the number of subscribers specified by the number\n * `maxSubscriptionsPerChannel`, new channels in excess of `minChannel` will be created,\n * returned, and added to the pool.\n * 5. A channel will be destroyed once all of its subscribers' abort signals fire.\n */\nexport function getChannelPoolingChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n>(createChannel: TChannelCreator, { maxSubscriptionsPerChannel, minChannels }: Config): TChannelCreator {\n const pool = createChannelPool();\n /**\n * This function advances the free channel index to the pool entry with the most capacity. It\n * sets the index to `-1` if all channels are full.\n */\n function recomputeFreeChannelIndex() {\n if (pool.entries.length < minChannels) {\n // Don't set the free channel index until the pool fills up; we want to keep creating\n // channels before we start rotating among them.\n pool.freeChannelIndex = -1;\n return;\n }\n let mostFreeChannel: Readonly<{ poolIndex: number; subscriptionCount: number }> | undefined;\n for (let ii = 0; ii < pool.entries.length; ii++) {\n const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;\n const nextPoolEntry =\n // Start from the item two positions after the current item. This way, the\n // search will finish on the item after the current one. This ensures that, if\n // any channels tie for having the most capacity, the one that will be chosen is\n // the one immediately to the current one's right (wrapping around).\n pool.entries[nextPoolIndex];\n if (\n nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel &&\n (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)\n ) {\n mostFreeChannel = {\n poolIndex: nextPoolIndex,\n subscriptionCount: nextPoolEntry.subscriptionCount,\n };\n }\n }\n pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;\n }\n return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {\n let poolEntry: ChannelPoolEntry;\n function destroyPoolEntry() {\n const index = pool.entries.findIndex(entry => entry === poolEntry);\n pool.entries.splice(index, 1);\n poolEntry.dispose();\n recomputeFreeChannelIndex();\n }\n if (pool.freeChannelIndex === -1) {\n const abortController = new AbortController();\n const newChannelPromise = createChannel({ abortSignal: abortController.signal });\n newChannelPromise\n .then(newChannel => {\n newChannel.on('error', destroyPoolEntry, { signal: abortController.signal });\n })\n .catch(destroyPoolEntry);\n poolEntry = {\n channel: newChannelPromise,\n dispose() {\n abortController.abort();\n },\n subscriptionCount: 0,\n };\n pool.entries.push(poolEntry);\n } else {\n poolEntry = pool.entries[pool.freeChannelIndex];\n }\n /**\n * A note about subscription counts.\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they will be\n * assigned the same subscription id, and will occupy one subscription slot. We can't tell,\n * from here, whether a subscription will be treated in this way or not, so we\n * unconditionally increment the subscription count every time a subscription request is\n * made. This may result in subscription channels being treated as out-of-capacity when in\n * fact they are not.\n */\n poolEntry.subscriptionCount++;\n abortSignal.addEventListener('abort', function destroyConsumer() {\n poolEntry.subscriptionCount--;\n if (poolEntry.subscriptionCount === 0) {\n destroyPoolEntry();\n } else if (pool.freeChannelIndex !== -1) {\n // Back the free channel index up one position, and recompute it.\n pool.freeChannelIndex--;\n recomputeFreeChannelIndex();\n }\n });\n recomputeFreeChannelIndex();\n return poolEntry.channel;\n } as TChannelCreator;\n}\n","import { pipe } from '@solana/functional';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that parses data published to\n * the `'message'` channel as JSON, and JSON-stringifies messages sent via the\n * {@link RpcSubscriptionsChannel.send | send(message)} method.\n */\nexport function getRpcSubscriptionsChannelWithJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, JSON.parse),\n c => transformChannelOutboundMessages(c, JSON.stringify),\n );\n}\n","import { pipe } from '@solana/functional';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Similarly, to {@link getRpcSubscriptionsChannelWithJSONSerialization}, this function will\n * stringify and parse JSON message to and from the given `string` channel. However, this function\n * parses any integer value as a `BigInt` in order to safely handle numbers that exceed the\n * JavaScript [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\n * value.\n */\nexport function getRpcSubscriptionsChannelWithBigIntJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, parseJsonWithBigInts),\n c => transformChannelOutboundMessages(c, stringifyJsonWithBigInts),\n );\n}\n","import { createWebSocketChannel } from '@solana/rpc-subscriptions-channel-websocket';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { getRpcSubscriptionsChannelWithAutoping } from './rpc-subscriptions-autopinger';\nimport { getChannelPoolingChannelCreator } from './rpc-subscriptions-channel-pool';\nimport { RpcSubscriptionsChannelCreatorFromClusterUrl } from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsChannelWithJSONSerialization } from './rpc-subscriptions-json';\nimport { getRpcSubscriptionsChannelWithBigIntJSONSerialization } from './rpc-subscriptions-json-bigint';\n\nexport type DefaultRpcSubscriptionsChannelConfig = Readonly<{\n /**\n * The number of milliseconds to wait since the last message sent or received over the channel\n * before sending a ping message to keep the channel open.\n */\n intervalMs?: number;\n /**\n * The number of subscribers that may share a channel before a new channel must be created.\n *\n * It is important that you set this to the maximum number of subscriptions that your RPC\n * provider recommends making over a single connection; the default is set deliberately low, so\n * as to comply with the restrictive limits of the public mainnet RPC node.\n *\n * @defaultValue 100\n */\n maxSubscriptionsPerChannel?: number;\n /** The number of channels to create before reusing a channel for a new subscription. */\n minChannels?: number;\n /**\n * The number of bytes of data to admit into the\n * [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) buffer before\n * buffering data on the client.\n */\n sendBufferHighWatermark?: number;\n /** The URL of the web socket server. Must use the `ws` or `wss` protocols. */\n url: TClusterUrl;\n}>;\n\n/**\n * Similar to {@link createDefaultRpcSubscriptionsChannelCreator} with some Solana-specific\n * defaults.\n *\n * For instance, it safely handles `BigInt` values in JSON messages since Solana RPC servers accept\n * and return integers larger than [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER).\n */\nexport function createDefaultSolanaRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization,\n });\n}\n\n/**\n * Creates a function that returns new subscription channels when called.\n */\nexport function createDefaultRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithJSONSerialization,\n });\n}\n\nfunction createDefaultRpcSubscriptionsChannelCreatorImpl(\n config: DefaultRpcSubscriptionsChannelConfig & {\n jsonSerializer: (channel: RpcSubscriptionsChannel) => RpcSubscriptionsChannel;\n },\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n if (/^wss?:/i.test(config.url) === false) {\n const protocolMatch = config.url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? \"Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or \" +\n `'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`,\n );\n }\n const { intervalMs, ...rest } = config;\n const createDefaultRpcSubscriptionsChannel = (({ abortSignal }) => {\n return createWebSocketChannel({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n signal: abortSignal,\n })\n .then(config.jsonSerializer)\n .then(channel =>\n getRpcSubscriptionsChannelWithAutoping({\n abortSignal,\n channel,\n intervalMs: intervalMs ?? 5_000,\n }),\n );\n }) as RpcSubscriptionsChannelCreatorFromClusterUrl;\n return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {\n maxSubscriptionsPerChannel:\n config.maxSubscriptionsPerChannel ??\n /**\n * A note about this default. The idea here is that, because some RPC providers impose\n * an upper limit on the number of subscriptions you can make per channel, we must\n * choose a number low enough to avoid hitting that limit. Without knowing what provider\n * a given person is using, or what their limit is, we have to choose the lowest of all\n * known limits. As of this writing (October 2024) that is the public mainnet RPC node\n * (api.mainnet-beta.solana.com) at 100 subscriptions.\n */\n 100,\n minChannels: config.minChannels ?? 1,\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport fastStableStringify from '@solana/fast-stable-stringify';\nimport { RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype CacheEntry = {\n readonly abortController: AbortController;\n readonly dataPublisherPromise: Promise;\n numSubscribers: number;\n};\n\n/**\n * Given a {@link RpcSubscriptionsTransport}, will return a new transport that coalesces identical\n * subscriptions into a single subscription request to the server. The determination of whether a\n * subscription is the same as another is based on the `rpcRequest` returned by its\n * {@link RpcSubscriptionsPlan}. The subscription will only be aborted once all subscribers abort,\n * or there is an error.\n */\nexport function getRpcSubscriptionsTransportWithSubscriptionCoalescing(\n transport: TTransport,\n): TTransport {\n const cache = new Map();\n return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {\n const { request, signal } = config;\n const subscriptionConfigurationHash = fastStableStringify([request.methodName, request.params]);\n\n let cachedDataPublisherPromise = cache.get(subscriptionConfigurationHash);\n if (!cachedDataPublisherPromise) {\n const abortController = new AbortController();\n const dataPublisherPromise = transport({\n ...config,\n signal: abortController.signal,\n });\n dataPublisherPromise\n .then(dataPublisher => {\n dataPublisher.on(\n 'error',\n () => {\n cache.delete(subscriptionConfigurationHash);\n abortController.abort();\n },\n { signal: abortController.signal },\n );\n })\n .catch(() => {});\n cache.set(\n subscriptionConfigurationHash,\n (cachedDataPublisherPromise = {\n abortController,\n dataPublisherPromise,\n numSubscribers: 0,\n }),\n );\n }\n cachedDataPublisherPromise.numSubscribers++;\n signal.addEventListener(\n 'abort',\n () => {\n cachedDataPublisherPromise.numSubscribers--;\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n queueMicrotask(() => {\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n cache.delete(subscriptionConfigurationHash);\n cachedDataPublisherPromise.abortController.abort();\n }\n });\n }\n },\n { signal: cachedDataPublisherPromise.abortController.signal },\n );\n return cachedDataPublisherPromise.dataPublisherPromise;\n } as TTransport;\n}\n","import { pipe } from '@solana/functional';\nimport { RpcSubscriptionsChannelCreator, RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport {\n RpcSubscriptionsChannelCreatorDevnet,\n RpcSubscriptionsChannelCreatorFromClusterUrl,\n RpcSubscriptionsChannelCreatorMainnet,\n RpcSubscriptionsChannelCreatorTestnet,\n RpcSubscriptionsTransportDevnet,\n RpcSubscriptionsTransportFromClusterUrl,\n RpcSubscriptionsTransportMainnet,\n RpcSubscriptionsTransportTestnet,\n} from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsTransportWithSubscriptionCoalescing } from './rpc-subscriptions-coalescer';\n\nexport type DefaultRpcSubscriptionsTransportConfig = Readonly<{\n createChannel: RpcSubscriptionsChannelCreatorFromClusterUrl;\n}>;\n\n/**\n * Creates a {@link RpcSubscriptionsTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - Logic that coalesces multiple subscriptions for the same notifications with the same arguments\n * into a single subscription.\n *\n * @param config\n */\nexport function createDefaultRpcSubscriptionsTransport({\n createChannel,\n}: DefaultRpcSubscriptionsTransportConfig) {\n return pipe(\n createRpcSubscriptionsTransportFromChannelCreator(\n createChannel,\n ) as RpcSubscriptionsTransport as RpcSubscriptionsTransportFromClusterUrl,\n transport => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport),\n );\n}\n\nexport function createRpcSubscriptionsTransportFromChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n TInboundMessage,\n TOutboundMessage,\n>(createChannel: TChannelCreator) {\n return (async ({ execute, signal }) => {\n const channel = await createChannel({ abortSignal: signal });\n return await execute({ channel, signal });\n }) as TChannelCreator extends RpcSubscriptionsChannelCreatorDevnet\n ? RpcSubscriptionsTransportDevnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorTestnet\n ? RpcSubscriptionsTransportTestnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorMainnet\n ? RpcSubscriptionsTransportMainnet\n : RpcSubscriptionsTransport;\n}\n","import type { SolanaRpcSubscriptionsApi, SolanaRpcSubscriptionsApiUnstable } from '@solana/rpc-subscriptions-api';\nimport { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\nimport {\n createSubscriptionRpc,\n RpcSubscriptionsApiMethods,\n type RpcSubscriptionsTransport,\n} from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport { DEFAULT_RPC_SUBSCRIPTIONS_CONFIG } from './rpc-default-config';\nimport {\n createDefaultSolanaRpcSubscriptionsChannelCreator,\n DefaultRpcSubscriptionsChannelConfig,\n} from './rpc-subscriptions-channel';\nimport type { RpcSubscriptionsFromTransport } from './rpc-subscriptions-clusters';\nimport { createDefaultRpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\ntype Config = DefaultRpcSubscriptionsChannelConfig;\n\nfunction createSolanaRpcSubscriptionsImpl(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n const transport = createDefaultRpcSubscriptionsTransport({\n createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ ...config, url: clusterUrl }),\n });\n return createSolanaRpcSubscriptionsFromTransport(transport);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(clusterUrl, config);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API,\n * including its unstable methods, given a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(\n clusterUrl,\n config,\n );\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * the supplied {@link RpcSubscriptionsTransport}.\n */\nexport function createSolanaRpcSubscriptionsFromTransport<\n TTransport extends RpcSubscriptionsTransport,\n TApi extends RpcSubscriptionsApiMethods = SolanaRpcSubscriptionsApi,\n>(transport: TTransport) {\n return createSubscriptionRpc({\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_SUBSCRIPTIONS_CONFIG),\n transport,\n }) as RpcSubscriptionsFromTransport;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SolanaError } from '@solana/errors';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Removes all duplicated {@link MessageSigner | MessageSigners} and\n * {@link TransactionSigner | TransactionSigners} from a provided array\n * by comparing their {@link Address | addresses}.\n *\n * @internal\n */\nexport function deduplicateSigners(\n signers: readonly TSigner[],\n): readonly TSigner[] {\n const deduplicated: Record = {};\n signers.forEach(signer => {\n if (!deduplicated[signer.address]) {\n deduplicated[signer.address] = signer;\n } else if (deduplicated[signer.address] !== signer) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, {\n address: signer.address,\n });\n }\n });\n return Object.values(deduplicated);\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionModifyingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that potentially modifies the provided {@link Transaction | Transactions}\n * before signing them.\n *\n * For instance, this enables wallets to inject additional instructions into the\n * transaction before signing them. For each transaction, instead of returning a\n * {@link SignatureDictionary}, its\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} function\n * returns an updated {@link Transaction} with a potentially modified set of instructions and\n * signature dictionary. The returned transaction must be within the transaction size limit,\n * and include a `lifetimeConstraint`.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignTransactions: async (\n * transactions: Transaction[]\n * ): Promise<(Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the provided transactions.\n * - **First signers**. For a given transaction, a modifying signer must always\n * be used before a partial signer as the former will likely modify the\n * transaction and thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided,\n * the second signer may invalidate the signature of the first one. However,\n * modifying signers may decide not to modify a transaction based on the\n * existence of signatures for that transaction.\n *\n * @see {@link isTransactionModifyingSigner}\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport type TransactionModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport function isTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionModifyingSigner {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionModifyingSigner}\n */\nexport function assertIsTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionModifyingSigner {\n if (!isTransactionModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionPartialSigner#signTransactions | signTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionPartialSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link Transaction | Transactions}\n * without modifying their content. It defines a\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * function that returns a {@link SignatureDictionary} for each provided transaction.\n *\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionPartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signTransactions: async (\n * transactions: Transaction[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. It returns a signature dictionary for each provided\n * transaction without modifying them, making it possible for multiple\n * partial signers to sign the same transaction in parallel.\n * - **Flexible order**. The order in which we use these signers for\n * a given transaction doesn’t matter.\n *\n * @see {@link isTransactionPartialSigner}\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport type TransactionPartialSigner = Readonly<{\n address: Address;\n signTransactions(\n transactions: readonly (Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[],\n config?: TransactionPartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionPartialSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionPartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport function isTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionPartialSigner {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionPartialSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionPartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionPartialSigner}\n */\nexport function assertIsTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionPartialSigner {\n if (!isTransactionPartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { Transaction, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionSendingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs one or multiple transactions\n * before sending them immediately to the blockchain.\n *\n * It defines a {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions}\n * function that returns the transaction signature (i.e. its identifier) for each provided\n * {@link Transaction}.\n *\n * This interface is required for PDA wallets and other types of wallets that don't provide an\n * interface for signing transactions without sending them.\n *\n * Note that it is also possible for such signers to modify the provided transactions\n * before signing and sending them. This enables use cases where the modified transactions\n * cannot be shared with the app and thus must be sent directly.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signAndSendTransactions: async (transactions: Transaction[]): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Single signer**. Since this signer also sends the provided transactions,\n * we can only use a single {@link TransactionSendingSigner} for a given set of transactions.\n * - **Last signer**. Trivially, that signer must also be the last one used.\n * - **Potential conflicts**. Since signers may decide to modify the given\n * transactions before sending them, they may invalidate previous signatures.\n * However, signers may decide not to modify a transaction based\n * on the existence of signatures for that transaction.\n * - **Potential confirmation**. Whilst this is not required by this interface,\n * it is also worth noting that most wallets will also wait for the transaction\n * to be confirmed (typically with a `confirmed` commitment)\n * before notifying the app that they are done.\n *\n * @see {@link isTransactionSendingSigner}\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport type TransactionSendingSigner = Readonly<{\n address: Address;\n signAndSendTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionSendingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSendingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport function isTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSendingSigner {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSendingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSendingSigner}\n */\nexport function assertIsTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSendingSigner {\n if (!isTransactionSendingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a signer capable of signing transactions.\n *\n * @see {@link TransactionModifyingSigner} For signers that can modify transactions before signing them.\n * @see {@link TransactionPartialSigner} For signers that can be used in parallel.\n * @see {@link TransactionSendingSigner} For signers that send transactions after signing them.\n * @see {@link isTransactionSigner}\n * @see {@link assertIsTransactionSigner}\n */\nexport type TransactionSigner =\n | TransactionModifyingSigner\n | TransactionPartialSigner\n | TransactionSendingSigner;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSigner}\n */\nexport function isTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSigner {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSigner}\n */\nexport function assertIsTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSigner {\n if (!isTransactionSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionVersion,\n} from '@solana/transaction-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionMessageWithFeePayerSigner } from './fee-payer-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * An extension of the {@link AccountMeta} type that allows us to store {@link TransactionSigner | TransactionSigners} inside it.\n *\n * Note that, because this type represents a signer, it must use one the following two roles:\n * - {@link AccountRole.READONLY_SIGNER}\n * - {@link AccountRole.WRITABLE_SIGNER}\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner} to use within the account meta.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole } from '@solana/instructions';\n * import { generateKeyPairSigner, AccountSignerMeta } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const account: AccountSignerMeta = {\n * address: signer.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer,\n * };\n * ```\n */\nexport interface AccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> extends AccountMeta {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\n/**\n * A union type that supports base account metas as well as {@link AccountSignerMeta | signer account metas}.\n */\ntype AccountMetaWithSigner =\n | AccountLookupMeta\n | AccountMeta\n | AccountSignerMeta;\n\n/**\n * Composable type that allows {@link AccountSignerMeta | AccountSignerMetas} to be used inside the instruction's `accounts` array\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { generateKeyPairSigner, InstructionWithSigners } from '@solana/signers';\n *\n * const [authority, buffer] = await Promise.all([\n * generateKeyPairSigner(),\n * generateKeyPairSigner(),\n * ]);\n * const instruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [\n * // The authority is a signer account.\n * {\n * address: authority.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer: authority,\n * },\n * // The buffer is a writable account.\n * { address: buffer.address, role: AccountRole.WRITABLE },\n * ],\n * };\n * ```\n */\nexport type InstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Pick, 'accounts'>;\n\n/**\n * A {@link BaseTransactionMessage} type extension that accept {@link TransactionSigner | TransactionSigners}.\n *\n * Namely, it allows:\n * - a {@link TransactionSigner} to be used as the fee payer and\n * - {@link InstructionWithSigners} to be used in its instructions.\n *\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, InstructionWithSigners, TransactionMessageWithSigners } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const firstInstruction: Instruction = { ... };\n * const secondInstruction: InstructionWithSigners = { ... };\n * const transactionMessage: BaseTransactionMessage & TransactionMessageWithSigners = {\n * feePayer: signer,\n * instructions: [firstInstruction, secondInstruction],\n * }\n * ```\n */\nexport type TransactionMessageWithSigners<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Partial | TransactionMessageWithFeePayerSigner> &\n Pick<\n BaseTransactionMessage>,\n 'instructions'\n >;\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside the account metas of an {@link InstructionWithSigners | instruction}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n *\n * @example\n * ```ts\n * import { InstructionWithSigners, getSignersFromInstruction } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const instructionWithSigners: InstructionWithSigners = {\n * accounts: [\n * { address: signerA.address, signer: signerA, ... },\n * { address: signerB.address, signer: signerB, ... },\n * { address: signerA.address, signer: signerA, ... },\n * ],\n * };\n *\n * const instructionSigners = getSignersFromInstruction(instructionWithSigners);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromInstruction(\n instruction: InstructionWithSigners,\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : [])),\n );\n}\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside a given {@link TransactionMessageWithSigners | transaction message}.\n *\n * This includes any {@link TransactionSigner | TransactionSigners} stored\n * as the fee payer or in the instructions of the transaction message.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { InstructionWithSigners, TransactionMessageWithSigners, getSignersFromTransactionMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const firstInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerA.address, signer: signerA, ... }],\n * };\n * const secondInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerB.address, signer: signerB, ... }],\n * };\n * const transactionMessage: TransactionMessageWithSigners = {\n * feePayer: signerA,\n * instructions: [firstInstruction, secondInstruction],\n * }\n *\n * const transactionSigners = getSignersFromTransactionMessage(transactionMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromTransactionMessage<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TTransactionMessage extends TransactionMessageWithSigners = TransactionMessageWithSigners<\n TAddress,\n TSigner\n >,\n>(transaction: TTransactionMessage): readonly TSigner[] {\n return deduplicateSigners([\n ...(transaction.feePayer && isTransactionSigner(transaction.feePayer) ? [transaction.feePayer as TSigner] : []),\n ...transaction.instructions.flatMap(getSignersFromInstruction),\n ]);\n}\n","import { Address } from '@solana/addresses';\nimport { Instruction, isSignerRole } from '@solana/instructions';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { AccountSignerMeta, InstructionWithSigners, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of an instruction when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TInstruction - The inferred type of the instruction provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { addSignersToInstruction, TransactionSigner } from '@solana/signers';\n *\n * const instruction: Instruction = {\n * accounts: [\n * { address: '1111' as Address, role: AccountRole.READONLY_SIGNER },\n * { address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER },\n * ],\n * // ...\n * };\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const instructionWithSigners = addSignersToInstruction(\n * [signerA, signerB],\n * instruction\n * );\n *\n * // instructionWithSigners.accounts[0].signer === signerA\n * // instructionWithSigners.accounts[1].signer === signerB\n * ```\n */\nexport function addSignersToInstruction(\n signers: TransactionSigner[],\n instruction: TInstruction | (InstructionWithSigners & TInstruction),\n): InstructionWithSigners & TInstruction {\n if (!instruction.accounts || instruction.accounts.length === 0) {\n return instruction as InstructionWithSigners & TInstruction;\n }\n\n const signerByAddress = new Map(deduplicateSigners(signers).map(signer => [signer.address, signer]));\n return Object.freeze({\n ...instruction,\n accounts: instruction.accounts.map(account => {\n const signer = signerByAddress.get(account.address);\n if (!isSignerRole(account.role) || 'signer' in account || !signer) {\n return account;\n }\n return Object.freeze({ ...account, signer } as AccountSignerMeta);\n }),\n });\n}\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of all instructions inside a transaction message and/or\n * the transaction message fee payer, when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { addSignersToTransactionMessage, TransactionSigner } from '@solana/signers';\n *\n * const instructionA: Instruction = {\n * accounts: [{ address: '1111' as Address, role: AccountRole.READONLY_SIGNER }],\n * // ...\n * };\n * const instructionB: Instruction = {\n * accounts: [{ address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER }],\n * // ...\n * };\n * const transactionMessage: BaseTransactionMessage = {\n * instructions: [instructionA, instructionB],\n * // ...\n * }\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const transactionMessageWithSigners = addSignersToTransactionMessage(\n * [signerA, signerB],\n * transactionMessage\n * );\n *\n * // transactionMessageWithSigners.instructions[0].accounts[0].signer === signerA\n * // transactionMessageWithSigners.instructions[1].accounts[0].signer === signerB\n * ```\n */\nexport function addSignersToTransactionMessage(\n signers: TransactionSigner[],\n transactionMessage: TTransactionMessage | (TransactionMessageWithSigners & TTransactionMessage),\n): TransactionMessageWithSigners & TTransactionMessage {\n const feePayerSigner = hasAddressOnlyFeePayer(transactionMessage)\n ? signers.find(signer => signer.address === transactionMessage.feePayer.address)\n : undefined;\n\n if (!feePayerSigner && transactionMessage.instructions.length === 0) {\n return transactionMessage as TransactionMessageWithSigners & TTransactionMessage;\n }\n\n return Object.freeze({\n ...transactionMessage,\n ...(feePayerSigner ? { feePayer: feePayerSigner } : null),\n instructions: transactionMessage.instructions.map(instruction => addSignersToInstruction(signers, instruction)),\n });\n}\n\nfunction hasAddressOnlyFeePayer(\n message: BaseTransactionMessage & Partial,\n): message is BaseTransactionMessage & { feePayer: { address: Address } } {\n return (\n !!message &&\n 'feePayer' in message &&\n !!message.feePayer &&\n typeof message.feePayer.address === 'string' &&\n !isTransactionSigner(message.feePayer)\n );\n}\n","import { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Alternative to {@link TransactionMessageWithFeePayer} that uses a {@link TransactionSigner} for the fee payer.\n *\n * @typeParam TAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner}.\n *\n * @example\n * ```ts\n * import { TransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, TransactionMessageWithFeePayerSigner } from '@solana/signers';\n *\n * const transactionMessage: TransactionMessage & TransactionMessageWithFeePayerSigner = {\n * feePayer: await generateKeyPairSigner(),\n * instructions: [],\n * version: 0,\n * };\n * ```\n */\nexport interface TransactionMessageWithFeePayerSigner<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> {\n readonly feePayer: TSigner;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Sets the fee payer of a {@link TransactionMessage | transaction message}\n * using a {@link TransactionSigner}.\n *\n * @typeParam TFeePayerAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { pipe } from '@solana/functional';\n * import { generateKeyPairSigner, setTransactionMessageFeePayerSigner } from '@solana/signers';\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const feePayer = await generateKeyPairSigner();\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(signer, message),\n * );\n * ```\n */\nexport function setTransactionMessageFeePayerSigner<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial &\n TransactionMessage,\n>(\n feePayer: TransactionSigner,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayerSigner {\n Object.freeze(feePayer);\n const out = { ...transactionMessage, feePayer };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayerSigner;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessagePartialSigner#signMessages | signMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessagePartialSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link SignableMessage | SignableMessages}\n * without modifying their content.\n *\n * It defines a {@link MessagePartialSigner#signMessages | signMessages} function\n * that returns a {@link SignatureDictionary} for each provided message.\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessagePartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. When multiple signers sign the same message, we can\n * perform this operation in parallel to obtain all their signatures.\n * - **Flexible order**. The order in which we use these signers\n * for a given message doesn’t matter.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessagePartialSigner}\n * @see {@link assertIsMessagePartialSigner}\n */\nexport type MessagePartialSigner = Readonly<{\n address: Address;\n signMessages(\n messages: readonly SignableMessage[],\n config?: MessagePartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessagePartialSigner({ address, signMessages: async () => {} }); // true\n * isMessagePartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessagePartialSigner}\n */\nexport function isMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessagePartialSigner {\n return 'signMessages' in value && typeof value.signMessages === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessagePartialSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessagePartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessagePartialSigner}\n */\nexport function assertIsMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessagePartialSigner {\n if (!isMessagePartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SolanaError } from '@solana/errors';\nimport { createKeyPairFromBytes, createKeyPairFromPrivateKeyBytes, generateKeyPair, signBytes } from '@solana/keys';\nimport { partiallySignTransaction } from '@solana/transactions';\n\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a signer that uses a {@link CryptoKeyPair} to sign messages and transactions.\n *\n * It implements both the {@link MessagePartialSigner} and {@link TransactionPartialSigner}\n * interfaces and keeps track of the {@link CryptoKeyPair} instance used\n * to sign messages and transactions.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = generateKeyPairSigner();\n * signer.address; // Address;\n * signer.keyPair; // CryptoKeyPair;\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * ```\n *\n * @see {@link generateKeyPairSigner}\n * @see {@link createSignerFromKeyPair}\n * @see {@link createKeyPairSignerFromBytes}\n * @see {@link createKeyPairSignerFromPrivateKeyBytes}\n * @see {@link isKeyPairSigner}\n * @see {@link assertIsKeyPairSigner}\n */\nexport type KeyPairSigner = MessagePartialSigner &\n TransactionPartialSigner & { keyPair: CryptoKeyPair };\n\n/**\n * Checks whether the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, isKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * isKeyPairSigner(signer); // true\n * isKeyPairSigner({ address: address('1234..5678') }); // false\n * ```\n */\nexport function isKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is KeyPairSigner {\n return (\n 'keyPair' in value &&\n typeof value.keyPair === 'object' &&\n isMessagePartialSigner(value) &&\n isTransactionPartialSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, assertIsKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * assertIsKeyPairSigner(signer); // void\n * assertIsKeyPairSigner({ address: address('1234..5678') }); // Throws an error.\n * ```\n */\nexport function assertIsKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is KeyPairSigner {\n if (!isKeyPairSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, {\n address: value.address,\n });\n }\n}\n\n/**\n * Creates a {@link KeyPairSigner} from a provided {@link CryptoKeyPair}.\n *\n * The {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * functions of the returned signer will use the private key of the provided\n * key pair to sign messages and transactions.\n *\n * Note that both the {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions} implementations\n * are parallelized, meaning that they will sign all provided messages and transactions in parallel.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { createSignerFromKeyPair, KeyPairSigner } from '@solana/signers';\n *\n * const keyPair: CryptoKeyPair = await generateKeyPair();\n * const signer: KeyPairSigner = await createSignerFromKeyPair(keyPair);\n * ```\n */\nexport async function createSignerFromKeyPair(keyPair: CryptoKeyPair): Promise {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const out: KeyPairSigner = {\n address,\n keyPair,\n signMessages: messages =>\n Promise.all(\n messages.map(async message =>\n Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) }),\n ),\n ),\n signTransactions: transactions =>\n Promise.all(\n transactions.map(async transaction => {\n const signedTransaction = await partiallySignTransaction([keyPair], transaction);\n // we know that the address has signed `signedTransaction` because it comes from the keypair\n return Object.freeze({ [address]: signedTransaction.signatures[address]! });\n }),\n ),\n };\n\n return Object.freeze(out);\n}\n\n/**\n * Generates a signer capable of signing messages and transactions by generating\n * a {@link CryptoKeyPair} and creating a {@link KeyPairSigner} from it.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * ```\n *\n * @see {@link createSignerFromKeyPair}\n */\nexport async function generateKeyPairSigner(): Promise {\n return await createSignerFromKeyPair(await generateKeyPair());\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 64-bytes `Uint8Array` secret key (private key and public key).\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairSignerFromBytes } from '@solana/signers';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a KeyPairSigner from the bytes.\n * const signer = await createKeyPairSignerFromBytes(keypairBytes);\n * ```\n *\n * @see {@link createKeyPairSignerFromPrivateKeyBytes} if you only have the 32-bytes private key instead.\n */\nexport async function createKeyPairSignerFromBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromBytes(bytes, extractable));\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 32-bytes `Uint8Array` private key.\n *\n * @example\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairSignerFromPrivateKeyBytes } from '@solana/signers';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedSigner = await createKeyPairSignerFromPrivateKeyBytes(seed);\n * ```\n *\n * @see {@link createKeyPairSignerFromBytes} if you have the 64-bytes secret key instead (private key and public key).\n */\nexport async function createKeyPairSignerFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromPrivateKeyBytes(bytes, extractable));\n}\n","import { Address, isAddress } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessageModifyingSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that _potentially_ modifies the content\n * of the provided {@link SignableMessage | SignableMessages} before signing them.\n *\n * For instance, this enables wallets to prefix or suffix nonces to the messages they sign.\n * For each message, instead of returning a {@link SignatureDictionary}, the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} function\n * returns an updated {@link SignableMessage} with a potentially modified content and signature dictionary.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessageModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the content of the message.\n * - **First signers**. For a given message, a modifying signer must always be used\n * before a partial signer as the former will likely modify the message and\n * thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided, the second\n * signer may invalidate the signature of the first one. However, modifying signers\n * may decide not to modify a message based on the existence of signatures for that message.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessageModifyingSigner}\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport type MessageModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignMessages(\n messages: readonly SignableMessage[],\n config?: MessageModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport function isMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageModifyingSigner {\n return (\n isAddress(value.address) &&\n 'modifyAndSignMessages' in value &&\n typeof value.modifyAndSignMessages === 'function'\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageModifyingSigner}\n */\nexport function assertIsMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageModifyingSigner {\n if (!isMessageModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isMessageModifyingSigner, MessageModifyingSigner } from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\n\n/**\n * Defines a signer capable of signing messages.\n *\n * @see {@link MessageModifyingSigner} For signers that can modify messages before signing them.\n * @see {@link MessagePartialSigner} For signers that can be used in parallel.\n * @see {@link isMessageSigner}\n * @see {@link assertIsMessageSigner}\n */\nexport type MessageSigner =\n | MessageModifyingSigner\n | MessagePartialSigner;\n\n/**\n * Checks whether the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageSigner({ address, signMessages: async () => {} }); // true\n * isMessageSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageSigner}\n */\nexport function isMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageSigner {\n return isMessagePartialSigner(value) || isMessageModifyingSigner(value);\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessageSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageSigner}\n */\nexport function assertIsMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageSigner {\n if (!isMessageSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { MessagePartialSigner } from './message-partial-signer';\nimport { TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a Noop (No-Operation) signer that pretends to partially sign messages and transactions.\n *\n * For a given {@link Address}, a Noop Signer can be created to offer an implementation of both\n * the {@link MessagePartialSigner} and {@link TransactionPartialSigner} interfaces such that\n * they do not sign anything. Namely, signing a transaction or a message with a `NoopSigner`\n * will return an empty `SignatureDictionary`.\n *\n * @typeParam TAddress - Supply a string literal to define a Noop signer having a particular address.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * // ^ Both messageSignatures and transactionSignatures are empty.\n * ```\n *\n * @remarks\n * This signer may be useful:\n *\n * - For testing purposes.\n * - For indicating that a given account is a signer and taking the responsibility to provide\n * the signature for that account ourselves. For instance, if we need to send the transaction\n * to a server that will sign it and send it for us.\n *\n * @see {@link createNoopSigner}\n */\nexport type NoopSigner = MessagePartialSigner &\n TransactionPartialSigner;\n\n/**\n * Creates a {@link NoopSigner} from the provided {@link Address}.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * ```\n */\nexport function createNoopSigner(address: Address): NoopSigner {\n const out: NoopSigner = {\n address,\n signMessages: messages => Promise.resolve(messages.map(() => Object.freeze({}))),\n signTransactions: transactions => Promise.resolve(transactions.map(() => Object.freeze({}))),\n };\n\n return Object.freeze(out);\n}\n","import { OffchainMessageWithRequiredSignatories } from '@solana/offchain-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isMessageSigner, MessageSigner } from './message-signer';\n\n/**\n * Represents a {@link Signer} that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatorySigner = MessageSigner;\n\n/**\n * Extracts and deduplicates all {@link MessageSigner | MessageSigners} stored inside a given\n * {@link OffchainMessageWithSigners | offchain message}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link MessageSigner | MessageSigners}.\n * @typeParam TOffchainMessage - The inferred type of the offchain message provided.\n *\n * @example\n * ```ts\n * import { OffchainMessageWithSigners, getSignersFromOffchainMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signMessages: async () => {} };\n * const signerB = { address: address('2222..2222'), modifyAndSignMessages: async () => {} };\n * const OffchainMessage: OffchainMessageWithSigners = {\n * /* ... *\\/\n * requiredSignatories: [signerA, signerB],\n * };\n *\n * const messageSigners = getSignersFromOffchainMessage(offchainMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromOffchainMessage({\n requiredSignatories,\n}: OffchainMessageWithRequiredSignatories): readonly MessageSigner[] {\n const messageSigners = requiredSignatories.filter(isMessageSigner);\n return deduplicateSigners(messageSigners);\n}\n","import {\n assertIsFullySignedOffchainMessageEnvelope,\n compileOffchainMessageEnvelope,\n FullySignedOffchainMessageEnvelope,\n OffchainMessage,\n OffchainMessageEnvelope,\n OffchainMessageSignatory,\n OffchainMessageWithRequiredSignatories,\n} from '@solana/offchain-messages';\n\nimport {\n isMessageModifyingSigner,\n MessageModifyingSigner,\n MessageModifyingSignerConfig,\n} from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner, MessagePartialSignerConfig } from './message-partial-signer';\nimport { MessageSigner } from './message-signer';\nimport { getSignersFromOffchainMessage, OffchainMessageSignatorySigner } from './offchain-message-signer';\nimport { SignableMessage } from './signable-message';\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope.\n *\n * It first uses all {@link MessageModifyingSigner | MessageModifyingSigners} sequentially before\n * using all {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link MessageModifyingSigner} if no other signer implements that interface. Otherwise, it will\n * be used as a {@link MessagePartialSigner}.\n *\n * @example\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @see {@link signOffchainMessageWithSigners}\n */\nexport async function partiallySignOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeMessageSigners(\n getSignersFromOffchainMessage(offchainMessage),\n );\n return await signModifyingAndPartialMessageSigners(offchainMessage, modifyingSigners, partialSigners, config);\n}\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope before asserting that all signatures required\n * by the message are present.\n *\n * This function delegates to the {@link partiallySignOffchainMessageWithSigners} function\n * in order to extract signers from the offchain message and sign it.\n *\n * @example\n * ```ts\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage);\n *\n * // With additional config.\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the offchain message is fully signed.\n * mySignedOffchainMessageEnvelope satisfies FullySignedOffchainMessageEnvelope;\n * ```\n *\n * @see {@link partiallySignOffchainMessageWithSigners}\n */\nexport async function signOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, config);\n assertIsFullySignedOffchainMessageEnvelope(signedOffchainMessageEnvelope);\n return signedOffchainMessageEnvelope;\n}\n\n/**\n * Identifies each provided {@link MessageSigner} and categorizes them into their respective types.\n * When a signer implements multiple interfaces, it will try to used to most powerful interface but\n * fall back to the least powerful interface when necessary.\n *\n * For instance, if a signer implements {@link MessageSigner} and {@link MessageModifyingSigner},\n * it will be categorized as a `MessageModifyingSigner`.\n */\nfunction categorizeMessageSigners(signers: readonly MessageSigner[]): Readonly<{\n modifyingSigners: readonly MessageModifyingSigner[];\n partialSigners: readonly MessagePartialSigner[];\n}> {\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyMessageModifyingSigners(signers);\n\n // Use any remaining signers as partial signers.\n const partialSigners = signers\n .filter(isMessagePartialSigner)\n .filter(signer => !(modifyingSigners as typeof signers).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners });\n}\n\n/** Identifies the best signers to use as MessageModifyingSigners, if any */\nfunction identifyMessageModifyingSigners(\n signers: readonly (MessageModifyingSigner | MessagePartialSigner)[],\n): readonly MessageModifyingSigner[] {\n // Ensure there are any MessageModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isMessageModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isMessagePartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs an offchain message using the provided\n * {@link MessageModifyingSigner | MessageModifyingSigners} sequentially followed by the\n * {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n */\nasync function signModifyingAndPartialMessageSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n modifyingSigners: readonly MessageModifyingSigner[] = [],\n partialSigners: readonly MessagePartialSigner[] = [],\n config?: MessageModifyingSignerConfig,\n): Promise {\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n const offchainMessageEnvelope: SignableMessage = compileOffchainMessageEnvelope(offchainMessage);\n\n // Handle modifying signers sequentially.\n const modifiedOffchainMessage = await modifyingSigners.reduce(async (offchainMessageEnvelope, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [message] = await modifyingSigner.modifyAndSignMessages([await offchainMessageEnvelope], config);\n return Object.freeze(message);\n }, Promise.resolve(offchainMessageEnvelope));\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signMessages([modifiedOffchainMessage], config);\n return signatures;\n }),\n );\n\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n return Object.freeze({\n ...modifiedOffchainMessage,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedOffchainMessage.signatures ?? {}),\n ),\n } as OffchainMessageEnvelope);\n}\n","import {\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { isTransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a transaction message with exactly one {@link TransactionSendingSigner}.\n *\n * This type is used to narrow the type of transaction messages that have been\n * checked to have exactly one sending signer.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithSingleSendingSigner } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithSingleSendingSigner;\n * ```\n *\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport type TransactionMessageWithSingleSendingSigner = Brand<\n TransactionMessageWithSigners,\n 'TransactionMessageWithSingleSendingSigner'\n>;\n\n/**\n * Checks whether the provided transaction has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using {@link signAndSendTransactionMessageWithSigners} to provide\n * a fallback strategy in case the transaction message cannot be send using this function.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * isTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners,\n * signTransactionMessageWithSigners,\n * } from '@solana/signers';\n * import { getBase64EncodedWireTransaction } from '@solana/transactions';\n *\n * let transactionSignature: SignatureBytes;\n * if (isTransactionMessageWithSingleSendingSigner(transactionMessage)) {\n * transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * } else {\n * const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);\n * const encodedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * transactionSignature = await rpc.sendTransaction(encodedTransaction).send();\n * }\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport function isTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transaction: TTransactionMessage): transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n try {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Asserts that the provided transaction message has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using the {@link signAndSendTransactionMessageWithSigners} function\n * to ensure it will be able to select the correct signer to send the transaction.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * assertIsTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners\n * } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n */\nexport function assertIsTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transaction: TTransactionMessage,\n): asserts transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n const signers = getSignersFromTransactionMessage(transaction);\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n\n if (sendingSigners.length === 0) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n // When identifying if there are multiple sending signers, we only need to check for\n // sending signers that do not implement other transaction signer interfaces as\n // they will be used as these other signer interfaces in case of a conflict.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer),\n );\n\n if (sendingOnlySigners.length > 1) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS);\n }\n}\n","import { SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport {\n assertIsFullySignedTransaction,\n compileTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithinSizeLimit,\n TransactionWithLifetime,\n} from '@solana/transactions';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport {\n isTransactionModifyingSigner,\n TransactionModifyingSigner,\n TransactionModifyingSignerConfig,\n} from './transaction-modifying-signer';\nimport {\n isTransactionPartialSigner,\n TransactionPartialSigner,\n TransactionPartialSignerConfig,\n} from './transaction-partial-signer';\nimport {\n isTransactionSendingSigner,\n TransactionSendingSigner,\n TransactionSendingSignerConfig,\n} from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { assertIsTransactionMessageWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction.\n *\n * It first uses all {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before\n * using all {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link TransactionModifyingSigner} if no other signer implements that interface.\n * Otherwise, it will be used as a {@link TransactionPartialSigner}.\n *\n * @example\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Finally, note that this function ignores {@link TransactionSendingSigner | TransactionSendingSigners}\n * as it does not send the transaction. Check out the {@link signAndSendTransactionMessageWithSigners}\n * function for more details on how to use sending signers.\n *\n * @see {@link signTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function partiallySignTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transactionMessage).filter(isTransactionSigner)),\n { identifySendingSigner: false },\n );\n\n return await signModifyingAndPartialTransactionSigners(\n transactionMessage,\n modifyingSigners,\n partialSigners,\n config,\n );\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction before asserting\n * that all signatures required by the transaction are present.\n *\n * This function delegates to the {@link partiallySignTransactionMessageWithSigners} function\n * in order to extract signers from the transaction message and sign the transaction.\n *\n * @example\n * ```ts\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage);\n *\n * // With additional config.\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the transaction is fully signed.\n * mySignedTransaction satisfies FullySignedTransaction;\n * ```\n *\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function signTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, config);\n assertIsFullySignedTransaction(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to sign it before sending it immediately to the blockchain.\n *\n * It returns the signature of the sent transaction (i.e. its identifier) as bytes.\n *\n * @example\n * ```ts\n * import { signAndSendTransactionMessageWithSigners } from '@solana/signers';\n *\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n *\n * // With additional config.\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Similarly to the {@link partiallySignTransactionMessageWithSigners} function, it first uses all\n * {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before using all\n * {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n * It then sends the transaction using the {@link TransactionSendingSigner} it identified.\n *\n * Composite transaction signers are treated such that at least one sending signer is used if any.\n * When a {@link TransactionSigner} implements more than one interface, we use it as a:\n *\n * - {@link TransactionSendingSigner}, if no other {@link TransactionSendingSigner} exists.\n * - {@link TransactionModifyingSigner}, if no other {@link TransactionModifyingSigner} exists.\n * - {@link TransactionPartialSigner}, otherwise.\n *\n * The provided transaction must contain exactly one {@link TransactionSendingSigner} inside its account metas.\n * If more than one composite signers implement the {@link TransactionSendingSigner} interface,\n * one of them will be selected as the sending signer. Otherwise, if multiple\n * {@link TransactionSendingSigner | TransactionSendingSigners} must be selected, the function will throw an error.\n *\n * If you'd like to assert that a transaction makes use of exactly one {@link TransactionSendingSigner}\n * _before_ calling this function, you may use the {@link assertIsTransactionMessageWithSingleSendingSigner} function.\n *\n * Alternatively, you may use the {@link isTransactionMessageWithSingleSendingSigner} function to provide a\n * fallback in case the transaction does not contain any sending signer.\n *\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signTransactionMessageWithSigners}\n *\n */\nexport async function signAndSendTransactionMessageWithSigners(\n transaction: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionSendingSignerConfig,\n): Promise {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n\n const abortSignal = config?.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transaction).filter(isTransactionSigner)),\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n config,\n );\n\n if (!sendingSigner) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], config);\n abortSignal?.throwIfAborted();\n\n return signature;\n}\n\n/**\n * Identifies each provided TransactionSigner and categorizes them into their respective types.\n * When a signer implements multiple interface, it will try to used to most powerful interface\n * but fallback to the least powerful interface when necessary.\n * For instance, if a signer implements TransactionSendingSigner and TransactionModifyingSigner,\n * it will be categorized as a TransactionSendingSigner if and only if no other signers implement\n * the TransactionSendingSigner interface.\n */\nfunction categorizeTransactionSigners(\n signers: readonly TransactionSigner[],\n config: { identifySendingSigner?: boolean } = {},\n): Readonly<{\n modifyingSigners: readonly TransactionModifyingSigner[];\n partialSigners: readonly TransactionPartialSigner[];\n sendingSigner: TransactionSendingSigner | null;\n}> {\n // Identify the unique sending signer that should be used.\n const identifySendingSigner = config.identifySendingSigner ?? true;\n const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;\n\n // Now, focus on the other signers.\n // I.e. the modifying or partial signers that are not the identified sending signer.\n // Note that any other sending only signers will be discarded.\n const otherSigners = signers.filter(\n (signer): signer is TransactionModifyingSigner | TransactionPartialSigner =>\n signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer)),\n );\n\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);\n\n // Use any remaining signers as partial signers.\n const partialSigners = otherSigners\n .filter(isTransactionPartialSigner)\n .filter(signer => !(modifyingSigners as typeof otherSigners).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });\n}\n\n/** Identifies the best signer to use as a TransactionSendingSigner, if any */\nfunction identifyTransactionSendingSigner(signers: readonly TransactionSigner[]): TransactionSendingSigner | null {\n // Ensure there are any TransactionSendingSigners in the first place.\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n if (sendingSigners.length === 0) return null;\n\n // Prefer sending signers that do not offer other interfaces.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer),\n );\n if (sendingOnlySigners.length > 0) {\n return sendingOnlySigners[0];\n }\n\n // Otherwise, choose any sending signer.\n return sendingSigners[0];\n}\n\n/** Identifies the best signers to use as TransactionModifyingSigners, if any */\nfunction identifyTransactionModifyingSigners(\n signers: readonly (TransactionModifyingSigner | TransactionPartialSigner)[],\n): readonly TransactionModifyingSigner[] {\n // Ensure there are any TransactionModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isTransactionModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isTransactionPartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs a transaction using the provided TransactionModifyingSigners\n * sequentially followed by the TransactionPartialSigners in parallel.\n */\nasync function signModifyingAndPartialTransactionSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n config?: TransactionModifyingSignerConfig,\n): Promise {\n // serialize the transaction\n const transaction = compileTransaction(transactionMessage);\n\n // Handle modifying signers sequentially.\n const modifiedTransaction = (await modifyingSigners.reduce(\n async (transaction, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], config);\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise>,\n )) as Transaction & TransactionWithinSizeLimit & TransactionWithLifetime;\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], config);\n return signatures;\n }),\n );\n\n return Object.freeze({\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {}),\n ),\n });\n}\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import { TextEncoder } from '@solana/text-encoding-impl';\n\nimport { SignatureDictionary } from './types';\n\n/**\n * Defines a message that needs signing and its current set of signatures if any.\n *\n * This interface allows {@link MessageModifyingSigner | MessageModifyingSigners}\n * to decide on whether or not they should modify the provided message depending\n * on whether or not signatures already exist for such message.\n *\n * It also helps create a more consistent API by providing a structure analogous\n * to transactions which also keep track of their {@link SignatureDictionary}.\n *\n * @example\n * ```ts\n * import { createSignableMessage } from '@solana/signers';\n *\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * message.content; // The content of the message as bytes.\n * message.signatures; // The current set of signatures for this message.\n * ```\n *\n * @see {@link createSignableMessage}\n */\nexport type SignableMessage = Readonly<{\n content: Uint8Array;\n signatures: SignatureDictionary;\n}>;\n\n/**\n * Creates a {@link SignableMessage} from a `Uint8Array` or a UTF-8 string.\n *\n * It optionally accepts a signature dictionary if the message already contains signatures.\n *\n * @example\n * ```ts\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * const messageFromText = createSignableMessage('Hello world!');\n * const messageWithSignatures = createSignableMessage('Hello world!', {\n * [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes,\n * });\n * ```\n */\nexport function createSignableMessage(\n content: Uint8Array | string,\n signatures: SignatureDictionary = {},\n): SignableMessage {\n return Object.freeze({\n content: typeof content === 'string' ? new TextEncoder().encode(content) : content,\n signatures: Object.freeze({ ...signatures }),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { GetEpochInfoApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport type { Commitment } from '@solana/rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the block height as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /** The block height after which to reject the promise */\n lastValidBlockHeight: bigint;\n}) => Promise;\n\ntype CreateBlockHeightExceedencePromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that throws when the network progresses past the block height after which the\n * supplied blockhash is considered expired for use as a transaction lifetime specifier.\n *\n * When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the\n * network until that blockhash expires. All blockhashes have a block height after which they are\n * considered to have expired.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getBlockHeightExceedencePromise({ lastValidBlockHeight });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error(\n * `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` +\n * `It is now ${e.context.currentBlockHeight}`,\n * );\n * // Re-sign and retry the transaction.\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'devnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'testnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'mainnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({\n abortSignal: callerAbortSignal,\n commitment,\n lastValidBlockHeight,\n }): Promise {\n callerAbortSignal.throwIfAborted();\n const abortController = new AbortController();\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {\n const { absoluteSlot, blockHeight } = await rpc\n .getEpochInfo({ commitment })\n .send({ abortSignal: abortController.signal });\n return {\n blockHeight,\n differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight,\n };\n }\n try {\n const [slotNotifications, { blockHeight: initialBlockHeight, differenceBetweenSlotHeightAndBlockHeight }] =\n await Promise.all([\n rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),\n getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight(),\n ]);\n callerAbortSignal.throwIfAborted();\n let currentBlockHeight = initialBlockHeight;\n if (currentBlockHeight <= lastValidBlockHeight) {\n let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;\n for await (const slotNotification of slotNotifications) {\n const { slot } = slotNotification;\n if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {\n // Before making a final decision, recheck the actual block height.\n const {\n blockHeight: recheckedBlockHeight,\n differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight,\n } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();\n currentBlockHeight = recheckedBlockHeight;\n if (currentBlockHeight > lastValidBlockHeight) {\n // Verified; the block height has been exceeded.\n break;\n } else {\n // The block height has not been exceeded, which implies that the\n // difference between the slot height and the block height has grown\n // (ie. some blocks have been skipped since we started). Recalibrate the\n // difference and keep waiting.\n lastKnownDifferenceBetweenSlotHeightAndBlockHeight =\n currentDifferenceBetweenSlotHeightAndBlockHeight;\n }\n }\n }\n }\n callerAbortSignal.throwIfAborted();\n throw new SolanaError(SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, {\n currentBlockHeight,\n lastValidBlockHeight,\n });\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport type { GetAccountInfoApi, Rpc } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions } from '@solana/rpc-subscriptions';\nimport type { Base64EncodedDataResponse, Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transaction-messages';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the nonce account details as of the highest slot that has reached this level of\n * commitment.\n */\n commitment: Commitment;\n /**\n * The value of the nonce that we would expect to see in the nonce account in order for any\n * transaction with that nonce-based lifetime to be considered valid.\n */\n currentNonceValue: Nonce;\n /** The address of the account in which the currently-valid nonce value is stored */\n nonceAccountAddress: Address;\n}) => Promise;\n\ntype CreateNonceInvalidationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\n/**\n * Creates a promise that throws when the value stored in a nonce account is not the expected one.\n *\n * When a transaction's lifetime is tied to the value stored in a nonce account, that transaction\n * can be landed on the network until the nonce is advanced to a new value.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getNonceInvalidationPromise({\n * currentNonceValue,\n * nonceAccountAddress,\n * });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) {\n * console.error(`The nonce has advanced to ${e.context.actualNonceValue}`);\n * // Re-sign and retry the transaction.\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(`No nonce account was found at ${nonceAccountAddress}`);\n * }\n * throw e;\n * }\n * ```\n */\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'devnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'testnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'mainnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue: expectedNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes) as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new SolanaError(SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, {\n nonceAccountAddress,\n });\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { getSolanaErrorFromTransactionError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { GetSignatureStatusesApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { type Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * The level of commitment the transaction must have achieved in order for the promise to\n * resolve.\n */\n commitment: Commitment;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}) => Promise;\n\ntype CreateRecentSignatureConfirmationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that resolves when a recently-landed transaction achieves the target\n * confirmation commitment, and throws when the transaction fails with an error.\n *\n * The status of recently-landed transactions is available in the network's status cache. This\n * confirmation strategy will only yield a result if the signature is still in the status cache. To\n * fetch the status of transactions older than those available in the status cache, use the\n * {@link GetSignatureStatusesApi.getSignatureStatuses} method setting the\n * `searchTransactionHistory` configuration param to `true`.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getRecentSignatureConfirmationPromise({\n * commitment,\n * signature,\n * });\n * console.log(`The transaction with signature \\`${signature}\\` has achieved a commitment level of \\`${commitment}\\``);\n * } catch (e) {\n * console.error(`The transaction with signature \\`${signature}\\` failed`, e.cause);\n * throw e;\n * }\n * ```\n */\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'devnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'testnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'mainnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n throw getSolanaErrorFromTransactionError(signatureStatusNotification.value.err);\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (signatureStatus?.err) {\n throw getSolanaErrorFromTransactionError(signatureStatus.err);\n } else if (\n signatureStatus?.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n /**\n * The timeout promise will throw after 30 seconds when the commitment is `processed`, and 60\n * seconds otherwise.\n */\n commitment: Commitment;\n}>;\n\n/**\n * When no other heuristic exists to infer that a transaction has expired, you can use this promise\n * factory with a commitment level. It throws after 30 seconds when the commitment is `processed`,\n * and 60 seconds otherwise. You would typically race this with another confirmation strategy.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { safeRace } from '@solana/promises';\n * import { getTimeoutPromise } from '@solana/transaction-confirmation';\n *\n * try {\n * await safeRace([getCustomTransactionConfirmationPromise(/* ... *\\/), getTimeoutPromise({ commitment })]);\n * } catch (e) {\n * if (e instanceof DOMException && e.name === 'TimeoutError') {\n * console.log('Could not confirm transaction after a timeout');\n * }\n * throw e;\n * }\n * ```\n */\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType;\n}\n\ntype WithNonNullableAbortSignal = Omit & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal) => readonly Promise[],\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await safeRace([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport {\n getSignatureFromTransaction,\n Transaction,\n TransactionWithBlockhashLifetime,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './confirmation-strategy-racer';\nimport { getTimeoutPromise } from './confirmation-strategy-timeout';\n\nexport type TransactionWithLastValidBlockHeight = Omit & {\n lifetimeConstraint: Omit;\n};\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom nonce\n * transaction confirmation strategy.\n *\n * @example\n * ```ts\n * import { waitForDurableNonceTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForDurableNonceTransactionConfirmation({\n * getNonceInvalidationPromise({ abortSignal, commitment, currentNonceValue, nonceAccountAddress }) {\n * // Return a promise that rejects when a nonce becomes invalid.\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.lifetimeConstraint.nonceAccountAddress,\n }),\n ];\n },\n );\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom confirmation\n * strategy for recently-landed transactions.\n *\n * @example\n * ```ts\n * import { waitForRecentTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForRecentTransactionConfirmation({\n * getBlockHeightExceedencePromise({ abortSignal, commitment, lastValidBlockHeight }) {\n * // Return a promise that rejects when the blockhash's block height has been exceeded\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({\n abortSignal,\n commitment,\n getBlockHeightExceedencePromise,\n transaction,\n }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n commitment,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n },\n );\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n },\n );\n}\n","import type { Address } from '@solana/addresses';\nimport type { Signature } from '@solana/keys';\nimport type { RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { Commitment, Lamports } from '@solana/rpc-types';\nimport { waitForRecentTransactionConfirmationUntilTimeout } from '@solana/transaction-confirmation';\n\ntype RequestAndConfirmAirdropConfig = Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: (\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) => Promise;\n lamports: Lamports;\n recipientAddress: Address;\n rpc: Rpc;\n}>;\n\nexport async function requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: RequestAndConfirmAirdropConfig): Promise {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import type { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createRecentSignatureConfirmationPromiseFactory,\n getTimeoutPromise,\n waitForRecentTransactionConfirmationUntilTimeout,\n} from '@solana/transaction-confirmation';\n\nimport { requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT } from './airdrop-internal';\n\ntype AirdropFunction = (\n config: Omit<\n Parameters[0],\n 'confirmSignatureOnlyTransaction' | 'rpc'\n >,\n) => Promise;\n\ntype AirdropFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link RequestAirdropApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to airdrop a certain amount of {@link Lamports} to a Solana\n * address.\n *\n * > [!NOTE] This only works on test clusters.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit';\n *\n * const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899'));\n * const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900'));\n *\n * const airdrop = airdropFactory({ rpc, rpcSubscriptions });\n *\n * await airdrop({\n * commitment: 'confirmed',\n * recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'),\n * lamports: lamports(10_000_000n),\n * });\n * ```\n */\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'devnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'mainnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'testnet'>): AirdropFunction;\nexport function airdropFactory({\n rpc,\n rpcSubscriptions,\n}: AirdropFactoryConfig): AirdropFunction {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmSignatureOnlyTransaction(\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n }\n return async function airdrop(config) {\n return await requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n","import {\n assertAccountsDecoded,\n assertAccountsExist,\n type FetchAccountsConfig,\n fetchJsonParsedAccounts,\n} from '@solana/accounts';\nimport type { Address } from '@solana/addresses';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport { type AddressesByLookupTableAddress } from '@solana/transaction-messages';\n\ntype FetchedAddressLookup = {\n addresses: Address[];\n};\n\n/**\n * Given a list of addresses belonging to address lookup tables, returns a map of lookup table\n * addresses to an ordered array of the addresses they contain.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function fetchAddressesForLookupTables(\n lookupTableAddresses: Address[],\n rpc: Rpc,\n config?: FetchAccountsConfig,\n): Promise {\n if (lookupTableAddresses.length === 0) {\n return {};\n }\n\n const fetchedLookupTables = await fetchJsonParsedAccounts(\n rpc,\n lookupTableAddresses,\n config,\n );\n\n assertAccountsDecoded(fetchedLookupTables);\n assertAccountsExist(fetchedLookupTables);\n\n return fetchedLookupTables.reduce((acc, lookup) => {\n return {\n ...acc,\n [lookup.address]: lookup.data.addresses,\n };\n }, {});\n}\n","import { type FetchAccountsConfig } from '@solana/accounts';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n decompileTransactionMessage,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithLifetime,\n} from '@solana/transaction-messages';\n\nimport { fetchAddressesForLookupTables } from './fetch-lookup-tables';\n\ntype DecompileTransactionMessageFetchingLookupTablesConfig = FetchAccountsConfig & {\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Returns a {@link TransactionMessage} from a {@link CompiledTransactionMessage}. If any of the\n * accounts in the compiled message require an address lookup table to find their address, this\n * function will use the supplied RPC instance to fetch the contents of the address lookup table\n * from the network.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function decompileTransactionMessageFetchingLookupTables(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n rpc: Rpc,\n config?: DecompileTransactionMessageFetchingLookupTablesConfig,\n): Promise {\n const lookupTables =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? compiledTransactionMessage.addressTableLookups\n : [];\n const lookupTableAddresses = lookupTables.map(l => l.lookupTableAddress);\n\n const { lastValidBlockHeight, ...fetchAccountsConfig } = config ?? {};\n const addressesByLookupTableAddress =\n lookupTableAddresses.length > 0\n ? await fetchAddressesForLookupTables(lookupTableAddresses, rpc, fetchAccountsConfig)\n : {};\n\n return decompileTransactionMessage(compiledTransactionMessage, {\n addressesByLookupTableAddress,\n lastValidBlockHeight,\n });\n}\n","import type { Lamports } from '@solana/rpc-types';\n\n/**\n * Calculates the minimum {@link Lamports | lamports} required to make an account rent exempt for a\n * given data size, without performing an RPC call.\n *\n * Values are sourced from the on-chain rent parameters in the Solana runtime:\n * https://github.com/anza-xyz/solana-sdk/blob/c07f692e41d757057c8700211a9300cdcd6d33b1/rent/src/lib.rs#L93-L97\n *\n * Note that this logic may change, or be incorrect depending on the cluster you are connected to.\n * You can always use the RPC method `getMinimumBalanceForRentExemption` to get the current value.\n *\n * @param space The number of bytes of account data.\n */\nexport function getMinimumBalanceForRentExemption(space: bigint): Lamports {\n const RENT = {\n ACCOUNT_STORAGE_OVERHEAD: 128n,\n DEFAULT_EXEMPTION_THRESHOLD: 2n,\n DEFAULT_LAMPORTS_PER_BYTE_YEAR: 3_480n,\n } as const;\n const requiredLamports =\n (RENT.ACCOUNT_STORAGE_OVERHEAD + space) *\n RENT.DEFAULT_LAMPORTS_PER_BYTE_YEAR *\n RENT.DEFAULT_EXEMPTION_THRESHOLD;\n return requiredLamports as Lamports;\n}\n","import type { Signature } from '@solana/keys';\nimport type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n TransactionWithLastValidBlockHeight,\n waitForDurableNonceTransactionConfirmation,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getBase64EncodedWireTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: (\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: (\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight;\n}\n\ninterface SendTransactionBaseConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc;\n transaction: SendableTransaction & Transaction;\n}\n\ntype SendTransactionConfigWithoutEncoding = Omit<\n NonNullable[1]>,\n 'encoding'\n>;\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding,\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nexport async function sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionBaseConfig): Promise {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport async function sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { getSolanaErrorFromTransactionError, isSolanaError, SOLANA_ERROR__INVALID_NONCE } from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport type { GetAccountInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { commitmentComparator } from '@solana/rpc-types';\nimport {\n createNonceInvalidationPromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n waitForDurableNonceTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getSignatureFromTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmDurableNonceTransactionFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime,\n config: Omit<\n Parameters[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmDurableNonceTransactionFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link AccountNotificationsApi} and the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a nonce-based transaction to the network and to wait\n * until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * isSolanaError,\n * sendAndConfirmDurableNonceTransactionFactory,\n * SOLANA_ERROR__INVALID_NONCE,\n * SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n * } from '@solana/kit';\n *\n * const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(\n * 'The lifetime specified by this transaction refers to a nonce account ' +\n * `\\`${e.context.nonceAccountAddress}\\` that does not exist`,\n * );\n * } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n * console.error('This transaction depends on a nonce that is no longer valid');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'devnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'testnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'mainnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig): SendAndConfirmDurableNonceTransactionFunction {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions } as Parameters<\n typeof createNonceInvalidationPromiseFactory\n >[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n\n /**\n * Creates a wrapped version of getNonceInvalidationPromise that handles the race condition\n * where the nonce account update notification arrives before the signature confirmation.\n *\n * When the nonce changes, we check if our transaction actually landed on-chain.\n * If it did, we don't throw - letting the signature confirmation promise continue.\n */\n function createNonceInvalidationPromiseHandlingRaceCondition(\n signature: Signature,\n ): typeof getNonceInvalidationPromise {\n return async function wrappedGetNonceInvalidationPromise(config) {\n try {\n return await getNonceInvalidationPromise(config);\n } catch (e) {\n // If nonce became invalid, check if our transaction actually landed\n if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n let status;\n try {\n const { value: statuses } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: config.abortSignal });\n status = statuses[0];\n } catch {\n // RPC failed - propagate the original nonce error\n throw e;\n }\n\n if (status === null || status === undefined) {\n // Transaction doesn't exist - nonce was truly invalid\n throw e;\n }\n\n // Check if status meets required commitment\n if (\n status.confirmationStatus !== null &&\n commitmentComparator(status.confirmationStatus, config.commitment) >= 0\n ) {\n // Transaction failed on-chain, throw the error from the transaction\n if (status.err !== null) {\n throw getSolanaErrorFromTransactionError(status.err);\n }\n // Transaction succeeded, resolve the promise successfully\n return;\n }\n\n // Commitment not met yet - return a never-resolving promise\n // This lets the signature confirmation promise continue\n return await new Promise(() => {});\n }\n throw e;\n }\n };\n }\n\n async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n const wrappedGetNonceInvalidationPromise = createNonceInvalidationPromiseHandlingRaceCondition(\n getSignatureFromTransaction(config.transaction),\n );\n\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise: wrappedGetNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmDurableNonceTransaction(transaction, config) {\n await sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { GetEpochInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createBlockHeightExceedencePromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n TransactionWithLastValidBlockHeight,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight,\n config: Omit<\n Parameters[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} and the {@link SlotNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a blockhash-based transaction to the network and to\n * wait until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit';\n *\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error('This transaction depends on a blockhash that has expired');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'devnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'testnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'mainnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig): SendAndConfirmTransactionWithBlockhashLifetimeFunction {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmRecentTransaction(\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmTransaction(transaction, config) {\n await sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendTransactionWithoutConfirmingFunction = (\n transaction: SendableTransaction & Transaction,\n config: Omit[0], 'rpc' | 'transaction'>,\n) => Promise;\n\ninterface SendTransactionWithoutConfirmingFactoryConfig {\n /** An object that supports the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}\n\n/**\n * Returns a function that you can call to send a transaction with any kind of lifetime to the\n * network without waiting for it to be confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * sendTransactionWithoutConfirmingFactory,\n * SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n * } from '@solana/kit';\n *\n * const sendTransaction = sendTransactionWithoutConfirmingFactory({ rpc });\n *\n * try {\n * await sendTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) {\n * console.error('The transaction failed in simulation', e.cause);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendTransactionWithoutConfirmingFactory({\n rpc,\n}: SendTransactionWithoutConfirmingFactoryConfig): SendTransactionWithoutConfirmingFunction {\n return async function sendTransactionWithoutConfirming(transaction, config) {\n await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n rpc,\n transaction,\n });\n };\n}\n","/**\n * Wallet Key Derivation\n *\n * BIP-39 mnemonic generation + BIP-44 HD key derivation for EVM and Solana.\n * Absorbed from @blockrun/clawwallet. No file I/O here - auth.ts handles persistence.\n *\n * Solana uses SLIP-10 Ed25519 derivation (Phantom/Solflare/Backpack compatible).\n * EVM uses standard BIP-32 secp256k1 derivation.\n */\n\nimport { HDKey } from \"@scure/bip32\";\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from \"@scure/bip39\";\nimport { wordlist as english } from \"@scure/bip39/wordlists/english\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha512 } from \"@noble/hashes/sha512\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst ETH_DERIVATION_PATH = \"m/44'/60'/0'/0/0\";\nconst SOLANA_HARDENED_INDICES = [44 + 0x80000000, 501 + 0x80000000, 0 + 0x80000000, 0 + 0x80000000]; // m/44'/501'/0'/0'\n\nexport interface DerivedKeys {\n mnemonic: string;\n evmPrivateKey: `0x${string}`;\n evmAddress: string;\n solanaPrivateKeyBytes: Uint8Array; // 32 bytes\n}\n\n/**\n * Generate a 24-word BIP-39 mnemonic.\n */\nexport function generateWalletMnemonic(): string {\n return generateMnemonic(english, 256);\n}\n\n/**\n * Validate a BIP-39 mnemonic.\n */\nexport function isValidMnemonic(mnemonic: string): boolean {\n return validateMnemonic(mnemonic, english);\n}\n\n/**\n * Derive EVM private key and address from a BIP-39 mnemonic.\n * Path: m/44'/60'/0'/0/0 (standard Ethereum derivation)\n */\nexport function deriveEvmKey(mnemonic: string): { privateKey: `0x${string}`; address: string } {\n const seed = mnemonicToSeedSync(mnemonic);\n const hdKey = HDKey.fromMasterSeed(seed);\n const derived = hdKey.derive(ETH_DERIVATION_PATH);\n if (!derived.privateKey) throw new Error(\"Failed to derive EVM private key\");\n const hex = `0x${Buffer.from(derived.privateKey).toString(\"hex\")}` as `0x${string}`;\n const account = privateKeyToAccount(hex);\n return { privateKey: hex, address: account.address };\n}\n\n/**\n * Derive 32-byte Solana private key using SLIP-10 Ed25519 derivation.\n * Path: m/44'/501'/0'/0' (Phantom / Solflare / Backpack compatible)\n *\n * Algorithm (SLIP-0010 for Ed25519):\n * 1. Master: HMAC-SHA512(key=\"ed25519 seed\", data=bip39_seed) → IL=key, IR=chainCode\n * 2. For each hardened child index:\n * HMAC-SHA512(key=chainCode, data=0x00 || key || ser32(index)) → split again\n * 3. Final IL (32 bytes) = Ed25519 private key seed\n */\nexport function deriveSolanaKeyBytes(mnemonic: string): Uint8Array {\n const seed = mnemonicToSeedSync(mnemonic);\n\n // Master key from SLIP-10\n let I = hmac(sha512, \"ed25519 seed\", seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n // Derive each hardened child: m/44'/501'/0'/0'\n for (const index of SOLANA_HARDENED_INDICES) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n // ser32 big-endian\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n return new Uint8Array(key);\n}\n\n/**\n * Derive both EVM and Solana keys from a single mnemonic.\n */\nexport function deriveAllKeys(mnemonic: string): DerivedKeys {\n const { privateKey: evmPrivateKey, address: evmAddress } = deriveEvmKey(mnemonic);\n const solanaPrivateKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return { mnemonic, evmPrivateKey, evmAddress, solanaPrivateKeyBytes };\n}\n\n/**\n * Get the Solana address from 32-byte private key bytes.\n * Uses @solana/kit's createKeyPairSignerFromPrivateKeyBytes (dynamic import).\n */\nexport async function getSolanaAddress(privateKeyBytes: Uint8Array): Promise {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(privateKeyBytes);\n return signer.address;\n}\n","/**\n * Solana USDC Balance Monitor\n *\n * Checks USDC balance on Solana mainnet with caching.\n * Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).\n */\n\nimport { address as solAddress, createSolanaRpc } from \"@solana/kit\";\n\nconst SOLANA_USDC_MINT = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nconst SOLANA_DEFAULT_RPC = \"https://api.mainnet-beta.solana.com\";\nconst BALANCE_TIMEOUT_MS = 10_000;\nconst CACHE_TTL_MS = 30_000;\n\nexport type SolanaBalanceInfo = {\n balance: bigint;\n balanceUSD: string;\n isLow: boolean;\n isEmpty: boolean;\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SolanaSufficiencyResult = {\n sufficient: boolean;\n info: SolanaBalanceInfo;\n shortfall?: string;\n};\n\nexport class SolanaBalanceMonitor {\n private readonly rpc: ReturnType;\n private readonly walletAddress: string;\n private cachedBalance: bigint | null = null;\n private cachedAt = 0;\n\n constructor(walletAddress: string, rpcUrl?: string) {\n this.walletAddress = walletAddress;\n const url = rpcUrl || process[\"env\"].CLAWROUTER_SOLANA_RPC_URL || SOLANA_DEFAULT_RPC;\n this.rpc = createSolanaRpc(url);\n }\n\n async checkBalance(): Promise {\n const now = Date.now();\n if (\n this.cachedBalance !== null &&\n this.cachedBalance > 0n &&\n now - this.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(this.cachedBalance);\n }\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n const balance = await this.fetchBalance();\n if (balance > 0n) {\n this.cachedBalance = balance;\n this.cachedAt = now;\n }\n return this.buildInfo(balance);\n }\n\n deductEstimated(amountMicros: bigint): void {\n if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {\n this.cachedBalance -= amountMicros;\n }\n }\n\n invalidate(): void {\n this.cachedBalance = null;\n this.cachedAt = 0;\n }\n\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSDC(shortfall),\n };\n }\n\n /**\n * Format USDC amount (in micros) as \"$X.XX\".\n */\n formatUSDC(amountMicros: bigint): string {\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n /**\n * Check native SOL balance (in lamports). Useful for detecting users who\n * funded with SOL instead of USDC.\n */\n async checkSolBalance(): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n try {\n const owner = solAddress(this.walletAddress);\n const response = await this.rpc.getBalance(owner).send({ abortSignal: controller.signal });\n return BigInt(response.value);\n } catch {\n return 0n;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async fetchBalance(): Promise {\n const owner = solAddress(this.walletAddress);\n const mint = solAddress(SOLANA_USDC_MINT);\n\n // The public Solana RPC frequently returns empty token account lists even\n // for funded wallets. Retry once on empty before accepting $0 as truth.\n for (let attempt = 0; attempt < 2; attempt++) {\n const result = await this.fetchBalanceOnce(owner, mint);\n if (result > 0n || attempt === 1) return result;\n await new Promise((r) => setTimeout(r, 1_000));\n }\n return 0n;\n }\n\n private async fetchBalanceOnce(\n owner: ReturnType,\n mint: ReturnType,\n ): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n\n try {\n const response = await this.rpc\n .getTokenAccountsByOwner(owner, { mint }, { encoding: \"jsonParsed\" })\n .send({ abortSignal: controller.signal });\n\n if (response.value.length === 0) return 0n;\n\n let total = 0n;\n for (const account of response.value) {\n const parsed = account.account.data as {\n parsed: { info: { tokenAmount: { amount: string } } };\n };\n total += BigInt(parsed.parsed.info.tokenAmount.amount);\n }\n return total;\n } catch (err) {\n throw new Error(\n `Failed to fetch Solana USDC balance: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n private buildInfo(balance: bigint): SolanaBalanceInfo {\n const dollars = Number(balance) / 1_000_000;\n return {\n balance,\n balanceUSD: `$${dollars.toFixed(2)}`,\n isLow: balance < 1_000_000n,\n isEmpty: balance < 100n,\n walletAddress: this.walletAddress,\n };\n }\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n};\n\nexport function getMintEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintCodec(): FixedSizeCodec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n\nexport function getMintSize(): number {\n return 82;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getTokenEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenCodec(): FixedSizeCodec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n\nexport function getTokenSize(): number {\n return 165;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n} from '../instructions';\n\nexport const TOKEN_PROGRAM_ADDRESS =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n\nexport enum TokenAccount {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyTokenAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenAccount {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return TokenAccount.Mint;\n }\n if (data.length === 165) {\n return TokenAccount.Token;\n }\n if (data.length === 355) {\n return TokenAccount.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token account.'\n );\n}\n\nexport enum TokenInstruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n}\n\nexport function identifyTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return TokenInstruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return TokenInstruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return TokenInstruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return TokenInstruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return TokenInstruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return TokenInstruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return TokenInstruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return TokenInstruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return TokenInstruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return TokenInstruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return TokenInstruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return TokenInstruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return TokenInstruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return TokenInstruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return TokenInstruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return TokenInstruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return TokenInstruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return TokenInstruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return TokenInstruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return TokenInstruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return TokenInstruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return TokenInstruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return TokenInstruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return TokenInstruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return TokenInstruction.UiAmountToAmount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token instruction.'\n );\n}\n\nexport type ParsedTokenInstruction<\n TProgram extends string = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n> =\n | ({\n instructionType: TokenInstruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: TokenInstruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: TokenInstruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: TokenInstruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: TokenInstruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: TokenInstruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: TokenInstruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: TokenInstruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: TokenInstruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: TokenInstruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: TokenInstruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: TokenInstruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: TokenInstruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: TokenInstruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: TokenInstruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: TokenInstruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: TokenInstruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: TokenInstruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type TokenError =\n | typeof TOKEN_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_ERROR__ALREADY_IN_USE\n | typeof TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__FIXED_SUPPLY\n | typeof TOKEN_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_ERROR__INVALID_MINT\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_STATE\n | typeof TOKEN_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_ERROR__MINT_MISMATCH\n | typeof TOKEN_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_ERROR__OVERFLOW\n | typeof TOKEN_ERROR__OWNER_MISMATCH\n | typeof TOKEN_ERROR__UNINITIALIZED_STATE;\n\nlet tokenErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n tokenErrorMessages = {\n [TOKEN_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getTokenErrorMessage(code: TokenError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (tokenErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isTokenError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU32Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAdvanceNonceAccountInstruction,\n type ParsedAllocateInstruction,\n type ParsedAllocateWithSeedInstruction,\n type ParsedAssignInstruction,\n type ParsedAssignWithSeedInstruction,\n type ParsedAuthorizeNonceAccountInstruction,\n type ParsedCreateAccountInstruction,\n type ParsedCreateAccountWithSeedInstruction,\n type ParsedInitializeNonceAccountInstruction,\n type ParsedTransferSolInstruction,\n type ParsedTransferSolWithSeedInstruction,\n type ParsedUpgradeNonceAccountInstruction,\n type ParsedWithdrawNonceAccountInstruction,\n} from '../instructions';\n\nexport const SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport enum SystemAccount {\n Nonce,\n}\n\nexport enum SystemInstruction {\n CreateAccount,\n Assign,\n TransferSol,\n CreateAccountWithSeed,\n AdvanceNonceAccount,\n WithdrawNonceAccount,\n InitializeNonceAccount,\n AuthorizeNonceAccount,\n Allocate,\n AllocateWithSeed,\n AssignWithSeed,\n TransferSolWithSeed,\n UpgradeNonceAccount,\n}\n\nexport function identifySystemInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): SystemInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU32Encoder().encode(0), 0)) {\n return SystemInstruction.CreateAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(1), 0)) {\n return SystemInstruction.Assign;\n }\n if (containsBytes(data, getU32Encoder().encode(2), 0)) {\n return SystemInstruction.TransferSol;\n }\n if (containsBytes(data, getU32Encoder().encode(3), 0)) {\n return SystemInstruction.CreateAccountWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(4), 0)) {\n return SystemInstruction.AdvanceNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(5), 0)) {\n return SystemInstruction.WithdrawNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(6), 0)) {\n return SystemInstruction.InitializeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(7), 0)) {\n return SystemInstruction.AuthorizeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(8), 0)) {\n return SystemInstruction.Allocate;\n }\n if (containsBytes(data, getU32Encoder().encode(9), 0)) {\n return SystemInstruction.AllocateWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(10), 0)) {\n return SystemInstruction.AssignWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(11), 0)) {\n return SystemInstruction.TransferSolWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(12), 0)) {\n return SystemInstruction.UpgradeNonceAccount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a system instruction.'\n );\n}\n\nexport type ParsedSystemInstruction<\n TProgram extends string = '11111111111111111111111111111111',\n> =\n | ({\n instructionType: SystemInstruction.CreateAccount;\n } & ParsedCreateAccountInstruction)\n | ({\n instructionType: SystemInstruction.Assign;\n } & ParsedAssignInstruction)\n | ({\n instructionType: SystemInstruction.TransferSol;\n } & ParsedTransferSolInstruction)\n | ({\n instructionType: SystemInstruction.CreateAccountWithSeed;\n } & ParsedCreateAccountWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AdvanceNonceAccount;\n } & ParsedAdvanceNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.WithdrawNonceAccount;\n } & ParsedWithdrawNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.InitializeNonceAccount;\n } & ParsedInitializeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.AuthorizeNonceAccount;\n } & ParsedAuthorizeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.Allocate;\n } & ParsedAllocateInstruction)\n | ({\n instructionType: SystemInstruction.AllocateWithSeed;\n } & ParsedAllocateWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AssignWithSeed;\n } & ParsedAssignWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.TransferSolWithSeed;\n } & ParsedTransferSolWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.UpgradeNonceAccount;\n } & ParsedUpgradeNonceAccountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\n\n/** AccountAlreadyInUse: an account with the same address already exists */\nexport const SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE = 0x0; // 0\n/** ResultWithNegativeLamports: account does not have enough SOL to perform the operation */\nexport const SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS = 0x1; // 1\n/** InvalidProgramId: cannot assign account to this program id */\nexport const SYSTEM_ERROR__INVALID_PROGRAM_ID = 0x2; // 2\n/** InvalidAccountDataLength: cannot allocate account data of this length */\nexport const SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH = 0x3; // 3\n/** MaxSeedLengthExceeded: length of requested seed is too long */\nexport const SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED = 0x4; // 4\n/** AddressWithSeedMismatch: provided address does not match addressed derived from seed */\nexport const SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH = 0x5; // 5\n/** NonceNoRecentBlockhashes: advancing stored nonce requires a populated RecentBlockhashes sysvar */\nexport const SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES = 0x6; // 6\n/** NonceBlockhashNotExpired: stored nonce is still in recent_blockhashes */\nexport const SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED = 0x7; // 7\n/** NonceUnexpectedBlockhashValue: specified nonce does not match stored nonce */\nexport const SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE = 0x8; // 8\n\nexport type SystemError =\n | typeof SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE\n | typeof SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH\n | typeof SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH\n | typeof SYSTEM_ERROR__INVALID_PROGRAM_ID\n | typeof SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED\n | typeof SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES\n | typeof SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE\n | typeof SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS;\n\nlet systemErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n systemErrorMessages = {\n [SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE]: `an account with the same address already exists`,\n [SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH]: `provided address does not match addressed derived from seed`,\n [SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH]: `cannot allocate account data of this length`,\n [SYSTEM_ERROR__INVALID_PROGRAM_ID]: `cannot assign account to this program id`,\n [SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED]: `length of requested seed is too long`,\n [SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED]: `stored nonce is still in recent_blockhashes`,\n [SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES]: `advancing stored nonce requires a populated RecentBlockhashes sysvar`,\n [SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE]: `specified nonce does not match stored nonce`,\n [SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS]: `account does not have enough SOL to perform the operation`,\n };\n}\n\nexport function getSystemErrorMessage(code: SystemError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (systemErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isSystemError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n SYSTEM_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n BASE_ACCOUNT_SIZE,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\nimport {\n getAccountMetaFactory,\n type InstructionWithByteDelta,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ACCOUNT_DISCRIMINATOR = 0;\n\nexport function getCreateAccountDiscriminatorBytes() {\n return getU32Encoder().encode(CREATE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNewAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNewAccount extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountNewAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAccountInstructionData = {\n discriminator: number;\n lamports: bigint;\n space: bigint;\n programAddress: Address;\n};\n\nexport type CreateAccountInstructionDataArgs = {\n lamports: number | bigint;\n space: number | bigint;\n programAddress: Address;\n};\n\nexport function getCreateAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU32Encoder()],\n ['lamports', getU64Encoder()],\n ['space', getU64Encoder()],\n ['programAddress', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: CREATE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU32Decoder()],\n ['lamports', getU64Decoder()],\n ['space', getU64Decoder()],\n ['programAddress', getAddressDecoder()],\n ]);\n}\n\nexport function getCreateAccountInstructionDataCodec(): FixedSizeCodec<\n CreateAccountInstructionDataArgs,\n CreateAccountInstructionData\n> {\n return combineCodec(\n getCreateAccountInstructionDataEncoder(),\n getCreateAccountInstructionDataDecoder()\n );\n}\n\nexport type CreateAccountInput<\n TAccountPayer extends string = string,\n TAccountNewAccount extends string = string,\n> = {\n payer: TransactionSigner;\n newAccount: TransactionSigner;\n lamports: CreateAccountInstructionDataArgs['lamports'];\n space: CreateAccountInstructionDataArgs['space'];\n programAddress: CreateAccountInstructionDataArgs['programAddress'];\n};\n\nexport function getCreateAccountInstruction<\n TAccountPayer extends string,\n TAccountNewAccount extends string,\n TProgramAddress extends Address = typeof SYSTEM_PROGRAM_ADDRESS,\n>(\n input: CreateAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n> &\n InstructionWithByteDelta {\n // Program address.\n const programAddress = config?.programAddress ?? SYSTEM_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n newAccount: { value: input.newAccount ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Bytes created or reallocated by the instruction.\n const byteDelta: number = [Number(args.space) + BASE_ACCOUNT_SIZE].reduce(\n (a, b) => a + b,\n 0\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'omitted');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.newAccount),\n ],\n byteDelta,\n data: getCreateAccountInstructionDataEncoder().encode(\n args as CreateAccountInstructionDataArgs\n ),\n programAddress,\n } as CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n > &\n InstructionWithByteDelta);\n}\n\nexport type ParsedCreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n payer: TAccountMetas[0];\n newAccount: TAccountMetas[1];\n };\n data: CreateAccountInstructionData;\n};\n\nexport function parseCreateAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAccountInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { payer: getNextAccount(), newAccount: getNextAccount() },\n data: getCreateAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import { getCreateAccountInstruction } from '@solana-program/system';\nimport {\n Address,\n InstructionPlan,\n OptionOrNullable,\n sequentialInstructionPlan,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n getInitializeMint2Instruction,\n getMintSize,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\n// RPC `getMinimumBalanceForRentExemption` for 82 bytes, which is token mint size\n// Hardcoded to avoid requiring an RPC request each time\nconst MINIMUM_BALANCE_FOR_MINT = 1461600;\n\nexport type CreateMintInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** New mint account to create. */\n newMint: TransactionSigner;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n /**\n * Optional override for the amount of Lamports to fund the mint account with.\n * @default 1461600\n * */\n mintAccountLamports?: number;\n};\n\ntype CreateMintInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n};\n\nexport function getCreateMintInstructionPlan(\n input: CreateMintInstructionPlanInput,\n config?: CreateMintInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAccountInstruction(\n {\n payer: input.payer,\n newAccount: input.newMint,\n lamports: input.mintAccountLamports ?? MINIMUM_BALANCE_FOR_MINT,\n space: getMintSize(),\n programAddress: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n },\n {\n programAddress: config?.systemProgram,\n }\n ),\n getInitializeMint2Instruction(\n {\n mint: input.newMint.address,\n decimals: input.decimals,\n mintAuthority: input.mintAuthority,\n freezeAuthority: input.freezeAuthority,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getMintToCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype MintToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to mint to.\n * Will be created if it does not already exist.\n * Note: Use {@link getMintToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n ata: Address;\n /** Wallet address for the associated token account. */\n owner: Address;\n /** The token mint for the associated token account. */\n mint: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: Address | TransactionSigner;\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype MintToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getMintToATAInstructionPlan(\n input: MintToATAInstructionPlanInput,\n config?: MintToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.ata,\n owner: input.owner,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n // mint to this token account\n getMintToCheckedInstruction(\n {\n mint: input.mint,\n token: input.ata,\n mintAuthority: input.mintAuthority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype MintToATAInstructionPlanAsyncInput = Omit<\n MintToATAInstructionPlanInput,\n 'ata'\n>;\n\nexport async function getMintToATAInstructionPlanAsync(\n input: MintToATAInstructionPlanAsyncInput,\n config?: MintToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.owner,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getMintToATAInstructionPlan(\n {\n ...input,\n ata: ataAddress,\n },\n config\n );\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getTransferCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype TransferToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** The token mint to transfer. */\n mint: Address;\n /** The source account for the transfer. */\n source: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n /** Associated token account address to transfer to.\n * Will be created if it does not already exist.\n * Note: Use {@link getTransferToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n destination: Address;\n /** Wallet address for the destination. */\n recipient: Address;\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype TransferToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getTransferToATAInstructionPlan(\n input: TransferToATAInstructionPlanInput,\n config?: TransferToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.destination,\n owner: input.recipient,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n getTransferCheckedInstruction(\n {\n source: input.source,\n mint: input.mint,\n destination: input.destination,\n authority: input.authority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype TransferToATAInstructionPlanAsyncInput = Omit<\n TransferToATAInstructionPlanInput,\n 'destination'\n>;\n\nexport async function getTransferToATAInstructionPlanAsync(\n input: TransferToATAInstructionPlanAsyncInput,\n config?: TransferToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.recipient,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getTransferToATAInstructionPlan(\n {\n ...input,\n destination: ataAddress,\n },\n config\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n TransferFeeConfig,\n WithheldWithdraw,\n CloseMint,\n InterestRate,\n PermanentDelegate,\n ConfidentialTransferMint,\n TransferHookProgramId,\n ConfidentialTransferFeeConfig,\n MetadataPointer,\n GroupPointer,\n GroupMemberPointer,\n ScaledUiAmount,\n Pause,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** Authenticated encryption containing an account balance. */\nexport type DecryptableBalance = ReadonlyUint8Array;\n\nexport type DecryptableBalanceArgs = DecryptableBalance;\n\nexport function getDecryptableBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 36);\n}\n\nexport function getDecryptableBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 36);\n}\n\nexport function getDecryptableBalanceCodec(): FixedSizeCodec<\n DecryptableBalanceArgs,\n DecryptableBalance\n> {\n return combineCodec(\n getDecryptableBalanceEncoder(),\n getDecryptableBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** ElGamal ciphertext containing an account balance. */\nexport type EncryptedBalance = ReadonlyUint8Array;\n\nexport type EncryptedBalanceArgs = EncryptedBalance;\n\nexport function getEncryptedBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 64);\n}\n\nexport function getEncryptedBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 64);\n}\n\nexport function getEncryptedBalanceCodec(): FixedSizeCodec<\n EncryptedBalanceArgs,\n EncryptedBalance\n> {\n return combineCodec(\n getEncryptedBalanceEncoder(),\n getEncryptedBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getF64Decoder,\n getF64Encoder,\n getI16Decoder,\n getI16Encoder,\n getMapDecoder,\n getMapEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n getEncryptedBalanceDecoder,\n getEncryptedBalanceEncoder,\n getTransferFeeDecoder,\n getTransferFeeEncoder,\n type AccountState,\n type AccountStateArgs,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n type EncryptedBalance,\n type EncryptedBalanceArgs,\n type TransferFee,\n type TransferFeeArgs,\n} from '.';\n\nexport type Extension =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFee;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFee;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: Option
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalance;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalance;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalance;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalance;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountState }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: Option
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: Option
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: Option
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: Option
;\n /** Optional account address that holds the group. */\n groupAddress: Option
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: bigint;\n /** The maximum number of group members. */\n maxSize: bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: Option
;\n /** Optional account address that holds the member. */\n memberAddress: Option
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: bigint;\n newMultiplier: number;\n }\n | { __kind: 'PausableConfig'; authority: Option
; paused: boolean }\n | { __kind: 'PausableAccount' };\n\nexport type ExtensionArgs =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: number | bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFeeArgs;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFeeArgs;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: number | bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: OptionOrNullable
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalanceArgs;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalanceArgs;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalanceArgs;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalanceArgs;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: number | bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: number | bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountStateArgs }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: number | bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: number | bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: OptionOrNullable
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: OptionOrNullable
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the group. */\n groupAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: number | bigint;\n /** The maximum number of group members. */\n maxSize: number | bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the member. */\n memberAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: number | bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: number | bigint;\n newMultiplier: number;\n }\n | {\n __kind: 'PausableConfig';\n authority: OptionOrNullable
;\n paused: boolean;\n }\n | { __kind: 'PausableAccount' };\n\nexport function getExtensionEncoder(): Encoder {\n return getDiscriminatedUnionEncoder(\n [\n ['Uninitialized', getUnitEncoder()],\n [\n 'TransferFeeConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['transferFeeConfigAuthority', getAddressEncoder()],\n ['withdrawWithheldAuthority', getAddressEncoder()],\n ['withheldAmount', getU64Encoder()],\n ['olderTransferFee', getTransferFeeEncoder()],\n ['newerTransferFee', getTransferFeeEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getU64Encoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addEncoderSizePrefix(\n getStructEncoder([['closeAuthority', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addEncoderSizePrefix(\n getStructEncoder([\n ['approved', getBooleanEncoder()],\n ['elgamalPubkey', getAddressEncoder()],\n ['pendingBalanceLow', getEncryptedBalanceEncoder()],\n ['pendingBalanceHigh', getEncryptedBalanceEncoder()],\n ['availableBalance', getEncryptedBalanceEncoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['allowConfidentialCredits', getBooleanEncoder()],\n ['allowNonConfidentialCredits', getBooleanEncoder()],\n ['pendingBalanceCreditCounter', getU64Encoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['actualPendingBalanceCreditCounter', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addEncoderSizePrefix(\n getStructEncoder([['state', getAccountStateEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'MemoTransfer',\n addEncoderSizePrefix(\n getStructEncoder([\n ['requireIncomingTransferMemos', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferable',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'InterestBearingConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['rateAuthority', getAddressEncoder()],\n ['initializationTimestamp', getU64Encoder()],\n ['preUpdateAverageRate', getI16Encoder()],\n ['lastUpdateTimestamp', getU64Encoder()],\n ['currentRate', getI16Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'CpiGuard',\n addEncoderSizePrefix(\n getStructEncoder([['lockCpi', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addEncoderSizePrefix(\n getStructEncoder([['delegate', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'TransferHook',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['programId', getAddressEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addEncoderSizePrefix(\n getStructEncoder([['transferring', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressEncoder()],\n ['harvestToMintEnabled', getBooleanEncoder()],\n ['withheldAmount', getEncryptedBalanceEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getEncryptedBalanceEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MetadataPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenMetadata',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n [\n 'additionalMetadata',\n getMapEncoder(\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())\n ),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroup',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['size', getU64Encoder()],\n ['maxSize', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addEncoderSizePrefix(\n getStructEncoder([\n ['mint', getAddressEncoder()],\n ['group', getAddressEncoder()],\n ['memberNumber', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitEncoder()],\n [\n 'ScaledUiAmountConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['multiplier', getF64Encoder()],\n ['newMultiplierEffectiveTimestamp', getU64Encoder()],\n ['newMultiplier', getF64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'PausableConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['PausableAccount', getUnitEncoder()],\n ],\n { size: getU16Encoder() }\n );\n}\n\nexport function getExtensionDecoder(): Decoder {\n return getDiscriminatedUnionDecoder(\n [\n ['Uninitialized', getUnitDecoder()],\n [\n 'TransferFeeConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['transferFeeConfigAuthority', getAddressDecoder()],\n ['withdrawWithheldAuthority', getAddressDecoder()],\n ['withheldAmount', getU64Decoder()],\n ['olderTransferFee', getTransferFeeDecoder()],\n ['newerTransferFee', getTransferFeeDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getU64Decoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addDecoderSizePrefix(\n getStructDecoder([['closeAuthority', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addDecoderSizePrefix(\n getStructDecoder([\n ['approved', getBooleanDecoder()],\n ['elgamalPubkey', getAddressDecoder()],\n ['pendingBalanceLow', getEncryptedBalanceDecoder()],\n ['pendingBalanceHigh', getEncryptedBalanceDecoder()],\n ['availableBalance', getEncryptedBalanceDecoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['allowConfidentialCredits', getBooleanDecoder()],\n ['allowNonConfidentialCredits', getBooleanDecoder()],\n ['pendingBalanceCreditCounter', getU64Decoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['actualPendingBalanceCreditCounter', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addDecoderSizePrefix(\n getStructDecoder([['state', getAccountStateDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'MemoTransfer',\n addDecoderSizePrefix(\n getStructDecoder([\n ['requireIncomingTransferMemos', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferable',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'InterestBearingConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['rateAuthority', getAddressDecoder()],\n ['initializationTimestamp', getU64Decoder()],\n ['preUpdateAverageRate', getI16Decoder()],\n ['lastUpdateTimestamp', getU64Decoder()],\n ['currentRate', getI16Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'CpiGuard',\n addDecoderSizePrefix(\n getStructDecoder([['lockCpi', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addDecoderSizePrefix(\n getStructDecoder([['delegate', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'TransferHook',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['programId', getAddressDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addDecoderSizePrefix(\n getStructDecoder([['transferring', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressDecoder()],\n ['harvestToMintEnabled', getBooleanDecoder()],\n ['withheldAmount', getEncryptedBalanceDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getEncryptedBalanceDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MetadataPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenMetadata',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n [\n 'additionalMetadata',\n getMapDecoder(\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())\n ),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroup',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['size', getU64Decoder()],\n ['maxSize', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addDecoderSizePrefix(\n getStructDecoder([\n ['mint', getAddressDecoder()],\n ['group', getAddressDecoder()],\n ['memberNumber', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitDecoder()],\n [\n 'ScaledUiAmountConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['multiplier', getF64Decoder()],\n ['newMultiplierEffectiveTimestamp', getU64Decoder()],\n ['newMultiplier', getF64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'PausableConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['PausableAccount', getUnitDecoder()],\n ],\n { size: getU16Decoder() }\n );\n}\n\nexport function getExtensionCodec(): Codec {\n return combineCodec(getExtensionEncoder(), getExtensionDecoder());\n}\n\n// Data Enum Helpers.\nexport function extension(\n kind: 'Uninitialized'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MintCloseAuthority',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MintCloseAuthority'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferMint',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n>;\nexport function extension(\n kind: 'ConfidentialTransferAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n>;\nexport function extension(\n kind: 'DefaultAccountState',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'DefaultAccountState'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ImmutableOwner',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ImmutableOwner'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MemoTransfer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MemoTransfer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferable',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferable'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'InterestBearingConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n>;\nexport function extension(\n kind: 'CpiGuard',\n data: GetDiscriminatedUnionVariantContent\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PermanentDelegate',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PermanentDelegate'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferableAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n>;\nexport function extension(\n kind: 'TransferHook',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHook'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferHookAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHookAccount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferFee',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n>;\nexport function extension(\n kind: 'ConfidentialTransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n>;\nexport function extension(\n kind: 'MetadataPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MetadataPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenMetadata',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenMetadata'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroup',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroup'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupMemberPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupMemberPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroupMember',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroupMember'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialMintBurn'\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialMintBurn'\n>;\nexport function extension(\n kind: 'ScaledUiAmountConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n>;\nexport function extension(\n kind: 'PausableConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PausableConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PausableAccount'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: K,\n data?: Data\n) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isExtension(\n kind: K,\n value: Extension\n): value is Extension & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n getU16Decoder,\n getU16Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\n/**\n * Extensions that can be applied to mints or accounts. Mint extensions must\n * only be applied to mint accounts, and account extensions must only be\n * applied to token holding accounts.\n */\nexport enum ExtensionType {\n Uninitialized,\n TransferFeeConfig,\n TransferFeeAmount,\n MintCloseAuthority,\n ConfidentialTransferMint,\n ConfidentialTransferAccount,\n DefaultAccountState,\n ImmutableOwner,\n MemoTransfer,\n NonTransferable,\n InterestBearingConfig,\n CpiGuard,\n PermanentDelegate,\n NonTransferableAccount,\n TransferHook,\n TransferHookAccount,\n ConfidentialTransferFee,\n ConfidentialTransferFeeAmount,\n ScaledUiAmountConfig,\n PausableConfig,\n PausableAccount,\n MetadataPointer,\n TokenMetadata,\n GroupPointer,\n TokenGroup,\n GroupMemberPointer,\n TokenGroupMember,\n}\n\nexport type ExtensionTypeArgs = ExtensionType;\n\nexport function getExtensionTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(ExtensionType, { size: getU16Encoder() });\n}\n\nexport function getExtensionTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(ExtensionType, { size: getU16Decoder() });\n}\n\nexport function getExtensionTypeCodec(): FixedSizeCodec<\n ExtensionTypeArgs,\n ExtensionType\n> {\n return combineCodec(getExtensionTypeEncoder(), getExtensionTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getU32Decoder,\n getU32Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n} from '@solana/kit';\n\n/** Fields in the metadata account, used for updating. */\nexport type TokenMetadataField =\n | { __kind: 'Name' }\n | { __kind: 'Symbol' }\n | { __kind: 'Uri' }\n | { __kind: 'Key'; fields: readonly [string] };\n\nexport type TokenMetadataFieldArgs = TokenMetadataField;\n\nexport function getTokenMetadataFieldEncoder(): Encoder {\n return getDiscriminatedUnionEncoder([\n ['Name', getUnitEncoder()],\n ['Symbol', getUnitEncoder()],\n ['Uri', getUnitEncoder()],\n [\n 'Key',\n getStructEncoder([\n [\n 'fields',\n getTupleEncoder([\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldDecoder(): Decoder {\n return getDiscriminatedUnionDecoder([\n ['Name', getUnitDecoder()],\n ['Symbol', getUnitDecoder()],\n ['Uri', getUnitDecoder()],\n [\n 'Key',\n getStructDecoder([\n [\n 'fields',\n getTupleDecoder([\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldCodec(): Codec<\n TokenMetadataFieldArgs,\n TokenMetadataField\n> {\n return combineCodec(\n getTokenMetadataFieldEncoder(),\n getTokenMetadataFieldDecoder()\n );\n}\n\n// Data Enum Helpers.\nexport function tokenMetadataField(\n kind: 'Name'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Symbol'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Uri'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Key',\n data: GetDiscriminatedUnionVariantContent<\n TokenMetadataFieldArgs,\n '__kind',\n 'Key'\n >['fields']\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField<\n K extends TokenMetadataFieldArgs['__kind'],\n Data,\n>(kind: K, data?: Data) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isTokenMetadataField(\n kind: K,\n value: TokenMetadataField\n): value is TokenMetadataField & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport type TransferFee = {\n /** First epoch where the transfer fee takes effect. */\n epoch: bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport type TransferFeeArgs = {\n /** First epoch where the transfer fee takes effect. */\n epoch: number | bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: number | bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport function getTransferFeeEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['epoch', getU64Encoder()],\n ['maximumFee', getU64Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ]);\n}\n\nexport function getTransferFeeDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['epoch', getU64Decoder()],\n ['maximumFee', getU64Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ]);\n}\n\nexport function getTransferFeeCodec(): FixedSizeCodec<\n TransferFeeArgs,\n TransferFee\n> {\n return combineCodec(getTransferFeeEncoder(), getTransferFeeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n padLeftEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getExtensionDecoder,\n getExtensionEncoder,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n /** The extensions activated on the mint account. */\n extensions: Option>;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n /** The extensions activated on the mint account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getMintEncoder(): Encoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintDecoder(): Decoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintCodec(): Codec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Encoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getExtensionDecoder,\n getExtensionEncoder,\n type AccountState,\n type AccountStateArgs,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n /** The extensions activated on the token account. */\n extensions: Option>;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n /** The extensions activated on the token account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getTokenEncoder(): Encoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): Decoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenCodec(): Codec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApplyConfidentialPendingBalanceInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveConfidentialTransferAccountInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedConfidentialDepositInstruction,\n type ParsedConfidentialTransferInstruction,\n type ParsedConfidentialTransferWithFeeInstruction,\n type ParsedConfidentialWithdrawInstruction,\n type ParsedConfigureConfidentialTransferAccountInstruction,\n type ParsedCreateNativeMintInstruction,\n type ParsedDisableConfidentialCreditsInstruction,\n type ParsedDisableCpiGuardInstruction,\n type ParsedDisableHarvestToMintInstruction,\n type ParsedDisableMemoTransfersInstruction,\n type ParsedDisableNonConfidentialCreditsInstruction,\n type ParsedEmitTokenMetadataInstruction,\n type ParsedEmptyConfidentialTransferAccountInstruction,\n type ParsedEnableConfidentialCreditsInstruction,\n type ParsedEnableCpiGuardInstruction,\n type ParsedEnableHarvestToMintInstruction,\n type ParsedEnableMemoTransfersInstruction,\n type ParsedEnableNonConfidentialCreditsInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction,\n type ParsedHarvestWithheldTokensToMintInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeConfidentialTransferFeeInstruction,\n type ParsedInitializeConfidentialTransferMintInstruction,\n type ParsedInitializeDefaultAccountStateInstruction,\n type ParsedInitializeGroupMemberPointerInstruction,\n type ParsedInitializeGroupPointerInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeInterestBearingMintInstruction,\n type ParsedInitializeMetadataPointerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintCloseAuthorityInstruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedInitializeNonTransferableMintInstruction,\n type ParsedInitializePausableConfigInstruction,\n type ParsedInitializePermanentDelegateInstruction,\n type ParsedInitializeScaledUiAmountMintInstruction,\n type ParsedInitializeTokenGroupInstruction,\n type ParsedInitializeTokenGroupMemberInstruction,\n type ParsedInitializeTokenMetadataInstruction,\n type ParsedInitializeTransferFeeConfigInstruction,\n type ParsedInitializeTransferHookInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedPauseInstruction,\n type ParsedReallocateInstruction,\n type ParsedRemoveTokenMetadataKeyInstruction,\n type ParsedResumeInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSetTransferFeeInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferCheckedWithFeeInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n type ParsedUpdateConfidentialTransferMintInstruction,\n type ParsedUpdateDefaultAccountStateInstruction,\n type ParsedUpdateGroupMemberPointerInstruction,\n type ParsedUpdateGroupPointerInstruction,\n type ParsedUpdateMetadataPointerInstruction,\n type ParsedUpdateMultiplierScaledUiMintInstruction,\n type ParsedUpdateRateInterestBearingMintInstruction,\n type ParsedUpdateTokenGroupMaxSizeInstruction,\n type ParsedUpdateTokenGroupUpdateAuthorityInstruction,\n type ParsedUpdateTokenMetadataFieldInstruction,\n type ParsedUpdateTokenMetadataUpdateAuthorityInstruction,\n type ParsedUpdateTransferHookInstruction,\n type ParsedWithdrawExcessLamportsInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsInstruction,\n type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromMintInstruction,\n} from '../instructions';\n\nexport const TOKEN_2022_PROGRAM_ADDRESS =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n\nexport enum Token2022Account {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyToken2022Account(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Account {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return Token2022Account.Mint;\n }\n if (data.length === 165) {\n return Token2022Account.Token;\n }\n if (data.length === 355) {\n return Token2022Account.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token-2022 account.'\n );\n}\n\nexport enum Token2022Instruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n InitializeMintCloseAuthority,\n InitializeTransferFeeConfig,\n TransferCheckedWithFee,\n WithdrawWithheldTokensFromMint,\n WithdrawWithheldTokensFromAccounts,\n HarvestWithheldTokensToMint,\n SetTransferFee,\n InitializeConfidentialTransferMint,\n UpdateConfidentialTransferMint,\n ConfigureConfidentialTransferAccount,\n ApproveConfidentialTransferAccount,\n EmptyConfidentialTransferAccount,\n ConfidentialDeposit,\n ConfidentialWithdraw,\n ConfidentialTransfer,\n ApplyConfidentialPendingBalance,\n EnableConfidentialCredits,\n DisableConfidentialCredits,\n EnableNonConfidentialCredits,\n DisableNonConfidentialCredits,\n ConfidentialTransferWithFee,\n InitializeDefaultAccountState,\n UpdateDefaultAccountState,\n Reallocate,\n EnableMemoTransfers,\n DisableMemoTransfers,\n CreateNativeMint,\n InitializeNonTransferableMint,\n InitializeInterestBearingMint,\n UpdateRateInterestBearingMint,\n EnableCpiGuard,\n DisableCpiGuard,\n InitializePermanentDelegate,\n InitializeTransferHook,\n UpdateTransferHook,\n InitializeConfidentialTransferFee,\n WithdrawWithheldTokensFromMintForConfidentialTransferFee,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFee,\n HarvestWithheldTokensToMintForConfidentialTransferFee,\n EnableHarvestToMint,\n DisableHarvestToMint,\n WithdrawExcessLamports,\n InitializeMetadataPointer,\n UpdateMetadataPointer,\n InitializeGroupPointer,\n UpdateGroupPointer,\n InitializeGroupMemberPointer,\n UpdateGroupMemberPointer,\n InitializeScaledUiAmountMint,\n UpdateMultiplierScaledUiMint,\n InitializePausableConfig,\n Pause,\n Resume,\n InitializeTokenMetadata,\n UpdateTokenMetadataField,\n RemoveTokenMetadataKey,\n UpdateTokenMetadataUpdateAuthority,\n EmitTokenMetadata,\n InitializeTokenGroup,\n UpdateTokenGroupMaxSize,\n UpdateTokenGroupUpdateAuthority,\n InitializeTokenGroupMember,\n}\n\nexport function identifyToken2022Instruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Instruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return Token2022Instruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return Token2022Instruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return Token2022Instruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return Token2022Instruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return Token2022Instruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return Token2022Instruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return Token2022Instruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return Token2022Instruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return Token2022Instruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return Token2022Instruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return Token2022Instruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return Token2022Instruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return Token2022Instruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return Token2022Instruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return Token2022Instruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return Token2022Instruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return Token2022Instruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return Token2022Instruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return Token2022Instruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return Token2022Instruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return Token2022Instruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return Token2022Instruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return Token2022Instruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return Token2022Instruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return Token2022Instruction.UiAmountToAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(25), 0)) {\n return Token2022Instruction.InitializeMintCloseAuthority;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferFeeConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.TransferCheckedWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.SetTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.ConfigureConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.ApproveConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EmptyConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.ConfidentialDeposit;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(6), 1)\n ) {\n return Token2022Instruction.ConfidentialWithdraw;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(7), 1)\n ) {\n return Token2022Instruction.ConfidentialTransfer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(8), 1)\n ) {\n return Token2022Instruction.ApplyConfidentialPendingBalance;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(9), 1)\n ) {\n return Token2022Instruction.EnableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(10), 1)\n ) {\n return Token2022Instruction.DisableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(11), 1)\n ) {\n return Token2022Instruction.EnableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(12), 1)\n ) {\n return Token2022Instruction.DisableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(13), 1)\n ) {\n return Token2022Instruction.ConfidentialTransferWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeDefaultAccountState;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateDefaultAccountState;\n }\n if (containsBytes(data, getU8Encoder().encode(29), 0)) {\n return Token2022Instruction.Reallocate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableMemoTransfers;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableMemoTransfers;\n }\n if (containsBytes(data, getU8Encoder().encode(31), 0)) {\n return Token2022Instruction.CreateNativeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(32), 0)) {\n return Token2022Instruction.InitializeNonTransferableMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateRateInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableCpiGuard;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableCpiGuard;\n }\n if (containsBytes(data, getU8Encoder().encode(35), 0)) {\n return Token2022Instruction.InitializePermanentDelegate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EnableHarvestToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.DisableHarvestToMint;\n }\n if (containsBytes(data, getU8Encoder().encode(38), 0)) {\n return Token2022Instruction.WithdrawExcessLamports;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeScaledUiAmountMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMultiplierScaledUiMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializePausableConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.Pause;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.Resume;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([210, 225, 30, 162, 88, 184, 77, 141]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenMetadata;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([221, 233, 49, 45, 181, 202, 220, 200]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataField;\n }\n if (\n containsBytes(data, new Uint8Array([234, 18, 32, 56, 89, 141, 37, 181]), 0)\n ) {\n return Token2022Instruction.RemoveTokenMetadataKey;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([250, 166, 180, 250, 13, 12, 184, 70]),\n 0\n )\n ) {\n return Token2022Instruction.EmitTokenMetadata;\n }\n if (\n containsBytes(data, new Uint8Array([121, 113, 108, 39, 54, 51, 0, 4]), 0)\n ) {\n return Token2022Instruction.InitializeTokenGroup;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([108, 37, 171, 143, 248, 30, 18, 110]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupMaxSize;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([161, 105, 88, 1, 237, 221, 216, 203]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([152, 32, 222, 176, 223, 237, 116, 134]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenGroupMember;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token-2022 instruction.'\n );\n}\n\nexport type ParsedToken2022Instruction<\n TProgram extends string = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n> =\n | ({\n instructionType: Token2022Instruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: Token2022Instruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: Token2022Instruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: Token2022Instruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: Token2022Instruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: Token2022Instruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: Token2022Instruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: Token2022Instruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: Token2022Instruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: Token2022Instruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: Token2022Instruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: Token2022Instruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: Token2022Instruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMintCloseAuthority;\n } & ParsedInitializeMintCloseAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferFeeConfig;\n } & ParsedInitializeTransferFeeConfigInstruction)\n | ({\n instructionType: Token2022Instruction.TransferCheckedWithFee;\n } & ParsedTransferCheckedWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMint;\n } & ParsedWithdrawWithheldTokensFromMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n } & ParsedWithdrawWithheldTokensFromAccountsInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMint;\n } & ParsedHarvestWithheldTokensToMintInstruction)\n | ({\n instructionType: Token2022Instruction.SetTransferFee;\n } & ParsedSetTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferMint;\n } & ParsedInitializeConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateConfidentialTransferMint;\n } & ParsedUpdateConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.ConfigureConfidentialTransferAccount;\n } & ParsedConfigureConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveConfidentialTransferAccount;\n } & ParsedApproveConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.EmptyConfidentialTransferAccount;\n } & ParsedEmptyConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialDeposit;\n } & ParsedConfidentialDepositInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialWithdraw;\n } & ParsedConfidentialWithdrawInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransfer;\n } & ParsedConfidentialTransferInstruction)\n | ({\n instructionType: Token2022Instruction.ApplyConfidentialPendingBalance;\n } & ParsedApplyConfidentialPendingBalanceInstruction)\n | ({\n instructionType: Token2022Instruction.EnableConfidentialCredits;\n } & ParsedEnableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableConfidentialCredits;\n } & ParsedDisableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.EnableNonConfidentialCredits;\n } & ParsedEnableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableNonConfidentialCredits;\n } & ParsedDisableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransferWithFee;\n } & ParsedConfidentialTransferWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeDefaultAccountState;\n } & ParsedInitializeDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateDefaultAccountState;\n } & ParsedUpdateDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.Reallocate;\n } & ParsedReallocateInstruction)\n | ({\n instructionType: Token2022Instruction.EnableMemoTransfers;\n } & ParsedEnableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.DisableMemoTransfers;\n } & ParsedDisableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.CreateNativeMint;\n } & ParsedCreateNativeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeNonTransferableMint;\n } & ParsedInitializeNonTransferableMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeInterestBearingMint;\n } & ParsedInitializeInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateRateInterestBearingMint;\n } & ParsedUpdateRateInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.EnableCpiGuard;\n } & ParsedEnableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.DisableCpiGuard;\n } & ParsedDisableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePermanentDelegate;\n } & ParsedInitializePermanentDelegateInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferHook;\n } & ParsedInitializeTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTransferHook;\n } & ParsedUpdateTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferFee;\n } & ParsedInitializeConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n } & ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.EnableHarvestToMint;\n } & ParsedEnableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.DisableHarvestToMint;\n } & ParsedDisableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawExcessLamports;\n } & ParsedWithdrawExcessLamportsInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMetadataPointer;\n } & ParsedInitializeMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMetadataPointer;\n } & ParsedUpdateMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupPointer;\n } & ParsedInitializeGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupPointer;\n } & ParsedUpdateGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupMemberPointer;\n } & ParsedInitializeGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupMemberPointer;\n } & ParsedUpdateGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeScaledUiAmountMint;\n } & ParsedInitializeScaledUiAmountMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMultiplierScaledUiMint;\n } & ParsedUpdateMultiplierScaledUiMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePausableConfig;\n } & ParsedInitializePausableConfigInstruction)\n | ({\n instructionType: Token2022Instruction.Pause;\n } & ParsedPauseInstruction)\n | ({\n instructionType: Token2022Instruction.Resume;\n } & ParsedResumeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenMetadata;\n } & ParsedInitializeTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataField;\n } & ParsedUpdateTokenMetadataFieldInstruction)\n | ({\n instructionType: Token2022Instruction.RemoveTokenMetadataKey;\n } & ParsedRemoveTokenMetadataKeyInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n } & ParsedUpdateTokenMetadataUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.EmitTokenMetadata;\n } & ParsedEmitTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroup;\n } & ParsedInitializeTokenGroupInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupMaxSize;\n } & ParsedUpdateTokenGroupMaxSizeInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n } & ParsedUpdateTokenGroupUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroupMember;\n } & ParsedInitializeTokenGroupMemberInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_2022_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_2022_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_2022_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_2022_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_2022_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_2022_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_2022_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_2022_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_2022_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_2022_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_2022_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_2022_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_2022_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type Token2022Error =\n | typeof TOKEN_2022_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_2022_ERROR__ALREADY_IN_USE\n | typeof TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__FIXED_SUPPLY\n | typeof TOKEN_2022_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_2022_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_2022_ERROR__INVALID_MINT\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_STATE\n | typeof TOKEN_2022_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_2022_ERROR__MINT_MISMATCH\n | typeof TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_2022_ERROR__OVERFLOW\n | typeof TOKEN_2022_ERROR__OWNER_MISMATCH\n | typeof TOKEN_2022_ERROR__UNINITIALIZED_STATE;\n\nlet token2022ErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n token2022ErrorMessages = {\n [TOKEN_2022_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_2022_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_2022_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_2022_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_2022_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_2022_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_2022_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_2022_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_2022_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_2022_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_2022_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_2022_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_2022_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getToken2022ErrorMessage(code: Token2022Error): string {\n if (process.env.NODE_ENV !== 'production') {\n return (token2022ErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isToken2022Error(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_2022_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR = 27;\n\nexport function getApplyConfidentialPendingBalanceDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR\n );\n}\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 8;\n\nexport function getApplyConfidentialPendingBalanceConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApplyConfidentialPendingBalanceInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalance;\n};\n\nexport type ApplyConfidentialPendingBalanceInstructionDataArgs = {\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n};\n\nexport function getApplyConfidentialPendingBalanceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataCodec(): FixedSizeCodec<\n ApplyConfidentialPendingBalanceInstructionDataArgs,\n ApplyConfidentialPendingBalanceInstructionData\n> {\n return combineCodec(\n getApplyConfidentialPendingBalanceInstructionDataEncoder(),\n getApplyConfidentialPendingBalanceInstructionDataDecoder()\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n expectedPendingBalanceCreditCounter: ApplyConfidentialPendingBalanceInstructionDataArgs['expectedPendingBalanceCreditCounter'];\n newDecryptableAvailableBalance: ApplyConfidentialPendingBalanceInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getApplyConfidentialPendingBalanceInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApplyConfidentialPendingBalanceInput,\n config?: { programAddress?: TProgramAddress }\n): ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getApplyConfidentialPendingBalanceInstructionDataEncoder().encode(\n args as ApplyConfidentialPendingBalanceInstructionDataArgs\n ),\n programAddress,\n } as ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: ApplyConfidentialPendingBalanceInstructionData;\n};\n\nexport function parseApplyConfidentialPendingBalanceInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApplyConfidentialPendingBalanceInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getApplyConfidentialPendingBalanceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getApproveConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 3;\n\nexport function getApproveConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type ApproveConfidentialTransferAccountInstructionDataArgs = {};\n\nexport function getApproveConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ApproveConfidentialTransferAccountInstructionDataArgs,\n ApproveConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getApproveConfidentialTransferAccountInstructionDataEncoder(),\n getApproveConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ApproveConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account to approve. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n};\n\nexport function getApproveConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getApproveConfidentialTransferAccountInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account to approve. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[2];\n };\n data: ApproveConfidentialTransferAccountInstructionData;\n};\n\nexport function parseApproveConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getApproveConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CONFIDENTIAL_DEPOSIT_DISCRIMINATOR = 27;\n\nexport function getConfidentialDepositDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_DEPOSIT_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 5;\n\nexport function getConfidentialDepositConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialDepositInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to deposit. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ConfidentialDepositInstructionDataArgs = {\n /** The amount of tokens to deposit. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getConfidentialDepositInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_DEPOSIT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialDepositInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getConfidentialDepositInstructionDataCodec(): FixedSizeCodec<\n ConfidentialDepositInstructionDataArgs,\n ConfidentialDepositInstructionData\n> {\n return combineCodec(\n getConfidentialDepositInstructionDataEncoder(),\n getConfidentialDepositInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialDepositInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialDepositInstructionDataArgs['amount'];\n decimals: ConfidentialDepositInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialDepositInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialDepositInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialDepositInstructionDataEncoder().encode(\n args as ConfidentialDepositInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: ConfidentialDepositInstructionData;\n};\n\nexport function parseConfidentialDepositInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialDepositInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialDepositInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 7;\n\nexport function getConfidentialTransferConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferInstructionDataArgs,\n ConfidentialTransferInstructionData\n> {\n return combineCodec(\n getConfidentialTransferInstructionDataEncoder(),\n getConfidentialTransferInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['equalityProofInstructionOffset'];\n ciphertextValidityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['ciphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n ciphertextValidityRecord: {\n value: input.ciphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.ciphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferInstructionDataEncoder().encode(\n args as ConfidentialTransferInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[6] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[7];\n };\n data: ConfidentialTransferInstructionData;\n};\n\nexport function parseConfidentialTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferInstruction {\n if (instruction.accounts.length < 8) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n ciphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 13;\n\nexport function getConfidentialTransferWithFeeConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountTransferAmountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountFeeSigmaRecord extends string | AccountMeta = string,\n TAccountFeeCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord extends string\n ? ReadonlyAccount\n : TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferWithFeeInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferWithFeeInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n [\n 'transferAmountCiphertextValidityProofInstructionOffset',\n getI8Encoder(),\n ],\n ['feeSigmaProofInstructionOffset', getI8Encoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['transferAmountCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['feeSigmaProofInstructionOffset', getI8Decoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferWithFeeInstructionDataArgs,\n ConfidentialTransferWithFeeInstructionData\n> {\n return combineCodec(\n getConfidentialTransferWithFeeInstructionDataEncoder(),\n getConfidentialTransferWithFeeInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferWithFeeInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountTransferAmountCiphertextValidityRecord extends string = string,\n TAccountFeeSigmaRecord extends string = string,\n TAccountFeeCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: Address;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: Address;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferWithFeeInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['equalityProofInstructionOffset'];\n transferAmountCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['transferAmountCiphertextValidityProofInstructionOffset'];\n feeSigmaProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeSigmaProofInstructionOffset'];\n feeCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeCiphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferWithFeeInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountTransferAmountCiphertextValidityRecord extends string,\n TAccountFeeSigmaRecord extends string,\n TAccountFeeCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferWithFeeInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n transferAmountCiphertextValidityRecord: {\n value: input.transferAmountCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n feeSigmaRecord: { value: input.feeSigmaRecord ?? null, isWritable: false },\n feeCiphertextValidityRecord: {\n value: input.feeCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.transferAmountCiphertextValidityRecord),\n getAccountMeta(accounts.feeSigmaRecord),\n getAccountMeta(accounts.feeCiphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferWithFeeInstructionDataEncoder().encode(\n args as ConfidentialTransferWithFeeInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: TAccountMetas[6] | undefined;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: TAccountMetas[7] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[8] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[9];\n };\n data: ConfidentialTransferWithFeeInstructionData;\n};\n\nexport function parseConfidentialTransferWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferWithFeeInstruction {\n if (instruction.accounts.length < 10) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n transferAmountCiphertextValidityRecord: getNextOptionalAccount(),\n feeSigmaRecord: getNextOptionalAccount(),\n feeCiphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_WITHDRAW_DISCRIMINATOR = 27;\n\nexport function getConfidentialWithdrawDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_WITHDRAW_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 6;\n\nexport function getConfidentialWithdrawConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialWithdrawInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to withdraw. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialWithdrawInstructionDataArgs = {\n /** The amount of tokens to withdraw. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialWithdrawInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_WITHDRAW_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialWithdrawInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialWithdrawInstructionDataCodec(): FixedSizeCodec<\n ConfidentialWithdrawInstructionDataArgs,\n ConfidentialWithdrawInstructionData\n> {\n return combineCodec(\n getConfidentialWithdrawInstructionDataEncoder(),\n getConfidentialWithdrawInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialWithdrawInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialWithdrawInstructionDataArgs['amount'];\n decimals: ConfidentialWithdrawInstructionDataArgs['decimals'];\n newDecryptableAvailableBalance: ConfidentialWithdrawInstructionDataArgs['newDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['equalityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialWithdrawInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialWithdrawInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialWithdrawInstructionDataEncoder().encode(\n args as ConfidentialWithdrawInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[2] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[3] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[4] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[5];\n };\n data: ConfidentialWithdrawInstructionData;\n};\n\nexport function parseConfidentialWithdrawInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialWithdrawInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialWithdrawInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getConfigureConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 2;\n\nexport function getConfigureConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfigureConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalance;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type ConfigureConfidentialTransferAccountInstructionDataArgs = {\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalanceArgs;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getConfigureConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['decryptableZeroBalance', getDecryptableBalanceEncoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['decryptableZeroBalance', getDecryptableBalanceDecoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ConfigureConfidentialTransferAccountInstructionDataArgs,\n ConfigureConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getConfigureConfidentialTransferAccountInstructionDataEncoder(),\n getConfigureConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n decryptableZeroBalance: ConfigureConfidentialTransferAccountInstructionDataArgs['decryptableZeroBalance'];\n maximumPendingBalanceCreditCounter: ConfigureConfidentialTransferAccountInstructionDataArgs['maximumPendingBalanceCreditCounter'];\n proofInstructionOffset: ConfigureConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfigureConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfigureConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfigureConfidentialTransferAccountInstructionDataEncoder().encode(\n args as ConfigureConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[3] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[4];\n };\n data: ConfigureConfidentialTransferAccountInstructionData;\n};\n\nexport function parseConfigureConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfigureConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CREATE_NATIVE_MINT_DISCRIMINATOR = 31;\n\nexport function getCreateNativeMintDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_NATIVE_MINT_DISCRIMINATOR);\n}\n\nexport type CreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNativeMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNativeMint extends string\n ? WritableAccount\n : TAccountNativeMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateNativeMintInstructionData = { discriminator: number };\n\nexport type CreateNativeMintInstructionDataArgs = {};\n\nexport function getCreateNativeMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CREATE_NATIVE_MINT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateNativeMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateNativeMintInstructionDataCodec(): FixedSizeCodec<\n CreateNativeMintInstructionDataArgs,\n CreateNativeMintInstructionData\n> {\n return combineCodec(\n getCreateNativeMintInstructionDataEncoder(),\n getCreateNativeMintInstructionDataDecoder()\n );\n}\n\nexport type CreateNativeMintInput<\n TAccountPayer extends string = string,\n TAccountNativeMint extends string = string,\n TAccountSystemProgram extends string = string,\n> = {\n /** Funding account (must be a system account) */\n payer: TransactionSigner;\n /** The native mint address */\n nativeMint: Address;\n /** System program for mint account funding */\n systemProgram?: Address;\n};\n\nexport function getCreateNativeMintInstruction<\n TAccountPayer extends string,\n TAccountNativeMint extends string,\n TAccountSystemProgram extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CreateNativeMintInput<\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n nativeMint: { value: input.nativeMint ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.nativeMint),\n getAccountMeta(accounts.systemProgram),\n ],\n data: getCreateNativeMintInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >);\n}\n\nexport type ParsedCreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account) */\n payer: TAccountMetas[0];\n /** The native mint address */\n nativeMint: TAccountMetas[1];\n /** System program for mint account funding */\n systemProgram: TAccountMetas[2];\n };\n data: CreateNativeMintInstructionData;\n};\n\nexport function parseCreateNativeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateNativeMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n nativeMint: getNextAccount(),\n systemProgram: getNextAccount(),\n },\n data: getCreateNativeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 10;\n\nexport function getDisableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableConfidentialCreditsInstructionDataArgs,\n DisableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableConfidentialCreditsInstructionDataEncoder(),\n getDisableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getDisableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 1;\n\nexport function getDisableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type DisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type DisableCpiGuardInstructionDataArgs = {};\n\nexport function getDisableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n DisableCpiGuardInstructionDataArgs,\n DisableCpiGuardInstructionData\n> {\n return combineCodec(\n getDisableCpiGuardInstructionDataEncoder(),\n getDisableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type DisableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableCpiGuardInstructionData;\n};\n\nexport function parseDisableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getDisableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getDisableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type DisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type DisableHarvestToMintInstructionDataArgs = {};\n\nexport function getDisableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n DisableHarvestToMintInstructionDataArgs,\n DisableHarvestToMintInstructionData\n> {\n return combineCodec(\n getDisableHarvestToMintInstructionDataEncoder(),\n getDisableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type DisableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: DisableHarvestToMintInstructionData;\n};\n\nexport function parseDisableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getDisableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getDisableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 1;\n\nexport function getDisableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type DisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type DisableMemoTransfersInstructionDataArgs = {};\n\nexport function getDisableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n DisableMemoTransfersInstructionDataArgs,\n DisableMemoTransfersInstructionData\n> {\n return combineCodec(\n getDisableMemoTransfersInstructionDataEncoder(),\n getDisableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type DisableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableMemoTransfersInstructionData;\n};\n\nexport function parseDisableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 12;\n\nexport function getDisableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableNonConfidentialCreditsInstructionDataArgs,\n DisableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableNonConfidentialCreditsInstructionDataEncoder(),\n getDisableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMIT_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 250, 166, 180, 250, 13, 12, 184, 70,\n]);\n\nexport function getEmitTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(EMIT_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type EmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? ReadonlyAccount\n : TAccountMetadata,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmitTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Start of range of data to emit */\n start: Option;\n /** End of range of data to emit */\n end: Option;\n};\n\nexport type EmitTokenMetadataInstructionDataArgs = {\n /** Start of range of data to emit */\n start?: OptionOrNullable;\n /** End of range of data to emit */\n end?: OptionOrNullable;\n};\n\nexport function getEmitTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['start', getOptionEncoder(getU64Encoder())],\n ['end', getOptionEncoder(getU64Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: EMIT_TOKEN_METADATA_DISCRIMINATOR,\n start: value.start ?? none(),\n end: value.end ?? none(),\n })\n );\n}\n\nexport function getEmitTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['start', getOptionDecoder(getU64Decoder())],\n ['end', getOptionDecoder(getU64Decoder())],\n ]);\n}\n\nexport function getEmitTokenMetadataInstructionDataCodec(): Codec<\n EmitTokenMetadataInstructionDataArgs,\n EmitTokenMetadataInstructionData\n> {\n return combineCodec(\n getEmitTokenMetadataInstructionDataEncoder(),\n getEmitTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type EmitTokenMetadataInput = {\n metadata: Address;\n start?: EmitTokenMetadataInstructionDataArgs['start'];\n end?: EmitTokenMetadataInstructionDataArgs['end'];\n};\n\nexport function getEmitTokenMetadataInstruction<\n TAccountMetadata extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmitTokenMetadataInput,\n config?: { programAddress?: TProgramAddress }\n): EmitTokenMetadataInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.metadata)],\n data: getEmitTokenMetadataInstructionDataEncoder().encode(\n args as EmitTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as EmitTokenMetadataInstruction);\n}\n\nexport type ParsedEmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n };\n data: EmitTokenMetadataInstructionData;\n};\n\nexport function parseEmitTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmitTokenMetadataInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount() },\n data: getEmitTokenMetadataInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getEmptyConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 4;\n\nexport function getEmptyConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmptyConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type EmptyConfidentialTransferAccountInstructionDataArgs = {\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getEmptyConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n EmptyConfidentialTransferAccountInstructionDataArgs,\n EmptyConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getEmptyConfidentialTransferAccountInstructionDataEncoder(),\n getEmptyConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type EmptyConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n proofInstructionOffset: EmptyConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getEmptyConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmptyConfidentialTransferAccountInput<\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEmptyConfidentialTransferAccountInstructionDataEncoder().encode(\n args as EmptyConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[1];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[2] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: EmptyConfidentialTransferAccountInstructionData;\n};\n\nexport function parseEmptyConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmptyConfidentialTransferAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getEmptyConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 9;\n\nexport function getEnableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableConfidentialCreditsInstructionDataArgs,\n EnableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableConfidentialCreditsInstructionDataEncoder(),\n getEnableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getEnableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 0;\n\nexport function getEnableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type EnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type EnableCpiGuardInstructionDataArgs = {};\n\nexport function getEnableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n EnableCpiGuardInstructionDataArgs,\n EnableCpiGuardInstructionData\n> {\n return combineCodec(\n getEnableCpiGuardInstructionDataEncoder(),\n getEnableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type EnableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableCpiGuardInstructionData;\n};\n\nexport function parseEnableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getEnableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getEnableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type EnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type EnableHarvestToMintInstructionDataArgs = {};\n\nexport function getEnableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n EnableHarvestToMintInstructionDataArgs,\n EnableHarvestToMintInstructionData\n> {\n return combineCodec(\n getEnableHarvestToMintInstructionDataEncoder(),\n getEnableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type EnableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: EnableHarvestToMintInstructionData;\n};\n\nexport function parseEnableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getEnableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getEnableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 0;\n\nexport function getEnableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type EnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type EnableMemoTransfersInstructionDataArgs = {};\n\nexport function getEnableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n EnableMemoTransfersInstructionDataArgs,\n EnableMemoTransfersInstructionData\n> {\n return combineCodec(\n getEnableMemoTransfersInstructionDataEncoder(),\n getEnableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type EnableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableMemoTransfersInstructionData;\n};\n\nexport function parseEnableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 11;\n\nexport function getEnableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableNonConfidentialCreditsInstructionDataArgs,\n EnableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableNonConfidentialCreditsInstructionDataEncoder(),\n getEnableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR = 26;\n\nexport function getHarvestWithheldTokensToMintDiscriminatorBytes() {\n return getU8Encoder().encode(HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR);\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getHarvestWithheldTokensToMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type HarvestWithheldTokensToMintInstructionDataArgs = {};\n\nexport function getHarvestWithheldTokensToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintInstructionDataArgs,\n HarvestWithheldTokensToMintInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintInstructionDataEncoder(),\n getHarvestWithheldTokensToMintInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintInput<\n TAccountMint extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n sources: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.sources.map((address) => ({\n address,\n role: AccountRole.WRITABLE,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as HarvestWithheldTokensToMintInstruction);\n}\n\nexport type ParsedHarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData =\n { discriminator: number; confidentialTransferFeeDiscriminator: number };\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs =\n {};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs,\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(),\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n sources?: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintForConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.sources ?? []).map(\n (address) => ({ address, role: AccountRole.WRITABLE })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getInitializeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferFeeInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: Option
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferFeeInstructionDataArgs = {\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: OptionOrNullable
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferFeeInstructionDataArgs,\n InitializeConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferFeeInstructionDataEncoder(),\n getInitializeConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferFeeInstructionDataArgs['authority'];\n withdrawWithheldAuthorityElGamalPubkey: InitializeConfidentialTransferFeeInstructionDataArgs['withdrawWithheldAuthorityElGamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferFeeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferFeeInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferFeeInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferFeeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getInitializeConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: Option
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferMintInstructionDataArgs = {\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: OptionOrNullable
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferMintInstructionDataArgs,\n InitializeConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferMintInstructionDataEncoder(),\n getInitializeConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferMintInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferMintInstructionDataArgs['authority'];\n autoApproveNewAccounts: InitializeConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: InitializeConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferMintInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferMintInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferMintInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getInitializeDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 0;\n\nexport function getInitializeDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type InitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type InitializeDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getInitializeDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n InitializeDefaultAccountStateInstructionDataArgs,\n InitializeDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getInitializeDefaultAccountStateInstructionDataEncoder(),\n getInitializeDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type InitializeDefaultAccountStateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n state: InitializeDefaultAccountStateInstructionDataArgs['state'];\n};\n\nexport function getInitializeDefaultAccountStateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeDefaultAccountStateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeDefaultAccountStateInstructionDataEncoder().encode(\n args as InitializeDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as InitializeDefaultAccountStateInstruction);\n}\n\nexport type ParsedInitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeDefaultAccountStateInstructionData;\n};\n\nexport function parseInitializeDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeDefaultAccountStateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getInitializeGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The public key for the account that can update the group member address. */\n authority: Option
;\n /** The account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type InitializeGroupMemberPointerInstructionDataArgs = {\n /** The public key for the account that can update the group member address. */\n authority: OptionOrNullable
;\n /** The account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupMemberPointerInstructionDataArgs,\n InitializeGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupMemberPointerInstructionDataEncoder(),\n getInitializeGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupMemberPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupMemberPointerInstructionDataArgs['authority'];\n memberAddress: InitializeGroupMemberPointerInstructionDataArgs['memberAddress'];\n};\n\nexport function getInitializeGroupMemberPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupMemberPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupMemberPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupMemberPointerInstructionDataEncoder().encode(\n args as InitializeGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupMemberPointerInstruction);\n}\n\nexport type ParsedInitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupMemberPointerInstructionData;\n};\n\nexport function parseInitializeGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupMemberPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getInitializeGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The public key for the account that can update the group address. */\n authority: Option
;\n /** The account address that holds the group. */\n groupAddress: Option
;\n};\n\nexport type InitializeGroupPointerInstructionDataArgs = {\n /** The public key for the account that can update the group address. */\n authority: OptionOrNullable
;\n /** The account address that holds the group. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupPointerInstructionDataArgs,\n InitializeGroupPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupPointerInstructionDataEncoder(),\n getInitializeGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupPointerInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupPointerInstructionDataArgs['authority'];\n groupAddress: InitializeGroupPointerInstructionDataArgs['groupAddress'];\n };\n\nexport function getInitializeGroupPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupPointerInstructionDataEncoder().encode(\n args as InitializeGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupPointerInstruction);\n}\n\nexport type ParsedInitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupPointerInstructionData;\n};\n\nexport function parseInitializeGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getI16Decoder,\n getI16Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getInitializeInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The public key for the account that can update the rate */\n rateAuthority: Option
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport type InitializeInterestBearingMintInstructionDataArgs = {\n /** The public key for the account that can update the rate */\n rateAuthority: OptionOrNullable
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport function getInitializeInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n [\n 'rateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n [\n 'rateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getInitializeInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n InitializeInterestBearingMintInstructionDataArgs,\n InitializeInterestBearingMintInstructionData\n> {\n return combineCodec(\n getInitializeInterestBearingMintInstructionDataEncoder(),\n getInitializeInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeInterestBearingMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n rateAuthority: InitializeInterestBearingMintInstructionDataArgs['rateAuthority'];\n rate: InitializeInterestBearingMintInstructionDataArgs['rate'];\n};\n\nexport function getInitializeInterestBearingMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeInterestBearingMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeInterestBearingMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeInterestBearingMintInstructionDataEncoder().encode(\n args as InitializeInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeInterestBearingMintInstruction);\n}\n\nexport type ParsedInitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeInterestBearingMintInstructionData;\n};\n\nexport function parseInitializeInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeInterestBearingMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getInitializeMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The public key for the account that can update the metadata address. */\n authority: Option
;\n /** The account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type InitializeMetadataPointerInstructionDataArgs = {\n /** The public key for the account that can update the metadata address. */\n authority: OptionOrNullable
;\n /** The account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getInitializeMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeMetadataPointerInstructionDataArgs,\n InitializeMetadataPointerInstructionData\n> {\n return combineCodec(\n getInitializeMetadataPointerInstructionDataEncoder(),\n getInitializeMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeMetadataPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeMetadataPointerInstructionDataArgs['authority'];\n metadataAddress: InitializeMetadataPointerInstructionDataArgs['metadataAddress'];\n};\n\nexport function getInitializeMetadataPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMetadataPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMetadataPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMetadataPointerInstructionDataEncoder().encode(\n args as InitializeMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeMetadataPointerInstruction);\n}\n\nexport type ParsedInitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMetadataPointerInstructionData;\n};\n\nexport function parseInitializeMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMetadataPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR = 25;\n\nexport function getInitializeMintCloseAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type InitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintCloseAuthorityInstructionData = {\n discriminator: number;\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: Option
;\n};\n\nexport type InitializeMintCloseAuthorityInstructionDataArgs = {\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getInitializeMintCloseAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['closeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['closeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataCodec(): Codec<\n InitializeMintCloseAuthorityInstructionDataArgs,\n InitializeMintCloseAuthorityInstructionData\n> {\n return combineCodec(\n getInitializeMintCloseAuthorityInstructionDataEncoder(),\n getInitializeMintCloseAuthorityInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintCloseAuthorityInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n closeAuthority: InitializeMintCloseAuthorityInstructionDataArgs['closeAuthority'];\n};\n\nexport function getInitializeMintCloseAuthorityInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintCloseAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintCloseAuthorityInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMintCloseAuthorityInstructionDataEncoder().encode(\n args as InitializeMintCloseAuthorityInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintCloseAuthorityInstruction);\n}\n\nexport type ParsedInitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMintCloseAuthorityInstructionData;\n};\n\nexport function parseInitializeMintCloseAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintCloseAuthorityInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMintCloseAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR = 32;\n\nexport function getInitializeNonTransferableMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeNonTransferableMintInstructionData = {\n discriminator: number;\n};\n\nexport type InitializeNonTransferableMintInstructionDataArgs = {};\n\nexport function getInitializeNonTransferableMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeNonTransferableMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeNonTransferableMintInstructionDataCodec(): FixedSizeCodec<\n InitializeNonTransferableMintInstructionDataArgs,\n InitializeNonTransferableMintInstructionData\n> {\n return combineCodec(\n getInitializeNonTransferableMintInstructionDataEncoder(),\n getInitializeNonTransferableMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeNonTransferableMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint account to initialize. */\n mint: Address;\n};\n\nexport function getInitializeNonTransferableMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeNonTransferableMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeNonTransferableMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeNonTransferableMintInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeNonTransferableMintInstruction);\n}\n\nexport type ParsedInitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeNonTransferableMintInstructionData;\n};\n\nexport function parseInitializeNonTransferableMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeNonTransferableMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeNonTransferableMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR = 44;\n\nexport function getInitializePausableConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR = 0;\n\nexport function getInitializePausableConfigPausableDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR\n );\n}\n\nexport type InitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePausableConfigInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n /** The authority that can pause and resume the mint. */\n authority: Option
;\n};\n\nexport type InitializePausableConfigInstructionDataArgs = {\n /** The authority that can pause and resume the mint. */\n authority: OptionOrNullable
;\n};\n\nexport function getInitializePausableConfigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR,\n pausableDiscriminator: INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePausableConfigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializePausableConfigInstructionDataCodec(): FixedSizeCodec<\n InitializePausableConfigInstructionDataArgs,\n InitializePausableConfigInstructionData\n> {\n return combineCodec(\n getInitializePausableConfigInstructionDataEncoder(),\n getInitializePausableConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializePausableConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n authority: InitializePausableConfigInstructionDataArgs['authority'];\n};\n\nexport function getInitializePausableConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePausableConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePausableConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePausableConfigInstructionDataEncoder().encode(\n args as InitializePausableConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializePausableConfigInstruction);\n}\n\nexport type ParsedInitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializePausableConfigInstructionData;\n};\n\nexport function parseInitializePausableConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePausableConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePausableConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR = 35;\n\nexport function getInitializePermanentDelegateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR);\n}\n\nexport type InitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePermanentDelegateInstructionData = {\n discriminator: number;\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport type InitializePermanentDelegateInstructionDataArgs = {\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport function getInitializePermanentDelegateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['delegate', getAddressEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePermanentDelegateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['delegate', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializePermanentDelegateInstructionDataCodec(): FixedSizeCodec<\n InitializePermanentDelegateInstructionDataArgs,\n InitializePermanentDelegateInstructionData\n> {\n return combineCodec(\n getInitializePermanentDelegateInstructionDataEncoder(),\n getInitializePermanentDelegateInstructionDataDecoder()\n );\n}\n\nexport type InitializePermanentDelegateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n delegate: InitializePermanentDelegateInstructionDataArgs['delegate'];\n};\n\nexport function getInitializePermanentDelegateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePermanentDelegateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePermanentDelegateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePermanentDelegateInstructionDataEncoder().encode(\n args as InitializePermanentDelegateInstructionDataArgs\n ),\n programAddress,\n } as InitializePermanentDelegateInstruction);\n}\n\nexport type ParsedInitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializePermanentDelegateInstructionData;\n};\n\nexport function parseInitializePermanentDelegateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePermanentDelegateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePermanentDelegateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getF64Decoder,\n getF64Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 43;\n\nexport function getInitializeScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeScaledUiAmountMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeScaledUiAmountMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The authority that can update the multiplier */\n authority: Option
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport type InitializeScaledUiAmountMintInstructionDataArgs = {\n /** The authority that can update the multiplier */\n authority: OptionOrNullable
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport function getInitializeScaledUiAmountMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Decoder()],\n ]);\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataCodec(): FixedSizeCodec<\n InitializeScaledUiAmountMintInstructionDataArgs,\n InitializeScaledUiAmountMintInstructionData\n> {\n return combineCodec(\n getInitializeScaledUiAmountMintInstructionDataEncoder(),\n getInitializeScaledUiAmountMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeScaledUiAmountMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeScaledUiAmountMintInstructionDataArgs['authority'];\n multiplier: InitializeScaledUiAmountMintInstructionDataArgs['multiplier'];\n};\n\nexport function getInitializeScaledUiAmountMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeScaledUiAmountMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeScaledUiAmountMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeScaledUiAmountMintInstructionDataEncoder().encode(\n args as InitializeScaledUiAmountMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeScaledUiAmountMintInstruction);\n}\n\nexport type ParsedInitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeScaledUiAmountMintInstructionData;\n};\n\nexport function parseInitializeScaledUiAmountMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeScaledUiAmountMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeScaledUiAmountMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_DISCRIMINATOR = new Uint8Array([\n 121, 113, 108, 39, 54, 51, 0, 4,\n]);\n\nexport function getInitializeTokenGroupDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Update authority for the group */\n updateAuthority: Option
;\n /** The maximum number of group members */\n maxSize: bigint;\n};\n\nexport type InitializeTokenGroupInstructionDataArgs = {\n /** Update authority for the group */\n updateAuthority: OptionOrNullable
;\n /** The maximum number of group members */\n maxSize: number | bigint;\n};\n\nexport function getInitializeTokenGroupInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTokenGroupInstructionDataCodec(): Codec<\n InitializeTokenGroupInstructionDataArgs,\n InitializeTokenGroupInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupInstructionDataEncoder(),\n getInitializeTokenGroupInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupInput<\n TAccountGroup extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n group: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n updateAuthority: InitializeTokenGroupInstructionDataArgs['updateAuthority'];\n maxSize: InitializeTokenGroupInstructionDataArgs['maxSize'];\n};\n\nexport function getInitializeTokenGroupInstruction<\n TAccountGroup extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupInput<\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenGroupInstructionDataEncoder().encode(\n args as InitializeTokenGroupInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n mint: TAccountMetas[1];\n mintAuthority: TAccountMetas[2];\n };\n data: InitializeTokenGroupInstructionData;\n};\n\nexport function parseInitializeTokenGroupInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n group: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR = new Uint8Array([\n 152, 32, 222, 176, 223, 237, 116, 134,\n]);\n\nexport function getInitializeTokenGroupMemberDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMember extends string | AccountMeta = string,\n TAccountMemberMint extends string | AccountMeta = string,\n TAccountMemberMintAuthority extends string | AccountMeta = string,\n TAccountGroup extends string | AccountMeta = string,\n TAccountGroupUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMember extends string\n ? WritableAccount\n : TAccountMember,\n TAccountMemberMint extends string\n ? ReadonlyAccount\n : TAccountMemberMint,\n TAccountMemberMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMemberMintAuthority,\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountGroupUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupMemberInstructionData = {\n discriminator: ReadonlyUint8Array;\n};\n\nexport type InitializeTokenGroupMemberInstructionDataArgs = {};\n\nexport function getInitializeTokenGroupMemberInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getBytesEncoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataDecoder(): Decoder {\n return getStructDecoder([['discriminator', getBytesDecoder()]]);\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataCodec(): Codec<\n InitializeTokenGroupMemberInstructionDataArgs,\n InitializeTokenGroupMemberInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupMemberInstructionDataEncoder(),\n getInitializeTokenGroupMemberInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupMemberInput<\n TAccountMember extends string = string,\n TAccountMemberMint extends string = string,\n TAccountMemberMintAuthority extends string = string,\n TAccountGroup extends string = string,\n TAccountGroupUpdateAuthority extends string = string,\n> = {\n member: Address;\n memberMint: Address;\n memberMintAuthority: TransactionSigner;\n group: Address;\n groupUpdateAuthority: TransactionSigner;\n};\n\nexport function getInitializeTokenGroupMemberInstruction<\n TAccountMember extends string,\n TAccountMemberMint extends string,\n TAccountMemberMintAuthority extends string,\n TAccountGroup extends string,\n TAccountGroupUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupMemberInput<\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n member: { value: input.member ?? null, isWritable: true },\n memberMint: { value: input.memberMint ?? null, isWritable: false },\n memberMintAuthority: {\n value: input.memberMintAuthority ?? null,\n isWritable: false,\n },\n group: { value: input.group ?? null, isWritable: true },\n groupUpdateAuthority: {\n value: input.groupUpdateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.member),\n getAccountMeta(accounts.memberMint),\n getAccountMeta(accounts.memberMintAuthority),\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.groupUpdateAuthority),\n ],\n data: getInitializeTokenGroupMemberInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n member: TAccountMetas[0];\n memberMint: TAccountMetas[1];\n memberMintAuthority: TAccountMetas[2];\n group: TAccountMetas[3];\n groupUpdateAuthority: TAccountMetas[4];\n };\n data: InitializeTokenGroupMemberInstructionData;\n};\n\nexport function parseInitializeTokenGroupMemberInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupMemberInstruction {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n member: getNextAccount(),\n memberMint: getNextAccount(),\n memberMintAuthority: getNextAccount(),\n group: getNextAccount(),\n groupUpdateAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupMemberInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 210, 225, 30, 162, 88, 184, 77, 141,\n]);\n\nexport function getInitializeTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type InitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlyAccount\n : TAccountUpdateAuthority,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport type InitializeTokenMetadataInstructionDataArgs = {\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport function getInitializeTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_METADATA_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getInitializeTokenMetadataInstructionDataCodec(): Codec<\n InitializeTokenMetadataInstructionDataArgs,\n InitializeTokenMetadataInstructionData\n> {\n return combineCodec(\n getInitializeTokenMetadataInstructionDataEncoder(),\n getInitializeTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenMetadataInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n name: InitializeTokenMetadataInstructionDataArgs['name'];\n symbol: InitializeTokenMetadataInstructionDataArgs['symbol'];\n uri: InitializeTokenMetadataInstructionDataArgs['uri'];\n};\n\nexport function getInitializeTokenMetadataInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenMetadataInput<\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenMetadataInstructionDataEncoder().encode(\n args as InitializeTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n mint: TAccountMetas[2];\n mintAuthority: TAccountMetas[3];\n };\n data: InitializeTokenMetadataInstructionData;\n};\n\nexport function parseInitializeTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenMetadataInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n metadata: getNextAccount(),\n updateAuthority: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenMetadataInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR = 26;\n\nexport function getInitializeTransferFeeConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferFeeConfigTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferFeeConfigInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: Option
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: Option
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type InitializeTransferFeeConfigInstructionDataArgs = {\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: OptionOrNullable
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: OptionOrNullable
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getInitializeTransferFeeConfigInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeConfigAuthority', getOptionEncoder(getAddressEncoder())],\n ['withdrawWithheldAuthority', getOptionEncoder(getAddressEncoder())],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR,\n transferFeeDiscriminator:\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeConfigAuthority', getOptionDecoder(getAddressDecoder())],\n ['withdrawWithheldAuthority', getOptionDecoder(getAddressDecoder())],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataCodec(): Codec<\n InitializeTransferFeeConfigInstructionDataArgs,\n InitializeTransferFeeConfigInstructionData\n> {\n return combineCodec(\n getInitializeTransferFeeConfigInstructionDataEncoder(),\n getInitializeTransferFeeConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferFeeConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n transferFeeConfigAuthority: InitializeTransferFeeConfigInstructionDataArgs['transferFeeConfigAuthority'];\n withdrawWithheldAuthority: InitializeTransferFeeConfigInstructionDataArgs['withdrawWithheldAuthority'];\n transferFeeBasisPoints: InitializeTransferFeeConfigInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: InitializeTransferFeeConfigInstructionDataArgs['maximumFee'];\n};\n\nexport function getInitializeTransferFeeConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferFeeConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferFeeConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferFeeConfigInstructionDataEncoder().encode(\n args as InitializeTransferFeeConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferFeeConfigInstruction);\n}\n\nexport type ParsedInitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferFeeConfigInstructionData;\n};\n\nexport function parseInitializeTransferFeeConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferFeeConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferFeeConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getInitializeTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The public key for the account that can update the program id */\n authority: Option
;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type InitializeTransferHookInstructionDataArgs = {\n /** The public key for the account that can update the program id */\n authority: OptionOrNullable
;\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getInitializeTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeTransferHookInstructionDataCodec(): FixedSizeCodec<\n InitializeTransferHookInstructionDataArgs,\n InitializeTransferHookInstructionData\n> {\n return combineCodec(\n getInitializeTransferHookInstructionDataEncoder(),\n getInitializeTransferHookInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferHookInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeTransferHookInstructionDataArgs['authority'];\n programId: InitializeTransferHookInstructionDataArgs['programId'];\n };\n\nexport function getInitializeTransferHookInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferHookInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferHookInstructionDataEncoder().encode(\n args as InitializeTransferHookInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferHookInstruction);\n}\n\nexport type ParsedInitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferHookInstructionData;\n};\n\nexport function parseInitializeTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferHookInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const PAUSE_DISCRIMINATOR = 44;\n\nexport function getPauseDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_DISCRIMINATOR);\n}\n\nexport const PAUSE_PAUSABLE_DISCRIMINATOR = 1;\n\nexport function getPausePausableDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type PauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type PauseInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type PauseInstructionDataArgs = {};\n\nexport function getPauseInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: PAUSE_DISCRIMINATOR,\n pausableDiscriminator: PAUSE_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getPauseInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getPauseInstructionDataCodec(): FixedSizeCodec<\n PauseInstructionDataArgs,\n PauseInstructionData\n> {\n return combineCodec(\n getPauseInstructionDataEncoder(),\n getPauseInstructionDataDecoder()\n );\n}\n\nexport type PauseInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can pause the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getPauseInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: PauseInput,\n config?: { programAddress?: TProgramAddress }\n): PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getPauseInstructionDataEncoder().encode({}),\n programAddress,\n } as PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedPauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can pause the mint. */\n authority: TAccountMetas[1];\n };\n data: PauseInstructionData;\n};\n\nexport function parsePauseInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedPauseInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getPauseInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getExtensionTypeDecoder,\n getExtensionTypeEncoder,\n type ExtensionType,\n type ExtensionTypeArgs,\n} from '../types';\n\nexport const REALLOCATE_DISCRIMINATOR = 29;\n\nexport function getReallocateDiscriminatorBytes() {\n return getU8Encoder().encode(REALLOCATE_DISCRIMINATOR);\n}\n\nexport type ReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountPayer extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ReallocateInstructionData = {\n discriminator: number;\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport type ReallocateInstructionDataArgs = {\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport function getReallocateInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n [\n 'newExtensionTypes',\n getArrayEncoder(getExtensionTypeEncoder(), { size: 'remainder' }),\n ],\n ]),\n (value) => ({ ...value, discriminator: REALLOCATE_DISCRIMINATOR })\n );\n}\n\nexport function getReallocateInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n [\n 'newExtensionTypes',\n getArrayDecoder(getExtensionTypeDecoder(), { size: 'remainder' }),\n ],\n ]);\n}\n\nexport function getReallocateInstructionDataCodec(): Codec<\n ReallocateInstructionDataArgs,\n ReallocateInstructionData\n> {\n return combineCodec(\n getReallocateInstructionDataEncoder(),\n getReallocateInstructionDataDecoder()\n );\n}\n\nexport type ReallocateInput<\n TAccountToken extends string = string,\n TAccountPayer extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to reallocate. */\n token: Address;\n /** The payer account to fund reallocation. */\n payer: TransactionSigner;\n /** System program for reallocation funding. */\n systemProgram?: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n newExtensionTypes: ReallocateInstructionDataArgs['newExtensionTypes'];\n multiSigners?: Array;\n};\n\nexport function getReallocateInstruction<\n TAccountToken extends string,\n TAccountPayer extends string,\n TAccountSystemProgram extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ReallocateInput<\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n payer: { value: input.payer ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getReallocateInstructionDataEncoder().encode(\n args as ReallocateInstructionDataArgs\n ),\n programAddress,\n } as ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to reallocate. */\n token: TAccountMetas[0];\n /** The payer account to fund reallocation. */\n payer: TAccountMetas[1];\n /** System program for reallocation funding. */\n systemProgram: TAccountMetas[2];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ReallocateInstructionData;\n};\n\nexport function parseReallocateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedReallocateInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n payer: getNextAccount(),\n systemProgram: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getReallocateInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR = new Uint8Array([\n 234, 18, 32, 56, 89, 141, 37, 181,\n]);\n\nexport function getRemoveTokenMetadataKeyDiscriminatorBytes() {\n return getBytesEncoder().encode(REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR);\n}\n\nexport type RemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RemoveTokenMetadataKeyInstructionData = {\n discriminator: ReadonlyUint8Array;\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport type RemoveTokenMetadataKeyInstructionDataArgs = {\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent?: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport function getRemoveTokenMetadataKeyInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['idempotent', getBooleanEncoder()],\n ['key', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR,\n idempotent: value.idempotent ?? false,\n })\n );\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['idempotent', getBooleanDecoder()],\n ['key', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataCodec(): Codec<\n RemoveTokenMetadataKeyInstructionDataArgs,\n RemoveTokenMetadataKeyInstructionData\n> {\n return combineCodec(\n getRemoveTokenMetadataKeyInstructionDataEncoder(),\n getRemoveTokenMetadataKeyInstructionDataDecoder()\n );\n}\n\nexport type RemoveTokenMetadataKeyInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n idempotent?: RemoveTokenMetadataKeyInstructionDataArgs['idempotent'];\n key: RemoveTokenMetadataKeyInstructionDataArgs['key'];\n};\n\nexport function getRemoveTokenMetadataKeyInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RemoveTokenMetadataKeyInput,\n config?: { programAddress?: TProgramAddress }\n): RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getRemoveTokenMetadataKeyInstructionDataEncoder().encode(\n args as RemoveTokenMetadataKeyInstructionDataArgs\n ),\n programAddress,\n } as RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedRemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: RemoveTokenMetadataKeyInstructionData;\n};\n\nexport function parseRemoveTokenMetadataKeyInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRemoveTokenMetadataKeyInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getRemoveTokenMetadataKeyInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const RESUME_DISCRIMINATOR = 44;\n\nexport function getResumeDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_DISCRIMINATOR);\n}\n\nexport const RESUME_PAUSABLE_DISCRIMINATOR = 2;\n\nexport function getResumePausableDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type ResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ResumeInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type ResumeInstructionDataArgs = {};\n\nexport function getResumeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: RESUME_DISCRIMINATOR,\n pausableDiscriminator: RESUME_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getResumeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getResumeInstructionDataCodec(): FixedSizeCodec<\n ResumeInstructionDataArgs,\n ResumeInstructionData\n> {\n return combineCodec(\n getResumeInstructionDataEncoder(),\n getResumeInstructionDataDecoder()\n );\n}\n\nexport type ResumeInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can resume the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getResumeInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ResumeInput,\n config?: { programAddress?: TProgramAddress }\n): ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getResumeInstructionDataEncoder().encode({}),\n programAddress,\n } as ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can resume the mint. */\n authority: TAccountMetas[1];\n };\n data: ResumeInstructionData;\n};\n\nexport function parseResumeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedResumeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getResumeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SET_TRANSFER_FEE_DISCRIMINATOR = 26;\n\nexport function getSetTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport const SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getSetTransferFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport type SetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountTransferFeeConfigAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountTransferFeeConfigAuthority extends string\n ? ReadonlyAccount\n : TAccountTransferFeeConfigAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetTransferFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type SetTransferFeeInstructionDataArgs = {\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getSetTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_TRANSFER_FEE_DISCRIMINATOR,\n transferFeeDiscriminator: SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getSetTransferFeeInstructionDataCodec(): FixedSizeCodec<\n SetTransferFeeInstructionDataArgs,\n SetTransferFeeInstructionData\n> {\n return combineCodec(\n getSetTransferFeeInstructionDataEncoder(),\n getSetTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type SetTransferFeeInput<\n TAccountMint extends string = string,\n TAccountTransferFeeConfigAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority:\n | Address\n | TransactionSigner;\n transferFeeBasisPoints: SetTransferFeeInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: SetTransferFeeInstructionDataArgs['maximumFee'];\n multiSigners?: Array;\n};\n\nexport function getSetTransferFeeInstruction<\n TAccountMint extends string,\n TAccountTransferFeeConfigAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n transferFeeConfigAuthority: {\n value: input.transferFeeConfigAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.transferFeeConfigAuthority),\n ...remainingAccounts,\n ],\n data: getSetTransferFeeInstructionDataEncoder().encode(\n args as SetTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n >);\n}\n\nexport type ParsedSetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority: TAccountMetas[1];\n };\n data: SetTransferFeeInstructionData;\n};\n\nexport function parseSetTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetTransferFeeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n transferFeeConfigAuthority: getNextAccount(),\n },\n data: getSetTransferFeeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR = 26;\n\nexport function getTransferCheckedWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getTransferCheckedWithFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type TransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedWithFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: bigint;\n};\n\nexport type TransferCheckedWithFeeInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: number | bigint;\n};\n\nexport function getTransferCheckedWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['fee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR,\n transferFeeDiscriminator:\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getTransferCheckedWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['fee', getU64Decoder()],\n ]);\n}\n\nexport function getTransferCheckedWithFeeInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedWithFeeInstructionDataArgs,\n TransferCheckedWithFeeInstructionData\n> {\n return combineCodec(\n getTransferCheckedWithFeeInstructionDataEncoder(),\n getTransferCheckedWithFeeInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedWithFeeInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: Address;\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: Address;\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedWithFeeInstructionDataArgs['amount'];\n decimals: TransferCheckedWithFeeInstructionDataArgs['decimals'];\n fee: TransferCheckedWithFeeInstructionDataArgs['fee'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedWithFeeInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedWithFeeInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedWithFeeInstructionDataEncoder().encode(\n args as TransferCheckedWithFeeInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: TAccountMetas[0];\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[1];\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedWithFeeInstructionData;\n};\n\nexport function parseTransferCheckedWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedWithFeeInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getUpdateConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 1;\n\nexport function getUpdateConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type UpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type UpdateConfidentialTransferMintInstructionDataArgs = {\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getUpdateConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n UpdateConfidentialTransferMintInstructionDataArgs,\n UpdateConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getUpdateConfidentialTransferMintInstructionDataEncoder(),\n getUpdateConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateConfidentialTransferMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n autoApproveNewAccounts: UpdateConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: UpdateConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getUpdateConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getUpdateConfidentialTransferMintInstructionDataEncoder().encode(\n args as UpdateConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateConfidentialTransferMintInstructionData;\n};\n\nexport function parseUpdateConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateConfidentialTransferMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getUpdateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 1;\n\nexport function getUpdateDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type UpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFreezeAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFreezeAuthority extends string\n ? ReadonlyAccount\n : TAccountFreezeAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type UpdateDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getUpdateDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n UpdateDefaultAccountStateInstructionDataArgs,\n UpdateDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getUpdateDefaultAccountStateInstructionDataEncoder(),\n getUpdateDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type UpdateDefaultAccountStateInput<\n TAccountMint extends string = string,\n TAccountFreezeAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority:\n | Address\n | TransactionSigner;\n state: UpdateDefaultAccountStateInstructionDataArgs['state'];\n multiSigners?: Array;\n};\n\nexport function getUpdateDefaultAccountStateInstruction<\n TAccountMint extends string,\n TAccountFreezeAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n freezeAuthority: {\n value: input.freezeAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.freezeAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateDefaultAccountStateInstructionDataEncoder().encode(\n args as UpdateDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n >);\n}\n\nexport type ParsedUpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority: TAccountMetas[1];\n };\n data: UpdateDefaultAccountStateInstructionData;\n};\n\nexport function parseUpdateDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateDefaultAccountStateInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), freezeAuthority: getNextAccount() },\n data: getUpdateDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getUpdateGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupMemberPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupMemberPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupMemberPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The new account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type UpdateGroupMemberPointerInstructionDataArgs = {\n /** The new account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupMemberPointerInstructionDataArgs,\n UpdateGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupMemberPointerInstructionDataEncoder(),\n getUpdateGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupMemberPointerInput<\n TAccountMint extends string = string,\n TAccountGroupMemberPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority:\n | Address\n | TransactionSigner;\n memberAddress: UpdateGroupMemberPointerInstructionDataArgs['memberAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupMemberPointerInstruction<\n TAccountMint extends string,\n TAccountGroupMemberPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupMemberPointerInput<\n TAccountMint,\n TAccountGroupMemberPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupMemberPointerAuthority: {\n value: input.groupMemberPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupMemberPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupMemberPointerInstructionDataEncoder().encode(\n args as UpdateGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupMemberPointerInstructionData;\n};\n\nexport function parseUpdateGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupMemberPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupMemberPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getUpdateGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupPointerAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The new account address that holds the group configurations. */\n groupAddress: Option
;\n};\n\nexport type UpdateGroupPointerInstructionDataArgs = {\n /** The new account address that holds the group configurations. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupPointerInstructionDataArgs,\n UpdateGroupPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupPointerInstructionDataEncoder(),\n getUpdateGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupPointerInput<\n TAccountMint extends string = string,\n TAccountGroupPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority:\n | Address\n | TransactionSigner;\n groupAddress: UpdateGroupPointerInstructionDataArgs['groupAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupPointerInstruction<\n TAccountMint extends string,\n TAccountGroupPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupPointerAuthority: {\n value: input.groupPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupPointerInstructionDataEncoder().encode(\n args as UpdateGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupPointerInstructionData;\n};\n\nexport function parseUpdateGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getUpdateMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountMetadataPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountMetadataPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountMetadataPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The new account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type UpdateMetadataPointerInstructionDataArgs = {\n /** The new account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getUpdateMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateMetadataPointerInstructionDataArgs,\n UpdateMetadataPointerInstructionData\n> {\n return combineCodec(\n getUpdateMetadataPointerInstructionDataEncoder(),\n getUpdateMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateMetadataPointerInput<\n TAccountMint extends string = string,\n TAccountMetadataPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority:\n | Address\n | TransactionSigner;\n metadataAddress: UpdateMetadataPointerInstructionDataArgs['metadataAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMetadataPointerInstruction<\n TAccountMint extends string,\n TAccountMetadataPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMetadataPointerInput<\n TAccountMint,\n TAccountMetadataPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n metadataPointerAuthority: {\n value: input.metadataPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.metadataPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateMetadataPointerInstructionDataEncoder().encode(\n args as UpdateMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n >);\n}\n\nexport type ParsedUpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority: TAccountMetas[1];\n };\n data: UpdateMetadataPointerInstructionData;\n};\n\nexport function parseUpdateMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMetadataPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n metadataPointerAuthority: getNextAccount(),\n },\n data: getUpdateMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getF64Decoder,\n getF64Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR = 43;\n\nexport function getUpdateMultiplierScaledUiMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateMultiplierScaledUiMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? WritableAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMultiplierScaledUiMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: bigint;\n};\n\nexport type UpdateMultiplierScaledUiMintInstructionDataArgs = {\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: number | bigint;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n ['multiplier', getF64Encoder()],\n ['effectiveTimestamp', getI64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n ['multiplier', getF64Decoder()],\n ['effectiveTimestamp', getI64Decoder()],\n ]);\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataCodec(): FixedSizeCodec<\n UpdateMultiplierScaledUiMintInstructionDataArgs,\n UpdateMultiplierScaledUiMintInstructionData\n> {\n return combineCodec(\n getUpdateMultiplierScaledUiMintInstructionDataEncoder(),\n getUpdateMultiplierScaledUiMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The multiplier authority. */\n authority: Address | TransactionSigner;\n multiplier: UpdateMultiplierScaledUiMintInstructionDataArgs['multiplier'];\n effectiveTimestamp: UpdateMultiplierScaledUiMintInstructionDataArgs['effectiveTimestamp'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMultiplierScaledUiMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateMultiplierScaledUiMintInstructionDataEncoder().encode(\n args as UpdateMultiplierScaledUiMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The multiplier authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateMultiplierScaledUiMintInstructionData;\n};\n\nexport function parseUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMultiplierScaledUiMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateMultiplierScaledUiMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI16Decoder,\n getI16Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getUpdateRateInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateRateInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRateAuthority extends string\n ? WritableAccount\n : TAccountRateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateRateInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The interest rate to update. */\n rate: number;\n};\n\nexport type UpdateRateInterestBearingMintInstructionDataArgs = {\n /** The interest rate to update. */\n rate: number;\n};\n\nexport function getUpdateRateInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n UpdateRateInterestBearingMintInstructionDataArgs,\n UpdateRateInterestBearingMintInstructionData\n> {\n return combineCodec(\n getUpdateRateInterestBearingMintInstructionDataEncoder(),\n getUpdateRateInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateRateInterestBearingMintInput<\n TAccountMint extends string = string,\n TAccountRateAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint rate authority. */\n rateAuthority:\n | Address\n | TransactionSigner;\n rate: UpdateRateInterestBearingMintInstructionDataArgs['rate'];\n multiSigners?: Array;\n};\n\nexport function getUpdateRateInterestBearingMintInstruction<\n TAccountMint extends string,\n TAccountRateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateRateInterestBearingMintInput<\n TAccountMint,\n TAccountRateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rateAuthority: { value: input.rateAuthority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rateAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateRateInterestBearingMintInstructionDataEncoder().encode(\n args as UpdateRateInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n >);\n}\n\nexport type ParsedUpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint rate authority. */\n rateAuthority: TAccountMetas[1];\n };\n data: UpdateRateInterestBearingMintInstructionData;\n};\n\nexport function parseUpdateRateInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateRateInterestBearingMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rateAuthority: getNextAccount() },\n data: getUpdateRateInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR = new Uint8Array([\n 108, 37, 171, 143, 248, 30, 18, 110,\n]);\n\nexport function getUpdateTokenGroupMaxSizeDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR);\n}\n\nexport type UpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupMaxSizeInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New max size for the group */\n maxSize: bigint;\n};\n\nexport type UpdateTokenGroupMaxSizeInstructionDataArgs = {\n /** New max size for the group */\n maxSize: number | bigint;\n};\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataCodec(): Codec<\n UpdateTokenGroupMaxSizeInstructionDataArgs,\n UpdateTokenGroupMaxSizeInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupMaxSizeInstructionDataEncoder(),\n getUpdateTokenGroupMaxSizeInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupMaxSizeInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n updateAuthority: TransactionSigner;\n maxSize: UpdateTokenGroupMaxSizeInstructionDataArgs['maxSize'];\n};\n\nexport function getUpdateTokenGroupMaxSizeInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupMaxSizeInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupMaxSizeInstructionDataEncoder().encode(\n args as UpdateTokenGroupMaxSizeInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupMaxSizeInstructionData;\n};\n\nexport function parseUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupMaxSizeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupMaxSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR = new Uint8Array(\n [161, 105, 88, 1, 237, 221, 216, 203]\n);\n\nexport function getUpdateTokenGroupUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionDataArgs = {\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenGroupUpdateAuthorityInstructionDataArgs,\n UpdateTokenGroupUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n /** Current update authority */\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenGroupUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenGroupUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n /** Current update authority */\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupUpdateAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getTokenMetadataFieldDecoder,\n getTokenMetadataFieldEncoder,\n type TokenMetadataField,\n type TokenMetadataFieldArgs,\n} from '../types';\n\nexport const UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR = new Uint8Array([\n 221, 233, 49, 45, 181, 202, 220, 200,\n]);\n\nexport function getUpdateTokenMetadataFieldDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR);\n}\n\nexport type UpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataFieldInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Field to update in the metadata. */\n field: TokenMetadataField;\n /** Value to write for the field. */\n value: string;\n};\n\nexport type UpdateTokenMetadataFieldInstructionDataArgs = {\n /** Field to update in the metadata. */\n field: TokenMetadataFieldArgs;\n /** Value to write for the field. */\n value: string;\n};\n\nexport function getUpdateTokenMetadataFieldInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['field', getTokenMetadataFieldEncoder()],\n ['value', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['field', getTokenMetadataFieldDecoder()],\n ['value', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataCodec(): Codec<\n UpdateTokenMetadataFieldInstructionDataArgs,\n UpdateTokenMetadataFieldInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataFieldInstructionDataEncoder(),\n getUpdateTokenMetadataFieldInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataFieldInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n field: UpdateTokenMetadataFieldInstructionDataArgs['field'];\n value: UpdateTokenMetadataFieldInstructionDataArgs['value'];\n};\n\nexport function getUpdateTokenMetadataFieldInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataFieldInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataFieldInstructionDataEncoder().encode(\n args as UpdateTokenMetadataFieldInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataFieldInstructionData;\n};\n\nexport function parseUpdateTokenMetadataFieldInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataFieldInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataFieldInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR =\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]);\n\nexport function getUpdateTokenMetadataUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionDataArgs = {\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenMetadataUpdateAuthorityInstructionDataArgs,\n UpdateTokenMetadataUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenMetadataUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenMetadataUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getUpdateTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 1;\n\nexport function getUpdateTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type UpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type UpdateTransferHookInstructionDataArgs = {\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getUpdateTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTransferHookInstructionDataCodec(): FixedSizeCodec<\n UpdateTransferHookInstructionDataArgs,\n UpdateTransferHookInstructionData\n> {\n return combineCodec(\n getUpdateTransferHookInstructionDataEncoder(),\n getUpdateTransferHookInstructionDataDecoder()\n );\n}\n\nexport type UpdateTransferHookInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The transfer hook authority. */\n authority: Address | TransactionSigner;\n programId: UpdateTransferHookInstructionDataArgs['programId'];\n multiSigners?: Array;\n};\n\nexport function getUpdateTransferHookInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateTransferHookInstructionDataEncoder().encode(\n args as UpdateTransferHookInstructionDataArgs\n ),\n programAddress,\n } as UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The transfer hook authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateTransferHookInstructionData;\n};\n\nexport function parseUpdateTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTransferHookInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR = 38;\n\nexport function getWithdrawExcessLamportsDiscriminatorBytes() {\n return getU8Encoder().encode(WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR);\n}\n\nexport type WithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceAccount extends string | AccountMeta = string,\n TAccountDestinationAccount extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceAccount extends string\n ? WritableAccount\n : TAccountSourceAccount,\n TAccountDestinationAccount extends string\n ? WritableAccount\n : TAccountDestinationAccount,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawExcessLamportsInstructionData = { discriminator: number };\n\nexport type WithdrawExcessLamportsInstructionDataArgs = {};\n\nexport function getWithdrawExcessLamportsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawExcessLamportsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getWithdrawExcessLamportsInstructionDataCodec(): FixedSizeCodec<\n WithdrawExcessLamportsInstructionDataArgs,\n WithdrawExcessLamportsInstructionData\n> {\n return combineCodec(\n getWithdrawExcessLamportsInstructionDataEncoder(),\n getWithdrawExcessLamportsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawExcessLamportsInput<\n TAccountSourceAccount extends string = string,\n TAccountDestinationAccount extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** Account holding excess lamports. */\n sourceAccount: Address;\n /** Destination account for withdrawn lamports. */\n destinationAccount: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawExcessLamportsInstruction<\n TAccountSourceAccount extends string,\n TAccountDestinationAccount extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawExcessLamportsInput<\n TAccountSourceAccount,\n TAccountDestinationAccount,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceAccount: { value: input.sourceAccount ?? null, isWritable: true },\n destinationAccount: {\n value: input.destinationAccount ?? null,\n isWritable: true,\n },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceAccount),\n getAccountMeta(accounts.destinationAccount),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawExcessLamportsInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Account holding excess lamports. */\n sourceAccount: TAccountMetas[0];\n /** Destination account for withdrawn lamports. */\n destinationAccount: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: WithdrawExcessLamportsInstructionData;\n};\n\nexport function parseWithdrawExcessLamportsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawExcessLamportsInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceAccount: getNextAccount(),\n destinationAccount: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawExcessLamportsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromAccountsDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getWithdrawWithheldTokensFromAccountsTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport type WithdrawWithheldTokensFromAccountsInstructionDataArgs = {\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsInstructionDataArgs['numTokenAccounts'];\n multiSigners?: Array;\n sources: Array
;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = [\n ...(args.multiSigners ?? []).map((signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })),\n ...args.sources.map((address) => ({ address, role: AccountRole.WRITABLE })),\n ];\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromAccountsInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['numTokenAccounts'];\n proofInstructionOffset: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type WithdrawWithheldTokensFromMintInstructionDataArgs = {};\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintInstructionDataArgs,\n WithdrawWithheldTokensFromMintInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromMintInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account if proof is read from record */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n proofInstructionOffset: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account if proof is read from record */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","import {\n type GetAccountInfoApi,\n type Rpc,\n Address,\n UnixTimestamp,\n unwrapOption,\n} from '@solana/kit';\nimport { fetchSysvarClock } from '@solana/sysvars';\nimport { fetchMint } from './generated';\n\n// Constants\nconst ONE_IN_BASIS_POINTS = 10000;\nconst SECONDS_PER_YEAR = 60 * 60 * 24 * 365.24;\n\n/**\n * Calculates the exponent for the interest rate formula.\n * @param t1 - The start time in seconds.\n * @param t2 - The end time in seconds.\n * @param r - The interest rate in basis points.\n *\n * @returns The calculated exponent.\n */\nfunction calculateExponentForTimesAndRate(t1: number, t2: number, r: number) {\n const timespan = t2 - t1;\n if (timespan < 0) {\n throw new Error('Invalid timespan: end time before start time');\n }\n\n const numerator = r * timespan;\n const exponent = numerator / (SECONDS_PER_YEAR * ONE_IN_BASIS_POINTS);\n return Math.exp(exponent);\n}\n\n/**\n * Calculates the total scale factor for an interest bearing token by combining two exponential functions:\n * One for the period between initialization and last update using the pre-update average rate,\n * and another for the period between last update and current time using the current rate.\n *\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points before last update\n * @param currentRate Current interest rate in basis points\n *\n * @returns The total scale factor as a product of the two exponential functions\n */\nfunction calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n}: {\n currentTimestamp: number;\n lastUpdateTimestamp: number;\n initializationTimestamp: number;\n preUpdateAverageRate: number;\n currentRate: number;\n}): number {\n // Calculate pre-update exponent\n const preUpdateExp = calculateExponentForTimesAndRate(\n initializationTimestamp,\n lastUpdateTimestamp,\n preUpdateAverageRate\n );\n\n // Calculate post-update exponent\n const postUpdateExp = calculateExponentForTimesAndRate(\n lastUpdateTimestamp,\n currentTimestamp,\n currentRate\n );\n\n return preUpdateExp * postUpdateExp;\n}\n\n/**\n * Calculates the decimal factor for a given number of decimals\n * @param decimals - Number of decimals\n * @returns The decimal factor (e.g., 100 for 2 decimals)\n */\nfunction getDecimalFactor(decimals: number): number {\n return Math.pow(10, decimals);\n}\n\n/**\n * Retrieves the current timestamp from the Solana clock sysvar.\n * @param rpc - The Solana rpc object.\n * @returns A promise that resolves to the current timestamp in seconds.\n * @throws An error if the sysvar clock cannot be fetched or parsed.\n */\nasync function getSysvarClockTimestamp(\n rpc: Rpc\n): Promise {\n const info = await fetchSysvarClock(rpc);\n if (!info) {\n throw new Error('Failed to fetch sysvar clock');\n }\n return info.unixTimestamp;\n}\n\n// ========== INTEREST BEARING MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with interest bearing extension without simulating a transaction\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n * In general to calculate compounding interest over a period of time, the formula is:\n * A = P * e^(r * t) where\n * A = final amount after interest\n * P = principal amount (initial investment)\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n * e = mathematical constant (~2.718)\n *\n * In this case, we are calculating the total scale factor for the interest bearing extension which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 and r2 are the interest rates before and after the last update, and t1 and t2 are the times in years between\n * the initialization timestamp and the last update timestamp, and between the last update timestamp and the current timestamp.\n *\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (1 basis point = 0.01%) before last update\n * @param currentRate Current interest rate in basis points\n *\n * @return Amount scaled by accrued interest as a string with appropriate decimal places\n */\nexport function amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): string {\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Scale the amount by the total interest factor\n const scaledAmount = Number(amount) * totalScale;\n const decimalFactor = getDecimalFactor(decimals);\n\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert an amount with interest back to the original amount without interest\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n *\n * @param uiAmount UI Amount (principal plus continuously compounding interest) to be converted back to original principal\n * @param decimals Number of decimals for the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (hundredths of a percent) before the last update\n * @param currentRate Current interest rate in basis points\n *\n * In general to calculate the principal from the UI amount, the formula is:\n * P = A / (e^(r * t)) where\n * P = principal\n * A = UI amount\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n *\n * In this case, we are calculating the principal by dividing the UI amount by the total scale factor which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 is the pre-update average rate, r2 is the current rate, t1 is the time in years between the initialization timestamp and the last update timestamp,\n * and t2 is the time in years between the last update timestamp and the current timestamp.\n * then to calculate the principal, we divide the UI amount by the total scale factor:\n * P = A / totalScale\n *\n * @return Original amount (principal) without interest\n */\nexport function uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Calculate original principal by dividing the UI amount by the total scale\n const originalPrincipal = uiAmountScaled / totalScale;\n return BigInt(Math.trunc(originalPrincipal));\n}\n\n// ========== SCALED UI AMOUNT MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with scaled UI amount extension\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param multiplier Multiplier to scale the amount\n * @return Scaled UI amount as a string\n */\nexport function amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n multiplier: number\n): string {\n const scaledAmount = Number(amount) * multiplier;\n const decimalFactor = getDecimalFactor(decimals);\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert a UI amount back to the raw amount for a mint with a scaled UI amount extension\n * @param uiAmount UI Amount to be converted back to raw amount\n * @param decimals Number of decimals for the mint\n * @param multiplier Multiplier for the scaled UI amount\n *\n * @return Raw amount\n */\nexport function uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n multiplier: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n const rawAmount = uiAmountScaled / multiplier;\n return BigInt(Math.trunc(rawAmount));\n}\n\n// ========== MAIN ENTRY POINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint without simulating a transaction\n * This implements the same logic as `process_amount_to_ui_amount` in\n * solana-labs/solana-program-library/token/program-2022/src/processor.rs\n * and `process_amount_to_ui_amount` in solana-labs/solana-program-library/token/program/src/processor.rs\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param amount Amount of tokens to be converted to Ui Amount\n *\n * @return Ui Amount generated\n */\nexport async function amountToUiAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n amount: bigint\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const amountNumber = Number(amount);\n const decimalsFactor = getDecimalFactor(accountInfo.data.decimals);\n return (amountNumber / decimalsFactor).toString();\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n\n/**\n * Convert a UI amount back to the raw amount\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param uiAmount UI Amount to be converted back to raw amount\n *\n * @return Raw amount\n */\nexport async function uiAmountToAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n uiAmount: string\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const uiAmountScaled =\n parseFloat(uiAmount) * getDecimalFactor(accountInfo.data.decimals);\n return BigInt(Math.trunc(uiAmountScaled));\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n","import {\n Address,\n Instruction,\n isNone,\n isOption,\n TransactionSigner,\n wrapNullable,\n} from '@solana/kit';\nimport {\n ExtensionArgs,\n getDisableMemoTransfersInstruction,\n getEnableMemoTransfersInstruction,\n getEnableCpiGuardInstruction,\n getDisableCpiGuardInstruction,\n getInitializeConfidentialTransferMintInstruction,\n getInitializeDefaultAccountStateInstruction,\n getInitializeGroupMemberPointerInstruction,\n getInitializeGroupPointerInstruction,\n getInitializeInterestBearingMintInstruction,\n getInitializeMetadataPointerInstruction,\n getInitializeMintCloseAuthorityInstruction,\n getInitializeTokenGroupInstruction,\n getInitializeTokenMetadataInstruction,\n getInitializeTransferFeeConfigInstruction,\n getInitializeNonTransferableMintInstruction,\n getInitializeTransferHookInstruction,\n getInitializePermanentDelegateInstruction,\n getInitializeScaledUiAmountMintInstruction,\n getInitializeConfidentialTransferFeeInstruction,\n getInitializePausableConfigInstruction,\n} from './generated';\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _before_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPreInitializeInstructionsForMintExtensions(\n mint: Address,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'ConfidentialTransferMint':\n return [\n getInitializeConfidentialTransferMintInstruction({\n mint,\n ...extension,\n }),\n ];\n case 'DefaultAccountState':\n return [\n getInitializeDefaultAccountStateInstruction({\n mint,\n state: extension.state,\n }),\n ];\n case 'TransferFeeConfig':\n return [\n getInitializeTransferFeeConfigInstruction({\n mint,\n transferFeeConfigAuthority: extension.transferFeeConfigAuthority,\n withdrawWithheldAuthority: extension.withdrawWithheldAuthority,\n transferFeeBasisPoints:\n extension.newerTransferFee.transferFeeBasisPoints,\n maximumFee: extension.newerTransferFee.maximumFee,\n }),\n ];\n case 'MetadataPointer':\n return [\n getInitializeMetadataPointerInstruction({\n mint,\n authority: extension.authority,\n metadataAddress: extension.metadataAddress,\n }),\n ];\n case 'InterestBearingConfig':\n return [\n getInitializeInterestBearingMintInstruction({\n mint,\n rateAuthority: extension.rateAuthority,\n rate: extension.currentRate,\n }),\n ];\n case 'ScaledUiAmountConfig':\n return [\n getInitializeScaledUiAmountMintInstruction({\n mint,\n authority: extension.authority,\n multiplier: extension.multiplier,\n }),\n ];\n case 'PausableConfig':\n return [\n getInitializePausableConfigInstruction({\n mint,\n authority: extension.authority,\n }),\n ];\n case 'GroupPointer':\n return [\n getInitializeGroupPointerInstruction({\n mint,\n authority: extension.authority,\n groupAddress: extension.groupAddress,\n }),\n ];\n case 'GroupMemberPointer':\n return [\n getInitializeGroupMemberPointerInstruction({\n mint,\n authority: extension.authority,\n memberAddress: extension.memberAddress,\n }),\n ];\n case 'NonTransferable':\n return getInitializeNonTransferableMintInstruction({ mint });\n case 'TransferHook':\n return [\n getInitializeTransferHookInstruction({\n mint,\n authority: extension.authority,\n programId: extension.programId,\n }),\n ];\n case 'PermanentDelegate':\n return getInitializePermanentDelegateInstruction({\n mint,\n delegate: extension.delegate,\n });\n case 'ConfidentialTransferFee':\n return [\n getInitializeConfidentialTransferFeeInstruction({\n mint,\n authority: extension.authority,\n withdrawWithheldAuthorityElGamalPubkey: extension.elgamalPubkey,\n }),\n ];\n case 'MintCloseAuthority':\n return getInitializeMintCloseAuthorityInstruction({\n closeAuthority: extension.closeAuthority,\n mint,\n });\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _after_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPostInitializeInstructionsForMintExtensions(\n mint: Address,\n authority: TransactionSigner,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension): Instruction[] => {\n switch (extension.__kind) {\n case 'TokenMetadata':\n // eslint-disable-next-line no-case-declarations\n const tokenMetadataUpdateAuthority = isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority);\n if (isNone(tokenMetadataUpdateAuthority)) {\n return [];\n }\n return [\n getInitializeTokenMetadataInstruction({\n metadata: mint,\n updateAuthority: tokenMetadataUpdateAuthority.value,\n mint,\n mintAuthority: authority,\n name: extension.name,\n symbol: extension.symbol,\n uri: extension.uri,\n }),\n ];\n case 'TokenGroup':\n return [\n getInitializeTokenGroupInstruction({\n group: mint,\n updateAuthority: isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority),\n mint,\n mintAuthority: authority,\n maxSize: extension.maxSize,\n }),\n ];\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a token address, its owner and a list of token extensions, returns a list\n * of instructions that MUST be run _after_ the `initializeAccount` instruction\n * to properly initialize the given extensions on the token account.\n */\nexport function getPostInitializeInstructionsForTokenExtensions(\n token: Address,\n owner: TransactionSigner | Address,\n extensions: ExtensionArgs[],\n multiSigners?: TransactionSigner[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'MemoTransfer':\n return [\n extension.requireIncomingTransferMemos\n ? getEnableMemoTransfersInstruction({ owner, token, multiSigners })\n : getDisableMemoTransfersInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n case 'CpiGuard':\n return [\n extension.lockCpi\n ? getEnableCpiGuardInstruction({ owner, token, multiSigners })\n : getDisableCpiGuardInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n default:\n return [];\n }\n });\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst TOKEN_BASE_SIZE = 165;\n\nexport function getTokenSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return TOKEN_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n );\n return TOKEN_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n padLeftEncoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst MINT_BASE_SIZE = 82;\n\nexport function getMintSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return MINT_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n );\n return MINT_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","/**\n * Token program addresses for SPL Token and Token-2022\n * These addresses are the same across all Solana networks (mainnet, devnet, testnet)\n */\nexport const TOKEN_PROGRAM_ADDRESS = \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\";\nexport const TOKEN_2022_PROGRAM_ADDRESS = \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\";\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS = \"ComputeBudget111111111111111111111111111111\";\nexport const MEMO_PROGRAM_ADDRESS = \"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\";\n\n/**\n * Phantom/Solflare Lighthouse program address\n * Phantom and Solflare wallets inject Lighthouse instructions for user protection on mainnet transactions.\n * - Phantom adds 1 Lighthouse instruction (4th instruction)\n * - Solflare adds 2 Lighthouse instructions (4th and 5th instructions)\n * We allow these as optional instructions to support these wallets.\n * See: https://github.com/coinbase/x402/issues/828\n */\nexport const LIGHTHOUSE_PROGRAM_ADDRESS = \"L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95\";\n\n/**\n * Default RPC URLs for Solana networks\n */\nexport const DEVNET_RPC_URL = \"https://api.devnet.solana.com\";\nexport const TESTNET_RPC_URL = \"https://api.testnet.solana.com\";\nexport const MAINNET_RPC_URL = \"https://api.mainnet-beta.solana.com\";\nexport const DEVNET_WS_URL = \"wss://api.devnet.solana.com\";\nexport const TESTNET_WS_URL = \"wss://api.testnet.solana.com\";\nexport const MAINNET_WS_URL = \"wss://api.mainnet-beta.solana.com\";\n\n/**\n * USDC token mint addresses (default stablecoin)\n */\nexport const USDC_MAINNET_ADDRESS = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nexport const USDC_DEVNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\";\nexport const USDC_TESTNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\"; // Same as devnet\n\n/**\n * Compute budget configuration\n * All prices are in microlamports (1 lamport = 1,000,000 microlamports)\n */\nexport const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;\nexport const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 5_000_000; // 5 lamports\nexport const DEFAULT_COMPUTE_UNIT_LIMIT = 20_000;\n\n/**\n * How long a transaction is held in the duplicate settlement cache (ms).\n * Covers the Solana blockhash lifetime (~60-90s) with margin.\n */\nexport const SETTLEMENT_TTL_MS = 120_000;\n\n/**\n * Solana address validation regex (base58, 32-44 characters)\n */\nexport const SVM_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * CAIP-2 network identifiers for Solana (V2)\n */\nexport const SOLANA_MAINNET_CAIP2 = \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\";\nexport const SOLANA_DEVNET_CAIP2 = \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\";\nexport const SOLANA_TESTNET_CAIP2 = \"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z\";\n\n/**\n * V1 to V2 network identifier mappings (for backwards compatibility)\n * V1 used simple names like solana, V2 uses CAIP-2\n */\nexport const V1_TO_V2_NETWORK_MAP: Record = {\n solana: SOLANA_MAINNET_CAIP2,\n \"solana-devnet\": SOLANA_DEVNET_CAIP2,\n \"solana-testnet\": SOLANA_TESTNET_CAIP2,\n};\n","import {\n getBase64Encoder,\n getTransactionDecoder,\n getCompiledTransactionMessageDecoder,\n type Transaction,\n createSolanaRpc,\n devnet,\n testnet,\n mainnet,\n type RpcDevnet,\n type SolanaRpcApiDevnet,\n type RpcTestnet,\n type SolanaRpcApiTestnet,\n type RpcMainnet,\n type SolanaRpcApiMainnet,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { TOKEN_2022_PROGRAM_ADDRESS } from \"@solana-program/token-2022\";\nimport type { Network } from \"@x402/core/types\";\nimport {\n SVM_ADDRESS_REGEX,\n DEVNET_RPC_URL,\n TESTNET_RPC_URL,\n MAINNET_RPC_URL,\n USDC_MAINNET_ADDRESS,\n USDC_DEVNET_ADDRESS,\n USDC_TESTNET_ADDRESS,\n SOLANA_MAINNET_CAIP2,\n SOLANA_DEVNET_CAIP2,\n SOLANA_TESTNET_CAIP2,\n V1_TO_V2_NETWORK_MAP,\n} from \"./constants\";\nimport type { ExactSvmPayloadV1 } from \"./types\";\n\n/**\n * Normalize network identifier to CAIP-2 format\n * Handles both V1 names (solana, solana-devnet) and V2 CAIP-2 format\n *\n * @param network - Network identifier (V1 or V2 format)\n * @returns CAIP-2 network identifier\n */\nexport function normalizeNetwork(network: Network): string {\n // If it's already CAIP-2 format (contains \":\"), validate it's supported\n if (network.includes(\":\")) {\n const supported = [SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];\n if (!supported.includes(network)) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return network;\n }\n\n // Otherwise, it's a V1 network name, convert to CAIP-2\n const caip2Network = V1_TO_V2_NETWORK_MAP[network];\n if (!caip2Network) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return caip2Network;\n}\n\n/**\n * Validate Solana address format\n *\n * @param address - Base58 encoded address string\n * @returns true if address is valid, false otherwise\n */\nexport function validateSvmAddress(address: string): boolean {\n return SVM_ADDRESS_REGEX.test(address);\n}\n\n/**\n * Decode a base64 encoded transaction from an SVM payload\n *\n * @param svmPayload - The SVM payload containing a base64 encoded transaction\n * @returns Decoded Transaction object\n */\nexport function decodeTransactionFromPayload(svmPayload: ExactSvmPayloadV1): Transaction {\n try {\n const base64Encoder = getBase64Encoder();\n const transactionBytes = base64Encoder.encode(svmPayload.transaction);\n const transactionDecoder = getTransactionDecoder();\n return transactionDecoder.decode(transactionBytes);\n } catch (error) {\n console.error(\"Error decoding transaction:\", error);\n throw new Error(\"invalid_exact_svm_payload_transaction\");\n }\n}\n\n/**\n * Extract the token sender (owner of the source token account) from a TransferChecked instruction\n *\n * @param transaction - The decoded transaction\n * @returns The token payer address as a base58 string\n */\nexport function getTokenPayerFromTransaction(transaction: Transaction): string {\n const compiled = getCompiledTransactionMessageDecoder().decode(transaction.messageBytes);\n const staticAccounts = compiled.staticAccounts ?? [];\n const instructions = compiled.instructions ?? [];\n\n for (const ix of instructions) {\n const programIndex = ix.programAddressIndex;\n const programAddress = staticAccounts[programIndex].toString();\n\n // Check if this is a token program instruction\n if (\n programAddress === TOKEN_PROGRAM_ADDRESS.toString() ||\n programAddress === TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n const accountIndices: number[] = ix.accountIndices ?? [];\n // TransferChecked account order: [source, mint, destination, owner, ...]\n if (accountIndices.length >= 4) {\n const ownerIndex = accountIndices[3];\n const ownerAddress = staticAccounts[ownerIndex].toString();\n if (ownerAddress) return ownerAddress;\n }\n }\n }\n\n return \"\";\n}\n\n/**\n * Create an RPC client for the specified network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @param customRpcUrl - Optional custom RPC URL\n * @returns RPC client for the specified network\n */\nexport function createRpcClient(\n network: Network,\n customRpcUrl?: string,\n):\n | RpcDevnet\n | RpcTestnet\n | RpcMainnet {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_DEVNET_CAIP2: {\n const url = customRpcUrl || DEVNET_RPC_URL;\n return createSolanaRpc(devnet(url)) as RpcDevnet;\n }\n case SOLANA_TESTNET_CAIP2: {\n const url = customRpcUrl || TESTNET_RPC_URL;\n return createSolanaRpc(testnet(url)) as RpcTestnet;\n }\n case SOLANA_MAINNET_CAIP2: {\n const url = customRpcUrl || MAINNET_RPC_URL;\n return createSolanaRpc(mainnet(url)) as RpcMainnet;\n }\n default:\n throw new Error(`Unsupported network: ${network}`);\n }\n}\n\n/**\n * Get the default USDC mint address for a network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @returns USDC mint address for the network\n */\nexport function getUsdcAddress(network: Network): string {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_MAINNET_CAIP2:\n return USDC_MAINNET_ADDRESS;\n case SOLANA_DEVNET_CAIP2:\n return USDC_DEVNET_ADDRESS;\n case SOLANA_TESTNET_CAIP2:\n return USDC_TESTNET_ADDRESS;\n default:\n throw new Error(`No USDC address configured for network: ${network}`);\n }\n}\n\n/**\n * Convert a decimal amount to token smallest units\n *\n * @param decimalAmount - The decimal amount (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n const amount = parseFloat(decimalAmount);\n if (isNaN(amount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n // Convert to smallest unit (e.g., for USDC with 6 decimals: 0.10 * 10^6 = 100000)\n const [intPart, decPart = \"\"] = String(amount).split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n return tokenAmount;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedRequestHeapFrameInstruction,\n type ParsedRequestUnitsInstruction,\n type ParsedSetComputeUnitLimitInstruction,\n type ParsedSetComputeUnitPriceInstruction,\n type ParsedSetLoadedAccountsDataSizeLimitInstruction,\n} from '../instructions';\n\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS =\n 'ComputeBudget111111111111111111111111111111' as Address<'ComputeBudget111111111111111111111111111111'>;\n\nexport enum ComputeBudgetInstruction {\n RequestUnits,\n RequestHeapFrame,\n SetComputeUnitLimit,\n SetComputeUnitPrice,\n SetLoadedAccountsDataSizeLimit,\n}\n\nexport function identifyComputeBudgetInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ComputeBudgetInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return ComputeBudgetInstruction.RequestUnits;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return ComputeBudgetInstruction.RequestHeapFrame;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitLimit;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitPrice;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n }\n throw new Error(\n 'The provided instruction could not be identified as a computeBudget instruction.'\n );\n}\n\nexport type ParsedComputeBudgetInstruction<\n TProgram extends string = 'ComputeBudget111111111111111111111111111111',\n> =\n | ({\n instructionType: ComputeBudgetInstruction.RequestUnits;\n } & ParsedRequestUnitsInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.RequestHeapFrame;\n } & ParsedRequestHeapFrameInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitLimit;\n } & ParsedSetComputeUnitLimitInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitPrice;\n } & ParsedSetComputeUnitPriceInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n } & ParsedSetLoadedAccountsDataSizeLimitInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_HEAP_FRAME_DISCRIMINATOR = 1;\n\nexport function getRequestHeapFrameDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_HEAP_FRAME_DISCRIMINATOR);\n}\n\nexport type RequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestHeapFrameInstructionData = {\n discriminator: number;\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport type RequestHeapFrameInstructionDataArgs = {\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport function getRequestHeapFrameInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['bytes', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_HEAP_FRAME_DISCRIMINATOR })\n );\n}\n\nexport function getRequestHeapFrameInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['bytes', getU32Decoder()],\n ]);\n}\n\nexport function getRequestHeapFrameInstructionDataCodec(): FixedSizeCodec<\n RequestHeapFrameInstructionDataArgs,\n RequestHeapFrameInstructionData\n> {\n return combineCodec(\n getRequestHeapFrameInstructionDataEncoder(),\n getRequestHeapFrameInstructionDataDecoder()\n );\n}\n\nexport type RequestHeapFrameInput = {\n bytes: RequestHeapFrameInstructionDataArgs['bytes'];\n};\n\nexport function getRequestHeapFrameInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestHeapFrameInput,\n config?: { programAddress?: TProgramAddress }\n): RequestHeapFrameInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestHeapFrameInstructionDataEncoder().encode(\n args as RequestHeapFrameInstructionDataArgs\n ),\n programAddress,\n } as RequestHeapFrameInstruction);\n}\n\nexport type ParsedRequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: RequestHeapFrameInstructionData;\n};\n\nexport function parseRequestHeapFrameInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestHeapFrameInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestHeapFrameInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_UNITS_DISCRIMINATOR = 0;\n\nexport function getRequestUnitsDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_UNITS_DISCRIMINATOR);\n}\n\nexport type RequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestUnitsInstructionData = {\n discriminator: number;\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport type RequestUnitsInstructionDataArgs = {\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport function getRequestUnitsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ['additionalFee', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_UNITS_DISCRIMINATOR })\n );\n}\n\nexport function getRequestUnitsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ['additionalFee', getU32Decoder()],\n ]);\n}\n\nexport function getRequestUnitsInstructionDataCodec(): FixedSizeCodec<\n RequestUnitsInstructionDataArgs,\n RequestUnitsInstructionData\n> {\n return combineCodec(\n getRequestUnitsInstructionDataEncoder(),\n getRequestUnitsInstructionDataDecoder()\n );\n}\n\nexport type RequestUnitsInput = {\n units: RequestUnitsInstructionDataArgs['units'];\n additionalFee: RequestUnitsInstructionDataArgs['additionalFee'];\n};\n\nexport function getRequestUnitsInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestUnitsInput,\n config?: { programAddress?: TProgramAddress }\n): RequestUnitsInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestUnitsInstructionDataEncoder().encode(\n args as RequestUnitsInstructionDataArgs\n ),\n programAddress,\n } as RequestUnitsInstruction);\n}\n\nexport type ParsedRequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = { programAddress: Address; data: RequestUnitsInstructionData };\n\nexport function parseRequestUnitsInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestUnitsInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestUnitsInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR = 2;\n\nexport function getSetComputeUnitLimitDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitLimitInstructionData = {\n discriminator: number;\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport type SetComputeUnitLimitInstructionDataArgs = {\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport function getSetComputeUnitLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitLimitInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitLimitInstructionDataArgs,\n SetComputeUnitLimitInstructionData\n> {\n return combineCodec(\n getSetComputeUnitLimitInstructionDataEncoder(),\n getSetComputeUnitLimitInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitLimitInput = {\n units: SetComputeUnitLimitInstructionDataArgs['units'];\n};\n\nexport function getSetComputeUnitLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitLimitInstructionDataEncoder().encode(\n args as SetComputeUnitLimitInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitLimitInstruction);\n}\n\nexport type ParsedSetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitLimitInstructionData;\n};\n\nexport function parseSetComputeUnitLimitInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR = 3;\n\nexport function getSetComputeUnitPriceDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitPriceInstructionData = {\n discriminator: number;\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: bigint;\n};\n\nexport type SetComputeUnitPriceInstructionDataArgs = {\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: number | bigint;\n};\n\nexport function getSetComputeUnitPriceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['microLamports', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitPriceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['microLamports', getU64Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitPriceInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitPriceInstructionDataArgs,\n SetComputeUnitPriceInstructionData\n> {\n return combineCodec(\n getSetComputeUnitPriceInstructionDataEncoder(),\n getSetComputeUnitPriceInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitPriceInput = {\n microLamports: SetComputeUnitPriceInstructionDataArgs['microLamports'];\n};\n\nexport function getSetComputeUnitPriceInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitPriceInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitPriceInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitPriceInstructionDataEncoder().encode(\n args as SetComputeUnitPriceInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitPriceInstruction);\n}\n\nexport type ParsedSetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitPriceInstructionData;\n};\n\nexport function parseSetComputeUnitPriceInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitPriceInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitPriceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR = 4;\n\nexport function getSetLoadedAccountsDataSizeLimitDiscriminatorBytes() {\n return getU8Encoder().encode(\n SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetLoadedAccountsDataSizeLimitInstructionData = {\n discriminator: number;\n accountDataSizeLimit: number;\n};\n\nexport type SetLoadedAccountsDataSizeLimitInstructionDataArgs = {\n accountDataSizeLimit: number;\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['accountDataSizeLimit', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['accountDataSizeLimit', getU32Decoder()],\n ]);\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataCodec(): FixedSizeCodec<\n SetLoadedAccountsDataSizeLimitInstructionDataArgs,\n SetLoadedAccountsDataSizeLimitInstructionData\n> {\n return combineCodec(\n getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(),\n getSetLoadedAccountsDataSizeLimitInstructionDataDecoder()\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInput = {\n accountDataSizeLimit: SetLoadedAccountsDataSizeLimitInstructionDataArgs['accountDataSizeLimit'];\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetLoadedAccountsDataSizeLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetLoadedAccountsDataSizeLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetLoadedAccountsDataSizeLimitInstructionDataEncoder().encode(\n args as SetLoadedAccountsDataSizeLimitInstructionDataArgs\n ),\n programAddress,\n } as SetLoadedAccountsDataSizeLimitInstruction);\n}\n\nexport type ParsedSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetLoadedAccountsDataSizeLimitInstructionData;\n};\n\nexport function parseSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string,\n>(\n instruction: Instruction & InstructionWithData\n): ParsedSetLoadedAccountsDataSizeLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetLoadedAccountsDataSizeLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * A provisory compute unit limit is used to indicate that the transaction\n * should be estimated for compute units before being sent to the network.\n *\n * Setting it to zero ensures the transaction fails unless it is properly estimated.\n */\nexport const PROVISORY_COMPUTE_UNIT_LIMIT = 0;\n\n/**\n * The maximum compute unit limit that can be set for a transaction.\n */\nexport const MAX_COMPUTE_UNIT_LIMIT = 1_400_000;\n","import {\n BaseTransactionMessage,\n getU32Decoder,\n getU64Decoder,\n Instruction,\n MicroLamports,\n ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n COMPUTE_BUDGET_PROGRAM_ADDRESS,\n ComputeBudgetInstruction,\n identifyComputeBudgetInstruction,\n SetComputeUnitLimitInstruction,\n SetComputeUnitPriceInstruction,\n} from './generated';\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message\n * and its set limit, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndexAndUnits(\n transactionMessage: BaseTransactionMessage\n): { index: number; units: number } | null {\n const index = getSetComputeUnitLimitInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const units = getU32Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n );\n\n return { index, units };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitLimitInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitLimit` instruction.\n */\nexport function isSetComputeUnitLimitInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitLimitInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitLimit\n );\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message\n * and its set micro-lamports, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndexAndMicroLamports(\n transactionMessage: BaseTransactionMessage\n): { index: number; microLamports: MicroLamports } | null {\n const index = getSetComputeUnitPriceInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const microLamports = getU64Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n ) as MicroLamports;\n\n return { index, microLamports };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitPriceInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitPrice` instruction.\n */\nexport function isSetComputeUnitPriceInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitPriceInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitPrice\n );\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n} from '@solana/kit';\nimport { PROVISORY_COMPUTE_UNIT_LIMIT } from './constants';\nimport { getSetComputeUnitLimitInstruction } from './generated';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\n\n/**\n * Appends a `SetComputeUnitLimit` instruction with a provisory\n * compute unit limit to a given transaction message\n * if and only if it does not already have one.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * fillProvisorySetComputeUnitLimitInstruction,\n * // ...\n * );\n * ```\n */\nexport function fillProvisorySetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(transactionMessage: TTransactionMessage) {\n return updateOrAppendSetComputeUnitLimitInstruction(\n (previousUnits) =>\n previousUnits === null ? PROVISORY_COMPUTE_UNIT_LIMIT : previousUnits,\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitLimit` instruction in a transaction message\n * with the given units, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param units - The new compute unit limit, or a function that takes the previous\n * compute unit limit and returns the new limit.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitLimitInstruction(\n * // E.g. Keep the current limit if it is set, otherwise set it to the maximum.\n * (currentUnits) => currentUnits === null ? MAX_COMPUTE_UNIT_LIMIT : currentUnits,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n units: number | ((previousUnits: number | null) => number),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getUnits = (previousUnits: number | null): number =>\n typeof units === 'function' ? units(previousUnits) : units;\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: getUnits(null) }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, units: previousUnits } = instructionDetails;\n const newUnits = getUnits(previousUnits);\n if (newUnits === previousUnits) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitLimitInstruction({ units: newUnits });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport {\n MAX_COMPUTE_UNIT_LIMIT,\n PROVISORY_COMPUTE_UNIT_LIMIT,\n} from './constants';\nimport {\n EstimateComputeUnitLimitFactoryFunction,\n EstimateComputeUnitLimitFactoryFunctionConfig,\n} from './estimateComputeLimitInternal';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\n\ntype EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction = <\n TTransactionMessage extends BaseTransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\n/**\n * Given a transaction message, if it does not have an explicit compute unit limit,\n * estimates the compute unit limit and updates the transaction message with\n * the estimated limit. Otherwise, returns the transaction message unchanged.\n *\n * It requires a function that estimates the compute unit limit.\n *\n * @example\n * ```ts\n * const estimateAndUpdateCUs = estimateAndUpdateProvisoryComputeUnitLimitFactory(\n * estimateComputeUnitLimitFactory({ rpc })\n * );\n *\n * const transactionMessageWithCUs = await estimateAndUpdateCUs(transactionMessage);\n * ```\n *\n * @see {@link estimateAndUpdateProvisoryComputeUnitLimitFactory}\n */\nexport function estimateAndUpdateProvisoryComputeUnitLimitFactory(\n estimateComputeUnitLimit: EstimateComputeUnitLimitFactoryFunction\n): EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction {\n return async function fn(transactionMessage, config) {\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n // If the transaction message already has a compute unit limit instruction\n // which is set to a specific value — i.e. not 0 or the maximum limit —\n // we don't need to estimate the compute unit limit.\n if (\n instructionDetails &&\n instructionDetails.units !== PROVISORY_COMPUTE_UNIT_LIMIT &&\n instructionDetails.units !== MAX_COMPUTE_UNIT_LIMIT\n ) {\n return transactionMessage;\n }\n\n return updateOrAppendSetComputeUnitLimitInstruction(\n await estimateComputeUnitLimit(transactionMessage, config),\n transactionMessage\n );\n };\n}\n","import {\n BaseTransactionMessage,\n Commitment,\n compileTransaction,\n getBase64EncodedWireTransaction,\n isSolanaError,\n isTransactionMessageWithDurableNonceLifetime,\n pipe,\n Rpc,\n SimulateTransactionApi,\n Slot,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaError,\n Transaction,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\nimport { MAX_COMPUTE_UNIT_LIMIT } from './constants';\n\nexport type EstimateComputeUnitLimitFactoryConfig = Readonly<{\n /** An object that supports the {@link SimulateTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}>;\n\nexport type EstimateComputeUnitLimitFactoryFunction = (\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\nexport type EstimateComputeUnitLimitFactoryFunctionConfig = {\n abortSignal?: AbortSignal;\n /**\n * Compute the estimate as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\ntype EstimateComputeUnitLimitConfig =\n EstimateComputeUnitLimitFactoryFunctionConfig &\n Readonly<{\n rpc: Rpc;\n transactionMessage: BaseTransactionMessage &\n TransactionMessageWithFeePayer;\n }>;\n\n/**\n * Simulates a transaction message on the network and returns the number of compute units it\n * consumed during simulation.\n *\n * The estimate this function returns can be used to set a compute unit limit on the transaction.\n * Correctly budgeting a compute unit limit for your transaction message can increase the probability\n * that your transaction will be accepted for processing.\n *\n * If you don't declare a compute unit limit on your transaction, validators will assume an upper\n * limit of 200K compute units (CU) per instruction. Since validators have an incentive to pack as\n * many transactions into each block as possible, they may choose to include transactions that they\n * know will fit into the remaining compute budget for the current block over transactions that\n * might not. For this reason, you should set a compute unit limit on each of your transaction\n * messages, whenever possible.\n *\n * ## Example\n *\n * ```ts\n * import { getSetComputeLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const getComputeUnitEstimateForTransactionMessage =\n * getComputeUnitEstimateForTransactionMessageFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume.\n * const computeUnitsEstimate =\n * await getComputeUnitEstimateForTransactionMessage(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeLimitInstruction({ units: computeUnitsEstimate }),\n * transactionMessage,\n * );\n * ```\n *\n * > [!WARNING]\n * > The compute unit estimate is just that – an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n */\nexport async function estimateComputeUnitLimit({\n transactionMessage,\n ...configs\n}: EstimateComputeUnitLimitConfig): Promise {\n const replaceRecentBlockhash =\n !isTransactionMessageWithDurableNonceLifetime(transactionMessage);\n const transaction = pipe(\n transactionMessage,\n (m) =>\n updateOrAppendSetComputeUnitLimitInstruction(MAX_COMPUTE_UNIT_LIMIT, m),\n compileTransaction\n );\n\n return await simulateTransactionAndGetConsumedUnits({\n transaction,\n replaceRecentBlockhash,\n ...configs,\n });\n}\n\ntype SimulateTransactionAndGetConsumedUnitsConfig = Omit<\n EstimateComputeUnitLimitConfig,\n 'transactionMessage'\n> &\n Readonly<{ replaceRecentBlockhash?: boolean; transaction: Transaction }>;\n\nasync function simulateTransactionAndGetConsumedUnits({\n abortSignal,\n rpc,\n transaction,\n ...simulateConfig\n}: SimulateTransactionAndGetConsumedUnitsConfig): Promise {\n const wireTransactionBytes = getBase64EncodedWireTransaction(transaction);\n\n try {\n const {\n value: { err: transactionError, unitsConsumed },\n } = await rpc\n .simulateTransaction(wireTransactionBytes, {\n ...simulateConfig,\n encoding: 'base64',\n sigVerify: false,\n })\n .send({ abortSignal });\n if (unitsConsumed == null) {\n // This should never be hit, because all RPCs should support `unitsConsumed` by now.\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n );\n }\n // FIXME(https://github.com/anza-xyz/agave/issues/1295): The simulation response returns\n // compute units as a u64, but the `SetComputeLimit` instruction only accepts a u32. Until\n // this changes, downcast it.\n const downcastUnitsConsumed =\n unitsConsumed > 4_294_967_295n ? 4_294_967_295 : Number(unitsConsumed);\n if (transactionError) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n {\n cause: transactionError,\n unitsConsumed: downcastUnitsConsumed,\n }\n );\n }\n return downcastUnitsConsumed;\n } catch (e) {\n if (\n isSolanaError(\n e,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n )\n )\n throw e;\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n { cause: e }\n );\n }\n}\n","import {\n estimateComputeUnitLimit,\n EstimateComputeUnitLimitFactoryConfig,\n EstimateComputeUnitLimitFactoryFunction,\n} from './estimateComputeLimitInternal';\n\n/**\n * Use this utility to estimate the actual compute unit cost of a given transaction message.\n *\n * Correctly budgeting a compute unit limit for your transaction message can increase the\n * probability that your transaction will be accepted for processing. If you don't declare a compute\n * unit limit on your transaction, validators will assume an upper limit of 200K compute units (CU)\n * per instruction.\n *\n * Since validators have an incentive to pack as many transactions into each block as possible, they\n * may choose to include transactions that they know will fit into the remaining compute budget for\n * the current block over transactions that might not. For this reason, you should set a compute\n * unit limit on each of your transaction messages, whenever possible.\n *\n * > [!WARNING]\n * > The compute unit estimate is just that -- an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n *\n * > [!INFO]\n * > In the event that a transaction message does not already have a `SetComputeUnitLimit`\n * > instruction, this function will add one before simulation. This ensures that the compute unit\n * > consumption of the `SetComputeUnitLimit` instruction itself is included in the estimate.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, estimateComputeUnitLimitFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const estimateComputeUnitLimit = estimateComputeUnitLimitFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume. This is done by\n * // simulating the transaction and grabbing the estimated compute units from the result.\n * const estimatedUnits = await estimateComputeUnitLimit(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeUnitLimitInstruction({ units: estimatedUnits }),\n * transactionMessage,\n * );\n * ```\n */\nexport function estimateComputeUnitLimitFactory({\n rpc,\n}: EstimateComputeUnitLimitFactoryConfig): EstimateComputeUnitLimitFactoryFunction {\n return async function estimateComputeUnitLimitFactoryFunction(\n transactionMessage,\n config\n ) {\n return await estimateComputeUnitLimit({\n ...config,\n rpc,\n transactionMessage,\n });\n };\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n MicroLamports,\n} from '@solana/kit';\nimport { getSetComputeUnitPriceInstruction } from './generated';\nimport { getSetComputeUnitPriceInstructionIndexAndMicroLamports } from './internal';\n\n/**\n * Sets the compute unit price of a transaction message in micro-Lamports.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * (m) => setTransactionMessageComputeUnitPrice(10_000, m),\n * // ...\n * );\n * ```\n */\nexport function setTransactionMessageComputeUnitPrice<\n TTransactionMessage extends BaseTransactionMessage,\n>(microLamports: number | bigint, transactionMessage: TTransactionMessage) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({ microLamports }),\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitPrice` instruction in a transaction message\n * with the given micro-Lamports, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param microLamports - The new compute unit price, or a function that\n * takes the previous price and returns the new one.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitPriceInstruction(\n * // E.g. double the current price or set it to 10_000 if it isn't set.\n * (currentPrice) => currentPrice === null ? 10_000 : currentPrice * 2,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitPriceInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n microLamports:\n | MicroLamports\n | ((previousMicroLamports: MicroLamports | null) => MicroLamports),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getMicroLamports = (\n previousMicroLamports: MicroLamports | null\n ): MicroLamports =>\n typeof microLamports === 'function'\n ? microLamports(previousMicroLamports)\n : microLamports;\n const instructionDetails =\n getSetComputeUnitPriceInstructionIndexAndMicroLamports(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({\n microLamports: getMicroLamports(null),\n }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, microLamports: previousMicroLamports } = instructionDetails;\n const newMicroLamports = getMicroLamports(previousMicroLamports);\n if (newMicroLamports === previousMicroLamports) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitPriceInstruction({\n microLamports: newMicroLamports,\n });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../signer\";\nimport type { ExactSvmPayloadV2 } from \"../../types\";\nimport { createRpcClient } from \"../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme.\n */\nexport class ExactSvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClient instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClient instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise> {\n const rpc = createRpcClient(paymentRequirements.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, paymentRequirements.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: paymentRequirements.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: paymentRequirements.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(paymentRequirements.amount),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = paymentRequirements.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV2 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n}\n","/**\n * V1 exports for the SVM mechanism\n */\nexport { ExactSvmSchemeV1 } from \"../exact/v1\";\n\nexport const NETWORKS: string[] = [\"solana\", \"solana-devnet\", \"solana-testnet\"];\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport type { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../../signer\";\nimport type { ExactSvmPayloadV1 } from \"../../../types\";\nimport { createRpcClient } from \"../../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactSvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClientV1 instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClientV1 instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const rpc = createRpcClient(selectedV1.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, selectedV1.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: selectedV1.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: selectedV1.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(selectedV1.maxAmountRequired),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = selectedV1.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV1 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientSvmSigner } from \"../../signer\";\nimport { ExactSvmScheme } from \"./scheme\";\nimport { ExactSvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering SVM schemes to an x402Client\n */\nexport interface SvmClientConfig {\n /**\n * The SVM signer to use for creating payment payloads\n */\n signer: ClientSvmSigner;\n\n /**\n * Optional payment requirements selector function\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional specific networks to register\n */\n networks?: Network[];\n}\n\n/**\n * Registers SVM payment schemes to an existing x402Client instance.\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for SVM client registration\n * @returns The client instance for chaining\n */\nexport function registerExactSvmScheme(client: x402Client, config: SvmClientConfig): x402Client {\n // Register V2 scheme\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach(network => {\n client.register(network, new ExactSvmScheme(config.signer));\n });\n } else {\n client.register(\"solana:*\", new ExactSvmScheme(config.signer));\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactSvmSchemeV1(config.signer));\n });\n\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * BlockRun Model Definitions for OpenClaw\n *\n * Maps BlockRun's 55+ AI models to OpenClaw's ModelDefinitionConfig format.\n * All models use the \"openai-completions\" API since BlockRun is OpenAI-compatible.\n *\n * Pricing is in USD per 1M tokens. Operators pay these rates via x402;\n * they set their own markup when reselling to end users (Phase 2).\n */\n\nimport type { ModelDefinitionConfig, ModelProviderConfig } from \"./types.js\";\n\n/**\n * Model aliases for convenient shorthand access.\n * Users can type `/model claude` instead of `/model blockrun/anthropic/claude-sonnet-4-6`.\n */\nexport const MODEL_ALIASES: Record = {\n // Claude - use newest versions (4.6)\n claude: \"anthropic/claude-sonnet-4.6\",\n sonnet: \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4.6\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n opus: \"anthropic/claude-opus-4.6\",\n \"opus-4\": \"anthropic/claude-opus-4.6\",\n \"opus-4.6\": \"anthropic/claude-opus-4.6\",\n \"opus-4-6\": \"anthropic/claude-opus-4.6\",\n haiku: \"anthropic/claude-haiku-4.5\",\n // Claude - provider/shortname patterns (common in agent frameworks)\n \"anthropic/sonnet\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/opus\": \"anthropic/claude-opus-4.6\",\n \"anthropic/haiku\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude\": \"anthropic/claude-sonnet-4.6\",\n // Backward compatibility - map all variants to 4.6\n \"anthropic/claude-sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-opus-4\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4-6\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4.5\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-haiku-4\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude-haiku-4-5\": \"anthropic/claude-haiku-4.5\",\n\n // OpenAI\n gpt: \"openai/gpt-4o\",\n gpt4: \"openai/gpt-4o\",\n gpt5: \"openai/gpt-5.4\",\n \"gpt-5.4\": \"openai/gpt-5.4\",\n \"gpt-5.4-pro\": \"openai/gpt-5.4-pro\",\n \"gpt-5.4-nano\": \"openai/gpt-5.4-nano\",\n nano: \"openai/gpt-5.4-nano\",\n \"gpt-5-nano\": \"openai/gpt-5.4-nano\",\n codex: \"openai/gpt-5.3-codex\",\n mini: \"openai/gpt-4o-mini\",\n o1: \"openai/o1\",\n o3: \"openai/o3\",\n\n // DeepSeek\n deepseek: \"deepseek/deepseek-chat\",\n \"deepseek-chat\": \"deepseek/deepseek-chat\",\n reasoner: \"deepseek/deepseek-reasoner\",\n\n // Kimi / Moonshot\n kimi: \"moonshot/kimi-k2.5\",\n moonshot: \"moonshot/kimi-k2.5\",\n \"kimi-k2.5\": \"moonshot/kimi-k2.5\",\n\n // Google\n gemini: \"google/gemini-2.5-pro\",\n flash: \"google/gemini-2.5-flash\",\n \"gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"google/gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"gemini-3.1-flash-lite\": \"google/gemini-3.1-flash-lite\",\n\n // xAI\n grok: \"xai/grok-3\",\n \"grok-fast\": \"xai/grok-4-fast-reasoning\",\n \"grok-code\": \"deepseek/deepseek-chat\", // was grok-code-fast-1, delisted due to poor retention\n // Delisted model redirects — full model IDs that were previously valid but removed\n \"grok-code-fast-1\": \"deepseek/deepseek-chat\", // bare alias\n \"xai/grok-code-fast-1\": \"deepseek/deepseek-chat\", // delisted 2026-03-12\n \"xai/grok-3-fast\": \"xai/grok-4-fast-reasoning\", // delisted (too expensive)\n\n // NVIDIA — backward compat aliases (nvidia/xxx → free/xxx)\n nvidia: \"free/gpt-oss-120b\",\n \"gpt-120b\": \"free/gpt-oss-120b\",\n \"gpt-20b\": \"free/gpt-oss-20b\",\n \"nvidia/gpt-oss-120b\": \"free/gpt-oss-120b\",\n \"nvidia/gpt-oss-20b\": \"free/gpt-oss-20b\",\n \"nvidia/nemotron-ultra-253b\": \"free/nemotron-ultra-253b\",\n \"nvidia/nemotron-3-super-120b\": \"free/nemotron-3-super-120b\",\n \"nvidia/nemotron-super-49b\": \"free/nemotron-super-49b\",\n \"nvidia/deepseek-v3.2\": \"free/deepseek-v3.2\",\n \"nvidia/mistral-large-3-675b\": \"free/mistral-large-3-675b\",\n \"nvidia/qwen3-coder-480b\": \"free/qwen3-coder-480b\",\n \"nvidia/devstral-2-123b\": \"free/devstral-2-123b\",\n \"nvidia/glm-4.7\": \"free/glm-4.7\",\n \"nvidia/llama-4-maverick\": \"free/llama-4-maverick\",\n // Free model shorthand aliases\n \"deepseek-free\": \"free/deepseek-v3.2\",\n \"mistral-free\": \"free/mistral-large-3-675b\",\n \"glm-free\": \"free/glm-4.7\",\n \"llama-free\": \"free/llama-4-maverick\",\n nemotron: \"free/nemotron-ultra-253b\",\n \"nemotron-ultra\": \"free/nemotron-ultra-253b\",\n \"nemotron-253b\": \"free/nemotron-ultra-253b\",\n \"nemotron-super\": \"free/nemotron-super-49b\",\n \"nemotron-49b\": \"free/nemotron-super-49b\",\n \"nemotron-120b\": \"free/nemotron-3-super-120b\",\n devstral: \"free/devstral-2-123b\",\n \"devstral-2\": \"free/devstral-2-123b\",\n \"qwen-coder\": \"free/qwen3-coder-480b\",\n \"qwen-coder-free\": \"free/qwen3-coder-480b\",\n maverick: \"free/llama-4-maverick\",\n free: \"free/nemotron-ultra-253b\",\n\n // MiniMax\n minimax: \"minimax/minimax-m2.7\",\n \"minimax-m2.7\": \"minimax/minimax-m2.7\",\n \"minimax-m2.5\": \"minimax/minimax-m2.5\",\n\n // Z.AI GLM-5\n glm: \"zai/glm-5\",\n \"glm-5\": \"zai/glm-5\",\n \"glm-5-turbo\": \"zai/glm-5-turbo\",\n\n // Routing profile aliases (common variations)\n \"auto-router\": \"auto\",\n router: \"auto\",\n\n // Note: auto, eco, premium are virtual routing profiles registered in BLOCKRUN_MODELS\n // They don't need aliases since they're already top-level model IDs\n};\n\n/**\n * Resolve a model alias to its full model ID.\n * Also strips \"blockrun/\" prefix for direct model paths.\n * Examples:\n * - \"claude\" -> \"anthropic/claude-sonnet-4-6\" (alias)\n * - \"blockrun/claude\" -> \"anthropic/claude-sonnet-4-6\" (alias with prefix)\n * - \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\" (prefix stripped)\n * - \"openai/gpt-4o\" -> \"openai/gpt-4o\" (unchanged)\n */\nexport function resolveModelAlias(model: string): string {\n const normalized = model.trim().toLowerCase();\n const resolved = MODEL_ALIASES[normalized];\n if (resolved) return resolved;\n\n // Check with \"blockrun/\" prefix stripped\n if (normalized.startsWith(\"blockrun/\")) {\n const withoutPrefix = normalized.slice(\"blockrun/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // Even if not an alias, strip the prefix for direct model paths\n // e.g., \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\"\n return withoutPrefix;\n }\n\n // Strip \"openai/\" prefix when it wraps a virtual routing profile or alias.\n // OpenClaw sends virtual models as \"openai/eco\", \"openai/auto\", etc. because\n // the provider uses the openai-completions API type.\n if (normalized.startsWith(\"openai/\")) {\n const withoutPrefix = normalized.slice(\"openai/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // If it's a known BlockRun virtual profile (eco, auto, premium), return bare id\n const isVirtualProfile = BLOCKRUN_MODELS.some((m) => m.id === withoutPrefix);\n if (isVirtualProfile) return withoutPrefix;\n }\n\n return model;\n}\n\ntype BlockRunModel = {\n id: string;\n name: string;\n /** Model version (e.g., \"4.6\", \"3.1\", \"5.2\") for tracking updates */\n version?: string;\n inputPrice: number;\n outputPrice: number;\n contextWindow: number;\n maxOutput: number;\n reasoning?: boolean;\n vision?: boolean;\n /** Models optimized for agentic workflows (multi-step autonomous tasks) */\n agentic?: boolean;\n /**\n * Model supports OpenAI-compatible structured function/tool calling.\n * Models without this flag output tool invocations as plain text JSON,\n * which leaks raw {\"command\":\"...\"} into visible chat messages.\n * Default: false (must opt-in to prevent silent regressions on new models).\n */\n toolCalling?: boolean;\n /** Model is deprecated — will be routed to fallbackModel if set */\n deprecated?: boolean;\n /** Model ID to route to when this model is deprecated */\n fallbackModel?: string;\n};\n\nexport const BLOCKRUN_MODELS: BlockRunModel[] = [\n // Smart routing meta-models — proxy replaces with actual model\n // NOTE: Model IDs are WITHOUT provider prefix (OpenClaw adds \"blockrun/\" automatically)\n {\n id: \"auto\",\n name: \"Auto (Smart Router - Balanced)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"free\",\n name: \"Free → Nemotron Ultra 253B\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131_072,\n maxOutput: 16_384,\n reasoning: true,\n },\n {\n id: \"eco\",\n name: \"Eco (Smart Router - Cost Optimized)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"premium\",\n name: \"Premium (Smart Router - Best Quality)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 2_000_000,\n maxOutput: 200_000,\n },\n\n // OpenAI GPT-5 Family\n {\n id: \"openai/gpt-5.2\",\n name: \"GPT-5.2\",\n version: \"5.2\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-mini\",\n name: \"GPT-5 Mini\",\n version: \"5.0\",\n inputPrice: 0.25,\n outputPrice: 2.0,\n contextWindow: 200000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-nano\",\n name: \"GPT-5 Nano\",\n version: \"5.0\",\n inputPrice: 0.05,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 32768,\n toolCalling: true,\n deprecated: true,\n fallbackModel: \"openai/gpt-5.4-nano\",\n },\n {\n id: \"openai/gpt-5.2-pro\",\n name: \"GPT-5.2 Pro\",\n version: \"5.2\",\n inputPrice: 21.0,\n outputPrice: 168.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n // GPT-5.4 — newest flagship, same input price as 4o but much more capable\n {\n id: \"openai/gpt-5.4\",\n name: \"GPT-5.4\",\n version: \"5.4\",\n inputPrice: 2.5,\n outputPrice: 15.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-pro\",\n name: \"GPT-5.4 Pro\",\n version: \"5.4\",\n inputPrice: 30.0,\n outputPrice: 180.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-nano\",\n name: \"GPT-5.4 Nano\",\n version: \"5.4\",\n inputPrice: 0.2,\n outputPrice: 1.25,\n contextWindow: 1050000,\n maxOutput: 32768,\n toolCalling: true,\n },\n\n // OpenAI GPT-5.3 Family\n {\n id: \"openai/gpt-5.3\",\n name: \"GPT-5.3\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 128000,\n maxOutput: 16000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI Codex Family\n {\n id: \"openai/gpt-5.3-codex\",\n name: \"GPT-5.3 Codex\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI GPT-4 Family\n {\n id: \"openai/gpt-4.1\",\n name: \"GPT-4.1\",\n version: \"4.1\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-mini\",\n name: \"GPT-4.1 Mini\",\n version: \"4.1\",\n inputPrice: 0.4,\n outputPrice: 1.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-nano\",\n name: \"GPT-4.1 Nano\",\n version: \"4.1\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o\",\n name: \"GPT-4o\",\n version: \"4o\",\n inputPrice: 2.5,\n outputPrice: 10.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o-mini\",\n name: \"GPT-4o Mini\",\n version: \"4o-mini\",\n inputPrice: 0.15,\n outputPrice: 0.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // OpenAI O-series (Reasoning)\n {\n id: \"openai/o1\",\n name: \"o1\",\n version: \"1\",\n inputPrice: 15.0,\n outputPrice: 60.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o1-mini\",\n name: \"o1-mini\",\n version: \"1-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3\",\n name: \"o3\",\n version: \"3\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3-mini\",\n name: \"o3-mini\",\n version: \"3-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o4-mini\",\n name: \"o4-mini\",\n version: \"4-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n\n // Anthropic - all Claude models excel at agentic workflows\n // Use newest versions (4.6) with full provider prefix\n {\n id: \"anthropic/claude-haiku-4.5\",\n name: \"Claude Haiku 4.5\",\n version: \"4.5\",\n inputPrice: 1.0,\n outputPrice: 5.0,\n contextWindow: 200000,\n maxOutput: 8192,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-sonnet-4.6\",\n name: \"Claude Sonnet 4.6\",\n version: \"4.6\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 200000,\n maxOutput: 64000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-opus-4.6\",\n name: \"Claude Opus 4.6\",\n version: \"4.6\",\n inputPrice: 5.0,\n outputPrice: 25.0,\n contextWindow: 200000,\n maxOutput: 32000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Google\n {\n id: \"google/gemini-3.1-pro\",\n name: \"Gemini 3.1 Pro\",\n version: \"3.1\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-pro-preview\",\n name: \"Gemini 3 Pro Preview\",\n version: \"3.0\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-flash-preview\",\n name: \"Gemini 3 Flash Preview\",\n version: \"3.0\",\n inputPrice: 0.5,\n outputPrice: 3.0,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n },\n {\n id: \"google/gemini-2.5-pro\",\n name: \"Gemini 2.5 Pro\",\n version: \"2.5\",\n inputPrice: 1.25,\n outputPrice: 10.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash\",\n name: \"Gemini 2.5 Flash\",\n version: \"2.5\",\n inputPrice: 0.3,\n outputPrice: 2.5,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash-lite\",\n name: \"Gemini 2.5 Flash Lite\",\n version: \"2.5\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 1000000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3.1-flash-lite\",\n name: \"Gemini 3.1 Flash Lite\",\n version: \"3.1\",\n inputPrice: 0.25,\n outputPrice: 1.5,\n contextWindow: 1000000,\n maxOutput: 8192,\n toolCalling: true,\n },\n\n // DeepSeek\n {\n id: \"deepseek/deepseek-chat\",\n name: \"DeepSeek V3.2 Chat\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n toolCalling: true,\n },\n {\n id: \"deepseek/deepseek-reasoner\",\n name: \"DeepSeek V3.2 Reasoner\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n reasoning: true,\n toolCalling: true,\n },\n\n // Moonshot / Kimi - optimized for agentic workflows\n {\n id: \"moonshot/kimi-k2.5\",\n name: \"Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 8192,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // xAI / Grok\n {\n id: \"xai/grok-3\",\n name: \"Grok 3\",\n version: \"3\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n // grok-3-fast removed - too expensive ($5/$25), use grok-4-fast instead\n {\n id: \"xai/grok-3-mini\",\n name: \"Grok 3 Mini\",\n version: \"3-mini\",\n inputPrice: 0.3,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // xAI Grok 4 Family - Ultra-cheap fast models\n {\n id: \"xai/grok-4-fast-reasoning\",\n name: \"Grok 4 Fast Reasoning\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-fast-non-reasoning\",\n name: \"Grok 4 Fast\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-reasoning\",\n name: \"Grok 4.1 Fast Reasoning\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-non-reasoning\",\n name: \"Grok 4.1 Fast\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n // xai/grok-code-fast-1 delisted 2026-03-12: poor retention (coding users churn),\n // no structured tool calling, alias \"grok-code\" redirected to deepseek-chat\n {\n id: \"xai/grok-4-0709\",\n name: \"Grok 4 (0709)\",\n version: \"4-0709\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-2-vision\",\n name: \"Grok 2 Vision\",\n version: \"2\",\n inputPrice: 2.0,\n outputPrice: 10.0,\n contextWindow: 131072,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n\n // MiniMax\n {\n id: \"minimax/minimax-m2.7\",\n name: \"MiniMax M2.7\",\n version: \"m2.7\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"minimax/minimax-m2.5\",\n name: \"MiniMax M2.5\",\n version: \"m2.5\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Free models (hosted by NVIDIA, billingMode: \"free\" on server)\n // IDs use \"free/\" prefix so users see them as free in the /model picker.\n // ClawRouter maps free/xxx → nvidia/xxx before sending to BlockRun upstream.\n // toolCalling intentionally omitted: structured function calling unverified.\n {\n id: \"free/gpt-oss-120b\",\n name: \"[Free] GPT-OSS 120B\",\n version: \"120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/gpt-oss-20b\",\n name: \"[Free] GPT-OSS 20B\",\n version: \"20b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/nemotron-ultra-253b\",\n name: \"[Free] Nemotron Ultra 253B\",\n version: \"253b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-3-super-120b\",\n name: \"[Free] Nemotron 3 Super 120B\",\n version: \"3-super-120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-super-49b\",\n name: \"[Free] Nemotron Super 49B\",\n version: \"super-49b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/deepseek-v3.2\",\n name: \"[Free] DeepSeek V3.2\",\n version: \"v3.2\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/mistral-large-3-675b\",\n name: \"[Free] Mistral Large 675B\",\n version: \"3-675b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/qwen3-coder-480b\",\n name: \"[Free] Qwen3 Coder 480B\",\n version: \"480b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/devstral-2-123b\",\n name: \"[Free] Devstral 2 123B\",\n version: \"2-123b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/glm-4.7\",\n name: \"[Free] GLM-4.7\",\n version: \"4.7\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/llama-4-maverick\",\n name: \"[Free] Llama 4 Maverick\",\n version: \"4-maverick\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n\n // NVIDIA - Paid models\n {\n id: \"nvidia/kimi-k2.5\",\n name: \"NVIDIA Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // Z.AI GLM-5 Models\n {\n id: \"zai/glm-5\",\n name: \"GLM-5\",\n version: \"5\",\n inputPrice: 1.0,\n outputPrice: 3.2,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n {\n id: \"zai/glm-5-turbo\",\n name: \"GLM-5 Turbo\",\n version: \"5-turbo\",\n inputPrice: 1.2,\n outputPrice: 4.0,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n];\n\n/**\n * Convert BlockRun model definitions to OpenClaw ModelDefinitionConfig format.\n */\nfunction toOpenClawModel(m: BlockRunModel): ModelDefinitionConfig {\n return {\n id: m.id,\n name: m.name,\n api: \"openai-completions\",\n reasoning: m.reasoning ?? false,\n input: m.vision ? [\"text\", \"image\"] : [\"text\"],\n cost: {\n input: m.inputPrice,\n output: m.outputPrice,\n cacheRead: 0,\n cacheWrite: 0,\n },\n contextWindow: m.contextWindow,\n maxTokens: m.maxOutput,\n };\n}\n\n/**\n * Alias models that map to real models.\n * These allow users to use friendly names like \"free\" or \"gpt-120b\".\n */\nconst ALIAS_MODELS: ModelDefinitionConfig[] = Object.entries(MODEL_ALIASES)\n .map(([alias, targetId]) => {\n const target = BLOCKRUN_MODELS.find((m) => m.id === targetId);\n if (!target) return null;\n return toOpenClawModel({ ...target, id: alias, name: `${alias} → ${target.name}` });\n })\n .filter((m): m is ModelDefinitionConfig => m !== null);\n\n/**\n * All BlockRun models in OpenClaw format (including aliases).\n */\nexport const OPENCLAW_MODELS: ModelDefinitionConfig[] = [\n ...BLOCKRUN_MODELS.map(toOpenClawModel),\n ...ALIAS_MODELS,\n];\n\n/**\n * Build a ModelProviderConfig for BlockRun.\n *\n * @param baseUrl - The proxy's local base URL (e.g., \"http://127.0.0.1:12345\")\n */\nexport function buildProviderModels(baseUrl: string): ModelProviderConfig {\n return {\n baseUrl: `${baseUrl}/v1`,\n api: \"openai-completions\",\n models: OPENCLAW_MODELS,\n };\n}\n\n/**\n * Check if a model is optimized for agentic workflows.\n * Agentic models continue autonomously with multi-step tasks\n * instead of stopping and waiting for user input.\n */\nexport function isAgenticModel(modelId: string): boolean {\n const model = BLOCKRUN_MODELS.find(\n (m) => m.id === modelId || m.id === modelId.replace(\"blockrun/\", \"\"),\n );\n return model?.agentic ?? false;\n}\n\n/**\n * Get all agentic-capable models.\n */\nexport function getAgenticModels(): string[] {\n return BLOCKRUN_MODELS.filter((m) => m.agentic).map((m) => m.id);\n}\n\n/**\n * Check if a model supports OpenAI-compatible structured tool/function calling.\n * Models without this flag (e.g. grok-code-fast-1) output tool invocations as\n * plain text JSON, which leaks {\"command\":\"...\"} into visible chat messages.\n */\nexport function supportsToolCalling(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.toolCalling ?? false;\n}\n\n/**\n * Check if a model supports vision (image inputs).\n * Models without this flag cannot process image_url content parts.\n */\nexport function supportsVision(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.vision ?? false;\n}\n\n/**\n * Get context window size for a model.\n * Returns undefined if model not found.\n */\nexport function getModelContextWindow(modelId: string): number | undefined {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.contextWindow;\n}\n\n/**\n * Check if a model has reasoning/thinking capabilities.\n * Reasoning models may require reasoning_content in assistant tool_call messages.\n */\nexport function isReasoningModel(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.reasoning ?? false;\n}\n","/**\n * BlockRun ProviderPlugin for OpenClaw\n *\n * Registers BlockRun as an LLM provider in OpenClaw.\n * Uses a local x402 proxy to handle micropayments transparently —\n * pi-ai sees a standard OpenAI-compatible API at localhost.\n */\n\nimport type { ProviderPlugin } from \"./types.js\";\nimport { buildProviderModels } from \"./models.js\";\nimport type { ProxyHandle } from \"./proxy.js\";\n\n/**\n * State for the running proxy (set when the plugin activates).\n */\nlet activeProxy: ProxyHandle | null = null;\n\n/**\n * Update the proxy handle (called from index.ts when the proxy starts).\n */\nexport function setActiveProxy(proxy: ProxyHandle): void {\n activeProxy = proxy;\n}\n\nexport function getActiveProxy(): ProxyHandle | null {\n return activeProxy;\n}\n\n/**\n * BlockRun provider plugin definition.\n */\nexport const blockrunProvider: ProviderPlugin = {\n id: \"blockrun\",\n label: \"BlockRun\",\n docsPath: \"https://blockrun.ai/docs\",\n aliases: [\"br\"],\n envVars: [\"BLOCKRUN_WALLET_KEY\"],\n\n // Model definitions — dynamically set to proxy URL\n get models() {\n if (!activeProxy) {\n // Fallback: point to BlockRun API directly (won't handle x402, but\n // allows config loading before proxy starts)\n return buildProviderModels(\"https://blockrun.ai/api\");\n }\n return buildProviderModels(activeProxy.baseUrl);\n },\n\n // No auth required — the x402 proxy handles wallet-based payments internally.\n // The proxy auto-generates a wallet on first run and stores it at\n // ~/.openclaw/blockrun/wallet.key. Users just fund that wallet with USDC.\n auth: [],\n};\n","/**\n * Local x402 Proxy Server\n *\n * Sits between OpenClaw's pi-ai (which makes standard OpenAI-format requests)\n * and BlockRun's API (which requires x402 micropayments).\n *\n * Flow:\n * pi-ai → http://localhost:{port}/v1/chat/completions\n * → proxy forwards to https://blockrun.ai/api/v1/chat/completions\n * → gets 402 → @x402/fetch signs payment → retries\n * → streams response back to pi-ai\n *\n * Optimizations (v0.3.0):\n * - SSE heartbeat: for streaming requests, sends headers + heartbeat immediately\n * before the x402 flow, preventing OpenClaw's 10-15s timeout from firing.\n * - Response dedup: hashes request bodies and caches responses for 30s,\n * preventing double-charging when OpenClaw retries after timeout.\n * - Smart routing: when model is \"blockrun/auto\", classify query and pick cheapest model.\n * - Usage logging: log every request as JSON line to ~/.openclaw/blockrun/logs/\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\n\n// Per-request payment tracking via AsyncLocalStorage (safe for concurrent requests).\n// The x402 onAfterPaymentCreation hook writes the actual payment amount into the\n// request-scoped store, and the logging code reads it after payFetch completes.\nconst paymentStore = new AsyncLocalStorage<{ amountUsd: number }>();\nimport { finished } from \"node:stream\";\nimport type { AddressInfo } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdir, writeFile, readFile, stat as fsStat } from \"node:fs/promises\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { createPublicClient, http } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { x402Client } from \"@x402/fetch\";\nimport { createPayFetchWithPreAuth } from \"./payment-preauth.js\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { toClientEvmSigner } from \"@x402/evm\";\nimport {\n route,\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n DEFAULT_ROUTING_CONFIG,\n type RouterOptions,\n type RoutingDecision,\n type RoutingConfig,\n type ModelPricing,\n type Tier,\n} from \"./router/index.js\";\nimport { classifyByRules } from \"./router/rules.js\";\nimport {\n BLOCKRUN_MODELS,\n OPENCLAW_MODELS,\n resolveModelAlias,\n getModelContextWindow,\n isReasoningModel,\n supportsToolCalling,\n supportsVision,\n} from \"./models.js\";\nimport { logUsage, type UsageEntry } from \"./logger.js\";\nimport { getStats, clearStats } from \"./stats.js\";\nimport { RequestDeduplicator } from \"./dedup.js\";\nimport { ResponseCache, type ResponseCacheConfig } from \"./response-cache.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport type { SolanaBalanceMonitor } from \"./solana-balance.js\";\n\n/** Union type for chain-agnostic balance monitoring */\ntype AnyBalanceMonitor = BalanceMonitor | SolanaBalanceMonitor;\nimport { resolvePaymentChain } from \"./auth.js\";\nimport { compressContext, shouldCompress, type NormalizedMessage } from \"./compression/index.js\";\n// Error classes available for programmatic use but not used in proxy\n// (universal free fallback means we don't throw balance errors anymore)\n// import { InsufficientFundsError, EmptyWalletError } from \"./errors.js\";\nimport { USER_AGENT, VERSION } from \"./version.js\";\nimport {\n SessionStore,\n getSessionId,\n deriveSessionId,\n hashRequestContent,\n type SessionConfig,\n} from \"./session.js\";\nimport { checkForUpdates } from \"./updater.js\";\nimport { loadExcludeList } from \"./exclude-models.js\";\nimport { PROXY_PORT } from \"./config.js\";\nimport { SessionJournal } from \"./journal.js\";\n\nconst BLOCKRUN_API = \"https://blockrun.ai/api\";\nconst BLOCKRUN_SOLANA_API = \"https://sol.blockrun.ai/api\";\nconst IMAGE_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"images\");\n// Routing profile models - virtual models that trigger intelligent routing\nconst AUTO_MODEL = \"blockrun/auto\";\n\nconst ROUTING_PROFILES = new Set([\n \"blockrun/eco\",\n \"eco\",\n \"blockrun/auto\",\n \"auto\",\n \"blockrun/premium\",\n \"premium\",\n]);\nconst FREE_MODEL = \"free/gpt-oss-120b\"; // Last-resort single free model fallback\nconst FREE_MODELS = new Set([\n \"free/gpt-oss-120b\",\n \"free/gpt-oss-20b\",\n \"free/nemotron-ultra-253b\",\n \"free/nemotron-3-super-120b\",\n \"free/nemotron-super-49b\",\n \"free/deepseek-v3.2\",\n \"free/mistral-large-3-675b\",\n \"free/qwen3-coder-480b\",\n \"free/devstral-2-123b\",\n \"free/glm-4.7\",\n \"free/llama-4-maverick\",\n]);\n/**\n * Map free/xxx model IDs to nvidia/xxx for upstream BlockRun API.\n * The \"free/\" prefix is a ClawRouter convention for the /model picker;\n * BlockRun server expects \"nvidia/\" prefix.\n */\nfunction toUpstreamModelId(modelId: string): string {\n if (modelId.startsWith(\"free/\")) {\n return \"nvidia/\" + modelId.slice(\"free/\".length);\n }\n return modelId;\n}\nconst MAX_MESSAGES = 200; // BlockRun API limit - truncate older messages if exceeded\nconst CONTEXT_LIMIT_KB = 5120; // Server-side limit: 5MB in KB\nconst HEARTBEAT_INTERVAL_MS = 2_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 180_000; // 3 minutes (allows for on-chain tx + LLM response)\nconst PER_MODEL_TIMEOUT_MS = 60_000; // 60s per individual model attempt (fallback to next on exceed)\nconst MAX_FALLBACK_ATTEMPTS = 5; // Maximum models to try in fallback chain (increased from 3 to ensure cheap models are tried)\nconst HEALTH_CHECK_TIMEOUT_MS = 2_000; // Timeout for checking existing proxy\nconst RATE_LIMIT_COOLDOWN_MS = 60_000; // 60 seconds cooldown for rate-limited models\nconst OVERLOAD_COOLDOWN_MS = 15_000; // 15 seconds cooldown for overloaded providers\nconst PORT_RETRY_ATTEMPTS = 5; // Max attempts to bind port (handles TIME_WAIT)\nconst PORT_RETRY_DELAY_MS = 1_000; // Delay between retry attempts\nconst MODEL_BODY_READ_TIMEOUT_MS = 300_000; // 5 minutes for model responses (reasoning models are slow)\nconst ERROR_BODY_READ_TIMEOUT_MS = 30_000; // 30 seconds for error/partner body reads\n\nasync function readBodyWithTimeout(\n body: ReadableStream | null,\n timeoutMs: number = MODEL_BODY_READ_TIMEOUT_MS,\n): Promise {\n if (!body) return [];\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n\n let timer: ReturnType | undefined;\n try {\n while (true) {\n const result = await Promise.race([\n reader.read(),\n new Promise((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"Body read timeout\")), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (result.done) break;\n chunks.push(result.value);\n }\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n\n return chunks;\n}\n\n/**\n * Transform upstream payment errors into user-friendly messages.\n * Parses the raw x402 error and formats it nicely.\n */\nfunction transformPaymentError(errorBody: string): string {\n try {\n // Try to parse the error JSON\n const parsed = JSON.parse(errorBody) as {\n error?: string;\n details?: string;\n // blockrun-sol (Solana) format uses code+debug instead of details\n code?: string;\n debug?: string;\n payer?: string;\n };\n\n // Check if this is a payment verification error\n if (parsed.error === \"Payment verification failed\" && parsed.details) {\n // Extract the nested JSON from details\n // Format: \"Verification failed: {json}\\n\"\n const match = parsed.details.match(/Verification failed:\\s*(\\{.*\\})/s);\n if (match) {\n const innerJson = JSON.parse(match[1]) as {\n invalidMessage?: string;\n invalidReason?: string;\n payer?: string;\n };\n\n if (innerJson.invalidReason === \"insufficient_funds\" && innerJson.invalidMessage) {\n // Parse \"insufficient balance: 251 < 11463\"\n const balanceMatch = innerJson.invalidMessage.match(\n /insufficient balance:\\s*(\\d+)\\s*<\\s*(\\d+)/i,\n );\n if (balanceMatch) {\n const currentMicros = parseInt(balanceMatch[1], 10);\n const requiredMicros = parseInt(balanceMatch[2], 10);\n const currentUSD = (currentMicros / 1_000_000).toFixed(6);\n const requiredUSD = (requiredMicros / 1_000_000).toFixed(6);\n const wallet = innerJson.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n return JSON.stringify({\n error: {\n message: `Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,\n type: \"insufficient_funds\",\n wallet: wallet,\n current_balance_usd: currentUSD,\n required_usd: requiredUSD,\n help: `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free`,\n },\n });\n }\n }\n\n // Handle invalid_payload errors (signature issues, malformed payment)\n if (innerJson.invalidReason === \"invalid_payload\") {\n return JSON.stringify({\n error: {\n message: \"Payment signature invalid. This may be a temporary issue.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n // Handle transaction simulation failures (Solana on-chain validation)\n if (innerJson.invalidReason === \"transaction_simulation_failed\") {\n console.error(\n `[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage || \"unknown\"}`,\n );\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, check your Solana USDC balance or try: /model free\",\n },\n });\n }\n }\n }\n\n // Handle blockrun-sol (Solana) format: code=PAYMENT_INVALID + debug=invalidReason string\n if (\n parsed.error === \"Payment verification failed\" &&\n parsed.code === \"PAYMENT_INVALID\" &&\n parsed.debug\n ) {\n const debugLower = parsed.debug.toLowerCase();\n const wallet = parsed.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n if (debugLower.includes(\"insufficient\")) {\n return JSON.stringify({\n error: {\n message: \"Insufficient Solana USDC balance.\",\n type: \"insufficient_funds\",\n wallet,\n help: `Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base`,\n },\n });\n }\n\n if (\n debugLower.includes(\"transaction_simulation_failed\") ||\n debugLower.includes(\"simulation\")\n ) {\n console.error(`[ClawRouter] Solana transaction simulation failed: ${parsed.debug}`);\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n\n if (debugLower.includes(\"invalid signature\") || debugLower.includes(\"invalid_signature\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment signature invalid.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n if (debugLower.includes(\"expired\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment expired. Retrying.\",\n type: \"expired\",\n help: \"This is usually temporary.\",\n },\n });\n }\n\n // Unknown Solana verification error — surface the debug reason\n console.error(\n `[ClawRouter] Solana payment verification failed: ${parsed.debug} payer=${wallet}`,\n );\n return JSON.stringify({\n error: {\n message: `Solana payment verification failed: ${parsed.debug}`,\n type: \"payment_invalid\",\n wallet,\n help: \"Try again or switch to Base: /wallet base\",\n },\n });\n }\n\n // Handle settlement failures (gas estimation, on-chain errors)\n if (\n parsed.error === \"Settlement failed\" ||\n parsed.error === \"Payment settlement failed\" ||\n parsed.details?.includes(\"Settlement failed\") ||\n parsed.details?.includes(\"transaction_simulation_failed\")\n ) {\n const details = parsed.details || \"\";\n const gasError = details.includes(\"unable to estimate gas\");\n\n return JSON.stringify({\n error: {\n message: gasError\n ? \"Payment failed: network congestion or gas issue. Try again.\"\n : \"Payment settlement failed. Try again in a moment.\",\n type: \"settlement_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n } catch {\n // If parsing fails, return original\n }\n return errorBody;\n}\n\n/**\n * Semantic error categories from upstream provider responses.\n * Used to distinguish auth failures from rate limits from server errors\n * so each category can be handled independently without cross-contamination.\n */\nexport type ErrorCategory =\n | \"auth_failure\" // 401, 403: Wrong key or forbidden — don't retry with same key\n | \"quota_exceeded\" // 403 with plan/quota body: Plan limit hit\n | \"rate_limited\" // 429: Actual throttling — 60s cooldown\n | \"overloaded\" // 529, 503+overload body: Provider capacity — 15s cooldown\n | \"server_error\" // 5xx general: Transient — fallback immediately\n | \"payment_error\" // 402: x402 payment or funds issue\n | \"config_error\"; // 400, 413: Bad request content — skip this model\n\n/**\n * Classify an upstream error response into a semantic category.\n * Returns null if the status+body is not a provider-side issue worth retrying.\n */\nexport function categorizeError(status: number, body: string): ErrorCategory | null {\n if (status === 401) return \"auth_failure\";\n if (status === 402) return \"payment_error\";\n if (status === 403) {\n if (/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)) return \"quota_exceeded\";\n return \"auth_failure\"; // generic 403 = forbidden = likely auth issue\n }\n if (status === 429) return \"rate_limited\";\n if (status === 529) return \"overloaded\";\n if (status === 503 && /overload|capacity|too.*many.*request/i.test(body)) return \"overloaded\";\n if (status >= 500) return \"server_error\";\n if (status === 400 || status === 413) {\n // Only fallback on content-size or billing patterns; bare 400 = our bug, don't cycle\n if (PROVIDER_ERROR_PATTERNS.some((p) => p.test(body))) return \"config_error\";\n return null;\n }\n return null;\n}\n\n/**\n * Track rate-limited models to avoid hitting them again.\n * Maps model ID to the timestamp when the rate limit was hit.\n */\nconst rateLimitedModels = new Map();\n\n/** Per-model overload tracking (529/503 capacity errors) — shorter cooldown than rate limits. */\nconst overloadedModels = new Map();\n\n/** Per-model error category counts (in-memory, resets on restart). */\ntype ProviderErrorCounts = {\n auth_failure: number;\n quota_exceeded: number;\n rate_limited: number;\n overloaded: number;\n server_error: number;\n payment_error: number;\n config_error: number;\n};\nconst perProviderErrors = new Map();\n\n/** Record an error category hit for a model. */\nfunction recordProviderError(modelId: string, category: ErrorCategory): void {\n if (!perProviderErrors.has(modelId)) {\n perProviderErrors.set(modelId, {\n auth_failure: 0,\n quota_exceeded: 0,\n rate_limited: 0,\n overloaded: 0,\n server_error: 0,\n payment_error: 0,\n config_error: 0,\n });\n }\n perProviderErrors.get(modelId)![category]++;\n}\n\n/**\n * Check if a model is currently rate-limited (in cooldown period).\n */\nfunction isRateLimited(modelId: string): boolean {\n const hitTime = rateLimitedModels.get(modelId);\n if (!hitTime) return false;\n\n const elapsed = Date.now() - hitTime;\n if (elapsed >= RATE_LIMIT_COOLDOWN_MS) {\n rateLimitedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Mark a model as rate-limited.\n */\nfunction markRateLimited(modelId: string): void {\n rateLimitedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`);\n}\n\n/**\n * Mark a model as temporarily overloaded (529/503 capacity).\n * Shorter cooldown than rate limits since capacity restores quickly.\n */\nfunction markOverloaded(modelId: string): void {\n overloadedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`);\n}\n\n/** Check if a model is in its overload cooldown period. */\nfunction isOverloaded(modelId: string): boolean {\n const hitTime = overloadedModels.get(modelId);\n if (!hitTime) return false;\n if (Date.now() - hitTime >= OVERLOAD_COOLDOWN_MS) {\n overloadedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Reorder models to put rate-limited ones at the end.\n */\nfunction prioritizeNonRateLimited(models: string[]): string[] {\n const available: string[] = [];\n const degraded: string[] = [];\n\n for (const model of models) {\n if (isRateLimited(model) || isOverloaded(model)) {\n degraded.push(model);\n } else {\n available.push(model);\n }\n }\n\n return [...available, ...degraded];\n}\n\n/**\n * Check if response socket is writable (prevents write-after-close errors).\n * Returns true only if all conditions are safe for writing.\n */\nfunction canWrite(res: ServerResponse): boolean {\n return (\n !res.writableEnded &&\n !res.destroyed &&\n res.socket !== null &&\n !res.socket.destroyed &&\n res.socket.writable\n );\n}\n\n/**\n * Safe write with backpressure handling.\n * Returns true if write succeeded, false if socket is closed or write failed.\n */\nfunction safeWrite(res: ServerResponse, data: string | Buffer): boolean {\n if (!canWrite(res)) {\n const bytes = typeof data === \"string\" ? Buffer.byteLength(data) : data.length;\n console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`);\n return false;\n }\n return res.write(data);\n}\n\n// Extra buffer for balance check (on top of estimateAmount's 20% buffer)\n// Total effective buffer: 1.2 * 1.5 = 1.8x (80% safety margin)\n// This prevents x402 payment failures after streaming headers are sent,\n// which would trigger OpenClaw's 5-24 hour billing cooldown.\nconst BALANCE_CHECK_BUFFER = 1.5;\n\n/**\n * Get the proxy port from pre-loaded configuration.\n * Port is validated at module load time, this just returns the cached value.\n */\nexport function getProxyPort(): number {\n return PROXY_PORT;\n}\n\n/**\n * Check if a proxy is already running on the given port.\n * Returns the wallet address if running, undefined otherwise.\n */\nasync function checkExistingProxy(\n port: number,\n): Promise<{ wallet: string; paymentChain?: string } | undefined> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);\n\n try {\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const data = (await response.json()) as {\n status?: string;\n wallet?: string;\n paymentChain?: string;\n };\n if (data.status === \"ok\" && data.wallet) {\n return { wallet: data.wallet, paymentChain: data.paymentChain };\n }\n }\n return undefined;\n } catch {\n clearTimeout(timeoutId);\n return undefined;\n }\n}\n\n/**\n * Error patterns that indicate a provider-side issue (not user's fault).\n * These errors should trigger fallback to the next model in the chain.\n */\nconst PROVIDER_ERROR_PATTERNS = [\n /billing/i,\n /insufficient.*balance/i,\n /credits/i,\n /quota.*exceeded/i,\n /rate.*limit/i,\n /model.*unavailable/i,\n /model.*not.*available/i,\n /service.*unavailable/i,\n /capacity/i,\n /overloaded/i,\n /temporarily.*unavailable/i,\n /api.*key.*invalid/i,\n /authentication.*failed/i,\n /request too large/i,\n /request.*size.*exceeds/i,\n /payload too large/i,\n /payment.*verification.*failed/i,\n /model.*not.*allowed/i,\n /unknown.*model/i,\n];\n\n/**\n * \"Successful\" response bodies that are actually provider degradation placeholders.\n * Some upstream providers occasionally return these with HTTP 200.\n */\nconst DEGRADED_RESPONSE_PATTERNS = [\n /the ai service is temporarily overloaded/i,\n /service is temporarily overloaded/i,\n /please try again in a moment/i,\n];\n\n/**\n * Known low-quality loop signatures seen during provider degradation windows.\n */\nconst DEGRADED_LOOP_PATTERNS = [\n /the boxed is the response\\./i,\n /the response is the text\\./i,\n /the final answer is the boxed\\./i,\n];\n\nfunction extractAssistantContent(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") return undefined;\n const record = payload as Record;\n const choices = record.choices;\n if (!Array.isArray(choices) || choices.length === 0) return undefined;\n\n const firstChoice = choices[0];\n if (!firstChoice || typeof firstChoice !== \"object\") return undefined;\n const choice = firstChoice as Record;\n const message = choice.message;\n if (!message || typeof message !== \"object\") return undefined;\n const content = (message as Record).content;\n return typeof content === \"string\" ? content : undefined;\n}\n\nfunction hasKnownLoopSignature(text: string): boolean {\n const matchCount = DEGRADED_LOOP_PATTERNS.reduce(\n (count, pattern) => (pattern.test(text) ? count + 1 : count),\n 0,\n );\n if (matchCount >= 2) return true;\n\n // Generic repetitive loop fallback for short repeated lines.\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n if (lines.length < 8) return false;\n\n const counts = new Map();\n for (const line of lines) {\n counts.set(line, (counts.get(line) ?? 0) + 1);\n }\n\n const maxRepeat = Math.max(...counts.values());\n const uniqueRatio = counts.size / lines.length;\n return maxRepeat >= 3 && uniqueRatio <= 0.45;\n}\n\n/**\n * Detect degraded 200-response payloads that should trigger model fallback.\n * Returns a short reason when fallback should happen, otherwise undefined.\n */\nexport function detectDegradedSuccessResponse(body: string): string | undefined {\n const trimmed = body.trim();\n if (!trimmed) return undefined;\n\n // Plain-text placeholder response.\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(trimmed))) {\n return \"degraded response: overloaded placeholder\";\n }\n\n // Plain-text looping garbage response.\n if (hasKnownLoopSignature(trimmed)) {\n return \"degraded response: repetitive loop output\";\n }\n\n try {\n const parsed = JSON.parse(trimmed) as Record;\n\n // Some providers return JSON error payloads with HTTP 200.\n const errorField = parsed.error;\n let errorText = \"\";\n if (typeof errorField === \"string\") {\n errorText = errorField;\n } else if (errorField && typeof errorField === \"object\") {\n const errObj = errorField as Record;\n errorText = [\n typeof errObj.message === \"string\" ? errObj.message : \"\",\n typeof errObj.type === \"string\" ? errObj.type : \"\",\n typeof errObj.code === \"string\" ? errObj.code : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n }\n if (errorText && PROVIDER_ERROR_PATTERNS.some((pattern) => pattern.test(errorText))) {\n return `degraded response: ${errorText.slice(0, 120)}`;\n }\n\n // Successful wrapper with bad assistant content.\n const assistantContent = extractAssistantContent(parsed);\n if (!assistantContent) return undefined;\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(assistantContent))) {\n return \"degraded response: overloaded assistant content\";\n }\n if (hasKnownLoopSignature(assistantContent)) {\n return \"degraded response: repetitive assistant loop\";\n }\n } catch {\n // Not JSON - handled by plaintext checks above.\n }\n\n return undefined;\n}\n\n/**\n * Valid message roles for OpenAI-compatible APIs.\n * Some clients send non-standard roles (e.g., \"developer\" instead of \"system\").\n */\nconst VALID_ROLES = new Set([\"system\", \"user\", \"assistant\", \"tool\", \"function\"]);\n\n/**\n * Role mappings for non-standard roles.\n * Maps client-specific roles to standard OpenAI roles.\n */\nconst ROLE_MAPPINGS: Record = {\n developer: \"system\", // OpenAI's newer API uses \"developer\" for system messages\n model: \"assistant\", // Some APIs use \"model\" instead of \"assistant\"\n};\n\ntype ChatMessage = { role: string; content: string | unknown };\n\n/**\n * Anthropic tool ID pattern: only alphanumeric, underscore, and hyphen allowed.\n * Error: \"messages.X.content.Y.tool_use.id: String should match pattern '^[a-zA-Z0-9_-]+$'\"\n */\nconst VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\n/**\n * Sanitize a tool ID to match Anthropic's required pattern.\n * Replaces invalid characters with underscores.\n */\nfunction sanitizeToolId(id: string | undefined): string | undefined {\n if (!id || typeof id !== \"string\") return id;\n if (VALID_TOOL_ID_PATTERN.test(id)) return id;\n\n // Replace invalid characters with underscores\n return id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n}\n\n/**\n * Type for messages with tool calls (OpenAI format).\n */\ntype MessageWithTools = ChatMessage & {\n tool_calls?: Array<{ id?: string; type?: string; function?: unknown }>;\n tool_call_id?: string;\n};\n\n/**\n * Type for content blocks that may contain tool IDs (Anthropic format in OpenAI wrapper).\n */\ntype ContentBlock = {\n type?: string;\n id?: string;\n tool_use_id?: string;\n [key: string]: unknown;\n};\n\n/**\n * Sanitize all tool IDs in messages to match Anthropic's pattern.\n * Handles both OpenAI format (tool_calls, tool_call_id) and content block formats.\n */\nfunction sanitizeToolIds(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const sanitized = messages.map((msg) => {\n const typedMsg = msg as MessageWithTools;\n let msgChanged = false;\n let newMsg = { ...msg } as MessageWithTools;\n\n // Sanitize tool_calls[].id in assistant messages\n if (typedMsg.tool_calls && Array.isArray(typedMsg.tool_calls)) {\n const newToolCalls = typedMsg.tool_calls.map((tc) => {\n if (tc.id && typeof tc.id === \"string\") {\n const sanitized = sanitizeToolId(tc.id);\n if (sanitized !== tc.id) {\n msgChanged = true;\n return { ...tc, id: sanitized };\n }\n }\n return tc;\n });\n if (msgChanged) {\n newMsg = { ...newMsg, tool_calls: newToolCalls };\n }\n }\n\n // Sanitize tool_call_id in tool messages\n if (typedMsg.tool_call_id && typeof typedMsg.tool_call_id === \"string\") {\n const sanitized = sanitizeToolId(typedMsg.tool_call_id);\n if (sanitized !== typedMsg.tool_call_id) {\n msgChanged = true;\n newMsg = { ...newMsg, tool_call_id: sanitized };\n }\n }\n\n // Sanitize content blocks if content is an array (Anthropic-style content)\n if (Array.isArray(typedMsg.content)) {\n const newContent = (typedMsg.content as ContentBlock[]).map((block) => {\n if (!block || typeof block !== \"object\") return block;\n\n let blockChanged = false;\n let newBlock = { ...block };\n\n // tool_use blocks have \"id\"\n if (block.type === \"tool_use\" && block.id && typeof block.id === \"string\") {\n const sanitized = sanitizeToolId(block.id);\n if (sanitized !== block.id) {\n blockChanged = true;\n newBlock = { ...newBlock, id: sanitized };\n }\n }\n\n // tool_result blocks have \"tool_use_id\"\n if (\n block.type === \"tool_result\" &&\n block.tool_use_id &&\n typeof block.tool_use_id === \"string\"\n ) {\n const sanitized = sanitizeToolId(block.tool_use_id);\n if (sanitized !== block.tool_use_id) {\n blockChanged = true;\n newBlock = { ...newBlock, tool_use_id: sanitized };\n }\n }\n\n if (blockChanged) {\n msgChanged = true;\n return newBlock;\n }\n return block;\n });\n\n if (msgChanged) {\n newMsg = { ...newMsg, content: newContent };\n }\n }\n\n if (msgChanged) {\n hasChanges = true;\n return newMsg;\n }\n return msg;\n });\n\n return hasChanges ? sanitized : messages;\n}\n\n/**\n * Normalize message roles to standard OpenAI format.\n * Converts non-standard roles (e.g., \"developer\") to valid ones.\n */\nfunction normalizeMessageRoles(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n if (VALID_ROLES.has(msg.role)) return msg;\n\n const mappedRole = ROLE_MAPPINGS[msg.role];\n if (mappedRole) {\n hasChanges = true;\n return { ...msg, role: mappedRole };\n }\n\n // Unknown role - default to \"user\" to avoid API errors\n hasChanges = true;\n return { ...msg, role: \"user\" };\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Normalize messages for Google models.\n * Google's Gemini API requires the first non-system message to be from \"user\".\n * If conversation starts with \"assistant\"/\"model\", prepend a placeholder user message.\n */\n\nfunction normalizeMessagesForGoogle(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n // Find first non-system message\n let firstNonSystemIdx = -1;\n for (let i = 0; i < messages.length; i++) {\n if (messages[i].role !== \"system\") {\n firstNonSystemIdx = i;\n break;\n }\n }\n\n // If no non-system messages, return as-is\n if (firstNonSystemIdx === -1) return messages;\n\n const firstRole = messages[firstNonSystemIdx].role;\n\n // If first non-system message is already \"user\", no change needed\n if (firstRole === \"user\") return messages;\n\n // If first non-system message is \"assistant\" or \"model\", prepend a user message\n if (firstRole === \"assistant\" || firstRole === \"model\") {\n const normalized = [...messages];\n normalized.splice(firstNonSystemIdx, 0, {\n role: \"user\",\n content: \"(continuing conversation)\",\n });\n return normalized;\n }\n\n return messages;\n}\n\n/**\n * Check if a model is a Google model that requires message normalization.\n */\nfunction isGoogleModel(modelId: string): boolean {\n return modelId.startsWith(\"google/\") || modelId.startsWith(\"gemini\");\n}\n\n/**\n * Extended message type for thinking-enabled conversations.\n */\ntype ExtendedChatMessage = ChatMessage & {\n tool_calls?: unknown[];\n reasoning_content?: unknown;\n};\n\n/**\n * Normalize messages for thinking-enabled requests.\n * When thinking/extended_thinking is enabled, assistant messages with tool_calls\n * must have reasoning_content (can be empty string if not present).\n * Error: \"400 thinking is enabled but reasoning_content is missing in assistant tool call message\"\n */\nfunction normalizeMessagesForThinking(messages: ExtendedChatMessage[]): ExtendedChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n // Skip if not assistant or already has reasoning_content\n if (msg.role !== \"assistant\" || msg.reasoning_content !== undefined) {\n return msg;\n }\n\n // Check for OpenAI format: tool_calls array\n const hasOpenAIToolCalls =\n msg.tool_calls && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;\n\n // Check for Anthropic format: content array with tool_use blocks\n const hasAnthropicToolUse =\n Array.isArray(msg.content) &&\n (msg.content as Array<{ type?: string }>).some((block) => block?.type === \"tool_use\");\n\n if (hasOpenAIToolCalls || hasAnthropicToolUse) {\n hasChanges = true;\n return { ...msg, reasoning_content: \"\" };\n }\n return msg;\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Remove \"blockrun\" branding from system messages before sending upstream.\n *\n * OpenClaw embeds `model=blockrun/auto` and `default_model=blockrun/auto` in its\n * system prompt Runtime section. LLMs pick up \"blockrun\" and adopt it as their\n * identity (e.g. \"I'm Blockrun\"), overriding the user's SOUL.md persona.\n *\n * This function replaces `blockrun/` references with the actual resolved\n * model name, and strips any remaining \"blockrun/\" prefix so the upstream LLM\n * never sees \"blockrun\" as an identity to adopt.\n */\nexport function debrandSystemMessages(\n messages: ChatMessage[],\n resolvedModel: string,\n): ChatMessage[] {\n // Routing profile names that get replaced with the actual model\n const PROFILE_NAMES = [\"auto\", \"free\", \"eco\", \"premium\"];\n const profilePattern = new RegExp(`\\\\bblockrun/(${PROFILE_NAMES.join(\"|\")})\\\\b`, \"gi\");\n // Also handle \"blockrun//\" → \"/\"\n const prefixPattern = /\\bblockrun\\/(?=[a-z])/gi;\n\n let hasChanges = false;\n const result = messages.map((msg) => {\n if (msg.role !== \"system\" || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n\n // Replace routing profiles (blockrun/auto etc.) with resolved model\n const afterProfiles = content.replace(profilePattern, resolvedModel);\n\n // Replace remaining blockrun/ prefix (e.g. blockrun/openai/gpt-4o → openai/gpt-4o)\n const afterPrefix = afterProfiles.replace(prefixPattern, \"\");\n\n if (afterPrefix !== content) {\n hasChanges = true;\n content = afterPrefix;\n }\n\n return content !== msg.content ? { ...msg, content } : msg;\n });\n\n return hasChanges ? result : messages;\n}\n\n/**\n * Result of truncating messages.\n */\ntype TruncationResult = {\n messages: T[];\n wasTruncated: boolean;\n originalCount: number;\n truncatedCount: number;\n};\n\n/**\n * Truncate messages to stay under BlockRun's MAX_MESSAGES limit.\n * Keeps all system messages and the most recent conversation history.\n * Returns the messages and whether truncation occurred.\n */\nfunction truncateMessages(messages: T[]): TruncationResult {\n if (!messages || messages.length <= MAX_MESSAGES) {\n return {\n messages,\n wasTruncated: false,\n originalCount: messages?.length ?? 0,\n truncatedCount: messages?.length ?? 0,\n };\n }\n\n // Separate system messages from conversation\n const systemMsgs = messages.filter((m) => m.role === \"system\");\n const conversationMsgs = messages.filter((m) => m.role !== \"system\");\n\n // Keep all system messages + most recent conversation messages\n const maxConversation = MAX_MESSAGES - systemMsgs.length;\n const truncatedConversation = conversationMsgs.slice(-maxConversation);\n\n const result = [...systemMsgs, ...truncatedConversation];\n\n console.log(\n `[ClawRouter] Truncated messages: ${messages.length} → ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`,\n );\n\n return {\n messages: result,\n wasTruncated: true,\n originalCount: messages.length,\n truncatedCount: result.length,\n };\n}\n\n// Kimi/Moonshot models use special Unicode tokens for thinking boundaries.\n// Pattern: <|begin▁of▁thinking|>content<|end▁of▁thinking|>\n// The | is fullwidth vertical bar (U+FF5C), ▁ is lower one-eighth block (U+2581).\n\n// Match full Kimi thinking blocks: <|begin...|>content<|end...|>\nconst KIMI_BLOCK_RE = /<[||][^<>]*begin[^<>]*[||]>[\\s\\S]*?<[||][^<>]*end[^<>]*[||]>/gi;\n\n// Match standalone Kimi tokens like <|end▁of▁thinking|>\nconst KIMI_TOKEN_RE = /<[||][^<>]*[||]>/g;\n\n// Standard thinking tags that may leak through from various models\nconst THINKING_TAG_RE = /<\\s*\\/?\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>/gi;\n\n// Full thinking blocks: content\nconst THINKING_BLOCK_RE =\n /<\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>[\\s\\S]*?<\\s*\\/\\s*(?:think(?:ing)?|thought|antthinking)\\s*>/gi;\n\n/**\n * Strip thinking tokens and blocks from model response content.\n * Handles both Kimi-style Unicode tokens and standard XML-style tags.\n *\n * NOTE: DSML tags (<|DSML|...>) are NOT stripped - those are tool calls\n * that should be handled by the API, not hidden from users.\n */\nfunction stripThinkingTokens(content: string): string {\n if (!content) return content;\n // Strip full Kimi thinking blocks first (begin...end with content)\n let cleaned = content.replace(KIMI_BLOCK_RE, \"\");\n // Strip remaining standalone Kimi tokens\n cleaned = cleaned.replace(KIMI_TOKEN_RE, \"\");\n // Strip full thinking blocks (...)\n cleaned = cleaned.replace(THINKING_BLOCK_RE, \"\");\n // Strip remaining standalone thinking tags\n cleaned = cleaned.replace(THINKING_TAG_RE, \"\");\n return cleaned;\n}\n\n/** Callback info for low balance warning */\nexport type LowBalanceInfo = {\n balanceUSD: string;\n walletAddress: string;\n};\n\n/** Callback info for insufficient funds error */\nexport type InsufficientFundsInfo = {\n balanceUSD: string;\n requiredUSD: string;\n walletAddress: string;\n};\n\n/**\n * Wallet config: either a plain EVM private key string, or the full\n * resolution object from resolveOrGenerateWalletKey() which may include\n * Solana keys. Using the full object prevents callers from accidentally\n * forgetting to forward Solana key bytes.\n */\nexport type WalletConfig = string | { key: string; solanaPrivateKeyBytes?: Uint8Array };\n\nexport type PaymentChain = \"base\" | \"solana\";\n\nexport type ProxyOptions = {\n wallet: WalletConfig;\n apiBase?: string;\n /** Payment chain: \"base\" (default) or \"solana\". Can also be set via CLAWROUTER_PAYMENT_CHAIN env var. */\n paymentChain?: PaymentChain;\n /** Port to listen on (default: 8402) */\n port?: number;\n routingConfig?: Partial;\n /** Request timeout in ms (default: 180000 = 3 minutes). Covers on-chain tx + LLM response. */\n requestTimeoutMs?: number;\n /** Skip balance checks (for testing only). Default: false */\n skipBalanceCheck?: boolean;\n /** Override the balance monitor with a mock (for testing only). */\n _balanceMonitorOverride?: AnyBalanceMonitor;\n /**\n * Session persistence config. When enabled, maintains model selection\n * across requests within a session to prevent mid-task model switching.\n */\n sessionConfig?: Partial;\n /**\n * Auto-compress large requests to reduce network usage.\n * When enabled, requests are automatically compressed using\n * LLM-safe context compression (15-40% reduction).\n * Default: true\n */\n autoCompressRequests?: boolean;\n /**\n * Threshold in KB to trigger auto-compression (default: 180).\n * Requests larger than this are compressed before sending.\n * Set to 0 to compress all requests.\n */\n compressionThresholdKB?: number;\n /**\n * Response caching config. When enabled, identical requests return\n * cached responses instead of making new API calls.\n * Default: enabled with 10 minute TTL, 200 max entries.\n */\n cacheConfig?: ResponseCacheConfig;\n /**\n * Maximum total spend (in USD) per session run.\n * Default: undefined (no limit). Example: 0.5 = $0.50 per session.\n */\n maxCostPerRunUsd?: number;\n /**\n * How to enforce the per-run cost cap.\n * - 'graceful' (default): when budget runs low, downgrade to cheaper models; use free model\n * as last resort. Only hard-stops when no model can serve the request.\n * - 'strict': immediately return 429 once the session spend reaches the cap.\n */\n maxCostPerRunMode?: \"graceful\" | \"strict\";\n /**\n * Set of model IDs to exclude from routing.\n * Excluded models are filtered out of fallback chains.\n * Loaded from ~/.openclaw/blockrun/exclude-models.json\n */\n excludeModels?: Set;\n onReady?: (port: number) => void;\n onError?: (error: Error) => void;\n onPayment?: (info: { model: string; amount: string; network: string }) => void;\n onRouted?: (decision: RoutingDecision) => void;\n /** Called when balance drops below $1.00 (warning, request still proceeds) */\n onLowBalance?: (info: LowBalanceInfo) => void;\n /** Called when balance is insufficient for a request (request fails) */\n onInsufficientFunds?: (info: InsufficientFundsInfo) => void;\n};\n\nexport type ProxyHandle = {\n port: number;\n baseUrl: string;\n walletAddress: string;\n solanaAddress?: string;\n balanceMonitor: AnyBalanceMonitor;\n close: () => Promise;\n};\n\n/**\n * Build model pricing map from BLOCKRUN_MODELS.\n */\nfunction buildModelPricing(): Map {\n const map = new Map();\n for (const m of BLOCKRUN_MODELS) {\n if (m.id === AUTO_MODEL) continue; // skip meta-model\n map.set(m.id, { inputPrice: m.inputPrice, outputPrice: m.outputPrice });\n }\n return map;\n}\n\ntype ModelListEntry = {\n id: string;\n object: \"model\";\n created: number;\n owned_by: string;\n};\n\n/**\n * Build `/v1/models` response entries from the full OpenClaw model registry.\n * This includes alias IDs (e.g., `flash`, `kimi`) so `/model ` works reliably.\n */\nexport function buildProxyModelList(\n createdAt: number = Math.floor(Date.now() / 1000),\n): ModelListEntry[] {\n const seen = new Set();\n return OPENCLAW_MODELS.filter((model) => {\n if (seen.has(model.id)) return false;\n seen.add(model.id);\n return true;\n }).map((model) => ({\n id: model.id,\n object: \"model\",\n created: createdAt,\n owned_by: model.id.includes(\"/\") ? (model.id.split(\"/\")[0] ?? \"blockrun\") : \"blockrun\",\n }));\n}\n\n/**\n * Merge partial routing config overrides with defaults.\n */\nfunction mergeRoutingConfig(overrides?: Partial): RoutingConfig {\n if (!overrides) return DEFAULT_ROUTING_CONFIG;\n return {\n ...DEFAULT_ROUTING_CONFIG,\n ...overrides,\n classifier: { ...DEFAULT_ROUTING_CONFIG.classifier, ...overrides.classifier },\n scoring: { ...DEFAULT_ROUTING_CONFIG.scoring, ...overrides.scoring },\n tiers: { ...DEFAULT_ROUTING_CONFIG.tiers, ...overrides.tiers },\n overrides: { ...DEFAULT_ROUTING_CONFIG.overrides, ...overrides.overrides },\n };\n}\n\n/**\n * Estimate USDC cost for a request based on model pricing.\n * Returns amount string in USDC smallest unit (6 decimals) or undefined if unknown.\n */\nfunction estimateAmount(\n modelId: string,\n bodyLength: number,\n maxTokens: number,\n): string | undefined {\n const model = BLOCKRUN_MODELS.find((m) => m.id === modelId);\n if (!model) return undefined;\n\n // Rough estimate: ~4 chars per token for input\n const estimatedInputTokens = Math.ceil(bodyLength / 4);\n const estimatedOutputTokens = maxTokens || model.maxOutput || 4096;\n\n const costUsd =\n (estimatedInputTokens / 1_000_000) * model.inputPrice +\n (estimatedOutputTokens / 1_000_000) * model.outputPrice;\n\n // Convert to USDC 6-decimal integer, add 20% buffer for estimation error\n // Minimum 1000 ($0.001) to match CDP Facilitator's enforced minimum payment\n const amountMicros = Math.max(1000, Math.ceil(costUsd * 1.2 * 1_000_000));\n return amountMicros.toString();\n}\n\n// Image pricing table (must match server's IMAGE_MODELS in blockrun/src/lib/models.ts)\n// Server applies 5% margin on top of these prices.\nconst IMAGE_PRICING: Record }> = {\n \"openai/dall-e-3\": {\n default: 0.04,\n sizes: { \"1024x1024\": 0.04, \"1792x1024\": 0.08, \"1024x1792\": 0.08 },\n },\n \"openai/gpt-image-1\": {\n default: 0.02,\n sizes: { \"1024x1024\": 0.02, \"1536x1024\": 0.04, \"1024x1536\": 0.04 },\n },\n \"black-forest/flux-1.1-pro\": { default: 0.04 },\n \"google/nano-banana\": { default: 0.05 },\n \"google/nano-banana-pro\": {\n default: 0.1,\n sizes: { \"1024x1024\": 0.1, \"2048x2048\": 0.1, \"4096x4096\": 0.15 },\n },\n};\n\n/**\n * Estimate the cost of an image generation/editing request.\n * Matches server-side calculateImagePrice() including 5% margin.\n */\nfunction estimateImageCost(model: string, size?: string, n: number = 1): number {\n const pricing = IMAGE_PRICING[model];\n if (!pricing) return 0.04 * n * 1.05; // fallback: assume $0.04/image + margin\n const sizePrice = size && pricing.sizes ? pricing.sizes[size] : undefined;\n const pricePerImage = sizePrice ?? pricing.default;\n return pricePerImage * n * 1.05; // 5% server margin\n}\n\n/**\n * Proxy a partner API request through x402 payment flow.\n *\n * Simplified proxy for partner endpoints (/v1/x/*, /v1/partner/*).\n * No smart routing, SSE, compression, or sessions — just collect body,\n * forward via payFetch (which handles 402 automatically), and stream back.\n */\nasync function proxyPartnerRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n getActualPaymentUsd: () => number,\n): Promise {\n const startTime = Date.now();\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const body = Buffer.concat(bodyChunks);\n\n // Forward headers (strip hop-by-hop)\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") headers[key] = value;\n }\n if (!headers[\"content-type\"]) headers[\"content-type\"] = \"application/json\";\n headers[\"user-agent\"] = USER_AGENT;\n\n console.log(`[ClawRouter] Partner request: ${req.method} ${req.url}`);\n\n const upstream = await payFetch(upstreamUrl, {\n method: req.method ?? \"POST\",\n headers,\n body: body.length > 0 ? new Uint8Array(body) : undefined,\n });\n\n // Forward response headers\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\") return;\n responseHeaders[key] = value;\n });\n\n res.writeHead(upstream.status, responseHeaders);\n\n // Stream response body\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body, ERROR_BODY_READ_TIMEOUT_MS);\n for (const chunk of chunks) {\n safeWrite(res, Buffer.from(chunk));\n }\n }\n\n res.end();\n\n const latencyMs = Date.now() - startTime;\n console.log(`[ClawRouter] Partner response: ${upstream.status} (${latencyMs}ms)`);\n\n // Log partner usage with actual x402 payment amount (previously logged cost: 0)\n const partnerCost = getActualPaymentUsd();\n logUsage({\n timestamp: new Date().toISOString(),\n model: \"partner\",\n tier: \"PARTNER\",\n cost: partnerCost,\n baselineCost: partnerCost,\n savings: 0,\n latencyMs,\n partnerId:\n (req.url?.split(\"?\")[0] ?? \"\").replace(/^\\/v1\\//, \"\").replace(/\\//g, \"_\") || \"unknown\",\n service: \"partner\",\n }).catch(() => {});\n}\n\n/**\n * Read a local image file and return it as a base64 data URI.\n * Supports ~/ home directory expansion.\n */\nfunction readImageFileAsDataUri(filePath: string): string {\n const resolved = filePath.startsWith(\"~/\") ? join(homedir(), filePath.slice(2)) : filePath;\n\n if (!existsSync(resolved)) {\n throw new Error(`Image file not found: ${resolved}`);\n }\n\n const ext = resolved.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mimeMap: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n };\n const mime = mimeMap[ext] ?? \"image/png\";\n const data = readFileSync(resolved);\n return `data:${mime};base64,${data.toString(\"base64\")}`;\n}\n\n/**\n * Upload a base64 data URI to catbox.moe and return a public URL.\n * Google image models (nano-banana) return data URIs instead of hosted URLs,\n * which breaks Telegram and other clients that can't render raw base64.\n */\nasync function uploadDataUriToHost(dataUri: string): Promise {\n const match = dataUri.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (!match) throw new Error(\"Invalid data URI format\");\n const [, mimeType, b64Data] = match;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType.split(\"/\")[1] ?? \"png\");\n\n const buffer = Buffer.from(b64Data, \"base64\");\n const blob = new Blob([buffer], { type: mimeType });\n\n const form = new FormData();\n form.append(\"reqtype\", \"fileupload\");\n form.append(\"fileToUpload\", blob, `image.${ext}`);\n\n const uploadController = new AbortController();\n const uploadTimeout = setTimeout(() => uploadController.abort(), 30_000);\n try {\n const resp = await fetch(\"https://catbox.moe/user/api.php\", {\n method: \"POST\",\n body: form,\n signal: uploadController.signal,\n });\n\n if (!resp.ok) throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);\n const result = await resp.text();\n if (result.startsWith(\"https://\")) {\n return result.trim();\n }\n throw new Error(`catbox.moe upload failed: ${result}`);\n } finally {\n clearTimeout(uploadTimeout);\n }\n}\n\n/**\n * Start the local x402 proxy server.\n *\n * If a proxy is already running on the target port, reuses it instead of failing.\n * Port can be configured via BLOCKRUN_PROXY_PORT environment variable.\n *\n * Returns a handle with the assigned port, base URL, and a close function.\n */\nexport async function startProxy(options: ProxyOptions): Promise {\n // Normalize wallet config: string = EVM-only, object = full resolution\n const walletKey = typeof options.wallet === \"string\" ? options.wallet : options.wallet.key;\n const solanaPrivateKeyBytes =\n typeof options.wallet === \"string\" ? undefined : options.wallet.solanaPrivateKeyBytes;\n\n // Payment chain: options > env var > persisted file > default \"base\".\n // No dynamic switching — user selects chain via /wallet solana or /wallet base.\n const paymentChain = options.paymentChain ?? (await resolvePaymentChain());\n const apiBase =\n options.apiBase ??\n (paymentChain === \"solana\" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API);\n if (paymentChain === \"solana\" && !solanaPrivateKeyBytes) {\n console.warn(\n `[ClawRouter] ⚠ Payment chain is Solana but no mnemonic found — falling back to Base (EVM).`,\n );\n console.warn(\n `[ClawRouter] To fix: run \"npx @blockrun/clawrouter wallet recover\" if your mnemonic exists,`,\n );\n console.warn(`[ClawRouter] or run \"npx @blockrun/clawrouter chain base\" to switch to EVM.`);\n } else if (paymentChain === \"solana\") {\n console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`);\n }\n\n // Determine port: options.port > env var > default\n const listenPort = options.port ?? getProxyPort();\n\n // Check if a proxy is already running on this port\n const existingProxy = await checkExistingProxy(listenPort);\n if (existingProxy) {\n // Proxy already running — reuse it instead of failing with EADDRINUSE\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const baseUrl = `http://127.0.0.1:${listenPort}`;\n\n // Verify the existing proxy is using the same wallet (or warn if different)\n if (existingProxy.wallet !== account.address) {\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account.address}. Reusing existing proxy.`,\n );\n }\n\n // Verify the existing proxy is using the same payment chain\n if (existingProxy.paymentChain) {\n if (existingProxy.paymentChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${existingProxy.paymentChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n } else if (paymentChain !== \"base\") {\n // Old proxy doesn't report chain — assume Base. Reject if Solana was requested.\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`,\n );\n throw new Error(\n `Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n\n // Derive Solana address if keys are available (for wallet status display)\n let reuseSolanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n reuseSolanaAddress = solanaSigner.address;\n }\n\n // Use chain-appropriate balance monitor (lazy import to avoid loading @solana/kit on Base chain)\n let balanceMonitor: AnyBalanceMonitor;\n if (paymentChain === \"solana\" && reuseSolanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n balanceMonitor = new SolanaBalanceMonitor(reuseSolanaAddress);\n } else {\n balanceMonitor = new BalanceMonitor(account.address);\n }\n\n options.onReady?.(listenPort);\n\n return {\n port: listenPort,\n baseUrl,\n walletAddress: existingProxy.wallet,\n solanaAddress: reuseSolanaAddress,\n balanceMonitor,\n close: async () => {\n // No-op: we didn't start this proxy, so we shouldn't close it\n },\n };\n }\n\n // Create x402 payment client with EVM scheme (always available)\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const evmPublicClient = createPublicClient({ chain: base, transport: http() });\n const evmSigner = toClientEvmSigner(account, evmPublicClient);\n const x402 = new x402Client();\n registerExactEvmScheme(x402, { signer: evmSigner });\n\n // Register Solana scheme if key is available\n // Uses registerExactSvmScheme helper which registers:\n // - solana:* wildcard (catches any CAIP-2 Solana network)\n // - V1 compat names: \"solana\", \"solana-devnet\", \"solana-testnet\"\n let solanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { registerExactSvmScheme } = await import(\"@x402/svm/exact/client\");\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n solanaAddress = solanaSigner.address;\n registerExactSvmScheme(x402, { signer: solanaSigner });\n console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`);\n }\n\n // Log which chain is used for each payment and capture actual payment amount\n x402.onAfterPaymentCreation(async (context) => {\n const network = context.selectedRequirements.network;\n const chain = network.startsWith(\"eip155\")\n ? \"Base (EVM)\"\n : network.startsWith(\"solana\")\n ? \"Solana\"\n : network;\n // Capture actual payment amount in USD (amount is in USDC micro units, 6 decimals)\n const amountMicros = parseInt(context.selectedRequirements.amount || \"0\", 10);\n const amountUsd = amountMicros / 1_000_000;\n // Write to request-scoped store (if available)\n const store = paymentStore.getStore();\n if (store) store.amountUsd = amountUsd;\n console.log(`[ClawRouter] Payment signed on ${chain} (${network}) — $${amountUsd.toFixed(6)}`);\n });\n\n const payFetch = createPayFetchWithPreAuth(fetch, x402, undefined, {\n skipPreAuth: paymentChain === \"solana\",\n });\n\n // Create balance monitor for pre-request checks (lazy import to avoid loading @solana/kit on Base chain)\n let balanceMonitor: AnyBalanceMonitor;\n if (options._balanceMonitorOverride) {\n balanceMonitor = options._balanceMonitorOverride;\n } else if (paymentChain === \"solana\" && solanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n balanceMonitor = new SolanaBalanceMonitor(solanaAddress);\n } else {\n balanceMonitor = new BalanceMonitor(account.address);\n }\n\n // Build router options (100% local — no external API calls for routing)\n const routingConfig = mergeRoutingConfig(options.routingConfig);\n const modelPricing = buildModelPricing();\n const routerOpts: RouterOptions = {\n config: routingConfig,\n modelPricing,\n };\n\n // Request deduplicator (shared across all requests)\n const deduplicator = new RequestDeduplicator();\n\n // Response cache for identical requests (longer TTL than dedup)\n const responseCache = new ResponseCache(options.cacheConfig);\n\n // Session store for model persistence (prevents mid-task model switching)\n const sessionStore = new SessionStore(options.sessionConfig);\n\n // Session journal for memory (enables agents to recall earlier work)\n const sessionJournal = new SessionJournal();\n\n // Track active connections for graceful cleanup\n const connections = new Set();\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n // Wrap in paymentStore.run() so x402 hook can write actual payment amount per-request\n paymentStore.run({ amountUsd: 0 }, async () => {\n // Add stream error handlers to prevent server crashes\n req.on(\"error\", (err) => {\n console.error(`[ClawRouter] Request stream error: ${err.message}`);\n // Don't throw - just log and let request handler deal with it\n });\n\n res.on(\"error\", (err) => {\n console.error(`[ClawRouter] Response stream error: ${err.message}`);\n // Don't try to write to failed socket - just log\n });\n\n // Finished wrapper for guaranteed cleanup on response completion/error\n finished(res, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Response finished with error: ${err.message}`);\n }\n // Note: heartbeatInterval cleanup happens in res.on(\"close\") handler\n // Note: completed and dedup cleanup happens in the res.on(\"close\") handler below\n });\n\n // Request finished wrapper for complete stream lifecycle tracking\n finished(req, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Request finished with error: ${err.message}`);\n }\n });\n\n // Health check with optional balance info\n if (req.url === \"/health\" || req.url?.startsWith(\"/health?\")) {\n const url = new URL(req.url, \"http://localhost\");\n const full = url.searchParams.get(\"full\") === \"true\";\n\n const response: Record = {\n status: \"ok\",\n wallet: account.address,\n paymentChain,\n };\n if (solanaAddress) {\n response.solana = solanaAddress;\n }\n\n if (full) {\n try {\n const balanceInfo = await balanceMonitor.checkBalance();\n response.balance = balanceInfo.balanceUSD;\n response.isLow = balanceInfo.isLow;\n response.isEmpty = balanceInfo.isEmpty;\n } catch {\n response.balanceError = \"Could not fetch balance\";\n }\n }\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(response));\n return;\n }\n\n // Cache stats endpoint\n if (req.url === \"/cache\" || req.url?.startsWith(\"/cache?\")) {\n const stats = responseCache.getStats();\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(JSON.stringify(stats, null, 2));\n return;\n }\n\n // Stats clear endpoint - delete all log files\n if (req.url === \"/stats\" && req.method === \"DELETE\") {\n try {\n const result = await clearStats();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ cleared: true, deletedFiles: result.deletedFiles }));\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // Stats API endpoint - returns JSON for programmatic access\n if (req.url === \"/stats\" || req.url?.startsWith(\"/stats?\")) {\n try {\n const url = new URL(req.url, \"http://localhost\");\n const days = parseInt(url.searchParams.get(\"days\") || \"7\", 10);\n const stats = await getStats(Math.min(days, 30));\n\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(\n JSON.stringify(\n {\n ...stats,\n providerErrors: Object.fromEntries(perProviderErrors),\n },\n null,\n 2,\n ),\n );\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to get stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // --- Handle /v1/models locally (no upstream call needed) ---\n if (req.url === \"/v1/models\" && req.method === \"GET\") {\n const models = buildProxyModelList();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ object: \"list\", data: models }));\n return;\n }\n\n // --- Serve locally cached images (~/.openclaw/blockrun/images/) ---\n if (req.url?.startsWith(\"/images/\") && req.method === \"GET\") {\n const filename = req.url\n .slice(\"/images/\".length)\n .split(\"?\")[0]!\n .replace(/[^a-zA-Z0-9._-]/g, \"\");\n if (!filename) {\n res.writeHead(400);\n res.end(\"Bad request\");\n return;\n }\n const filePath = join(IMAGE_DIR, filename);\n try {\n const s = await fsStat(filePath);\n if (!s.isFile()) throw new Error(\"not a file\");\n const ext = filename.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mime: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n };\n const data = await readFile(filePath);\n res.writeHead(200, {\n \"Content-Type\": mime[ext] ?? \"application/octet-stream\",\n \"Content-Length\": data.length,\n });\n res.end(data);\n } catch {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image not found\" }));\n }\n return;\n }\n\n // --- Handle /v1/images/generations: proxy with x402 payment + save data URIs locally ---\n // NOTE: image generation endpoints bypass maxCostPerRun budget tracking entirely.\n // Cost is charged via x402 micropayment directly — no session accumulation or cap enforcement.\n if (req.url === \"/v1/images/generations\" && req.method === \"POST\") {\n const imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const reqBody = Buffer.concat(chunks);\n // Parse request for usage logging\n let imgModel = \"unknown\";\n let imgCost = 0;\n try {\n const parsed = JSON.parse(reqBody.toString());\n imgModel = parsed.model || \"openai/dall-e-3\";\n const n = parsed.n || 1;\n imgCost = estimateImageCost(imgModel, parsed.size, n);\n } catch {\n /* use defaults */\n }\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/generations`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image generation usage with actual x402 payment (previously missing entirely)\n const imgActualCost = paymentStore.getStore()?.amountUsd ?? imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: imgModel,\n tier: \"IMAGE\",\n cost: imgActualCost,\n baselineCost: imgActualCost,\n savings: 0,\n latencyMs: Date.now() - imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image generation error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image generation failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle /v1/images/image2image: proxy with x402 payment + save images locally ---\n // Accepts image as: data URI, local file path, ~/path, or HTTP(S) URL\n if (req.url === \"/v1/images/image2image\" && req.method === \"POST\") {\n const img2imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const rawBody = Buffer.concat(chunks);\n\n // Resolve image/mask fields: file paths and URLs → data URIs\n let reqBody: string;\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgModel = \"openai/gpt-image-1\";\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgCost = 0;\n try {\n const parsed = JSON.parse(rawBody.toString());\n for (const field of [\"image\", \"mask\"] as const) {\n const val = parsed[field];\n if (typeof val !== \"string\" || !val) continue;\n if (val.startsWith(\"data:\")) {\n // Already a data URI — pass through\n } else if (val.startsWith(\"https://\") || val.startsWith(\"http://\")) {\n // Download URL → data URI\n const imgResp = await fetch(val);\n if (!imgResp.ok)\n throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const buf = Buffer.from(await imgResp.arrayBuffer());\n parsed[field] = `data:${contentType};base64,${buf.toString(\"base64\")}`;\n console.log(\n `[ClawRouter] img2img: downloaded ${field} URL → data URI (${buf.length} bytes)`,\n );\n } else {\n // Local file path → data URI\n parsed[field] = readImageFileAsDataUri(val);\n console.log(`[ClawRouter] img2img: read ${field} file → data URI`);\n }\n }\n // Default model if not specified\n if (!parsed.model) parsed.model = \"openai/gpt-image-1\";\n img2imgModel = parsed.model;\n img2imgCost = estimateImageCost(img2imgModel, parsed.size, parsed.n || 1);\n reqBody = JSON.stringify(parsed);\n } catch (parseErr) {\n const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\", details: msg }));\n return;\n }\n\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image editing usage with actual x402 payment (previously missing entirely)\n const img2imgActualCost = paymentStore.getStore()?.amountUsd ?? img2imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost,\n baselineCost: img2imgActualCost,\n savings: 0,\n latencyMs: Date.now() - img2imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image editing error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image editing failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle partner API paths (/v1/x/*, /v1/partner/*) ---\n if (req.url?.match(/^\\/v1\\/(?:x|partner)\\//)) {\n try {\n await proxyPartnerRequest(\n req,\n res,\n apiBase,\n payFetch,\n () => paymentStore.getStore()?.amountUsd ?? 0,\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Partner proxy error: ${error.message}`, type: \"partner_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Only proxy paths starting with /v1\n if (!req.url?.startsWith(\"/v1\")) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not found\" }));\n return;\n }\n\n try {\n await proxyRequest(\n req,\n res,\n apiBase,\n payFetch,\n options,\n routerOpts,\n deduplicator,\n balanceMonitor,\n sessionStore,\n responseCache,\n sessionJournal,\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Proxy error: ${error.message}`, type: \"proxy_error\" },\n }),\n );\n } else if (!res.writableEnded) {\n // Headers already sent (streaming) — send error as SSE event\n res.write(\n `data: ${JSON.stringify({ error: { message: error.message, type: \"proxy_error\" } })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n }\n }\n }); // end paymentStore.run()\n });\n\n // Listen on configured port with retry logic for TIME_WAIT handling\n // When gateway restarts quickly, the port may still be in TIME_WAIT state.\n // We retry with delay instead of incorrectly assuming a proxy is running.\n const tryListen = (attempt: number): Promise => {\n return new Promise((resolveAttempt, rejectAttempt) => {\n const onError = async (err: NodeJS.ErrnoException) => {\n server.removeListener(\"error\", onError);\n\n if (err.code === \"EADDRINUSE\") {\n // Port is in use - check if a proxy is actually running\n const existingProxy2 = await checkExistingProxy(listenPort);\n if (existingProxy2) {\n // Proxy is actually running - this is fine, reuse it\n console.log(`[ClawRouter] Existing proxy detected on port ${listenPort}, reusing`);\n rejectAttempt({\n code: \"REUSE_EXISTING\",\n wallet: existingProxy2.wallet,\n existingChain: existingProxy2.paymentChain,\n });\n return;\n }\n\n // Port is in TIME_WAIT (no proxy responding) - retry after delay\n if (attempt < PORT_RETRY_ATTEMPTS) {\n console.log(\n `[ClawRouter] Port ${listenPort} in TIME_WAIT, retrying in ${PORT_RETRY_DELAY_MS}ms (attempt ${attempt}/${PORT_RETRY_ATTEMPTS})`,\n );\n rejectAttempt({ code: \"RETRY\", attempt });\n return;\n }\n\n // Max retries exceeded\n console.error(\n `[ClawRouter] Port ${listenPort} still in use after ${PORT_RETRY_ATTEMPTS} attempts`,\n );\n rejectAttempt(err);\n return;\n }\n\n rejectAttempt(err);\n };\n\n server.once(\"error\", onError);\n server.listen(listenPort, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onError);\n resolveAttempt();\n });\n });\n };\n\n // Retry loop for port binding\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= PORT_RETRY_ATTEMPTS; attempt++) {\n try {\n await tryListen(attempt);\n break; // Success\n } catch (err: unknown) {\n const error = err as {\n code?: string;\n wallet?: string;\n existingChain?: string;\n attempt?: number;\n };\n\n if (error.code === \"REUSE_EXISTING\" && error.wallet) {\n // Validate payment chain matches (same check as pre-listen reuse path)\n if (error.existingChain && error.existingChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${error.existingChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n { cause: err },\n );\n }\n\n // Proxy is running, reuse it\n const baseUrl = `http://127.0.0.1:${listenPort}`;\n options.onReady?.(listenPort);\n return {\n port: listenPort,\n baseUrl,\n walletAddress: error.wallet,\n balanceMonitor,\n close: async () => {\n // No-op: we didn't start this proxy, so we shouldn't close it\n },\n };\n }\n\n if (error.code === \"RETRY\") {\n // Wait before retry\n await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS));\n continue;\n }\n\n // Other error - throw\n lastError = err as Error;\n break;\n }\n }\n\n if (lastError) {\n throw lastError;\n }\n\n // Server is now listening - set up remaining handlers\n const addr = server.address() as AddressInfo;\n const port = addr.port;\n const baseUrl = `http://127.0.0.1:${port}`;\n\n options.onReady?.(port);\n\n // Check for updates (non-blocking)\n checkForUpdates();\n\n // Add runtime error handler AFTER successful listen\n // This handles errors that occur during server operation (not just startup)\n server.on(\"error\", (err) => {\n console.error(`[ClawRouter] Server runtime error: ${err.message}`);\n options.onError?.(err);\n // Don't crash - log and continue\n });\n\n // Handle client connection errors (bad requests, socket errors)\n server.on(\"clientError\", (err, socket) => {\n console.error(`[ClawRouter] Client error: ${err.message}`);\n // Send 400 Bad Request if socket is still writable\n if (socket.writable && !socket.destroyed) {\n socket.end(\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\");\n }\n });\n\n // Track connections for graceful cleanup\n server.on(\"connection\", (socket) => {\n connections.add(socket);\n\n // Set 5-minute timeout for streaming requests\n socket.setTimeout(300_000);\n\n socket.on(\"timeout\", () => {\n console.error(`[ClawRouter] Socket timeout, destroying connection`);\n socket.destroy();\n });\n\n socket.on(\"end\", () => {\n // Half-closed by client (FIN received)\n });\n\n socket.on(\"error\", (err) => {\n console.error(`[ClawRouter] Socket error: ${err.message}`);\n });\n\n socket.on(\"close\", () => {\n connections.delete(socket);\n });\n });\n\n return {\n port,\n baseUrl,\n walletAddress: account.address,\n solanaAddress,\n balanceMonitor,\n close: () =>\n new Promise((res, rej) => {\n const timeout = setTimeout(() => {\n rej(new Error(\"[ClawRouter] Close timeout after 4s\"));\n }, 4000);\n\n sessionStore.close();\n // Destroy all active connections before closing server\n for (const socket of connections) {\n socket.destroy();\n }\n connections.clear();\n server.close((err) => {\n clearTimeout(timeout);\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n }),\n };\n}\n\n/** Result of attempting a model request */\ntype ModelRequestResult = {\n success: boolean;\n response?: Response;\n errorBody?: string;\n errorStatus?: number;\n isProviderError?: boolean;\n errorCategory?: ErrorCategory; // Semantic error classification\n};\n\n/**\n * Attempt a request with a specific model.\n * Returns the response or error details for fallback decision.\n */\nasync function tryModelRequest(\n upstreamUrl: string,\n method: string,\n headers: Record,\n body: Buffer,\n modelId: string,\n maxTokens: number,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n balanceMonitor: AnyBalanceMonitor,\n signal: AbortSignal,\n): Promise {\n // Update model in body and normalize messages\n let requestBody = body;\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(modelId);\n\n // Normalize message roles (e.g., \"developer\" -> \"system\")\n if (Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessageRoles(parsed.messages as ChatMessage[]);\n }\n\n // Remove \"blockrun\" branding from system messages so upstream LLMs don't\n // adopt \"Blockrun\" as their identity (overriding user's SOUL.md persona).\n if (Array.isArray(parsed.messages)) {\n parsed.messages = debrandSystemMessages(parsed.messages as ChatMessage[], modelId);\n }\n\n // Truncate messages to stay under BlockRun's limit (200 messages)\n if (Array.isArray(parsed.messages)) {\n const truncationResult = truncateMessages(parsed.messages as ChatMessage[]);\n parsed.messages = truncationResult.messages;\n }\n\n // Sanitize tool IDs to match Anthropic's pattern (alphanumeric, underscore, hyphen only)\n if (Array.isArray(parsed.messages)) {\n parsed.messages = sanitizeToolIds(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for Google models (first non-system message must be \"user\")\n if (isGoogleModel(modelId) && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForGoogle(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for thinking-enabled requests (add reasoning_content to tool calls)\n // Check request flags AND target model - reasoning models have thinking enabled server-side\n const hasThinkingEnabled = !!(\n parsed.thinking ||\n parsed.extended_thinking ||\n isReasoningModel(modelId)\n );\n if (hasThinkingEnabled && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForThinking(parsed.messages as ExtendedChatMessage[]);\n }\n\n requestBody = Buffer.from(JSON.stringify(parsed));\n } catch {\n // If body isn't valid JSON, use as-is\n }\n\n try {\n const response = await payFetch(upstreamUrl, {\n method,\n headers,\n body: requestBody.length > 0 ? new Uint8Array(requestBody) : undefined,\n signal,\n });\n\n // Check for provider errors\n if (response.status !== 200) {\n // Clone response to read body without consuming it\n const errorBodyChunks = await readBodyWithTimeout(response.body, ERROR_BODY_READ_TIMEOUT_MS);\n const errorBody = Buffer.concat(errorBodyChunks).toString();\n const category = categorizeError(response.status, errorBody);\n\n return {\n success: false,\n errorBody,\n errorStatus: response.status,\n isProviderError: category !== null,\n errorCategory: category ?? undefined,\n };\n }\n\n // Detect provider degradation hidden inside HTTP 200 responses.\n const contentType = response.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"json\") || contentType.includes(\"text\")) {\n try {\n const clonedChunks = await readBodyWithTimeout(\n response.clone().body,\n ERROR_BODY_READ_TIMEOUT_MS,\n );\n const responseBody = Buffer.concat(clonedChunks).toString();\n const degradedReason = detectDegradedSuccessResponse(responseBody);\n if (degradedReason) {\n return {\n success: false,\n errorBody: degradedReason,\n errorStatus: 503,\n isProviderError: true,\n };\n }\n } catch {\n // Ignore body inspection failures and pass through response.\n }\n }\n\n return { success: true, response };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return {\n success: false,\n errorBody: errorMsg,\n errorStatus: 500,\n isProviderError: true, // Network errors are retryable\n };\n }\n}\n\n/**\n * Proxy a single request through x402 payment flow to BlockRun API.\n *\n * Optimizations applied in order:\n * 1. Dedup check — if same request body seen within 30s, replay cached response\n * 2. Streaming heartbeat — for stream:true, send 200 + heartbeats immediately\n * 3. Smart routing — when model is \"blockrun/auto\", pick cheapest capable model\n * 4. Fallback chain — on provider errors, try next model in tier's fallback list\n */\nasync function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n options: ProxyOptions,\n routerOpts: RouterOptions,\n deduplicator: RequestDeduplicator,\n balanceMonitor: AnyBalanceMonitor,\n sessionStore: SessionStore,\n responseCache: ResponseCache,\n sessionJournal: SessionJournal,\n): Promise {\n const startTime = Date.now();\n\n // Build upstream URL: /v1/chat/completions → https://blockrun.ai/api/v1/chat/completions\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n let body = Buffer.concat(bodyChunks);\n\n // Track original context size for response headers\n const originalContextSizeKB = Math.ceil(body.length / 1024);\n\n // Routing debug info is on by default; disable with x-clawrouter-debug: false\n const debugMode = req.headers[\"x-clawrouter-debug\"] !== \"false\";\n\n // --- Smart routing ---\n let routingDecision: RoutingDecision | undefined;\n let hasTools = false; // true when request includes a tools schema\n let hasVision = false; // true when request includes image_url content parts\n let isStreaming = false;\n let modelId = \"\";\n let maxTokens = 4096;\n let routingProfile: \"eco\" | \"auto\" | \"premium\" | null = null;\n let balanceFallbackNotice: string | undefined;\n let budgetDowngradeNotice: string | undefined;\n let budgetDowngradeHeaderMode: \"downgraded\" | undefined;\n let accumulatedContent = \"\"; // For session journal event extraction\n let responseInputTokens: number | undefined;\n let responseOutputTokens: number | undefined;\n const isChatCompletion = req.url?.includes(\"/chat/completions\");\n\n // Extract session ID early for journal operations (header-only at this point)\n const sessionId = getSessionId(req.headers as Record);\n // Full session ID (header + content-derived) — populated once messages are parsed\n let effectiveSessionId: string | undefined = sessionId;\n\n if (isChatCompletion && body.length > 0) {\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n isStreaming = parsed.stream === true;\n modelId = (parsed.model as string) || \"\";\n maxTokens = (parsed.max_tokens as number) || 4096;\n let bodyModified = false;\n\n // Extract last user message content (used by session journal + /debug command)\n const parsedMessages = Array.isArray(parsed.messages)\n ? (parsed.messages as Array<{ role: string; content: unknown }>)\n : [];\n const lastUserMsg = [...parsedMessages].reverse().find((m) => m.role === \"user\");\n\n // Early tool detection for ALL request types (explicit model + routing profile).\n // The routing-profile branch may re-assign below (no-op since same value).\n hasTools = Array.isArray(parsed.tools) && (parsed.tools as unknown[]).length > 0;\n const rawLastContent = lastUserMsg?.content;\n const lastContent =\n typeof rawLastContent === \"string\"\n ? rawLastContent\n : Array.isArray(rawLastContent)\n ? (rawLastContent as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n\n // --- Session Journal: Inject context if needed ---\n // Check if the last user message asks about past work\n if (sessionId && parsedMessages.length > 0) {\n const messages = parsedMessages;\n\n if (sessionJournal.needsContext(lastContent)) {\n const journalText = sessionJournal.format(sessionId);\n if (journalText) {\n // Find system message and prepend journal, or add a new system message\n const sysIdx = messages.findIndex((m) => m.role === \"system\");\n if (sysIdx >= 0 && typeof messages[sysIdx].content === \"string\") {\n messages[sysIdx] = {\n ...messages[sysIdx],\n content: journalText + \"\\n\\n\" + messages[sysIdx].content,\n };\n } else {\n messages.unshift({ role: \"system\", content: journalText });\n }\n parsed.messages = messages;\n bodyModified = true;\n console.log(\n `[ClawRouter] Injected session journal (${journalText.length} chars) for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n }\n\n // --- /debug command: return routing diagnostics without calling upstream ---\n if (lastContent.startsWith(\"/debug\")) {\n const debugPrompt = lastContent.slice(\"/debug\".length).trim() || \"hello\";\n const messages = parsed.messages as Array<{ role: string; content: unknown }>;\n const systemMsg = messages?.find((m) => m.role === \"system\");\n const systemPrompt = typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n const fullText = `${systemPrompt ?? \"\"} ${debugPrompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // Determine routing profile\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n const profileName = normalizedModel.replace(\"blockrun/\", \"\");\n const debugProfile = (\n [\"eco\", \"auto\", \"premium\"].includes(profileName) ? profileName : \"auto\"\n ) as \"eco\" | \"auto\" | \"premium\";\n\n // Run scoring\n const scoring = classifyByRules(\n debugPrompt,\n systemPrompt,\n estimatedTokens,\n DEFAULT_ROUTING_CONFIG.scoring,\n );\n\n // Run full routing decision\n const debugRouting = route(debugPrompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: debugProfile,\n });\n\n // Format dimension scores\n const dimLines = (scoring.dimensions ?? [])\n .map((d) => {\n const nameStr = (d.name + \":\").padEnd(24);\n const scoreStr = d.score.toFixed(2).padStart(6);\n const sigStr = d.signal ? ` [${d.signal}]` : \"\";\n return ` ${nameStr}${scoreStr}${sigStr}`;\n })\n .join(\"\\n\");\n\n // Session info\n const sess = sessionId ? sessionStore.getSession(sessionId) : undefined;\n const sessLine = sess\n ? `Session: ${sessionId!.slice(0, 8)}... → pinned: ${sess.model} (${sess.requestCount} requests)`\n : sessionId\n ? `Session: ${sessionId.slice(0, 8)}... → no pinned model`\n : \"Session: none\";\n\n const { simpleMedium, mediumComplex, complexReasoning } =\n DEFAULT_ROUTING_CONFIG.scoring.tierBoundaries;\n\n const debugText = [\n \"ClawRouter Debug\",\n \"\",\n `Profile: ${debugProfile} | Tier: ${debugRouting.tier} | Model: ${debugRouting.model}`,\n `Confidence: ${debugRouting.confidence.toFixed(2)} | Cost: $${debugRouting.costEstimate.toFixed(4)} | Savings: ${(debugRouting.savings * 100).toFixed(0)}%`,\n `Reasoning: ${debugRouting.reasoning}`,\n \"\",\n `Scoring (weighted: ${scoring.score.toFixed(3)})`,\n dimLines,\n \"\",\n `Tier Boundaries: SIMPLE <${simpleMedium.toFixed(2)} | MEDIUM <${mediumComplex.toFixed(2)} | COMPLEX <${complexReasoning.toFixed(2)} | REASONING >=${complexReasoning.toFixed(2)}`,\n \"\",\n sessLine,\n ].join(\"\\n\");\n\n // Build synthetic OpenAI chat completion response\n const completionId = `chatcmpl-debug-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n const syntheticResponse = {\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: debugText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n\n if (isStreaming) {\n // SSE streaming response\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n const sseChunk = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n delta: { role: \"assistant\", content: debugText },\n finish_reason: null,\n },\n ],\n };\n const sseDone = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }],\n };\n res.write(`data: ${JSON.stringify(sseChunk)}\\n\\n`);\n res.write(`data: ${JSON.stringify(sseDone)}\\n\\n`);\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(syntheticResponse));\n }\n console.log(`[ClawRouter] /debug command → ${debugRouting.tier} | ${debugRouting.model}`);\n return;\n }\n\n // --- /imagegen command: generate an image via BlockRun image API ---\n if (lastContent.startsWith(\"/imagegen\")) {\n const imageArgs = lastContent.slice(\"/imagegen\".length).trim();\n\n // Parse optional flags: /imagegen --model dall-e-3 --size 1792x1024 a cute cat\n let imageModel = \"google/nano-banana\";\n let imageSize = \"1024x1024\";\n let imagePrompt = imageArgs;\n\n // Extract --model flag\n const modelMatch = imageArgs.match(/--model\\s+(\\S+)/);\n if (modelMatch) {\n const raw = modelMatch[1];\n // Resolve shorthand aliases\n const IMAGE_MODEL_ALIASES: Record = {\n \"dall-e-3\": \"openai/dall-e-3\",\n dalle3: \"openai/dall-e-3\",\n dalle: \"openai/dall-e-3\",\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n flux: \"black-forest/flux-1.1-pro\",\n \"flux-pro\": \"black-forest/flux-1.1-pro\",\n banana: \"google/nano-banana\",\n \"nano-banana\": \"google/nano-banana\",\n \"banana-pro\": \"google/nano-banana-pro\",\n \"nano-banana-pro\": \"google/nano-banana-pro\",\n };\n imageModel = IMAGE_MODEL_ALIASES[raw] ?? raw;\n imagePrompt = imagePrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n // Extract --size flag\n const sizeMatch = imageArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (sizeMatch) {\n imageSize = sizeMatch[1];\n imagePrompt = imagePrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n if (!imagePrompt) {\n const errorText = [\n \"Usage: /imagegen \",\n \"\",\n \"Options:\",\n \" --model Model to use (default: nano-banana)\",\n \" --size Image size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" nano-banana Google Gemini Flash — $0.05/image\",\n \" banana-pro Google Gemini Pro — $0.10/image (up to 4K)\",\n \" dall-e-3 OpenAI DALL-E 3 — $0.04/image\",\n \" gpt-image OpenAI GPT Image 1 — $0.02/image\",\n \" flux Black Forest Flux 1.1 Pro — $0.04/image\",\n \"\",\n \"Examples:\",\n \" /imagegen a cat wearing sunglasses\",\n \" /imagegen --model dall-e-3 a futuristic city at sunset\",\n \" /imagegen --model banana-pro --size 2048x2048 mountain landscape\",\n ].join(\"\\n\");\n\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: errorText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: errorText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n console.log(`[ClawRouter] /imagegen command → showing usage help`);\n return;\n }\n\n // Call upstream image generation API\n console.log(\n `[ClawRouter] /imagegen command → ${imageModel} (${imageSize}): ${imagePrompt.slice(0, 80)}...`,\n );\n try {\n const imageUpstreamUrl = `${apiBase}/v1/images/generations`;\n const imageBody = JSON.stringify({\n model: imageModel,\n prompt: imagePrompt,\n size: imageSize,\n n: 1,\n });\n const imageResponse = await payFetch(imageUpstreamUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: imageBody,\n });\n\n const imageResult = (await imageResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!imageResponse.ok || imageResult.error) {\n const errMsg =\n typeof imageResult.error === \"string\"\n ? imageResult.error\n : ((imageResult.error as { message?: string })?.message ??\n `HTTP ${imageResponse.status}`);\n responseText = `Image generation failed: ${errMsg}`;\n console.log(`[ClawRouter] /imagegen error: ${errMsg}`);\n } else {\n const images = imageResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image generation returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /imagegen: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\n \"Image generated but upload failed. Try again or use --model dall-e-3.\",\n );\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${imageModel} | Size: ${imageSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /imagegen success: ${images.length} image(s) generated`);\n // Log /imagegen usage with actual x402 payment\n const imagegenActualCost =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(imageModel, imageSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: imageModel,\n tier: \"IMAGE\",\n cost: imagegenActualCost,\n baselineCost: imagegenActualCost,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n // Return as synthetic chat completion\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: responseText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: responseText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /imagegen error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image generation failed: ${errMsg}`, type: \"image_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // --- /img2img command: edit an image via BlockRun image2image API ---\n if (lastContent.startsWith(\"/img2img\")) {\n const imgArgs = lastContent.slice(\"/img2img\".length).trim();\n\n let img2imgModel = \"openai/gpt-image-1\";\n let img2imgSize = \"1024x1024\";\n let imagePath: string | null = null;\n let maskPath: string | null = null;\n let img2imgPrompt = imgArgs;\n\n const imageMatch = imgArgs.match(/--image\\s+(\\S+)/);\n if (imageMatch) {\n imagePath = imageMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--image\\s+\\S+/, \"\").trim();\n }\n\n const maskMatch = imgArgs.match(/--mask\\s+(\\S+)/);\n if (maskMatch) {\n maskPath = maskMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--mask\\s+\\S+/, \"\").trim();\n }\n\n const img2imgSizeMatch = imgArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (img2imgSizeMatch) {\n img2imgSize = img2imgSizeMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n const img2imgModelMatch = imgArgs.match(/--model\\s+(\\S+)/);\n if (img2imgModelMatch) {\n const raw = img2imgModelMatch[1];\n const IMG2IMG_ALIASES: Record = {\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n };\n img2imgModel = IMG2IMG_ALIASES[raw] ?? raw;\n img2imgPrompt = img2imgPrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n const usageText = [\n \"Usage: /img2img --image \",\n \"\",\n \"Options:\",\n \" --image Source image path (required)\",\n \" --mask Mask image path (optional, white = area to edit)\",\n \" --model Model (default: gpt-image-1)\",\n \" --size Output size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" gpt-image-1 OpenAI GPT Image 1 — $0.02/image\",\n \"\",\n \"Examples:\",\n \" /img2img --image ~/photo.png change background to starry sky\",\n \" /img2img --image ./cat.jpg --mask ./mask.png remove the background\",\n \" /img2img --image /tmp/portrait.png --size 1536x1024 add a hat\",\n ].join(\"\\n\");\n\n const sendImg2ImgText = (text: string) => {\n const completionId = `chatcmpl-img2img-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: { role: \"assistant\", content: text }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/img2img\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n };\n\n if (!imagePath || !img2imgPrompt) {\n sendImg2ImgText(usageText);\n return;\n }\n\n let imageDataUri: string;\n let maskDataUri: string | undefined;\n try {\n imageDataUri = readImageFileAsDataUri(imagePath);\n if (maskPath) maskDataUri = readImageFileAsDataUri(maskPath);\n } catch (fileErr) {\n const fileErrMsg = fileErr instanceof Error ? fileErr.message : String(fileErr);\n sendImg2ImgText(`Failed to read image file: ${fileErrMsg}`);\n return;\n }\n\n console.log(\n `[ClawRouter] /img2img → ${img2imgModel} (${img2imgSize}): ${img2imgPrompt.slice(0, 80)}`,\n );\n\n try {\n const img2imgBody = JSON.stringify({\n model: img2imgModel,\n prompt: img2imgPrompt,\n image: imageDataUri,\n ...(maskDataUri ? { mask: maskDataUri } : {}),\n size: img2imgSize,\n n: 1,\n });\n\n const img2imgResponse = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: img2imgBody,\n });\n\n const img2imgResult = (await img2imgResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!img2imgResponse.ok || img2imgResult.error) {\n const errMsg =\n typeof img2imgResult.error === \"string\"\n ? img2imgResult.error\n : ((img2imgResult.error as { message?: string })?.message ??\n `HTTP ${img2imgResponse.status}`);\n responseText = `Image editing failed: ${errMsg}`;\n console.log(`[ClawRouter] /img2img error: ${errMsg}`);\n } else {\n const images = img2imgResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image editing returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /img2img: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\"Image edited but upload failed. Try again.\");\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${img2imgModel} | Size: ${img2imgSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /img2img success: ${images.length} image(s)`);\n // Log /img2img usage with actual x402 payment\n const img2imgActualCost2 =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(img2imgModel, img2imgSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost2,\n baselineCost: img2imgActualCost2,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n sendImg2ImgText(responseText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /img2img error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image editing failed: ${errMsg}`, type: \"img2img_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Force stream: false — BlockRun API doesn't support streaming yet\n // ClawRouter handles SSE heartbeat simulation for upstream compatibility\n if (parsed.stream === true) {\n parsed.stream = false;\n bodyModified = true;\n }\n\n // Normalize model name for comparison (trim whitespace, lowercase)\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n\n // Resolve model aliases (e.g., \"claude\" -> \"anthropic/claude-sonnet-4-6\")\n const resolvedModel = resolveModelAlias(normalizedModel);\n const wasAlias = resolvedModel !== normalizedModel;\n\n // Check both normalizedModel and resolvedModel — OpenClaw may send \"openai/eco\"\n // which resolveModelAlias strips to \"eco\" (a valid routing profile)\n const isRoutingProfile =\n ROUTING_PROFILES.has(normalizedModel) || ROUTING_PROFILES.has(resolvedModel);\n\n // Extract routing profile type (free/eco/auto/premium)\n if (isRoutingProfile) {\n const profileName = resolvedModel.replace(\"blockrun/\", \"\");\n routingProfile = profileName as \"eco\" | \"auto\" | \"premium\";\n }\n\n // Debug: log received model name\n console.log(\n `[ClawRouter] Received model: \"${parsed.model}\" -> normalized: \"${normalizedModel}\"${wasAlias ? ` -> alias: \"${resolvedModel}\"` : \"\"}${routingProfile ? `, profile: ${routingProfile}` : \"\"}`,\n );\n\n // For explicit model requests, always canonicalize the model ID before upstream calls.\n // This ensures case/whitespace variants (e.g. \"DEEPSEEK/...\" or \" model \") route correctly.\n if (!isRoutingProfile) {\n if (parsed.model !== resolvedModel) {\n parsed.model = resolvedModel;\n bodyModified = true;\n }\n modelId = resolvedModel;\n }\n\n // Handle routing profiles (free/eco/auto/premium)\n if (isRoutingProfile) {\n {\n // eco/auto/premium - use tier routing\n // Check for session persistence - use pinned model if available\n // Fall back to deriving a session ID from message content when OpenClaw\n // doesn't send an explicit x-session-id header (the default behaviour).\n effectiveSessionId =\n getSessionId(req.headers as Record) ??\n deriveSessionId(parsedMessages);\n const existingSession = effectiveSessionId\n ? sessionStore.getSession(effectiveSessionId)\n : undefined;\n\n // Extract prompt from last user message (handles both string and Anthropic array content)\n const rawPrompt = lastUserMsg?.content;\n const prompt =\n typeof rawPrompt === \"string\"\n ? rawPrompt\n : Array.isArray(rawPrompt)\n ? (rawPrompt as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n const systemMsg = parsedMessages.find((m) => m.role === \"system\");\n const systemPrompt =\n typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n\n // Tool detection — when tools are present, force agentic tiers for reliable tool use\n const tools = parsed.tools as unknown[] | undefined;\n hasTools = Array.isArray(tools) && tools.length > 0;\n\n if (hasTools && tools) {\n console.log(`[ClawRouter] Tools detected (${tools.length}), forcing agentic tiers`);\n }\n\n // Vision detection: scan messages for image_url content parts\n hasVision = parsedMessages.some((m) => {\n if (Array.isArray(m.content)) {\n return (m.content as Array<{ type: string }>).some((p) => p.type === \"image_url\");\n }\n return false;\n });\n if (hasVision) {\n console.log(`[ClawRouter] Vision content detected, filtering to vision-capable models`);\n }\n\n // Always route based on current request content\n routingDecision = route(prompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: routingProfile ?? undefined,\n hasTools,\n });\n\n // Keep agentic routing when tools are present, even for SIMPLE queries.\n // Tool-using requests need models with reliable function-call support;\n // demoting to non-agentic tiers causes fallback to models that refuse\n // tool schemas (gemini-flash-lite, deepseek) or lack tool support entirely.\n if (hasTools && routingDecision.tier === \"SIMPLE\") {\n console.log(\n `[ClawRouter] SIMPLE+tools: keeping agentic model ${routingDecision.model} (tools need reliable function-call support)`,\n );\n }\n\n if (existingSession) {\n // Never downgrade: only upgrade the session when the current request needs a higher\n // tier. This fixes the OpenClaw startup-message bias (the startup message always\n // scores low-complexity, which previously pinned all subsequent real queries to a\n // cheap model) while still preventing mid-task model switching on simple follow-ups.\n const tierRank: Record = {\n SIMPLE: 0,\n MEDIUM: 1,\n COMPLEX: 2,\n REASONING: 3,\n };\n const existingRank = tierRank[existingSession.tier] ?? 0;\n const newRank = tierRank[routingDecision.tier] ?? 0;\n\n if (newRank > existingRank) {\n // Current request needs higher capability — upgrade the session\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... upgrading: ${existingSession.tier} → ${routingDecision.tier} (${routingDecision.model})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n }\n } else if (routingDecision.tier === \"SIMPLE\") {\n // SIMPLE follow-up in an active session: let it use cheap routing.\n // e.g. \"你好\" or \"thanks\" after a complex task should not inherit the\n // expensive session model or recount all context tokens on a paid model.\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... SIMPLE follow-up, using cheap model: ${routingDecision.model} (bypassing pinned ${existingSession.tier})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // routingDecision already reflects cheap model — no override needed\n } else {\n // Keep existing higher-tier model (prevent downgrade mid-task)\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... keeping pinned model: ${existingSession.model} (${existingSession.tier} >= ${routingDecision.tier})`,\n );\n parsed.model = existingSession.model;\n modelId = existingSession.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // Reflect the actual model used in the routing decision for logging/fallback\n routingDecision = {\n ...routingDecision,\n model: existingSession.model,\n tier: existingSession.tier as Tier,\n };\n }\n\n // --- Three-strike escalation: detect repetitive request patterns ---\n const lastAssistantMsg = [...parsedMessages]\n .reverse()\n .find((m) => m.role === \"assistant\");\n const assistantToolCalls = (\n lastAssistantMsg as { tool_calls?: Array<{ function?: { name?: string } }> }\n )?.tool_calls;\n const toolCallNames = Array.isArray(assistantToolCalls)\n ? assistantToolCalls\n .map((tc) => tc.function?.name)\n .filter((n): n is string => Boolean(n))\n : undefined;\n const contentHash = hashRequestContent(prompt, toolCallNames);\n const shouldEscalate = sessionStore.recordRequestHash(effectiveSessionId!, contentHash);\n\n if (shouldEscalate) {\n const activeTierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n const escalation = sessionStore.escalateSession(\n effectiveSessionId!,\n activeTierConfigs,\n );\n if (escalation) {\n console.log(\n `[ClawRouter] ⚡ 3-strike escalation: ${existingSession.model} → ${escalation.model} (${existingSession.tier} → ${escalation.tier})`,\n );\n parsed.model = escalation.model;\n modelId = escalation.model;\n routingDecision = {\n ...routingDecision,\n model: escalation.model,\n tier: escalation.tier as Tier,\n };\n }\n }\n } else {\n // No session — pin this routing decision for future requests\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... pinned to model: ${routingDecision.model}`,\n );\n }\n }\n\n options.onRouted?.(routingDecision);\n }\n }\n\n // Ensure effectiveSessionId is set for explicit model requests via content hash fallback.\n // Routing profile requests already derive session ID from message content (see line above).\n // Explicit model requests (openai/gpt-4o, anthropic/claude-*, etc.) without an\n // x-session-id header would otherwise have no session ID → maxCostPerRun not tracked.\n if (!effectiveSessionId && parsedMessages.length > 0) {\n effectiveSessionId = deriveSessionId(parsedMessages);\n }\n\n // Rebuild body if modified — map free/xxx → nvidia/xxx for upstream\n if (bodyModified) {\n if (parsed.model && typeof parsed.model === \"string\") {\n parsed.model = toUpstreamModelId(parsed.model);\n }\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Log routing errors so they're not silently swallowed\n const errorMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Routing error: ${errorMsg}`);\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n options.onError?.(new Error(`Routing failed: ${errorMsg}`));\n }\n }\n\n // --- Auto-compression ---\n // Compress large requests to reduce network usage and improve performance\n const autoCompress = options.autoCompressRequests ?? true;\n const compressionThreshold = options.compressionThresholdKB ?? 180;\n const requestSizeKB = Math.ceil(body.length / 1024);\n\n if (autoCompress && requestSizeKB > compressionThreshold) {\n try {\n console.log(\n `[ClawRouter] Request size ${requestSizeKB}KB exceeds threshold ${compressionThreshold}KB, applying compression...`,\n );\n\n // Parse messages for compression\n const parsed = JSON.parse(body.toString()) as {\n messages?: NormalizedMessage[];\n [key: string]: unknown;\n };\n\n if (parsed.messages && parsed.messages.length > 0 && shouldCompress(parsed.messages)) {\n // Apply compression with conservative settings\n const compressionResult = await compressContext(parsed.messages, {\n enabled: true,\n preserveRaw: false, // Don't need originals in proxy\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // Disabled: requires model to understand codebook\n paths: false, // Disabled: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // Disabled: may lose important context\n dynamicCodebook: false, // Disabled: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false,\n },\n });\n\n const compressedSizeKB = Math.ceil(compressionResult.compressedChars / 1024);\n const savings = (((requestSizeKB - compressedSizeKB) / requestSizeKB) * 100).toFixed(1);\n\n console.log(\n `[ClawRouter] Compressed ${requestSizeKB}KB → ${compressedSizeKB}KB (${savings}% reduction)`,\n );\n\n // Update request body with compressed messages\n parsed.messages = compressionResult.messages;\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Compression failed - continue with original request\n console.warn(\n `[ClawRouter] Compression failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // --- Response cache check (long-term, 10min TTL) ---\n const cacheKey = ResponseCache.generateKey(body);\n const reqHeaders: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (typeof value === \"string\") reqHeaders[key] = value;\n }\n if (responseCache.shouldCache(body, reqHeaders)) {\n const cachedResponse = responseCache.get(cacheKey);\n if (cachedResponse) {\n console.log(`[ClawRouter] Cache HIT for ${cachedResponse.model} (saved API call)`);\n res.writeHead(cachedResponse.status, cachedResponse.headers);\n res.end(cachedResponse.body);\n return;\n }\n }\n\n // --- Dedup check (short-term, 30s TTL for retries) ---\n const dedupKey = RequestDeduplicator.hash(body);\n\n // Check dedup cache (catches retries within 30s)\n const cached = deduplicator.getCached(dedupKey);\n if (cached) {\n res.writeHead(cached.status, cached.headers);\n res.end(cached.body);\n return;\n }\n\n // Check in-flight — wait for the original request to complete\n const inflight = deduplicator.getInflight(dedupKey);\n if (inflight) {\n const result = await inflight;\n res.writeHead(result.status, result.headers);\n res.end(result.body);\n return;\n }\n\n // Register this request as in-flight\n deduplicator.markInflight(dedupKey);\n\n // --- Pre-request balance check ---\n // Estimate cost and check if wallet has sufficient balance\n // Skip if skipBalanceCheck is set (for testing) or if using free model\n let estimatedCostMicros: bigint | undefined;\n // Use `let` so the balance-fallback path can update this when modelId is switched to a free model.\n let isFreeModel = FREE_MODELS.has(modelId ?? \"\");\n\n if (modelId && !options.skipBalanceCheck && !isFreeModel) {\n const estimated = estimateAmount(modelId, body.length, maxTokens);\n if (estimated) {\n estimatedCostMicros = BigInt(estimated);\n\n // Apply extra buffer for balance check to prevent x402 failures after streaming starts.\n // This is aggressive to avoid triggering OpenClaw's 5-24 hour billing cooldown.\n const bufferedCostMicros =\n (estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100))) / 100n;\n\n // Check balance before proceeding (using buffered amount)\n const sufficiency = await balanceMonitor.checkSufficient(bufferedCostMicros);\n\n if (sufficiency.info.isEmpty || !sufficiency.sufficient) {\n // Wallet is empty or insufficient — fallback to free model\n const originalModel = modelId;\n console.log(\n `[ClawRouter] Wallet ${sufficiency.info.isEmpty ? \"empty\" : \"insufficient\"} (${sufficiency.info.balanceUSD}), falling back to free model: ${FREE_MODEL} (requested: ${originalModel})`,\n );\n modelId = FREE_MODEL;\n isFreeModel = true; // keep in sync — budget logic gates on !isFreeModel\n // Update the body with new model (map free/ → nvidia/ for upstream)\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(FREE_MODEL);\n body = Buffer.from(JSON.stringify(parsed));\n\n // Set notice to prepend to response so user knows about the fallback\n balanceFallbackNotice = sufficiency.info.isEmpty\n ? `> **⚠️ Wallet empty** — using free model. Fund your wallet to use ${originalModel}.\\n\\n`\n : `> **⚠️ Insufficient balance** (${sufficiency.info.balanceUSD}) — using free model instead of ${originalModel}.\\n\\n`;\n\n // Notify about the fallback\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n });\n } else if (sufficiency.info.isLow) {\n // Balance is low but sufficient — warn and proceed\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n });\n }\n }\n }\n\n // --- Cost cap check: strict mode hard-stop ---\n // In 'strict' mode, reject if the projected session spend (accumulated + this request's\n // estimate) would exceed the cap. Checking projected cost (not just historical) prevents\n // a single large request from overshooting the cap before it's recorded.\n // In 'graceful' mode (default), the cap is enforced via model downgrade below.\n // Must happen before streaming headers are sent.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"strict\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n // Include this request's estimated cost so even the first request is blocked\n // if it would push the session over the cap.\n const thisReqEstStr =\n estimatedCostMicros !== undefined\n ? estimatedCostMicros.toString()\n : modelId\n ? estimateAmount(modelId, body.length, maxTokens)\n : undefined;\n const thisReqEstUsd = thisReqEstStr ? Number(thisReqEstStr) / 1_000_000 : 0;\n const projectedCostUsd = runCostUsd + thisReqEstUsd;\n if (projectedCostUsd > options.maxCostPerRunUsd) {\n console.log(\n `[ClawRouter] Cost cap exceeded for session ${effectiveSessionId.slice(0, 8)}...: projected $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) > $${options.maxCostPerRunUsd} limit`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter cost cap exceeded: projected spend $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) would exceed limit $${options.maxCostPerRunUsd}`,\n type: \"cost_cap_exceeded\",\n code: \"cost_cap_exceeded\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n\n // --- Budget pre-check: block when remaining budget can't cover the request ---\n // Must happen BEFORE streaming headers (429 can't be sent after SSE headers are flushed).\n // Three cases that require a hard block rather than graceful downgrade:\n // (A) tool/COMPLEX/REASONING routing profile — free model can't substitute\n // (B) explicit model request (no routing profile) — user chose a specific model,\n // silently substituting with free model would be deceptive regardless of task type\n // Simple routing profile requests are handled later via graceful downgrade.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const isComplexOrAgentic =\n hasTools || routingDecision?.tier === \"COMPLEX\" || routingDecision?.tier === \"REASONING\";\n\n if (isComplexOrAgentic) {\n // Case A: tool/complex/agentic routing profile — check global model table\n // Intentionally exclude free models: they cannot handle complex/agentic tasks.\n const canAffordAnyNonFreeModel = BLOCKRUN_MODELS.some((m) => {\n if (FREE_MODELS.has(m.id)) return false;\n const est = estimateAmount(m.id, body.length, maxTokens);\n return est !== undefined && Number(est) / 1_000_000 <= remainingUsd;\n });\n if (!canAffordAnyNonFreeModel) {\n console.log(\n `[ClawRouter] Budget insufficient for agentic/complex session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (silent downgrade would corrupt tool/complex responses)`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n } else if (!routingDecision && modelId && !FREE_MODELS.has(modelId)) {\n // Case B: explicit model request (user chose a specific model, not a routing profile).\n // Silently substituting their choice with free model is deceptive — block instead.\n const est = estimateAmount(modelId, body.length, maxTokens);\n const canAfford = !est || Number(est) / 1_000_000 <= remainingUsd;\n if (!canAfford) {\n console.log(\n `[ClawRouter] Budget insufficient for explicit model ${modelId} in session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (user explicitly chose ${modelId})`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue using ${modelId}.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n }\n\n // --- Streaming: early header flush + heartbeat ---\n let heartbeatInterval: ReturnType | undefined;\n let headersSentEarly = false;\n\n if (isStreaming) {\n // Send 200 + SSE headers immediately, before x402 flow\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n headersSentEarly = true;\n\n // First heartbeat immediately\n safeWrite(res, \": heartbeat\\n\\n\");\n\n // Continue heartbeats every 2s while waiting for upstream\n heartbeatInterval = setInterval(() => {\n if (canWrite(res)) {\n safeWrite(res, \": heartbeat\\n\\n\");\n } else {\n // Socket closed, stop heartbeat\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n }, HEARTBEAT_INTERVAL_MS);\n }\n\n // Forward headers, stripping host, connection, and content-length\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") {\n headers[key] = value;\n }\n }\n if (!headers[\"content-type\"]) {\n headers[\"content-type\"] = \"application/json\";\n }\n headers[\"user-agent\"] = USER_AGENT;\n\n // --- Client disconnect cleanup ---\n let completed = false;\n res.on(\"close\", () => {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n // Remove from in-flight if client disconnected before completion\n if (!completed) {\n deduplicator.removeInflight(dedupKey);\n }\n });\n\n // --- Request timeout ---\n // Global controller: hard deadline for the entire request (all model attempts combined).\n // Each model attempt gets its own per-model controller (PER_MODEL_TIMEOUT_MS).\n // If a model times out individually, we fall back to the next model instead of failing.\n // Only the global timeout causes an immediate error.\n const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const globalController = new AbortController();\n const timeoutId = setTimeout(() => globalController.abort(), timeoutMs);\n\n try {\n // --- Build fallback chain ---\n // If we have a routing decision, get the full fallback chain for the tier\n // Otherwise, just use the current model (no fallback for explicit model requests)\n let modelsToTry: string[];\n const excludeList = options.excludeModels ?? loadExcludeList();\n if (routingDecision) {\n // Estimate total context: input tokens (~4 chars per token) + max output tokens\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const estimatedTotalTokens = estimatedInputTokens + maxTokens;\n\n // Use tier configs from the routing decision (set by RouterStrategy)\n const tierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n // Get full chain first, then filter by context\n const fullChain = getFallbackChain(routingDecision.tier, tierConfigs);\n const contextFiltered = getFallbackChainFiltered(\n routingDecision.tier,\n tierConfigs,\n estimatedTotalTokens,\n getModelContextWindow,\n );\n\n // Log if models were filtered out due to context limits\n const contextExcluded = fullChain.filter((m) => !contextFiltered.includes(m));\n if (contextExcluded.length > 0) {\n console.log(\n `[ClawRouter] Context filter (~${estimatedTotalTokens} tokens): excluded ${contextExcluded.join(\", \")}`,\n );\n }\n\n // Filter out user-excluded models\n const excludeFiltered = filterByExcludeList(contextFiltered, excludeList);\n const excludeExcluded = contextFiltered.filter((m) => !excludeFiltered.includes(m));\n if (excludeExcluded.length > 0) {\n console.log(\n `[ClawRouter] Exclude filter: excluded ${excludeExcluded.join(\", \")} (user preference)`,\n );\n }\n\n // Filter to models that support tool calling when request has tools.\n // Prevents models like grok-code-fast-1 from outputting tool invocations\n // as plain text JSON (the \"talking to itself\" bug).\n let toolFiltered = filterByToolCalling(excludeFiltered, hasTools, supportsToolCalling);\n const toolExcluded = excludeFiltered.filter((m) => !toolFiltered.includes(m));\n if (toolExcluded.length > 0) {\n console.log(\n `[ClawRouter] Tool-calling filter: excluded ${toolExcluded.join(\", \")} (no structured function call support)`,\n );\n }\n\n // Filter out models that declare toolCalling but fail tool compliance in practice.\n // gemini-2.5-flash-lite refuses certain tool schemas (e.g. brave search) while\n // cheaper models like nvidia/gpt-oss-120b handle them fine.\n const TOOL_NONCOMPLIANT_MODELS = [\n \"google/gemini-2.5-flash-lite\",\n \"google/gemini-3-pro-preview\",\n \"google/gemini-3.1-pro\",\n ];\n if (hasTools && toolFiltered.length > 1) {\n const compliant = toolFiltered.filter((m) => !TOOL_NONCOMPLIANT_MODELS.includes(m));\n if (compliant.length > 0 && compliant.length < toolFiltered.length) {\n const dropped = toolFiltered.filter((m) => TOOL_NONCOMPLIANT_MODELS.includes(m));\n console.log(\n `[ClawRouter] Tool-compliance filter: excluded ${dropped.join(\", \")} (unreliable tool schema handling)`,\n );\n toolFiltered = compliant;\n }\n }\n\n // Filter to models that support vision when request has image_url content\n const visionFiltered = filterByVision(toolFiltered, hasVision, supportsVision);\n const visionExcluded = toolFiltered.filter((m) => !visionFiltered.includes(m));\n if (visionExcluded.length > 0) {\n console.log(\n `[ClawRouter] Vision filter: excluded ${visionExcluded.join(\", \")} (no vision support)`,\n );\n }\n\n // Limit to MAX_FALLBACK_ATTEMPTS to prevent infinite loops\n modelsToTry = visionFiltered.slice(0, MAX_FALLBACK_ATTEMPTS);\n\n // Deprioritize rate-limited models (put them at the end)\n modelsToTry = prioritizeNonRateLimited(modelsToTry);\n } else {\n // For explicit model requests, use the requested model\n modelsToTry = modelId ? [modelId] : [];\n }\n\n // Ensure free model is the last-resort fallback for non-tool requests.\n // Skip free fallback when tools are present — nvidia/gpt-oss-120b lacks\n // tool calling support and would produce broken responses for agentic tasks.\n if (!hasTools && !modelsToTry.includes(FREE_MODEL) && !excludeList.has(FREE_MODEL)) {\n modelsToTry.push(FREE_MODEL); // last-resort free fallback\n }\n\n // --- Budget-aware routing (graceful mode) ---\n // Filter modelsToTry to only models that fit within the remaining session budget.\n // Simple tasks (no tools, non-complex tier): downgrade with visible warning.\n // Complex/agentic tasks with no affordable model: already blocked above (before streaming headers).\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const beforeFilter = [...modelsToTry];\n modelsToTry = modelsToTry.filter((m) => {\n if (FREE_MODELS.has(m)) return true; // free models always fit (no cost)\n const est = estimateAmount(m, body.length, maxTokens);\n if (!est) return true; // no pricing data → keep (permissive)\n return Number(est) / 1_000_000 <= remainingUsd;\n });\n\n const excluded = beforeFilter.filter((m) => !modelsToTry.includes(m));\n\n // Second-pass block: the pre-check caught obvious cases early (before streaming headers).\n // Here we recheck against the actual filtered modelsToTry chain. If the ONLY remaining\n // models are free, we must block rather than silently degrade for:\n // (A) complex/agentic routing profile tasks (tools / COMPLEX / REASONING tier)\n // (B) explicit model requests (user chose a specific model; free substitution is deceptive)\n // The pre-check already handles case (B) for non-streaming; this is a safety net for\n // streaming requests where SSE headers may have already been sent.\n const isComplexOrAgenticFilter =\n hasTools ||\n routingDecision?.tier === \"COMPLEX\" ||\n routingDecision?.tier === \"REASONING\" ||\n routingDecision === undefined; // explicit model: no routing profile → user chose the model\n const filteredToFreeOnly =\n modelsToTry.length > 0 && modelsToTry.every((m) => FREE_MODELS.has(m));\n\n if (isComplexOrAgenticFilter && filteredToFreeOnly) {\n const budgetSummary = `$${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget filter left only free model for complex/agentic session — blocking (${budgetSummary})`,\n );\n const errPayload = JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: remaining budget (${budgetSummary}) cannot support a complex/tool request. Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n });\n if (heartbeatInterval) clearInterval(heartbeatInterval);\n if (headersSentEarly) {\n // Streaming: inject error SSE event + [DONE] and close\n safeWrite(res, `data: ${errPayload}\\n\\ndata: [DONE]\\n\\n`);\n res.end();\n } else {\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(errPayload);\n }\n deduplicator.removeInflight(dedupKey);\n return;\n }\n\n if (excluded.length > 0) {\n const budgetSummary =\n remainingUsd > 0\n ? `$${remainingUsd.toFixed(4)} remaining`\n : `budget exhausted ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget downgrade (${budgetSummary}): excluded ${excluded.join(\", \")}`,\n );\n\n // A: Set visible warning notice — prepended to response so user sees the downgrade\n const fromModel = excluded[0];\n const usingFree = modelsToTry.length === 1 && FREE_MODELS.has(modelsToTry[0]);\n if (usingFree) {\n budgetDowngradeNotice = `> **⚠️ Budget cap reached** ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd}) — downgraded to free model. Quality may be reduced. Increase \\`maxCostPerRun\\` to continue with ${fromModel}.\\n\\n`;\n } else {\n const toModel = modelsToTry[0] ?? FREE_MODEL; // last resort\n budgetDowngradeNotice = `> **⚠️ Budget low** ($${remainingUsd > 0 ? remainingUsd.toFixed(4) : \"0.0000\"} remaining) — using ${toModel} instead of ${fromModel}.\\n\\n`;\n }\n // B: Header flag for orchestration layers (e.g. OpenClaw can pause/warn the user)\n budgetDowngradeHeaderMode = \"downgraded\";\n }\n }\n\n // --- Fallback loop: try each model until success ---\n let upstream: Response | undefined;\n let lastError: { body: string; status: number } | undefined;\n let actualModelUsed = modelId;\n const failedAttempts: Array<{ model: string; reason: string; status: number }> = [];\n\n for (let i = 0; i < modelsToTry.length; i++) {\n const tryModel = modelsToTry[i];\n const isLastAttempt = i === modelsToTry.length - 1;\n\n // Abort immediately if global deadline has already fired\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n console.log(`[ClawRouter] Trying model ${i + 1}/${modelsToTry.length}: ${tryModel}`);\n\n // Per-model abort controller — each model attempt gets its own 60s window.\n // When it fires, the fallback loop moves to the next model rather than failing.\n const modelController = new AbortController();\n const modelTimeoutId = setTimeout(() => modelController.abort(), PER_MODEL_TIMEOUT_MS);\n const combinedSignal = AbortSignal.any([globalController.signal, modelController.signal]);\n\n const result = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n combinedSignal,\n );\n clearTimeout(modelTimeoutId);\n\n // If the global deadline fired during this attempt, bail out entirely\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n // If the per-model timeout fired (but not global), treat as fallback-worthy error\n if (!result.success && modelController.signal.aborted && !isLastAttempt) {\n console.log(\n `[ClawRouter] Model ${tryModel} timed out after ${PER_MODEL_TIMEOUT_MS}ms, trying fallback`,\n );\n recordProviderError(tryModel, \"server_error\");\n continue;\n }\n\n if (result.success && result.response) {\n upstream = result.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Success with model: ${tryModel}`);\n // Accumulate estimated cost to session for maxCostPerRun tracking\n if (options.maxCostPerRunUsd && effectiveSessionId && !FREE_MODELS.has(tryModel)) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n\n // Request failed\n lastError = {\n body: result.errorBody || \"Unknown error\",\n status: result.errorStatus || 500,\n };\n failedAttempts.push({\n model: tryModel,\n reason: result.errorCategory || `HTTP ${result.errorStatus || 500}`,\n status: result.errorStatus || 500,\n });\n\n // Payment error (insufficient funds, simulation failure) — skip remaining\n // paid models, jump straight to free model. No point trying other paid\n // models with the same wallet state.\n // Must be checked BEFORE isProviderError gate: payment settlement failures\n // may return non-standard HTTP codes that categorizeError doesn't recognize,\n // causing isProviderError=false and breaking out of the fallback loop.\n const isPaymentErr =\n /payment.*verification.*failed|payment.*settlement.*failed|insufficient.*funds|transaction_simulation_failed/i.test(\n result.errorBody || \"\",\n );\n if (isPaymentErr && !FREE_MODELS.has(tryModel) && !isLastAttempt) {\n failedAttempts.push({\n ...failedAttempts[failedAttempts.length - 1],\n reason: \"payment_error\",\n });\n const freeIdx = modelsToTry.indexOf(FREE_MODEL);\n if (freeIdx > i + 1) {\n console.log(`[ClawRouter] Payment error — skipping to free model: ${FREE_MODEL}`);\n i = freeIdx - 1; // loop will increment to freeIdx\n continue;\n }\n // Free model not in chain — add it and try\n if (freeIdx === -1) {\n modelsToTry.push(FREE_MODEL);\n console.log(`[ClawRouter] Payment error — appending free model: ${FREE_MODEL}`);\n continue;\n }\n }\n\n // If it's a provider error and not the last attempt, try next model\n if (result.isProviderError && !isLastAttempt) {\n const isExplicitModelError = !routingDecision;\n const isUnknownExplicitModel =\n isExplicitModelError && /unknown.*model|invalid.*model/i.test(result.errorBody || \"\");\n if (isUnknownExplicitModel) {\n console.log(\n `[ClawRouter] Explicit model error from ${tryModel}, not falling back: ${result.errorBody?.slice(0, 100)}`,\n );\n break;\n }\n\n // Record error and apply category-specific handling\n const errorCat = result.errorCategory;\n if (errorCat) {\n recordProviderError(tryModel, errorCat);\n }\n\n if (errorCat === \"rate_limited\") {\n // --- Stepped backoff retry (429) ---\n // Token-bucket rate limits often recover within milliseconds.\n // Retry once after 200ms before treating this as a model-level failure.\n if (!isLastAttempt && !globalController.signal.aborted) {\n console.log(\n `[ClawRouter] Rate-limited on ${tryModel}, retrying in 200ms before failover`,\n );\n await new Promise((resolve) => setTimeout(resolve, 200));\n if (!globalController.signal.aborted) {\n const retryController = new AbortController();\n const retryTimeoutId = setTimeout(\n () => retryController.abort(),\n PER_MODEL_TIMEOUT_MS,\n );\n const retrySignal = AbortSignal.any([\n globalController.signal,\n retryController.signal,\n ]);\n const retryResult = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n retrySignal,\n );\n clearTimeout(retryTimeoutId);\n if (retryResult.success && retryResult.response) {\n upstream = retryResult.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Rate-limit retry succeeded for: ${tryModel}`);\n if (options.maxCostPerRunUsd && effectiveSessionId && tryModel !== FREE_MODEL) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n // Retry also failed — fall through to markRateLimited\n }\n }\n markRateLimited(tryModel);\n // Check for server-side update hint in 429 response\n try {\n const parsed = JSON.parse(result.errorBody || \"{}\");\n if (parsed.update_available) {\n console.log(\"\");\n console.log(\n `\\x1b[33m⬆️ ClawRouter ${parsed.update_available} available (you have ${VERSION})\\x1b[0m`,\n );\n console.log(\n ` Run: \\x1b[36mcurl -fsSL ${parsed.update_url || \"https://blockrun.ai/ClawRouter-update\"} | bash\\x1b[0m`,\n );\n console.log(\"\");\n }\n } catch {\n /* ignore parse errors */\n }\n } else if (errorCat === \"overloaded\") {\n markOverloaded(tryModel);\n } else if (errorCat === \"auth_failure\" || errorCat === \"quota_exceeded\") {\n console.log(\n `[ClawRouter] 🔑 ${errorCat === \"auth_failure\" ? \"Auth failure\" : \"Quota exceeded\"} for ${tryModel} — check provider config`,\n );\n }\n\n console.log(\n `[ClawRouter] Provider error from ${tryModel}, trying fallback: ${result.errorBody?.slice(0, 100)}`,\n );\n continue;\n }\n\n // Not a provider error or last attempt — stop trying\n if (!result.isProviderError) {\n console.log(\n `[ClawRouter] Non-provider error from ${tryModel}, not retrying: ${result.errorBody?.slice(0, 100)}`,\n );\n }\n break;\n }\n\n // Clear timeout — request attempts completed\n clearTimeout(timeoutId);\n\n // Clear heartbeat — real data is about to flow\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // --- Emit routing debug info (opt-in via x-clawrouter-debug: true header) ---\n // For streaming: SSE comment (invisible to most clients, visible in raw stream)\n // For non-streaming: response headers added later\n if (debugMode && headersSentEarly && routingDecision) {\n const debugComment = `: x-clawrouter-debug profile=${routingProfile ?? \"auto\"} tier=${routingDecision.tier} model=${actualModelUsed} agentic=${routingDecision.agenticScore?.toFixed(2) ?? \"n/a\"} confidence=${routingDecision.confidence.toFixed(2)} reasoning=${routingDecision.reasoning}\\n\\n`;\n safeWrite(res, debugComment);\n }\n\n // Update routing decision with actual model used (for logging)\n // IMPORTANT: Recalculate cost for the actual model, not the original primary\n if (routingDecision && actualModelUsed !== routingDecision.model) {\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const newCosts = calculateModelCost(\n actualModelUsed,\n routerOpts.modelPricing,\n estimatedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n routingDecision = {\n ...routingDecision,\n model: actualModelUsed,\n reasoning: `${routingDecision.reasoning} | fallback to ${actualModelUsed}`,\n costEstimate: newCosts.costEstimate,\n baselineCost: newCosts.baselineCost,\n savings: newCosts.savings,\n };\n options.onRouted?.(routingDecision);\n\n // Update session pin to the actual model used — ensures the next request in\n // this conversation starts from the fallback model rather than retrying the\n // primary and falling back again (prevents the \"model keeps jumping\" issue).\n if (effectiveSessionId) {\n sessionStore.setSession(effectiveSessionId, actualModelUsed, routingDecision.tier);\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... updated pin to fallback: ${actualModelUsed}`,\n );\n }\n }\n\n // --- Handle case where all models failed ---\n if (!upstream) {\n // Build structured error summary listing all attempted models\n const attemptSummary =\n failedAttempts.length > 0\n ? failedAttempts.map((a) => `${a.model} (${a.reason})`).join(\", \")\n : \"unknown\";\n const structuredMessage =\n failedAttempts.length > 0\n ? `All ${failedAttempts.length} models failed. Tried: ${attemptSummary}`\n : \"All models in fallback chain failed\";\n console.log(`[ClawRouter] ${structuredMessage}`);\n const rawErrBody = lastError?.body || structuredMessage;\n const errStatus = lastError?.status || 502;\n\n // Transform payment errors into user-friendly messages\n const transformedErr = transformPaymentError(rawErrBody);\n\n if (headersSentEarly) {\n // Streaming: send error as SSE event\n // If transformed error is already JSON, parse and use it; otherwise wrap in standard format\n let errPayload: string;\n try {\n const parsed = JSON.parse(transformedErr);\n errPayload = JSON.stringify(parsed);\n } catch {\n errPayload = JSON.stringify({\n error: { message: rawErrBody, type: \"provider_error\", status: errStatus },\n });\n }\n const errEvent = `data: ${errPayload}\\n\\n`;\n safeWrite(res, errEvent);\n safeWrite(res, \"data: [DONE]\\n\\n\");\n res.end();\n\n const errBuf = Buffer.from(errEvent + \"data: [DONE]\\n\\n\");\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: errBuf,\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: send transformed error response with context headers\n res.writeHead(errStatus, {\n \"Content-Type\": \"application/json\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n res.end(transformedErr);\n\n deduplicator.complete(dedupKey, {\n status: errStatus,\n headers: { \"content-type\": \"application/json\" },\n body: Buffer.from(transformedErr),\n completedAt: Date.now(),\n });\n }\n return;\n }\n\n // --- Stream response and collect for dedup cache ---\n const responseChunks: Buffer[] = [];\n\n if (headersSentEarly) {\n // Streaming: headers already sent. Response should be 200 at this point\n // (non-200 responses are handled in the fallback loop above)\n\n // Convert non-streaming JSON response to SSE streaming format for client\n // (BlockRun API returns JSON since we forced stream:false)\n // OpenClaw expects: object=\"chat.completion.chunk\" with choices[].delta (not message)\n // We emit proper incremental deltas to match OpenAI's streaming format exactly\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n\n // Combine chunks and transform to streaming format\n const jsonBody = Buffer.concat(chunks);\n const jsonStr = jsonBody.toString();\n try {\n const rsp = JSON.parse(jsonStr) as {\n id?: string;\n object?: string;\n created?: number;\n model?: string;\n choices?: Array<{\n index?: number;\n message?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n delta?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: unknown;\n };\n\n // Extract input token count from upstream response\n if (rsp.usage && typeof rsp.usage === \"object\") {\n const u = rsp.usage as Record;\n if (typeof u.prompt_tokens === \"number\") responseInputTokens = u.prompt_tokens;\n if (typeof u.completion_tokens === \"number\") responseOutputTokens = u.completion_tokens;\n }\n\n // Build base chunk structure (reused for all chunks)\n // Match OpenAI's exact format including system_fingerprint\n const baseChunk = {\n id: rsp.id ?? `chatcmpl-${Date.now()}`,\n object: \"chat.completion.chunk\",\n created: rsp.created ?? Math.floor(Date.now() / 1000),\n model: actualModelUsed || rsp.model || \"unknown\",\n system_fingerprint: null,\n };\n\n // Process each choice (usually just one)\n if (rsp.choices && Array.isArray(rsp.choices)) {\n for (const choice of rsp.choices) {\n // Strip thinking tokens (Kimi <|...|> and standard tags)\n const rawContent = choice.message?.content ?? choice.delta?.content ?? \"\";\n const content = stripThinkingTokens(rawContent);\n const role = choice.message?.role ?? choice.delta?.role ?? \"assistant\";\n const index = choice.index ?? 0;\n\n // Accumulate content for session journal\n if (content) {\n accumulatedContent += content;\n }\n\n // Chunk 1: role only (mimics OpenAI's first chunk)\n const roleChunk = {\n ...baseChunk,\n choices: [{ index, delta: { role }, logprobs: null, finish_reason: null }],\n };\n const roleData = `data: ${JSON.stringify(roleChunk)}\\n\\n`;\n safeWrite(res, roleData);\n responseChunks.push(Buffer.from(roleData));\n\n // Chunk 1.5: balance fallback notice (tells user they got free model)\n if (balanceFallbackNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: balanceFallbackNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n balanceFallbackNotice = undefined; // Only inject once\n }\n\n // Chunk 1.6: budget downgrade notice (A: visible warning when model downgraded)\n if (budgetDowngradeNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: budgetDowngradeNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n budgetDowngradeNotice = undefined; // Only inject once\n }\n\n // Chunk 2: content (single chunk with full content)\n if (content) {\n const contentChunk = {\n ...baseChunk,\n choices: [{ index, delta: { content }, logprobs: null, finish_reason: null }],\n };\n const contentData = `data: ${JSON.stringify(contentChunk)}\\n\\n`;\n safeWrite(res, contentData);\n responseChunks.push(Buffer.from(contentData));\n }\n\n // Chunk 2b: tool_calls (forward tool calls from upstream)\n const toolCalls = choice.message?.tool_calls ?? choice.delta?.tool_calls;\n if (toolCalls && toolCalls.length > 0) {\n const toolCallChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { tool_calls: toolCalls },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const toolCallData = `data: ${JSON.stringify(toolCallChunk)}\\n\\n`;\n safeWrite(res, toolCallData);\n responseChunks.push(Buffer.from(toolCallData));\n }\n\n // Chunk 3: finish_reason (signals completion)\n const finishChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: {},\n logprobs: null,\n finish_reason:\n toolCalls && toolCalls.length > 0\n ? \"tool_calls\"\n : (choice.finish_reason ?? \"stop\"),\n },\n ],\n };\n const finishData = `data: ${JSON.stringify(finishChunk)}\\n\\n`;\n safeWrite(res, finishData);\n responseChunks.push(Buffer.from(finishData));\n }\n }\n } catch {\n // If parsing fails, send raw response as single chunk\n const sseData = `data: ${jsonStr}\\n\\n`;\n safeWrite(res, sseData);\n responseChunks.push(Buffer.from(sseData));\n }\n }\n\n // Send cost summary as SSE comment before terminator\n if (routingDecision) {\n const costComment = `: cost=$${routingDecision.costEstimate.toFixed(4)} savings=${(routingDecision.savings * 100).toFixed(0)}% model=${actualModelUsed} tier=${routingDecision.tier}\\n\\n`;\n safeWrite(res, costComment);\n responseChunks.push(Buffer.from(costComment));\n }\n\n // Send SSE terminator\n safeWrite(res, \"data: [DONE]\\n\\n\");\n responseChunks.push(Buffer.from(\"data: [DONE]\\n\\n\"));\n res.end();\n\n // Cache for dedup\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: Buffer.concat(responseChunks),\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: forward status and headers from upstream\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n // Skip hop-by-hop headers and content-encoding (fetch already decompresses)\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\")\n return;\n responseHeaders[key] = value;\n });\n\n // Add context usage headers\n responseHeaders[\"x-context-used-kb\"] = String(originalContextSizeKB);\n responseHeaders[\"x-context-limit-kb\"] = String(CONTEXT_LIMIT_KB);\n\n // Add routing debug headers (opt-in via x-clawrouter-debug: true header)\n if (debugMode && routingDecision) {\n responseHeaders[\"x-clawrouter-profile\"] = routingProfile ?? \"auto\";\n responseHeaders[\"x-clawrouter-tier\"] = routingDecision.tier;\n responseHeaders[\"x-clawrouter-model\"] = actualModelUsed;\n responseHeaders[\"x-clawrouter-confidence\"] = routingDecision.confidence.toFixed(2);\n responseHeaders[\"x-clawrouter-reasoning\"] = routingDecision.reasoning;\n if (routingDecision.agenticScore !== undefined) {\n responseHeaders[\"x-clawrouter-agentic-score\"] = routingDecision.agenticScore.toFixed(2);\n }\n }\n\n // Always include cost visibility headers when routing is active\n if (routingDecision) {\n responseHeaders[\"x-clawrouter-cost\"] = routingDecision.costEstimate.toFixed(6);\n responseHeaders[\"x-clawrouter-savings\"] = `${(routingDecision.savings * 100).toFixed(0)}%`;\n }\n\n // Collect full body for possible notice injection\n const bodyParts: Buffer[] = [];\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n for (const chunk of chunks) {\n bodyParts.push(Buffer.from(chunk));\n }\n }\n\n let responseBody = Buffer.concat(bodyParts);\n\n // Prepend balance fallback notice to response content\n if (balanceFallbackNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n balanceFallbackNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n balanceFallbackNotice = undefined;\n }\n\n // A: Prepend budget downgrade notice to response content\n if (budgetDowngradeNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n budgetDowngradeNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n budgetDowngradeNotice = undefined;\n }\n\n // Inject actualModelUsed into non-streaming response model field\n if (actualModelUsed && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as { model?: string };\n if (parsed.model !== undefined) {\n parsed.model = actualModelUsed;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip model injection */\n }\n }\n\n // B: Add budget downgrade headers for orchestration layers\n if (budgetDowngradeHeaderMode) {\n responseHeaders[\"x-clawrouter-budget-downgrade\"] = \"1\";\n responseHeaders[\"x-clawrouter-budget-mode\"] = budgetDowngradeHeaderMode;\n budgetDowngradeHeaderMode = undefined;\n }\n\n // Update content-length header since body may have changed\n responseHeaders[\"content-length\"] = String(responseBody.length);\n res.writeHead(upstream.status, responseHeaders);\n safeWrite(res, responseBody);\n responseChunks.push(responseBody);\n res.end();\n\n // Cache for dedup (short-term, 30s)\n deduplicator.complete(dedupKey, {\n status: upstream.status,\n headers: responseHeaders,\n body: responseBody,\n completedAt: Date.now(),\n });\n\n // Cache for response cache (long-term, 10min) - only successful non-streaming\n if (upstream.status === 200 && responseCache.shouldCache(body)) {\n responseCache.set(cacheKey, {\n body: responseBody,\n status: upstream.status,\n headers: responseHeaders,\n model: actualModelUsed,\n });\n console.log(\n `[ClawRouter] Cached response for ${actualModelUsed} (${responseBody.length} bytes)`,\n );\n }\n\n // Extract content and token usage from non-streaming response\n try {\n const rspJson = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n usage?: Record;\n };\n if (rspJson.choices?.[0]?.message?.content) {\n accumulatedContent = rspJson.choices[0].message.content;\n }\n if (rspJson.usage && typeof rspJson.usage === \"object\") {\n if (typeof rspJson.usage.prompt_tokens === \"number\")\n responseInputTokens = rspJson.usage.prompt_tokens;\n if (typeof rspJson.usage.completion_tokens === \"number\")\n responseOutputTokens = rspJson.usage.completion_tokens;\n }\n } catch {\n // Ignore parse errors - journal just won't have content for this response\n }\n }\n\n // --- Session Journal: Extract and record events from response ---\n if (sessionId && accumulatedContent) {\n const events = sessionJournal.extractEvents(accumulatedContent);\n if (events.length > 0) {\n sessionJournal.record(sessionId, events, actualModelUsed);\n console.log(\n `[ClawRouter] Recorded ${events.length} events to session journal for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n\n // --- Optimistic balance deduction after successful response ---\n if (estimatedCostMicros !== undefined) {\n balanceMonitor.deductEstimated(estimatedCostMicros);\n }\n\n // Mark request as completed (for client disconnect cleanup)\n completed = true;\n } catch (err) {\n // Clear timeout on error\n clearTimeout(timeoutId);\n\n // Clear heartbeat on error\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // Remove in-flight entry so retries aren't blocked\n deduplicator.removeInflight(dedupKey);\n\n // Invalidate balance cache on payment failure (might be out of date)\n balanceMonitor.invalidate();\n\n // Convert abort error to more descriptive timeout error\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err });\n }\n\n throw err;\n }\n\n // --- Usage logging (fire-and-forget) ---\n // Use actual x402 payment amount from the per-request AsyncLocalStorage store.\n // This is the real amount the user paid — no estimation needed.\n // Falls back to local estimate only for free models (no x402 payment).\n const logModel = routingDecision?.model ?? modelId;\n if (logModel) {\n const actualPayment = paymentStore.getStore()?.amountUsd ?? 0;\n\n // For free models (no x402 payment), use local cost calculation as fallback\n let logCost: number;\n let logBaseline: number;\n let logSavings: number;\n if (actualPayment > 0) {\n logCost = actualPayment;\n // Calculate baseline for savings comparison\n const chargedInputTokens = Math.ceil(body.length / 4);\n const modelDef = BLOCKRUN_MODELS.find((m) => m.id === logModel);\n const chargedOutputTokens = modelDef ? Math.min(maxTokens, modelDef.maxOutput) : maxTokens;\n const baseline = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n chargedOutputTokens,\n routingProfile ?? undefined,\n );\n logBaseline = baseline.baselineCost;\n logSavings = logBaseline > 0 ? Math.max(0, (logBaseline - logCost) / logBaseline) : 0;\n } else {\n // Free model — no payment, calculate locally\n const chargedInputTokens = Math.ceil(body.length / 4);\n const costs = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n logCost = costs.costEstimate;\n logBaseline = costs.baselineCost;\n logSavings = costs.savings;\n }\n\n const entry: UsageEntry = {\n timestamp: new Date().toISOString(),\n model: logModel,\n tier: routingDecision?.tier ?? \"DIRECT\",\n cost: logCost,\n baselineCost: logBaseline,\n savings: logSavings,\n latencyMs: Date.now() - startTime,\n ...(responseInputTokens !== undefined && { inputTokens: responseInputTokens }),\n ...(responseOutputTokens !== undefined && { outputTokens: responseOutputTokens }),\n };\n logUsage(entry).catch(() => {});\n }\n}\n","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\n}\n","import type {\n Abi,\n AbiParameter,\n AbiParameterToPrimitiveType,\n ExtractAbiEvents,\n} from 'abitype'\n\nimport {\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeEventTopics'\n\nexport type EncodeEventTopicsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n ///\n hasEvents = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiEvents] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >,\n allErrorNames = ContractEventName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { eventName?: eventName | allErrorNames | undefined }\n : { eventName: eventName | allErrorNames }\n : { eventName?: eventName | allErrorNames | undefined }\n> &\n (hasEvents extends true ? unknown : never)\n\nexport type EncodeEventTopicsReturnType = [Hex, ...(Hex | Hex[] | null)[]]\n\nexport type EncodeEventTopicsErrorType =\n | AbiEventNotFoundErrorType\n | EncodeArgErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nexport function encodeEventTopics<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n>(\n parameters: EncodeEventTopicsParameters,\n): EncodeEventTopicsReturnType {\n const { abi, eventName, args } = parameters as EncodeEventTopicsParameters\n\n let abiItem = abi[0]\n if (eventName) {\n const item = getAbiItem({ abi, name: eventName })\n if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'event')\n throw new AbiEventNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toEventSelector(definition as EventDefinition)\n\n let topics: (Hex | Hex[] | null)[] = []\n if (args && 'inputs' in abiItem) {\n const indexedInputs = abiItem.inputs?.filter(\n (param) => 'indexed' in param && param.indexed,\n )\n const args_ = Array.isArray(args)\n ? args\n : Object.values(args).length > 0\n ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])\n : []\n\n if (args_.length > 0) {\n topics =\n indexedInputs?.map((param, i) => {\n if (Array.isArray(args_[i]))\n return args_[i].map((_: any, j: number) =>\n encodeArg({ param, value: args_[i][j] }),\n )\n return typeof args_[i] !== 'undefined' && args_[i] !== null\n ? encodeArg({ param, value: args_[i] })\n : null\n }) ?? []\n }\n }\n return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | EncodeAbiParametersErrorType\n | FilterTypeNotSupportedErrorType\n | ErrorType\n\nfunction encodeArg({\n param,\n value,\n}: {\n param: AbiParameter\n value: AbiParameterToPrimitiveType\n}) {\n if (param.type === 'string' || param.type === 'bytes')\n return keccak256(toBytes(value as string))\n if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n throw new FilterTypeNotSupportedError(param.type)\n return encodeAbiParameters([param], [value])\n}\n","import { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n constructor(type: string) {\n super(`Filter type \"${type}\" is not supported.`, {\n name: 'FilterTypeNotSupportedError',\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n abi: abi\n eventName?: eventName | ContractEventName | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n * @default false\n */\n strict?: strict | boolean | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (undefined extends eventName\n ? {\n args?: undefined\n }\n : MaybeExtractEventArgsFromAbi extends infer eventFilterArgs\n ? {\n args?:\n | eventFilterArgs\n | (args extends eventFilterArgs ? args : never)\n | undefined\n }\n : {\n args?: undefined\n })\n\nexport type CreateContractEventFilterReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', abi, eventName, args, strict, fromBlock, toBlock>\n\nexport type CreateContractEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const { address, abi, args, eventName, fromBlock, strict, toBlock } =\n parameters as CreateContractEventFilterParameters\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n const topics = eventName\n ? encodeEventTopics({\n abi,\n args,\n eventName,\n } as unknown as EncodeEventTopicsParameters)\n : undefined\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n topics,\n },\n ],\n })\n\n return {\n abi,\n args,\n eventName,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n type: 'event',\n } as unknown as CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn, PublicRpcSchema } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n method:\n | 'eth_newFilter'\n | 'eth_newPendingTransactionFilter'\n | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n PublicRpcSchema,\n { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n id: Hex,\n) => EIP1193RequestFn\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope(\n client: Client,\n { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n const requestMap: Record = {}\n\n if (client.transport.type === 'fallback')\n client.transport.onResponse?.(\n ({\n method: method_,\n response: id,\n status,\n transport,\n }: Parameters[0]) => {\n if (status === 'success' && method === method_)\n requestMap[id as Hex] = transport.request\n },\n )\n\n return ((id) =>\n requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi } 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 type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n GetValue,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from './estimateGas.js'\n\nexport type EstimateContractGasParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n> = ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit, 'data' | 'to' | 'value'> &\n GetValue<\n abi,\n functionName,\n EstimateGasParameters extends EstimateGasParameters\n ? EstimateGasParameters['value']\n : EstimateGasParameters['value']\n > & {\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n }\n\nexport type EstimateContractGasReturnType = bigint\n\nexport type EstimateContractGasErrorType = GetContractErrorReturnType<\n EncodeFunctionDataErrorType | EstimateGasErrorType | ParseAccountErrorType\n>\n\n/**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateContractGas } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await estimateContractGas(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\nexport async function estimateContractGas<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs,\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n parameters: EstimateContractGasParameters,\n): Promise {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...request\n } = parameters as EstimateContractGasParameters\n const data = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n\n try {\n const gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n data: `${data}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...request,\n } as unknown as EstimateGasParameters)\n return gas\n } catch (error) {\n const account = request.account ? parseAccount(request.account) : undefined\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/estimateContractGas',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport { InternalRpcError, InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType = Omit<\n ContractFunctionExecutionErrorType,\n 'cause'\n> & {\n cause:\n | cause\n | ContractFunctionZeroDataErrorType\n | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError>(\n err: err,\n {\n abi,\n address,\n args,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args: any\n address?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const error = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as BaseError\n const { code, data, details, message, shortMessage } =\n error as RawContractError\n\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName })\n if (\n ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || details || message || shortMessage)) ||\n (code === InvalidInputRpcError.code &&\n details === 'execution reverted' &&\n data)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message:\n error instanceof RpcRequestError\n ? details\n : (shortMessage ?? message),\n })\n }\n return err\n })()\n\n return new ContractFunctionExecutionError(cause as BaseError, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n }) as GetContractErrorReturnType\n}\n","import type { Address } from 'abitype'\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 { BaseError } from '../../errors/base.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestParameterType,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n account?: Account | Address | undefined\n prepare?:\n | boolean\n | readonly PrepareTransactionRequestParameterType[]\n | undefined\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 FormattedEstimateGas =\n FormattedTransactionRequest\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\n | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in gas units). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n args: EstimateGasParameters,\n): Promise {\n const { account: account_ = client.account, prepare = true } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n const parameters = (() => {\n if (Array.isArray(prepare)) return prepare\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n if (account?.type !== 'local') return ['blobVersionedHashes']\n return undefined\n })()\n\n try {\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (args.to) return args.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (args.authorizationList && args.authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: args.authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = prepare\n ? ((await prepareTransactionRequest(client, {\n ...args,\n parameters,\n to,\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters)\n : args\n\n // If we get `gas` back from the prepared transaction request, which is\n // different from the `gas` we provided, it was likely filled by other means\n // during request preparation (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n // (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n if (gas && args.gas !== gas) return gas\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\n\n assertRequest(args as AssertRequestParameters)\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest,\n 'estimateGas',\n )\n\n return BigInt(\n await client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [\n request,\n block ?? client.experimental_blockTag ?? 'latest',\n rpcStateOverride,\n ]\n : block\n ? [request, block]\n : [request],\n }),\n )\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise {\n return publicKeyToAddress(await recoverPublicKey({ hash, signature }))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { size } from '../data/size.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n if (size(signatureHex) !== 65) throw new Error('invalid signature length')\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../signature/recoverAddress.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n > = OneOf,\n //\n _signature = Hex | ByteArray | OneOf,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization:\n | authorization\n | OneOf\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n >,\n>(\n parameters: RecoverAuthorizationAddressParameters,\n): Promise {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as AuthorizationRequest),\n signature: (signature ?? authorization) as Signature,\n })\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError 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, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Estimate Gas Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'EstimateGasExecutionError',\n })\n this.cause = cause\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.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 GetEstimateGasErrorReturnType = Omit<\n EstimateGasExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError>(\n err: err,\n {\n docsPath,\n ...args\n }: Omit & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n): GetEstimateGasErrorReturnType {\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 EstimateGasExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetEstimateGasErrorReturnType\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n type EstimateFeesPerGasErrorType,\n internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type GetBlockErrorType,\n getBlock as getBlock_,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetTransactionCountErrorType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { LruMap } from '../../utils/lru.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport {\n type FillTransactionErrorType,\n type FillTransactionParameters,\n fillTransaction,\n} from '../public/fillTransaction.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\n/** @internal */\nexport const eip1559NetworkCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport const supportsFillTransaction = /*#__PURE__*/ new LruMap(128)\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType extends 'legacy'\n ? unknown\n : GetTransactionType,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick)\n>\n\nexport type PrepareTransactionRequestErrorType =\n | AccountNotFoundErrorType\n | AssertRequestErrorType\n | ParseAccountErrorType\n | GetBlockErrorType\n | GetTransactionCountErrorType\n | EstimateGasErrorType\n | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n let request = args as PrepareTransactionRequestParameters\n\n request.account ??= client.account\n request.parameters ??= defaultParameters\n\n const {\n account: account_,\n chain = client.chain,\n nonceManager,\n parameters,\n } = request\n\n const prepareTransactionRequest = (() => {\n if (typeof chain?.prepareTransactionRequest === 'function')\n return {\n fn: chain.prepareTransactionRequest,\n runAt: ['beforeFillTransaction'],\n }\n if (Array.isArray(chain?.prepareTransactionRequest))\n return {\n fn: chain.prepareTransactionRequest[0],\n runAt: chain.prepareTransactionRequest[1].runAt,\n }\n return undefined\n })()\n\n let chainId: number | undefined\n async function getChainId(): Promise {\n if (chainId) return chainId\n if (typeof request.chainId !== 'undefined') return request.chainId\n if (chain) return chain.id\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n const account = account_ ? parseAccount(account_) : account_\n\n let nonce = request.nonce\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n nonceManager\n ) {\n const chainId = await getChainId()\n nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n }\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillTransaction')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillTransaction',\n },\n )\n nonce ??= request.nonce\n }\n\n const attemptFill = (() => {\n // Do not attempt if blobs are provided.\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n request.kzg &&\n request.blobs\n )\n return false\n\n // Do not attempt if `eth_fillTransaction` is not supported.\n if (supportsFillTransaction.get(client.uid) === false) return false\n\n // Should attempt `eth_fillTransaction` if \"fees\" or \"gas\" are required to be populated,\n // otherwise, can just use the other individual calls.\n const shouldAttempt = ['fees', 'gas'].some((parameter) =>\n parameters.includes(parameter as PrepareTransactionRequestParameterType),\n )\n if (!shouldAttempt) return false\n\n // Check if `eth_fillTransaction` needs to be called.\n if (parameters.includes('chainId') && typeof request.chainId !== 'number')\n return true\n if (parameters.includes('nonce') && typeof nonce !== 'number') return true\n if (\n parameters.includes('fees') &&\n typeof request.gasPrice !== 'bigint' &&\n (typeof request.maxFeePerGas !== 'bigint' ||\n typeof (request as any).maxPriorityFeePerGas !== 'bigint')\n )\n return true\n if (parameters.includes('gas') && typeof request.gas !== 'bigint')\n return true\n return false\n })()\n\n const fillResult = attemptFill\n ? await getAction(\n client,\n fillTransaction,\n 'fillTransaction',\n )({ ...request, nonce } as FillTransactionParameters)\n .then((result) => {\n const {\n chainId,\n from,\n gas,\n gasPrice,\n nonce,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n type,\n ...rest\n } = result.transaction\n supportsFillTransaction.set(client.uid, true)\n return {\n ...request,\n ...(from ? { from } : {}),\n ...(type ? { type } : {}),\n ...(typeof chainId !== 'undefined' ? { chainId } : {}),\n ...(typeof gas !== 'undefined' ? { gas } : {}),\n ...(typeof gasPrice !== 'undefined' ? { gasPrice } : {}),\n ...(typeof nonce !== 'undefined' ? { nonce } : {}),\n ...(typeof maxFeePerBlobGas !== 'undefined'\n ? { maxFeePerBlobGas }\n : {}),\n ...(typeof maxFeePerGas !== 'undefined' ? { maxFeePerGas } : {}),\n ...(typeof maxPriorityFeePerGas !== 'undefined'\n ? { maxPriorityFeePerGas }\n : {}),\n ...('nonceKey' in rest && typeof rest.nonceKey !== 'undefined'\n ? { nonceKey: rest.nonceKey }\n : {}),\n }\n })\n .catch((e) => {\n const error = e as FillTransactionErrorType\n\n if (error.name !== 'TransactionExecutionError') return request\n\n const unsupported = error.walk?.((e) => {\n const error = e as BaseError\n return (\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n )\n })\n if (unsupported) supportsFillTransaction.set(client.uid, false)\n\n return request\n })\n : request\n\n nonce ??= fillResult.nonce\n\n request = {\n ...(fillResult as any),\n ...(account ? { from: account?.address } : {}),\n ...(nonce ? { nonce } : {}),\n }\n const { blobs, gas, kzg, type } = request\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillParameters')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillParameters',\n },\n )\n }\n\n let block: Block | undefined\n async function getBlock(): Promise {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n !nonceManager\n )\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n let isEip1559Network = eip1559NetworkCache.get(client.uid)\n if (typeof isEip1559Network === 'undefined') {\n const block = await getBlock()\n isEip1559Network = typeof block?.baseFeePerGas === 'bigint'\n eip1559NetworkCache.set(client.uid, isEip1559Network)\n }\n request.type = isEip1559Network ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof request.maxPriorityFeePerGas === 'undefined' &&\n request.maxFeePerGas &&\n request.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof request.maxFeePerGas !== 'undefined' ||\n typeof request.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n if (typeof request.gasPrice === 'undefined') {\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account,\n prepare: account?.type === 'local' ? [] : ['blobVersionedHashes'],\n } as EstimateGasParameters)\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('afterFillParameters')\n )\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'afterFillParameters',\n },\n )\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\n )\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToBigIntErrorType,\n hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChainParameter\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n | GetBlockErrorType\n | HexToBigIntErrorType\n | RequestErrorType\n | GetBlockErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n): Promise {\n return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args: EstimateMaxPriorityFeePerGasParameters & {\n block?: Block | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\n const maxPriorityFeePerGasHex = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n })\n return hexToBigInt(maxPriorityFeePerGasHex)\n } catch {\n // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n const [block, gasPrice] = await Promise.all([\n block_\n ? Promise.resolve(block_)\n : getAction(client, getBlock, 'getBlock')({}),\n getAction(client, getGasPrice, 'getGasPrice')({}),\n ])\n\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n if (maxPriorityFeePerGas < 0n) return 0n\n return maxPriorityFeePerGas\n }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n }) {\n let identifier = 'Block'\n if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n super(`${identifier} could not be found.`, { name: 'BlockNotFoundError' })\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetBlockErrorType =\n | BlockNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n includeTransactions: includeTransactions_,\n }: GetBlockParameters = {},\n): Promise> {\n const includeTransactions = includeTransactions_ ?? false\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let block: RpcBlock | null = null\n if (blockHash) {\n block = await client.request(\n {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n const format = client.chain?.formatters?.block?.format || formatBlock\n return format(block, 'getBlock')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(\n block: ExactPartial,\n _?: string | undefined,\n) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string') return transaction\n return formatTransaction(transaction)\n })\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { SignedAuthorizationList } from '../../types/authorization.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcAuthorizationList, RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n | 'blockHash'\n | 'blockNumber'\n | 'transactionIndex'\n\nexport type FormattedTransaction<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(\n transaction: ExactPartial,\n _?: string | undefined,\n) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? (transactionType as any)[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n } as Transaction\n\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\n\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity) return Number(transaction.yParity)\n\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n) return 0\n if (transaction_.v === 1n || transaction_.v === 28n) return 1\n if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n }\n\n return undefined\n })()\n\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') delete transaction_.maxFeePerBlobGas\n\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map((authorization) => ({\n address: (authorization as any).address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n })) as SignedAuthorizationList\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const gasPrice = await client.request({\n method: 'eth_gasPrice',\n })\n return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesLegacy,\n FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n type EstimateMaxPriorityFeePerGasErrorType,\n internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n type extends FeeValuesType = FeeValuesType,\n> = {\n /**\n * The type of fee values to return.\n *\n * - `legacy`: Returns the legacy gas price.\n * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n *\n * @default 'eip1559'\n */\n type?: type | FeeValuesType | undefined\n} & GetChainParameter\n\nexport type EstimateFeesPerGasReturnType<\n type extends FeeValuesType = FeeValuesType,\n> =\n | (type extends 'legacy' ? FeeValuesLegacy : never)\n | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n | BaseFeeScalarErrorType\n | EstimateMaxPriorityFeePerGasErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args?: EstimateFeesPerGasParameters | undefined,\n): Promise> {\n return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args: EstimateFeesPerGasParameters & {\n block?: Block | undefined\n request?: PrepareTransactionRequestParameters | undefined\n },\n): Promise> {\n const {\n block: block_,\n chain = client.chain,\n request,\n type = 'eip1559',\n } = args || {}\n\n const baseFeeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n return chain.fees.baseFeeMultiplier({\n block: block_ as Block,\n client,\n request,\n } as ChainFeesFnParameters)\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiply = (base: bigint) =>\n (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n BigInt(denominator)\n\n const block = block_\n ? block_\n : await getAction(client, getBlock, 'getBlock')({})\n\n if (typeof chain?.fees?.estimateFeesPerGas === 'function') {\n const fees = (await chain.fees.estimateFeesPerGas({\n block: block_ as Block,\n client,\n multiply,\n request,\n type,\n } as ChainEstimateFeesPerGasFnParameters)) as unknown as EstimateFeesPerGasReturnType\n\n if (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client,\n {\n block: block as Block,\n chain,\n request,\n },\n )\n\n const baseFeePerGas = multiply(block.baseFeePerGas)\n const maxFeePerGas =\n request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as EstimateFeesPerGasReturnType\n }\n\n const gasPrice =\n request?.gasPrice ??\n multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n return {\n gasPrice,\n } as EstimateFeesPerGasReturnType\n}\n","import type { Address } from 'abitype'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { BaseFeeScalarError } from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport { getBlock } from './getBlock.js'\nimport { getChainId as getChainId_ } from './getChainId.js'\n\nexport type FillTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetAccountParameter &\n GetChainParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n }\n\nexport type FillTransactionReturnType<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = {\n raw: Hex\n transaction: FormattedTransaction<_derivedChain>\n}\n\nexport type FillTransactionErrorType =\n | GetTransactionErrorReturnType\n | ErrorType\n\n/**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { fillTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await fillTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function fillTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n): Promise> {\n const {\n account = client.account,\n accessList,\n authorizationList,\n chain = client.chain,\n blobVersionedHashes,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce: nonce_,\n nonceManager,\n to,\n type,\n value,\n ...rest\n } = parameters\n\n const nonce = await (async () => {\n if (!account) return nonce_\n if (!nonceManager) return nonce_\n if (typeof nonce_ !== 'undefined') return nonce_\n const account_ = parseAccount(account)\n const chainId = chain\n ? chain.id\n : await getAction(client, getChainId_, 'getChainId')({})\n return await nonceManager.consume({\n address: account_.address,\n chainId,\n client,\n })\n })()\n\n assertRequest(parameters)\n\n const chainFormat = chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account: account ? parseAccount(account) : undefined,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'fillTransaction',\n )\n\n try {\n const response = await client.request({\n method: 'eth_fillTransaction',\n params: [request],\n })\n const format = chain?.formatters?.transaction?.format || formatTransaction\n\n const transaction = format(response.tx)\n\n // Remove unnecessary fields.\n delete transaction.blockHash\n delete transaction.blockNumber\n delete transaction.r\n delete transaction.s\n delete transaction.transactionIndex\n delete transaction.v\n delete transaction.yParity\n\n // Rewrite fields.\n transaction.data = transaction.input\n\n // Preference supplied fees (some nodes do not take these preferences).\n if (transaction.gas) transaction.gas = parameters.gas ?? transaction.gas\n if (transaction.gasPrice)\n transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice\n if (transaction.maxFeePerBlobGas)\n transaction.maxFeePerBlobGas =\n parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas\n if (transaction.maxFeePerGas)\n transaction.maxFeePerGas =\n parameters.maxFeePerGas ?? transaction.maxFeePerGas\n if (transaction.maxPriorityFeePerGas)\n transaction.maxPriorityFeePerGas =\n parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas\n if (transaction.nonce)\n transaction.nonce = parameters.nonce ?? transaction.nonce\n\n // Build fee multiplier function.\n const feeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function') {\n const block = await getAction(client, getBlock, 'getBlock')({})\n return chain.fees.baseFeeMultiplier({\n block,\n client,\n request: parameters,\n } as ChainFeesFnParameters)\n }\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (feeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = feeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiplyFee = (base: bigint) =>\n (base * BigInt(Math.ceil(feeMultiplier * denominator))) /\n BigInt(denominator)\n\n // Apply fee multiplier.\n if (transaction.maxFeePerGas && !parameters.maxFeePerGas)\n transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas)\n if (transaction.gasPrice && !parameters.gasPrice)\n transaction.gasPrice = multiplyFee(transaction.gasPrice)\n\n return {\n raw: response.raw,\n transaction: {\n from: request.from,\n ...transaction,\n },\n }\n } catch (err) {\n throw getTransactionError(\n err as BaseError,\n {\n ...parameters,\n chain: client.chain,\n } as never,\n )\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport {\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n} from '../../errors/transaction.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 GetTransactionErrorParameters = Omit<\n SendTransactionParameters,\n 'account' | 'chain'\n> & {\n account: Account | null\n chain?: Chain | undefined\n docsPath?: string | undefined\n}\n\nexport type GetTransactionErrorReturnType = Omit<\n TransactionExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getTransactionError>(\n err: err,\n { docsPath, ...args }: GetTransactionErrorParameters,\n): GetTransactionErrorReturnType {\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 TransactionExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetTransactionErrorReturnType\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type GetLogsErrorType,\n type GetLogsParameters,\n getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n)\n\nexport type GetContractEventsReturnType<\n abi extends Abi | readonly unknown[] = readonly unknown[],\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n ///\n isPending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetContractEventsErrorType =\n | GetAbiItemErrorType\n | GetLogsErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/contract/getContractEvents#getcontractevents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetContractEventsReturnType\n> {\n const {\n abi,\n address,\n args,\n blockHash,\n eventName,\n fromBlock,\n toBlock,\n strict,\n } = parameters\n const event = eventName\n ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n : undefined\n const events = !event\n ? (abi as Abi).filter((x) => x.type === 'event')\n : undefined\n return getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n blockHash,\n event,\n events,\n fromBlock,\n toBlock,\n strict,\n } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","// TODO(v3): checksum address.\n\nimport type { Abi, AbiEvent, AbiEventParameter, Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractEventName, GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport { toBytes } from '../encoding/toBytes.js'\nimport { formatLog } from '../formatters/log.js'\nimport { keccak256 } from '../hash/keccak256.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type DecodeEventLogErrorType,\n decodeEventLog,\n} from './decodeEventLog.js'\n\nexport type ParseEventLogsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n allArgs = GetEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n {\n EnableUnion: true\n IndexedOnly: false\n Required: false\n }\n >,\n> = {\n /** Contract ABI. */\n abi: abi\n /** Arguments for the event. */\n args?: allArgs | undefined\n /** Contract event. */\n eventName?:\n | eventName\n | ContractEventName\n | ContractEventName[]\n | undefined\n /** List of logs. */\n logs: (Log | RpcLog)[]\n strict?: strict | boolean | undefined\n}\n\nexport type ParseEventLogsReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n derivedEventName extends\n | ContractEventName\n | undefined = eventName extends ContractEventName[]\n ? eventName[number]\n : eventName,\n> = Log[]\n\nexport type ParseEventLogsErrorType = DecodeEventLogErrorType | ErrorType\n\n/**\n * Extracts & decodes logs matching the provided signature(s) (`abi` + optional `eventName`)\n * from a set of opaque logs.\n *\n * @param parameters - {@link ParseEventLogsParameters}\n * @returns The logs. {@link ParseEventLogsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { parseEventLogs } from 'viem/op-stack'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const receipt = await getTransactionReceipt(client, {\n * hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea',\n * })\n *\n * const logs = parseEventLogs({ logs: receipt.logs })\n * // [{ args: { ... }, eventName: 'TransactionDeposited', ... }, ...]\n */\nexport function parseEventLogs<\n abi extends Abi | readonly unknown[],\n strict extends boolean | undefined = true,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = undefined,\n>(\n parameters: ParseEventLogsParameters,\n): ParseEventLogsReturnType {\n const { abi, args, logs, strict = true } = parameters\n\n const eventName = (() => {\n if (!parameters.eventName) return undefined\n if (Array.isArray(parameters.eventName)) return parameters.eventName\n return [parameters.eventName as string]\n })()\n\n const abiTopics = (abi as Abi)\n .filter((abiItem) => abiItem.type === 'event')\n .map((abiItem) => ({\n abi: abiItem,\n selector: toEventSelector(abiItem),\n }))\n\n return logs\n .map((log) => {\n // Normalize RpcLog (hex-encoded quantities) to Log (bigint/number).\n // When logs come directly from an RPC response (e.g. eth_getLogs),\n // fields like blockNumber are hex strings instead of bigints.\n const formattedLog =\n typeof log.blockNumber === 'string' ? formatLog(log as RpcLog) : log\n\n // Find all matching ABI items with the same selector.\n // Multiple events can share the same selector but differ in indexed parameters\n // (e.g., ERC20 vs ERC721 Transfer events).\n const abiItems = abiTopics.filter(\n (abiTopic) => formattedLog.topics[0] === abiTopic.selector,\n )\n if (abiItems.length === 0) return null\n\n // Try each matching ABI item until one successfully decodes.\n let event: { eventName: string; args: unknown } | undefined\n let abiItem: { abi: AbiEvent; selector: Address } | undefined\n\n for (const item of abiItems) {\n try {\n event = decodeEventLog({\n ...formattedLog,\n abi: [item.abi],\n strict: true,\n })\n abiItem = item\n break\n } catch {\n // Try next ABI item\n }\n }\n\n // If strict decoding failed for all, and we're in non-strict mode,\n // fall back to the first matching ABI item.\n if (!event && !strict) {\n abiItem = abiItems[0]\n try {\n event = decodeEventLog({\n data: formattedLog.data,\n topics: formattedLog.topics,\n abi: [abiItem.abi],\n strict: false,\n })\n } catch {\n // If decoding still fails, return partial log in non-strict mode.\n const isUnnamed = abiItem.abi.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n return {\n ...formattedLog,\n args: isUnnamed ? [] : {},\n eventName: abiItem.abi.name,\n }\n }\n }\n\n // If no event was found, return null.\n if (!event || !abiItem) return null\n\n // Check that the decoded event name matches the provided event name.\n if (eventName && !eventName.includes(event.eventName)) return null\n\n // Check that the decoded event args match the provided args.\n if (\n !includesArgs({\n args: event.args,\n inputs: abiItem.abi.inputs,\n matchArgs: args,\n })\n )\n return null\n\n return { ...event, ...formattedLog }\n })\n .filter(Boolean) as unknown as ParseEventLogsReturnType<\n abi,\n eventName,\n strict\n >\n}\n\nfunction includesArgs(parameters: {\n args: unknown\n inputs: AbiEvent['inputs']\n matchArgs: unknown\n}) {\n const { args, inputs, matchArgs } = parameters\n\n if (!matchArgs) return true\n if (!args) return false\n\n function isEqual(input: AbiEventParameter, value: unknown, arg: unknown) {\n try {\n if (input.type === 'address')\n return isAddressEqual(value as Address, arg as Address)\n if (input.type === 'string' || input.type === 'bytes')\n return keccak256(toBytes(value as string)) === arg\n return value === arg\n } catch {\n return false\n }\n }\n\n if (Array.isArray(args) && Array.isArray(matchArgs)) {\n return matchArgs.every((value, index) => {\n if (value === null || value === undefined) return true\n const input = inputs[index]\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) => isEqual(input, value, args[index]))\n })\n }\n\n if (\n typeof args === 'object' &&\n !Array.isArray(args) &&\n typeof matchArgs === 'object' &&\n !Array.isArray(matchArgs)\n )\n return Object.entries(matchArgs).every(([key, value]) => {\n if (value === null || value === undefined) return true\n const input = inputs.find((input) => input.name === key)\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) =>\n isEqual(input, value, (args as Record)[key]),\n )\n })\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n blockTimestamp: log.blockTimestamp\n ? BigInt(log.blockTimestamp)\n : log.blockTimestamp === null\n ? null\n : undefined,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n } as Log\n}\n","import type { Abi, AbiParameter } from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgsFromTopics,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n Prettify,\n UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n> = {\n abi: abi\n data?: data | undefined\n eventName?: eventName | ContractEventName | undefined\n strict?: strict | boolean | undefined\n topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n ///\n allEventNames extends\n ContractEventName = eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n> = IsNarrowable extends true\n ? {\n [name in allEventNames]: Prettify<\n {\n eventName: name\n } & UnionEvaluate<\n ContractEventArgsFromTopics extends infer allArgs\n ? topics extends readonly []\n ? data extends undefined\n ? { args?: undefined }\n : { args?: allArgs | undefined }\n : { args: allArgs }\n : never\n >\n >\n }[allEventNames]\n : {\n eventName: eventName\n args: readonly unknown[] | undefined\n }\n\nexport type DecodeEventLogErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiEventSignatureEmptyTopicsErrorType\n | AbiEventSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | DecodeLogTopicsMismatchErrorType\n | DecodeLogDataMismatchErrorType\n | FormatAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n>(\n parameters: DecodeEventLogParameters,\n): DecodeEventLogReturnType {\n const {\n abi,\n data,\n strict: strict_,\n topics,\n } = parameters as DecodeEventLogParameters\n\n const strict = strict_ ?? true\n const [signature, ...argTopics] = topics\n if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n const abiItem = abi.find(\n (x) =>\n x.type === 'event' &&\n signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n )\n\n if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n const { name, inputs } = abiItem\n const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n const args: any = isUnnamed ? [] : {}\n\n // Decode topics (indexed args).\n const indexedInputs = inputs\n .map((x, i) => [x, i] as const)\n .filter(([x]) => 'indexed' in x && x.indexed)\n\n const missingIndexedInputs: [AbiParameter, number][] = []\n\n for (let i = 0; i < indexedInputs.length; i++) {\n const [param, argIndex] = indexedInputs[i]\n const topic = argTopics[i]\n if (!topic) {\n if (strict)\n throw new DecodeLogTopicsMismatch({\n abiItem,\n param: param as AbiParameter & { indexed: boolean },\n })\n // Track missing indexed inputs to decode from data when strict is false\n missingIndexedInputs.push([param, argIndex])\n continue\n }\n args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({\n param,\n value: topic,\n })\n }\n\n // Decode data (non-indexed args + missing indexed args when strict is false).\n const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n\n // When strict is false, missing indexed inputs should be decoded from data\n const inputsToDecode = strict\n ? nonIndexedInputs\n : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]\n\n if (inputsToDecode.length > 0) {\n if (data && data !== '0x') {\n try {\n const decodedData = decodeAbiParameters(\n inputsToDecode,\n data,\n ) as unknown[]\n if (decodedData) {\n let dataIndex = 0\n // First, assign missing indexed parameters (when strict is false)\n if (!strict) {\n for (const [param, argIndex] of missingIndexedInputs) {\n args[isUnnamed ? argIndex : param.name || argIndex] =\n decodedData[dataIndex++]\n }\n }\n // Then, assign non-indexed parameters\n if (isUnnamed) {\n for (let i = 0; i < inputs.length; i++)\n if (args[i] === undefined && dataIndex < decodedData.length)\n args[i] = decodedData[dataIndex++]\n } else\n for (let i = 0; i < nonIndexedInputs.length; i++)\n args[nonIndexedInputs[i].name!] = decodedData[dataIndex++]\n }\n } catch (err) {\n if (strict) {\n if (\n err instanceof AbiDecodingDataSizeTooSmallError ||\n err instanceof PositionOutOfBoundsError\n )\n throw new DecodeLogDataMismatch({\n abiItem,\n data: data,\n params: inputsToDecode,\n size: size(data),\n })\n throw err\n }\n }\n } else if (strict) {\n throw new DecodeLogDataMismatch({\n abiItem,\n data: '0x',\n params: inputsToDecode,\n size: 0,\n })\n }\n }\n\n return {\n eventName: name,\n args: Object.values(args).length > 0 ? args : undefined,\n } as unknown as DecodeEventLogReturnType\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n if (\n param.type === 'string' ||\n param.type === 'bytes' ||\n param.type === 'tuple' ||\n param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n )\n return value\n const decodedArg = decodeAbiParameters([param], value) || []\n return decodedArg[0]\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** Address or list of addresses from which logs originated */\n address?: Address | Address[] | undefined\n} & (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events: abiEvents\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n) &\n (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n )\n\nexport type GetLogsReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetLogsErrorType =\n | DecodeEventLogErrorType\n | EncodeEventTopicsErrorType\n | FormatLogErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n {\n address,\n blockHash,\n fromBlock,\n toBlock,\n event,\n events: events_,\n args,\n strict: strict_,\n }: GetLogsParameters = {},\n): Promise> {\n const strict = strict_ ?? false\n const events = events_ ?? (event ? [event] : undefined)\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args: events_ ? undefined : args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n let logs: RpcLog[]\n if (blockHash) {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [{ address, topics, blockHash }],\n })\n } else {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [\n {\n address,\n topics,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n },\n ],\n })\n }\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!events)\n return formattedLogs as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: events,\n args: args as any,\n logs: formattedLogs,\n strict,\n }) as unknown as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = ContractFunctionReturnType\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n>(\n client: Client,\n parameters: ReadContractParameters,\n): Promise> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { Abi, AbiFunction, AbiStateMutability, Address } from 'abitype'\n\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 type { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, ParseAccount } from '../../types/account.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n ExtractAbiFunctionForArgs,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type {\n IsNarrowable,\n NoInfer,\n Prettify,\n UnionEvaluate,\n UnionOmit,\n} from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { WriteContractParameters } from '../wallet/writeContract.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type GetMutabilityAwareValue<\n abi extends Abi | readonly unknown[],\n mutability extends AbiStateMutability = AbiStateMutability,\n functionName extends ContractFunctionName<\n abi,\n mutability\n > = ContractFunctionName,\n valueType = TransactionRequest['value'],\n args extends ContractFunctionArgs<\n abi,\n mutability,\n functionName\n > = ContractFunctionArgs,\n abiFunction extends AbiFunction = abi extends Abi\n ? ExtractAbiFunctionForArgs\n : AbiFunction,\n _Narrowable extends boolean = IsNarrowable,\n> = _Narrowable extends true\n ? abiFunction['stateMutability'] extends 'payable'\n ? { value?: NoInfer | undefined }\n : abiFunction['payable'] extends true\n ? { value?: NoInfer | undefined }\n : { value?: undefined }\n : { value?: NoInfer | undefined }\n\nexport type SimulateContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n ///\n derivedChain extends Chain | undefined = DeriveChain,\n callParameters extends\n CallParameters = CallParameters,\n> = {\n account?: accountOverride | null | undefined\n chain?: chainOverride | undefined\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n} & ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit<\n callParameters,\n | 'account'\n | 'batch'\n | 'code'\n | 'to'\n | 'data'\n | 'factory'\n | 'factoryData'\n | 'value'\n > &\n GetMutabilityAwareValue<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n callParameters['value'],\n args\n >\n\nexport type SimulateContractReturnType<\n out abi extends Abi | readonly unknown[] = Abi,\n in out functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n in out args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n /** @ts-expect-error cast variance */\n out chain extends Chain | undefined = Chain | undefined,\n out account extends Account | undefined = Account | undefined,\n out chainOverride extends Chain | undefined = Chain | undefined,\n out accountOverride extends Account | Address | null | undefined =\n | Account\n | Address\n | null\n | undefined,\n ///\n in out minimizedAbi extends Abi = readonly [\n ExtractAbiFunctionForArgs<\n abi extends Abi ? abi : Abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >,\n ],\n out resolvedAccount extends\n | Account\n | null\n | undefined = accountOverride extends Account | Address | null\n ? ParseAccount\n : account,\n> = {\n result: ContractFunctionReturnType<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >\n request: Prettify<\n UnionEvaluate<\n UnionOmit<\n WriteContractParameters<\n minimizedAbi,\n functionName,\n args,\n chain,\n undefined,\n chainOverride\n >,\n 'account' | 'abi' | 'args' | 'chain' | 'functionName'\n >\n > &\n ContractFunctionParameters<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n > & {\n chain: DeriveChain\n } & (resolvedAccount extends Account | null\n ? { account: resolvedAccount }\n : { account?: undefined })\n >\n}\n\nexport type SimulateContractErrorType =\n | ParseAccountErrorType\n | EncodeFunctionDataErrorType\n | GetContractErrorReturnType\n | ErrorType\n\n/**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await simulateContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function simulateContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n): Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n> {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...callRequest\n } = parameters as SimulateContractParameters\n\n const account = callRequest.account\n ? parseAccount(callRequest.account)\n : client.account\n const calldata = encodeFunctionData({ abi, args, functionName })\n\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n batch: false,\n data: `${calldata}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...callRequest,\n account,\n })\n const result = decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n })\n const minimizedAbi = abi.filter(\n (abiItem) =>\n 'name' in abiItem && abiItem.name === parameters.functionName,\n )\n return {\n result,\n request: {\n abi: minimizedAbi,\n address,\n args,\n dataSuffix,\n functionName,\n ...callRequest,\n account,\n },\n } as unknown as SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/simulateContract',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport { createContractEventFilter } from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n type GetContractEventsParameters,\n getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchContractEventOnLogsParameter<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = abi extends Abi\n ? Abi extends abi\n ? Log[]\n : Log, strict>[]\n : Log[]\n\nexport type WatchContractEventOnLogsFn<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter) => void\n\nexport type WatchContractEventParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchContractEventOnLogsFn<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n strict\n >\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & GetPollOptions\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n>(\n client: Client,\n parameters: WatchContractEventParameters,\n): WatchContractEventReturnType {\n const {\n abi,\n address,\n args,\n batch = true,\n eventName,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n } = parameters\n\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n const pollContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abi, eventName> | undefined\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createContractEventFilter,\n 'createContractEventFilter',\n )({\n abi,\n address,\n args: args as any,\n eventName: eventName as any,\n strict: strict as any,\n fromBlock,\n })) as Filter<'event', abi, eventName>\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber < blockNumber) {\n logs = await getAction(\n client,\n getContractEvents,\n 'getContractEvents',\n )({\n abi,\n address,\n args,\n eventName,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n strict,\n } as {} as GetContractEventsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n ])\n\n let active = true\n let unsubscribe = () => (active = false)\n return observe(observerId, { onLogs, onError }, (emit) => {\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const topics: LogTopic[] = eventName\n ? encodeEventTopics({\n abi: abi,\n eventName: eventName,\n args,\n } as EncodeEventTopicsParameters)\n : []\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: abi,\n data: log.data,\n topics: log.topics as any,\n strict: strict_,\n })\n const formatted = formatLog(log, {\n args,\n eventName: eventName as string,\n })\n emit.onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n emit.onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollContractEvent() : subscribeContractEvent()\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record\n\nexport type ObserveErrorType = ErrorType\n\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map<\n string,\n () => void | Promise\n>()\n\ntype EmitFunction = (\n emit: callbacks,\n) => MaybePromise void) | (() => Promise)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction,\n) {\n const callbackId = ++callbackCount\n\n const getListeners = () => listenersCache.get(observerId) || []\n\n const unsubscribe = () => {\n const listeners = getListeners()\n listenersCache.set(\n observerId,\n listeners.filter((cb: any) => cb.id !== callbackId),\n )\n }\n\n const unwatch = () => {\n const listeners = getListeners()\n if (!listeners.some((cb: any) => cb.id === callbackId)) return\n const cleanup = cleanupCache.get(observerId)\n if (listeners.length === 1 && cleanup) {\n const p = cleanup()\n if (p instanceof Promise) p.catch(() => {})\n }\n unsubscribe()\n }\n\n const listeners = getListeners()\n listenersCache.set(observerId, [\n ...listeners,\n { id: callbackId, fns: callbacks },\n ])\n\n if (listeners && listeners.length > 0) return unwatch\n\n const emit: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract]\n }\n\n const cleanup = fn(emit)\n if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n return unwatch\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise) | undefined\n // The interval (in ms).\n interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise,\n { emitOnBegin, initialWaitTime, interval }: PollOptions,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | undefined | void\n if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n const initialWait = (await initialWaitTime?.(data)) ?? interval\n await wait(initialWait)\n\n const poll = async () => {\n if (!active) return\n await fn({ unpoll: unwatch })\n await wait(interval)\n poll()\n }\n\n poll()\n }\n watch()\n\n return unwatch\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache(cacheKey: string) {\n const buildCache = (cacheKey: string, cache: Map) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype WithCacheParameters = {\n /** The key to cache the data against. */\n cacheKey: string\n /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n cacheTime?: number | undefined\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache(\n fn: () => Promise,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache(cacheKey)\n\n // If a response exists in the cache, and it's not expired, return it\n // and do not invoke the promise.\n // If the max age is 0, the cache is disabled.\n const response = cache.response.get()\n if (response && cacheTime > 0) {\n const age = Date.now() - response.created.getTime()\n if (age < cacheTime) return response.data\n }\n\n let promise = cache.promise.get()\n if (!promise) {\n promise = fn()\n\n // Store the promise in the cache so that subsequent invocations\n // will wait for the same promise to resolve (deduping).\n cache.promise.set(promise)\n }\n\n try {\n const data = await promise\n\n // Store the response in the cache so that subsequent invocations\n // will return the same response.\n cache.response.set({ created: new Date(), data })\n\n return data\n } finally {\n // Clear the promise cache so that subsequent invocations will\n // invoke the promise again.\n cache.promise.clear()\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\nexport function getBlockNumberCache(id: string) {\n return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber(\n client: Client,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcLog } from '../../index.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter\n}\n\nexport type GetFilterChangesReturnType<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = filterType extends 'event'\n ? Log[]\n : Hash[]\n\nexport type GetFilterChangesErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n transport extends Transport,\n chain extends Chain | undefined,\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const strict = 'strict' in filter && filter.strict\n\n const logs = await filter.request({\n method: 'eth_getFilterChanges',\n params: [filter.id],\n })\n\n if (typeof logs[0] === 'string')\n return logs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n\n const formattedLogs = logs.map((log) => formatLog(log as RpcLog))\n if (!('abi' in filter) || !filter.abi)\n return formattedLogs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n filter: Filter\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n _client: Client,\n { filter }: UninstallFilterParameters,\n): Promise {\n return filter.request({\n method: 'eth_uninstallFilter',\n params: [filter.id],\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction(\n client: Client,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry(\n fn: () => Promise,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial,\n _?: string | undefined,\n) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[\n transactionReceipt.type as keyof typeof transactionType\n ] || transactionReceipt.type\n : null,\n } as TransactionReceipt\n\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { DataSuffix } from '../types/dataSuffix.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify | undefined\n }\n | undefined\n /**\n * Default block tag to use for RPC requests.\n *\n * If the chain supports a pre-confirmation mechanism\n * (set via `chain.experimental_preconfirmationTime`), defaults to `'pending'`.\n *\n * @default 'latest'\n */\n experimental_blockTag?: BlockTag | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default chain.blockTime / 3\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default chain.blockTime / 3\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial>,\n >(\n fn: (\n client: Client,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** Default block tag to use for RPC requests. */\n experimental_blockTag?: BlockTag | undefined\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType['config'] & ReturnType['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n chain,\n ccipRead,\n dataSuffix,\n key = 'base',\n name = 'Base Client',\n type = 'base',\n } = parameters\n\n const experimental_blockTag =\n parameters.experimental_blockTag ??\n (typeof chain?.experimental_preconfirmationTime === 'number'\n ? 'pending'\n : undefined)\n const blockTime = chain?.blockTime ?? 12_000\n\n const defaultPollingInterval = Math.min(\n Math.max(Math.floor(blockTime / 2), 500),\n 4_000,\n )\n const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval\n const cacheTime = parameters.cacheTime ?? pollingInterval\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n account,\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n dataSuffix,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n ...(experimental_blockTag ? { experimental_blockTag } : {}),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema(): rpcSchema {\n return null as any\n}\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n addressResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n Pick & {\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS address for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Name to get the address for.\n */\n name: string\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n | GetChainContractAddressErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | DecodeFunctionResultErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress(\n client: Client,\n parameters: GetEnsAddressParameters,\n): Promise {\n const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } =\n parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n const args = (() => {\n if (coinType != null) return [namehash(name), BigInt(coinType)] as const\n return [namehash(name)] as const\n })()\n\n try {\n const functionData = encodeFunctionData({\n abi: addressResolverAbi,\n functionName: 'addr',\n args,\n })\n\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolveWithGateways',\n args: [\n toHex(packetToBytes(name)),\n functionData,\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const address = decodeFunctionResult({\n abi: addressResolverAbi,\n args,\n functionName: 'addr',\n data: res[0],\n })\n\n if (address === '0x') return null\n if (trim(address) === '0x00') return null\n return address\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(err: unknown): boolean {\n if (!(err instanceof BaseError)) return false\n const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (!(cause instanceof ContractFunctionRevertedError)) return false\n\n if (cause.data?.errorName === 'HttpError') return true\n if (cause.data?.errorName === 'ResolverError') return true\n if (cause.data?.errorName === 'ResolverNotContract') return true\n if (cause.data?.errorName === 'ResolverNotFound') return true\n if (cause.data?.errorName === 'ReverseAddressMismatch') return true\n if (cause.data?.errorName === 'UnsupportedResolverProfile') return true\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n type ToBytesErrorType,\n toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | ToBytesErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ConcatErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0x08c85f2f4059e930c45a6aeff9dcd3bd95dc3c5c1cddef6a0626b31152248560'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n let result = new Uint8Array(32).fill(0) as ByteArray\n if (!name) return bytesToHex(result)\n\n const labels = name.split('.')\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n const hashed = hashFromEncodedLabel\n ? toBytes(hashFromEncodedLabel)\n : keccak256(stringToBytes(labels[i]), 'bytes')\n result = keccak256(concat([result, hashed]), 'bytes')\n }\n\n return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n if (label.length !== 66) return null\n if (label.indexOf('[') !== 0) return null\n if (label.indexOf(']') !== 65) return null\n const hash = `0x${label.slice(1, 65)}`\n if (!isHex(hash)) return null\n return hash\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n type EncodeLabelhashErrorType,\n encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n | EncodeLabelhashErrorType\n | LabelhashErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n *\n * @example\n * packetToBytes('awkweb.eth')\n * '0x0661776b7765620365746800'\n *\n * @see https://docs.ens.domains/resolution/names#dns\n *\n */\nexport function packetToBytes(packet: string): ByteArray {\n // strip leading and trailing `.`\n const value = packet.replace(/^\\.|\\.$/gm, '')\n if (value.length === 0) return new Uint8Array(1)\n\n const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n let offset = 0\n const list = value.split('.')\n for (let i = 0; i < list.length; i++) {\n let encoded = stringToBytes(list[i])\n // if the length is > 255, make the encoded label value a labelhash\n // this is compatible with the universal resolver\n if (encoded.byteLength > 255)\n encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n bytes[offset] = encoded.length\n bytes.set(encoded, offset + 1)\n offset += encoded.length + 1\n }\n\n if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n return bytes\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n const result = new Uint8Array(32).fill(0)\n if (!label) return bytesToHex(result)\n return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","import { BaseError } from './base.js'\n\nexport type EnsAvatarInvalidMetadataErrorType =\n EnsAvatarInvalidMetadataError & {\n name: 'EnsAvatarInvalidMetadataError'\n }\nexport class EnsAvatarInvalidMetadataError extends BaseError {\n constructor({ data }: { data: any }) {\n super(\n 'Unable to extract image from metadata. The metadata may be malformed or invalid.',\n {\n metaMessages: [\n '- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.',\n '',\n `Provided data: ${JSON.stringify(data)}`,\n ],\n name: 'EnsAvatarInvalidMetadataError',\n },\n )\n }\n}\n\nexport type EnsAvatarInvalidNftUriErrorType = EnsAvatarInvalidNftUriError & {\n name: 'EnsAvatarInvalidNftUriError'\n}\nexport class EnsAvatarInvalidNftUriError extends BaseError {\n constructor({ reason }: { reason: string }) {\n super(`ENS NFT avatar URI is invalid. ${reason}`, {\n name: 'EnsAvatarInvalidNftUriError',\n })\n }\n}\n\nexport type EnsAvatarUriResolutionErrorType = EnsAvatarUriResolutionError & {\n name: 'EnsAvatarUriResolutionError'\n}\nexport class EnsAvatarUriResolutionError extends BaseError {\n constructor({ uri }: { uri: string }) {\n super(\n `Unable to resolve ENS avatar URI \"${uri}\". The URI may be malformed, invalid, or does not respond with a valid image.`,\n { name: 'EnsAvatarUriResolutionError' },\n )\n }\n}\n\nexport type EnsAvatarUnsupportedNamespaceErrorType =\n EnsAvatarUnsupportedNamespaceError & {\n name: 'EnsAvatarUnsupportedNamespaceError'\n }\nexport class EnsAvatarUnsupportedNamespaceError extends BaseError {\n constructor({ namespace }: { namespace: string }) {\n super(\n `ENS NFT avatar namespace \"${namespace}\" is not supported. Must be \"erc721\" or \"erc1155\".`,\n { name: 'EnsAvatarUnsupportedNamespaceError' },\n )\n }\n}\n\nexport type EnsInvalidChainIdErrorType = EnsInvalidChainIdError & {\n name: 'EnsInvalidChainIdError'\n}\nexport class EnsInvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId: number }) {\n super(\n `Invalid ENSIP-11 chainId: ${chainId}. Must be between 0 and 0x7fffffff, or 1.`,\n {\n name: 'EnsInvalidChainIdError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n type ReadContractErrorType,\n readContract,\n} from '../../../actions/public/readContract.js'\nimport type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport {\n EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n} from '../../../errors/ens.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\ntype UriItem = {\n uri: string\n isOnChain: boolean\n isEncoded: boolean\n}\n\nconst networkRegex =\n /(?https?:\\/\\/[^/]*|ipfs:\\/|ipns:\\/|ar:\\/)?(?\\/)?(?ipfs\\/|ipns\\/)?(?[\\w\\-.]+)(?\\/.*)?/\nconst ipfsHashRegex =\n /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\\/(?[\\w\\-.]+))?(?\\/.*)?$/\nconst base64Regex = /^data:([a-zA-Z\\-/+]*);base64,([^\"].*)/\nconst dataURIRegex = /^data:([a-zA-Z\\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/\n\ntype IsImageUriErrorType = ErrorType\n\n/** @internal */\nexport async function isImageUri(uri: string) {\n try {\n const res = await fetch(uri, { method: 'HEAD' })\n // retrieve content type header to check if content is image\n if (res.status === 200) {\n const contentType = res.headers.get('content-type')\n return contentType?.startsWith('image/')\n }\n return false\n } catch (error: any) {\n // if error is not cors related then fail\n if (typeof error === 'object' && typeof error.response !== 'undefined') {\n return false\n }\n // fail in NodeJS, since the error is not cors but any other network issue\n if (!Object.hasOwn(globalThis, 'Image')) return false\n // in case of cors, use image api to validate if given url is an actual image\n return new Promise((resolve) => {\n const img = new Image()\n img.onload = () => {\n resolve(true)\n }\n img.onerror = () => {\n resolve(false)\n }\n img.src = uri\n })\n }\n}\n\ntype GetGatewayErrorType = ErrorType\n\n/** @internal */\nexport function getGateway(custom: string | undefined, defaultGateway: string) {\n if (!custom) return defaultGateway\n if (custom.endsWith('/')) return custom.slice(0, -1)\n return custom\n}\n\nexport type ResolveAvatarUriErrorType =\n | GetGatewayErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport function resolveAvatarUri({\n uri,\n gatewayUrls,\n}: {\n uri: string\n gatewayUrls?: AssetGatewayUrls | undefined\n}): UriItem {\n const isEncoded = base64Regex.test(uri)\n if (isEncoded) return { uri, isOnChain: true, isEncoded }\n\n const ipfsGateway = getGateway(gatewayUrls?.ipfs, 'https://ipfs.io')\n const arweaveGateway = getGateway(gatewayUrls?.arweave, 'https://arweave.net')\n\n const networkRegexMatch = uri.match(networkRegex)\n const {\n protocol,\n subpath,\n target,\n subtarget = '',\n } = networkRegexMatch?.groups || {}\n\n const isIPNS = protocol === 'ipns:/' || subpath === 'ipns/'\n const isIPFS =\n protocol === 'ipfs:/' || subpath === 'ipfs/' || ipfsHashRegex.test(uri)\n\n if (uri.startsWith('http') && !isIPNS && !isIPFS) {\n let replacedUri = uri\n if (gatewayUrls?.arweave)\n replacedUri = uri.replace(/https:\\/\\/arweave.net/g, gatewayUrls?.arweave)\n return { uri: replacedUri, isOnChain: false, isEncoded: false }\n }\n\n if ((isIPNS || isIPFS) && target) {\n return {\n uri: `${ipfsGateway}/${isIPNS ? 'ipns' : 'ipfs'}/${target}${subtarget}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n if (protocol === 'ar:/' && target) {\n return {\n uri: `${arweaveGateway}/${target}${subtarget || ''}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n let parsedUri = uri.replace(dataURIRegex, '')\n if (parsedUri.startsWith(' {\n try {\n const res = await fetch(uri).then((res) => res.json())\n const image = await parseAvatarUri({\n gatewayUrls,\n uri: getJsonImage(res),\n })\n return image\n } catch {\n throw new EnsAvatarUriResolutionError({ uri })\n }\n}\n\nexport type ParseAvatarUriErrorType =\n | ResolveAvatarUriErrorType\n | IsImageUriErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport async function parseAvatarUri({\n gatewayUrls,\n uri,\n}: {\n gatewayUrls?: AssetGatewayUrls | undefined\n uri: string\n}): Promise {\n const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls })\n if (isOnChain) return resolvedURI\n\n // check if resolvedURI is an image, if it is return the url\n const isImage = await isImageUri(resolvedURI)\n if (isImage) return resolvedURI\n\n throw new EnsAvatarUriResolutionError({ uri })\n}\n\ntype ParsedNft = {\n chainID: number\n namespace: string\n contractAddress: Address\n tokenID: string\n}\n\nexport type ParseNftUriErrorType = EnsAvatarInvalidNftUriErrorType | ErrorType\n\nexport function parseNftUri(uri_: string): ParsedNft {\n let uri = uri_\n // parse valid nft spec (CAIP-22/CAIP-29)\n // @see: https://github.com/ChainAgnostic/CAIPs/tree/master/CAIPs\n if (uri.startsWith('did:nft:')) {\n // convert DID to CAIP\n uri = uri.replace('did:nft:', '').replace(/_/g, '/')\n }\n\n const [reference, asset_namespace, tokenID] = uri.split('/')\n const [eip_namespace, chainID] = reference.split(':')\n const [erc_namespace, contractAddress] = asset_namespace.split(':')\n\n if (!eip_namespace || eip_namespace.toLowerCase() !== 'eip155')\n throw new EnsAvatarInvalidNftUriError({ reason: 'Only EIP-155 supported' })\n if (!chainID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Chain ID not found' })\n if (!contractAddress)\n throw new EnsAvatarInvalidNftUriError({\n reason: 'Contract address not found',\n })\n if (!tokenID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Token ID not found' })\n if (!erc_namespace)\n throw new EnsAvatarInvalidNftUriError({ reason: 'ERC namespace not found' })\n\n return {\n chainID: Number.parseInt(chainID, 10),\n namespace: erc_namespace.toLowerCase(),\n contractAddress: contractAddress as Address,\n tokenID,\n }\n}\n\nexport type GetNftTokenUriErrorType =\n | ReadContractErrorType\n | EnsAvatarUnsupportedNamespaceErrorType\n | ErrorType\n\nexport async function getNftTokenUri(\n client: Client,\n { nft }: { nft: ParsedNft },\n) {\n if (nft.namespace === 'erc721') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'tokenURI',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'tokenURI',\n args: [BigInt(nft.tokenID)],\n })\n }\n if (nft.namespace === 'erc1155') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'uri',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: '_id', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'uri',\n args: [BigInt(nft.tokenID)],\n })\n }\n throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace })\n}\n","import type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\nimport {\n type GetJsonImageErrorType,\n type GetMetadataAvatarUriErrorType,\n type GetNftTokenUriErrorType,\n getJsonImage,\n getMetadataAvatarUri,\n getNftTokenUri,\n type ParseAvatarUriErrorType,\n type ParseNftUriErrorType,\n parseAvatarUri,\n parseNftUri,\n type ResolveAvatarUriErrorType,\n resolveAvatarUri,\n} from './utils.js'\n\nexport type ParseAvatarRecordErrorType =\n | ParseNftAvatarUriErrorType\n | ParseAvatarUriErrorType\n | ErrorType\n\n/*\n * @description Parses an ENS avatar record.\n *\n * @example\n * parseAvatarRecord('eip155:1/erc1155:0xb32979486938aa9694bfc898f35dbed459f44424/10063')\n * 'https://ipfs.io/ipfs/QmSP4nq9fnN9dAiCj42ug9Wa79rqmQerZXZch82VqpiH7U/image.gif'\n *\n * @see https://docs.ens.domains/web/avatars\n *\n */\nexport async function parseAvatarRecord(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n if (/eip155:/i.test(record))\n return parseNftAvatarUri(client, { gatewayUrls, record })\n return parseAvatarUri({ uri: record, gatewayUrls })\n}\n\ntype ParseNftAvatarUriErrorType =\n | ParseNftUriErrorType\n | GetNftTokenUriErrorType\n | ResolveAvatarUriErrorType\n | ParseAvatarUriErrorType\n | GetJsonImageErrorType\n | GetMetadataAvatarUriErrorType\n | ErrorType\n\nasync function parseNftAvatarUri(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n // parse NFT URI into properties\n const nft = parseNftUri(record)\n // fetch tokenURI from the NFT contract\n const nftUri = await getNftTokenUri(client, { nft })\n // resolve the URI from the fetched tokenURI\n const {\n uri: resolvedNftUri,\n isOnChain,\n isEncoded,\n } = resolveAvatarUri({ uri: nftUri, gatewayUrls })\n\n // if the resolved URI is on chain, return the data\n if (\n isOnChain &&\n (resolvedNftUri.includes('data:application/json;base64,') ||\n resolvedNftUri.startsWith('{'))\n ) {\n const encodedJson = isEncoded\n ? // if it is encoded, decode it\n atob(resolvedNftUri.replace('data:application/json;base64,', ''))\n : // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)\n resolvedNftUri\n\n const decoded = JSON.parse(encodedJson)\n return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls })\n }\n\n let uriTokenId = nft.tokenID\n if (nft.namespace === 'erc1155')\n uriTokenId = uriTokenId.replace('0x', '').padStart(64, '0')\n\n return getMetadataAvatarUri({\n gatewayUrls,\n uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId),\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n textResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsTextParameters = Prettify<\n Pick & {\n /** ENS name to get Text for. */\n name: string\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Text record to retrieve. */\n key: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsTextReturnType = string | null\n\nexport type GetEnsTextErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | DecodeFunctionResultErrorType\n\n/**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsText, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await getEnsText(client, {\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\nexport async function getEnsText(\n client: Client,\n parameters: GetEnsTextParameters,\n): Promise {\n const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n args: [\n toHex(packetToBytes(name)),\n encodeFunctionData({\n abi: textResolverAbi,\n functionName: 'text',\n args: [namehash(name), key],\n }),\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n functionName: 'resolveWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const record = decodeFunctionResult({\n abi: textResolverAbi,\n functionName: 'text',\n data: res[0],\n })\n\n return record === '' ? null : record\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../types/ens.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type ParseAvatarRecordErrorType,\n parseAvatarRecord,\n} from '../../utils/ens/avatar/parseAvatarRecord.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetEnsTextErrorType,\n type GetEnsTextParameters,\n getEnsText,\n} from './getEnsText.js'\n\nexport type GetEnsAvatarParameters = Prettify<\n Omit & {\n /** Gateway urls to resolve IPFS and/or Arweave assets. */\n assetGatewayUrls?: AssetGatewayUrls | undefined\n }\n>\n\nexport type GetEnsAvatarReturnType = string | null\n\nexport type GetEnsAvatarErrorType =\n | GetEnsTextErrorType\n | ParseAvatarRecordErrorType\n | ErrorType\n\n/**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAvatar, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await getEnsAvatar(client, {\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\nexport async function getEnsAvatar(\n client: Client,\n {\n blockNumber,\n blockTag,\n assetGatewayUrls,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress,\n }: GetEnsAvatarParameters,\n): Promise {\n const record = await getAction(\n client,\n getEnsText,\n 'getEnsText',\n )({\n blockNumber,\n blockTag,\n key: 'avatar',\n name,\n universalResolverAddress,\n gatewayUrls,\n strict,\n })\n if (!record) return null\n try {\n return await parseAvatarRecord(client, {\n record,\n gatewayUrls: assetGatewayUrls,\n })\n } catch {\n return null\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalResolverReverseAbi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport type { PacketToBytesErrorType } from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsNameParameters = Prettify<\n Pick & {\n /**\n * Address to get ENS name for.\n */\n address: Address\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS name for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsNameReturnType = string | null\n\nexport type GetEnsNameErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName(\n client: Client,\n parameters: GetEnsNameParameters,\n): Promise {\n const {\n address,\n blockNumber,\n blockTag,\n coinType = 60n,\n gatewayUrls,\n strict,\n } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverReverseAbi,\n args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]],\n functionName: 'reverseWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const [name] = await readContractAction(readContractParameters)\n\n return name || null\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsResolverParameters = Prettify<\n Pick & {\n /** Name to get the address for. */\n name: string\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsResolverReturnType = Address\n\nexport type GetEnsResolverErrorType =\n | GetChainContractAddressErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsResolver, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await getEnsResolver(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\nexport async function getEnsResolver(\n client: Client,\n parameters: GetEnsResolverParameters,\n): Promise {\n const { blockNumber, blockTag, name } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld)))\n throw new Error(\n `${name} is not a valid ENS TLD (${tlds?.join(', ')}) for chain \"${chain.name}\" (id: ${chain.id}).`,\n )\n\n const [resolverAddress] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address: universalResolverAddress,\n abi: [\n {\n inputs: [{ type: 'bytes' }],\n name: 'findResolver',\n outputs: [\n { type: 'address' },\n { type: 'bytes32' },\n { type: 'uint256' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ],\n functionName: 'findResolver',\n args: [toHex(packetToBytes(name))],\n blockNumber,\n blockTag,\n })\n return resolverAddress\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport {\n type GetEnsAddressParameters,\n type GetEnsAddressReturnType,\n getEnsAddress,\n} from '../../actions/ens/getEnsAddress.js'\nimport {\n type GetEnsAvatarParameters,\n type GetEnsAvatarReturnType,\n getEnsAvatar,\n} from '../../actions/ens/getEnsAvatar.js'\nimport {\n type GetEnsNameParameters,\n type GetEnsNameReturnType,\n getEnsName,\n} from '../../actions/ens/getEnsName.js'\nimport {\n type GetEnsResolverParameters,\n type GetEnsResolverReturnType,\n getEnsResolver,\n} from '../../actions/ens/getEnsResolver.js'\nimport {\n type GetEnsTextParameters,\n type GetEnsTextReturnType,\n getEnsText,\n} from '../../actions/ens/getEnsText.js'\nimport {\n type CallParameters,\n type CallReturnType,\n call,\n} from '../../actions/public/call.js'\nimport {\n type CreateAccessListParameters,\n type CreateAccessListReturnType,\n createAccessList,\n} from '../../actions/public/createAccessList.js'\nimport {\n type CreateBlockFilterReturnType,\n createBlockFilter,\n} from '../../actions/public/createBlockFilter.js'\nimport {\n type CreateContractEventFilterParameters,\n type CreateContractEventFilterReturnType,\n createContractEventFilter,\n} from '../../actions/public/createContractEventFilter.js'\nimport {\n type CreateEventFilterParameters,\n type CreateEventFilterReturnType,\n createEventFilter,\n} from '../../actions/public/createEventFilter.js'\nimport {\n type CreatePendingTransactionFilterReturnType,\n createPendingTransactionFilter,\n} from '../../actions/public/createPendingTransactionFilter.js'\nimport {\n type EstimateContractGasParameters,\n type EstimateContractGasReturnType,\n estimateContractGas,\n} from '../../actions/public/estimateContractGas.js'\nimport {\n type EstimateFeesPerGasParameters,\n type EstimateFeesPerGasReturnType,\n estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasParameters,\n type EstimateGasReturnType,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type EstimateMaxPriorityFeePerGasParameters,\n type EstimateMaxPriorityFeePerGasReturnType,\n estimateMaxPriorityFeePerGas,\n} from '../../actions/public/estimateMaxPriorityFeePerGas.js'\nimport {\n type FillTransactionParameters,\n type FillTransactionReturnType,\n fillTransaction,\n} from '../../actions/public/fillTransaction.js'\nimport {\n type GetBalanceParameters,\n type GetBalanceReturnType,\n getBalance,\n} from '../../actions/public/getBalance.js'\nimport {\n type GetBlobBaseFeeReturnType,\n getBlobBaseFee,\n} from '../../actions/public/getBlobBaseFee.js'\nimport {\n type GetBlockParameters,\n type GetBlockReturnType,\n getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetBlockNumberParameters,\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from '../../actions/public/getBlockNumber.js'\nimport {\n type GetBlockTransactionCountParameters,\n type GetBlockTransactionCountReturnType,\n getBlockTransactionCount,\n} from '../../actions/public/getBlockTransactionCount.js'\nimport {\n type GetChainIdReturnType,\n getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n type GetCodeParameters,\n type GetCodeReturnType,\n getCode,\n} from '../../actions/public/getCode.js'\nimport {\n type GetContractEventsParameters,\n type GetContractEventsReturnType,\n getContractEvents,\n} from '../../actions/public/getContractEvents.js'\nimport {\n type GetDelegationParameters,\n type GetDelegationReturnType,\n getDelegation,\n} from '../../actions/public/getDelegation.js'\nimport {\n type GetEip712DomainParameters,\n type GetEip712DomainReturnType,\n getEip712Domain,\n} from '../../actions/public/getEip712Domain.js'\nimport {\n type GetFeeHistoryParameters,\n type GetFeeHistoryReturnType,\n getFeeHistory,\n} from '../../actions/public/getFeeHistory.js'\nimport {\n type GetFilterChangesParameters,\n type GetFilterChangesReturnType,\n getFilterChanges,\n} from '../../actions/public/getFilterChanges.js'\nimport {\n type GetFilterLogsParameters,\n type GetFilterLogsReturnType,\n getFilterLogs,\n} from '../../actions/public/getFilterLogs.js'\nimport {\n type GetGasPriceReturnType,\n getGasPrice,\n} from '../../actions/public/getGasPrice.js'\nimport {\n type GetLogsParameters,\n type GetLogsReturnType,\n getLogs,\n} from '../../actions/public/getLogs.js'\nimport {\n type GetProofParameters,\n type GetProofReturnType,\n getProof,\n} from '../../actions/public/getProof.js'\nimport {\n type GetStorageAtParameters,\n type GetStorageAtReturnType,\n getStorageAt,\n} from '../../actions/public/getStorageAt.js'\nimport {\n type GetTransactionParameters,\n type GetTransactionReturnType,\n getTransaction,\n} from '../../actions/public/getTransaction.js'\nimport {\n type GetTransactionConfirmationsParameters,\n type GetTransactionConfirmationsReturnType,\n getTransactionConfirmations,\n} from '../../actions/public/getTransactionConfirmations.js'\nimport {\n type GetTransactionCountParameters,\n type GetTransactionCountReturnType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport {\n type GetTransactionReceiptParameters,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from '../../actions/public/getTransactionReceipt.js'\nimport {\n type MulticallParameters,\n type MulticallReturnType,\n multicall,\n} from '../../actions/public/multicall.js'\nimport {\n type ReadContractParameters,\n type ReadContractReturnType,\n readContract,\n} from '../../actions/public/readContract.js'\nimport {\n type SimulateBlocksParameters,\n type SimulateBlocksReturnType,\n simulateBlocks,\n} from '../../actions/public/simulateBlocks.js'\nimport {\n type SimulateCallsParameters,\n type SimulateCallsReturnType,\n simulateCalls,\n} from '../../actions/public/simulateCalls.js'\nimport {\n type SimulateContractParameters,\n type SimulateContractReturnType,\n simulateContract,\n} from '../../actions/public/simulateContract.js'\nimport {\n type UninstallFilterParameters,\n type UninstallFilterReturnType,\n uninstallFilter,\n} from '../../actions/public/uninstallFilter.js'\nimport {\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from '../../actions/public/verifyHash.js'\nimport {\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from '../../actions/public/verifyMessage.js'\nimport {\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from '../../actions/public/verifyTypedData.js'\nimport {\n type WaitForTransactionReceiptParameters,\n type WaitForTransactionReceiptReturnType,\n waitForTransactionReceipt,\n} from '../../actions/public/waitForTransactionReceipt.js'\nimport {\n type WatchBlockNumberParameters,\n type WatchBlockNumberReturnType,\n watchBlockNumber,\n} from '../../actions/public/watchBlockNumber.js'\nimport {\n type WatchBlocksParameters,\n type WatchBlocksReturnType,\n watchBlocks,\n} from '../../actions/public/watchBlocks.js'\nimport {\n type WatchContractEventParameters,\n type WatchContractEventReturnType,\n watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n type WatchEventParameters,\n type WatchEventReturnType,\n watchEvent,\n} from '../../actions/public/watchEvent.js'\nimport {\n type WatchPendingTransactionsParameters,\n type WatchPendingTransactionsReturnType,\n watchPendingTransactions,\n} from '../../actions/public/watchPendingTransactions.js'\nimport {\n type VerifySiweMessageParameters,\n type VerifySiweMessageReturnType,\n verifySiweMessage,\n} from '../../actions/siwe/verifySiweMessage.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\n type PrepareTransactionRequestReturnType,\n prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n type SendRawTransactionSyncParameters,\n type SendRawTransactionSyncReturnType,\n sendRawTransactionSync,\n} from '../../actions/wallet/sendRawTransactionSync.js'\nimport type { Account } from '../../types/account.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { FeeValuesType } from '../../types/fee.js'\nimport type { FilterType } from '../../types/filter.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type PublicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\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 args - {@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 *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await client.call({\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n call: (parameters: CallParameters) => Promise\n /**\n * Creates an EIP-2930 access list that you can include in a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param args - {@link CreateAccessListParameters}\n * @returns The call data. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const data = await client.createAccessList({\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n createAccessList: (\n parameters: CreateAccessListParameters,\n ) => Promise\n /**\n * Creates a Filter to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @returns Filter. {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, createBlockFilter, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\n createBlockFilter: () => Promise\n /**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param args - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\n createContractEventFilter: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param args - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\n createEventFilter: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _EventName extends string | undefined = MaybeAbiEventName,\n _Args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n >(\n args?:\n | CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n | undefined,\n ) => Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n >\n /**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\n createPendingTransactionFilter: () => Promise\n /**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * @remarks\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await client.estimateContractGas({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\n estimateContractGas: <\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n >(\n args: EstimateContractGasParameters,\n ) => Promise\n /**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param args - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await client.estimateGas({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n estimateGas: (\n args: EstimateGasParameters,\n ) => Promise\n /**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.fillTransaction({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n fillTransaction: <\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n ) => Promise>\n /**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * @remarks\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param args - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await client.getBalance({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\n getBalance: (args: GetBalanceParameters) => Promise\n /**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await client.getBlobBaseFee()\n */\n getBlobBaseFee: () => Promise\n /**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getBlock()\n */\n getBlock: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args?: GetBlockParameters | undefined,\n ) => Promise>\n /**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param args - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await client.getBlockNumber()\n * // 69420n\n */\n getBlockNumber: (\n args?: GetBlockNumberParameters | undefined,\n ) => Promise\n /**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await client.getBlockTransactionCount()\n */\n getBlockTransactionCount: (\n args?: GetBlockTransactionCountParameters | undefined,\n ) => Promise\n /** @deprecated Use `getCode` instead. */\n getBytecode: (args: GetCodeParameters) => Promise\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await client.getChainId()\n * // 1\n */\n getChainId: () => Promise\n /**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param args - {@link GetBytecodeParameters}\n * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getCode({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\n getCode: (args: GetCodeParameters) => Promise\n /**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/actions/public/getContractEvents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { wagmiAbi } from './abi'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\n getContractEvents: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetContractEventsReturnType\n >\n /**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param args - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await client.getDelegation({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getDelegation: (\n args: GetDelegationParameters,\n ) => Promise\n /**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await client.getEip712Domain({\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\n getEip712Domain: (\n args: GetEip712DomainParameters,\n ) => Promise\n /**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await client.getEnsAddress({\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\n getEnsAddress: (\n args: GetEnsAddressParameters,\n ) => Promise\n /**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await client.getEnsAvatar({\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\n getEnsAvatar: (\n args: GetEnsAvatarParameters,\n ) => Promise\n /**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param args - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await client.getEnsName({\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\n getEnsName: (args: GetEnsNameParameters) => Promise\n /**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await client.getEnsResolver({\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\n getEnsResolver: (\n args: GetEnsResolverParameters,\n ) => Promise\n /**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await client.getEnsText({\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\n getEnsText: (args: GetEnsTextParameters) => Promise\n /**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param args - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await client.getFeeHistory({\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\n getFeeHistory: (\n args: GetFeeHistoryParameters,\n ) => Promise\n /**\n * Returns an estimate for the fees per gas for a transaction to be included\n * in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateFeesPerGas()\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\n estimateFeesPerGas: <\n chainOverride extends Chain | undefined = undefined,\n type extends FeeValuesType = 'eip1559',\n >(\n args?: EstimateFeesPerGasParameters | undefined,\n ) => Promise>\n /**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * @remarks\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param args - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createBlockFilter()\n * const hashes = await client.getFilterChanges({ filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * const hashes = await client.getFilterChanges({ filter })\n */\n getFilterChanges: <\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * @remarks\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param args - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterLogs({ filter })\n */\n getFilterLogs: <\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterLogsParameters,\n ) => Promise<\n GetFilterLogsReturnType\n >\n /**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await client.getGasPrice()\n */\n getGasPrice: () => Promise\n /**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param args - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getLogs()\n */\n getLogs: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args?:\n | GetLogsParameters\n | undefined,\n ) => Promise<\n GetLogsReturnType\n >\n /**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getProof({\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\n getProof: (args: GetProofParameters) => Promise\n /**\n * Returns an estimate for the max priority fee per gas (in wei) for a transaction\n * to be included in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()\n * // 10000000n\n */\n estimateMaxPriorityFeePerGas: <\n chainOverride extends Chain | undefined = undefined,\n >(\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n ) => Promise\n /**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param args - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getStorageAt({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\n getStorageAt: (\n args: GetStorageAtParameters,\n ) => Promise\n /**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param args - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await client.getTransaction({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransaction: (\n args: GetTransactionParameters,\n ) => Promise>\n /**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param args - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await client.getTransactionConfirmations({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionConfirmations: (\n args: GetTransactionConfirmationsParameters,\n ) => Promise\n /**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has broadcast / sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param args - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await client.getTransactionCount({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getTransactionCount: (\n args: GetTransactionCountParameters,\n ) => Promise\n /**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt)\n *\n * @param args - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.getTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionReceipt: (\n args: GetTransactionReceiptParameters,\n ) => Promise>\n /**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param args - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const result = await client.multicall({\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\n multicall: <\n const contracts extends readonly unknown[],\n allowFailure extends boolean = true,\n >(\n args: MulticallParameters,\n ) => Promise>\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\n prepareTransactionRequest: <\n const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * @remarks\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.readContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\n readContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n >(\n args: ReadContractParameters,\n ) => Promise>\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await client.sendRawTransaction({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransaction: (\n args: SendRawTransactionParameters,\n ) => Promise\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionSyncParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await client.sendRawTransactionSync({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransactionSync: (\n args: SendRawTransactionSyncParameters,\n ) => Promise>\n /**\n * @deprecated Use `simulateBlocks` instead.\n */\n simulate: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateBlocks({\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateParameters}\n * @returns Simulated blocks. {@link SimulateReturnType}\n */\n simulateBlocks: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateCalls({\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n */\n simulateCalls: (\n args: SimulateCallsParameters,\n ) => Promise>\n /**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * @remarks\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.simulateContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n simulateContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n ) => Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n >\n /**\n * Verify that a hash was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyHash}\n *\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\n verifyHash: (args: VerifyHashParameters) => Promise\n /**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\n verifyMessage: (\n args: VerifyMessageParameters,\n ) => Promise\n /**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\n verifySiweMessage: (\n args: VerifySiweMessageParameters,\n ) => Promise\n /**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\n verifyTypedData: (\n args: VerifyTypedDataParameters,\n ) => Promise\n /**\n * Destroys a Filter that was created from one of the following Actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * @param args - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await client.createPendingTransactionFilter()\n * const uninstalled = await client.uninstallFilter({ filter })\n * // true\n */\n uninstallFilter: (\n args: UninstallFilterParameters,\n ) => Promise\n /**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * @remarks\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param args - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.waitForTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n waitForTransactionReceipt: (\n args: WaitForTransactionReceiptParameters,\n ) => Promise>\n /**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlockNumber({\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\n watchBlockNumber: (\n args: WatchBlockNumberParameters,\n ) => WatchBlockNumberReturnType\n /**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlocks({\n * onBlock: (block) => console.log(block),\n * })\n */\n watchBlocks: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args: WatchBlocksParameters<\n transport,\n chain,\n includeTransactions,\n blockTag\n >,\n ) => WatchBlocksReturnType\n /**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * @remarks\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchContractEvent({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchContractEvent: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchContractEventParameters,\n ) => WatchContractEventReturnType\n /**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * @remarks\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchEvent({\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchEvent: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchEventParameters,\n ) => WatchEventReturnType\n /**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * @remarks\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param args - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchPendingTransactions({\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\n watchPendingTransactions: (\n args: WatchPendingTransactionsParameters,\n ) => WatchPendingTransactionsReturnType\n}\n\nexport function publicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(\n client: Client,\n): PublicActions {\n return {\n call: (args) => call(client, args),\n createAccessList: (args) => createAccessList(client, args),\n createBlockFilter: () => createBlockFilter(client),\n createContractEventFilter: (args) =>\n createContractEventFilter(client, args),\n createEventFilter: (args) => createEventFilter(client, args),\n createPendingTransactionFilter: () =>\n createPendingTransactionFilter(client),\n estimateContractGas: (args) => estimateContractGas(client, args as any),\n estimateGas: (args) => estimateGas(client, args),\n getBalance: (args) => getBalance(client, args),\n getBlobBaseFee: () => getBlobBaseFee(client),\n getBlock: (args) => getBlock(client, args),\n getBlockNumber: (args) => getBlockNumber(client, args),\n getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),\n getBytecode: (args) => getCode(client, args),\n getChainId: () => getChainId(client),\n getCode: (args) => getCode(client, args),\n getContractEvents: (args) => getContractEvents(client, args),\n getDelegation: (args) => getDelegation(client, args),\n getEip712Domain: (args) => getEip712Domain(client, args),\n getEnsAddress: (args) => getEnsAddress(client, args),\n getEnsAvatar: (args) => getEnsAvatar(client, args),\n getEnsName: (args) => getEnsName(client, args),\n getEnsResolver: (args) => getEnsResolver(client, args),\n getEnsText: (args) => getEnsText(client, args),\n getFeeHistory: (args) => getFeeHistory(client, args),\n estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),\n getFilterChanges: (args) => getFilterChanges(client, args),\n getFilterLogs: (args) => getFilterLogs(client, args),\n getGasPrice: () => getGasPrice(client),\n getLogs: (args) => getLogs(client, args as any),\n getProof: (args) => getProof(client, args),\n estimateMaxPriorityFeePerGas: (args) =>\n estimateMaxPriorityFeePerGas(client, args),\n fillTransaction: (args) => fillTransaction(client, args),\n getStorageAt: (args) => getStorageAt(client, args),\n getTransaction: (args) => getTransaction(client, args),\n getTransactionConfirmations: (args) =>\n getTransactionConfirmations(client, args),\n getTransactionCount: (args) => getTransactionCount(client, args),\n getTransactionReceipt: (args) => getTransactionReceipt(client, args),\n multicall: (args) => multicall(client, args),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n readContract: (args) => readContract(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n sendRawTransactionSync: (args) => sendRawTransactionSync(client, args),\n simulate: (args) => simulateBlocks(client, args),\n simulateBlocks: (args) => simulateBlocks(client, args),\n simulateCalls: (args) => simulateCalls(client, args),\n simulateContract: (args) => simulateContract(client, args),\n verifyHash: (args) => verifyHash(client, args),\n verifyMessage: (args) => verifyMessage(client, args),\n verifySiweMessage: (args) => verifySiweMessage(client, args),\n verifyTypedData: (args) => verifyTypedData(client, args),\n uninstallFilter: (args) => uninstallFilter(client, args),\n waitForTransactionReceipt: (args) =>\n waitForTransactionReceipt(client, args),\n watchBlocks: (args) => watchBlocks(client, args),\n watchBlockNumber: (args) => watchBlockNumber(client, args),\n watchContractEvent: (args) => watchContractEvent(client, args),\n watchEvent: (args) => watchEvent(client, args),\n watchPendingTransactions: (args) => watchPendingTransactions(client, args),\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { AccessList, TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, Prettify, UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\n\nexport type CreateAccessListParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n FormattedTransactionRequest,\n 'from' | 'nonce' | 'accessList'\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | 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 )\n\nexport type CreateAccessListReturnType = Prettify<{\n accessList: AccessList\n gasUsed: bigint\n}>\n\nexport type CreateAccessListErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | RequestErrorType\n>\n\n/**\n * Creates an EIP-2930 access list.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param client - Client to use\n * @param parameters - {@link CreateAccessListParameters}\n * @returns The access list. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createAccessList } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await createAccessList(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function createAccessList(\n client: Client,\n args: CreateAccessListParameters,\n): Promise {\n const {\n account: account_ = client.account,\n blockNumber,\n blockTag = 'latest',\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n } as TransactionRequest,\n 'createAccessList',\n ) as TransactionRequest\n\n const response = await client.request({\n method: 'eth_createAccessList',\n params: [request as ExactPartial, block],\n })\n return {\n accessList: response.accessList,\n gasUsed: BigInt(response.gasUsed),\n }\n } catch (err) {\n throw getCallError(err as ErrorType, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateBlockFilterReturnType = Filter<'block'>\n\nexport type CreateBlockFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\nexport async function createBlockFilter(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newBlockFilter',\n })\n const id = await client.request({\n method: 'eth_newBlockFilter',\n })\n return { id, request: getRequest(id), type: 'block' }\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex, LogTopic } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateEventFilterParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (MaybeExtractEventArgsFromAbi<\n abiEvents,\n _eventName\n> extends infer eventFilterArgs\n ?\n | {\n args:\n | eventFilterArgs\n | (_args extends eventFilterArgs ? _args : never)\n event: abiEvent\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: abiEvent | undefined\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events: abiEvents | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n }\n : {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n })\n\nexport type CreateEventFilterReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = Prettify<\n Filter<'event', abiEvents, _eventName, _args, strict, fromBlock, toBlock>\n>\n\nexport type CreateEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param client - Client to use\n * @param parameters - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\nexport async function createEventFilter<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n event,\n events: events_,\n fromBlock,\n strict,\n toBlock,\n }: CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n > = {} as any,\n): Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n> {\n const events = events_ ?? (event ? [event] : undefined)\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n ...(topics.length ? { topics } : {}),\n },\n ],\n })\n\n return {\n abi: events,\n args,\n eventName: event ? (event as AbiEvent).name : undefined,\n fromBlock,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n toBlock,\n type: 'event',\n } as unknown as CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreatePendingTransactionFilterReturnType = Filter<'transaction'>\n\nexport type CreatePendingTransactionFilterErrorType =\n | RequestErrorType\n | ErrorType\n\n/**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\nexport async function createPendingTransactionFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newPendingTransactionFilter',\n })\n const id = await client.request({\n method: 'eth_newPendingTransactionFilter',\n })\n return { id, request: getRequest(id), type: 'transaction' }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport { decodeFunctionResult } from '../../utils/abi/decodeFunctionResult.js'\nimport { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type CallParameters, call } from './call.js'\n\nexport type GetBalanceParameters = {\n /** The address of the account. */\n address: Address\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 /** The balance of the account at a block tag. */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance(\n client: Client,\n {\n address,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n }: GetBalanceParameters,\n): Promise {\n if (client.batch?.multicall && client.chain?.contracts?.multicall3) {\n const multicall3Address = client.chain.contracts.multicall3.address\n\n const calldata = encodeFunctionData({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n })\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n to: multicall3Address,\n data: calldata,\n blockNumber,\n blockTag,\n } as unknown as CallParameters)\n\n return decodeFunctionResult({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n data: data || '0x',\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n\n const balance = await client.request({\n method: 'eth_getBalance',\n params: [address, blockNumberHex || blockTag],\n })\n return BigInt(balance)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetBlobBaseFeeReturnType = bigint\n\nexport type GetBlobBaseFeeErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await getBlobBaseFee(client)\n */\nexport async function getBlobBaseFee<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n): Promise {\n const baseFee = await client.request({\n method: 'eth_blobBaseFee',\n })\n return BigInt(baseFee)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Quantity } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBlockTransactionCountParameters =\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n\nexport type GetBlockTransactionCountReturnType = number\n\nexport type GetBlockTransactionCountErrorType =\n | NumberToHexErrorType\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await getBlockTransactionCount(client)\n */\nexport async function getBlockTransactionCount(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = 'latest',\n }: GetBlockTransactionCountParameters = {},\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let count: Quantity\n if (blockHash) {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByHash',\n params: [blockHash],\n },\n { dedupe: true },\n )\n } else {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByNumber',\n params: [blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n return hexToNumber(count)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetCodeParameters = {\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetCodeReturnType = Hex | undefined\n\nexport type GetCodeErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetCodeParameters}\n * @returns The contract's bytecode. {@link GetCodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCode } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getCode(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getCode(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetCodeParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const hex = await client.request(\n {\n method: 'eth_getCode',\n params: [address, blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n if (hex === '0x') return undefined\n return hex\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport { type SizeErrorType, size } from '../../utils/data/size.js'\nimport { type SliceErrorType, slice } from '../../utils/data/slice.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\n\nexport type GetDelegationParameters = {\n /** The address to check for delegation. */\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetDelegationReturnType = Address | undefined\n\nexport type GetDelegationErrorType =\n | GetAddressErrorType\n | GetCodeErrorType\n | SliceErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param client - Client to use\n * @param parameters - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getDelegation } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await getDelegation(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getDelegation(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetDelegationParameters,\n): Promise {\n const code = await getCode(client, {\n address,\n ...(blockNumber !== undefined ? { blockNumber } : { blockTag }),\n } as GetDelegationParameters)\n\n if (!code) return undefined\n\n // EIP-7702 delegation designator: 0xef0100 prefix (3 bytes) + address (20 bytes) = 23 bytes\n if (size(code) !== 23) return undefined\n\n // Check for EIP-7702 delegation designator prefix\n if (!code.startsWith('0xef0100')) return undefined\n\n // Extract the delegated address (bytes 3-23) and checksum it\n return getAddress(slice(code, 3, 23))\n}\n","import type { Address } from 'abitype'\nimport { BaseError } from './base.js'\n\nexport type Eip712DomainNotFoundErrorType = Eip712DomainNotFoundError & {\n name: 'Eip712DomainNotFoundError'\n}\nexport class Eip712DomainNotFoundError extends BaseError {\n constructor({ address }: { address: Address }) {\n super(`No EIP-712 domain found on contract \"${address}\".`, {\n metaMessages: [\n 'Ensure that:',\n `- The contract is deployed at the address \"${address}\".`,\n '- `eip712Domain()` function exists on the contract.',\n '- `eip712Domain()` function matches signature to ERC-5267 specification.',\n ],\n name: 'Eip712DomainNotFoundError',\n })\n }\n}\n","import type { Address, TypedDataDomain } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip712DomainNotFoundError,\n type Eip712DomainNotFoundErrorType,\n} from '../../errors/eip712.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequiredBy } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from './readContract.js'\n\nexport type GetEip712DomainParameters = {\n address: Address\n} & Pick\n\nexport type GetEip712DomainReturnType = {\n domain: RequiredBy<\n TypedDataDomain,\n 'chainId' | 'name' | 'verifyingContract' | 'salt' | 'version'\n >\n fields: Hex\n extensions: readonly bigint[]\n}\n\nexport type GetEip712DomainErrorType =\n | Eip712DomainNotFoundErrorType\n | ReadContractErrorType\n | ErrorType\n\n/**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, getEip712Domain } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await getEip712Domain(client, {\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\nexport async function getEip712Domain(\n client: Client,\n parameters: GetEip712DomainParameters,\n): Promise {\n const { address, factory, factoryData } = parameters\n\n try {\n const [\n fields,\n name,\n version,\n chainId,\n verifyingContract,\n salt,\n extensions,\n ] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi,\n address,\n functionName: 'eip712Domain',\n factory,\n factoryData,\n })\n\n return {\n domain: {\n name,\n version,\n chainId: Number(chainId),\n verifyingContract,\n salt,\n },\n extensions,\n fields,\n }\n } catch (e) {\n const error = e as ReadContractErrorType\n if (\n error.name === 'ContractFunctionExecutionError' &&\n error.cause.name === 'ContractFunctionZeroDataError'\n ) {\n throw new Eip712DomainNotFoundError({ address })\n }\n throw error\n }\n}\n\nconst abi = [\n {\n inputs: [],\n name: 'eip712Domain',\n outputs: [\n { name: 'fields', type: 'bytes1' },\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n { name: 'extensions', type: 'uint256[]' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatFeeHistoryErrorType,\n formatFeeHistory,\n} from '../../utils/formatters/feeHistory.js'\n\nexport type GetFeeHistoryParameters = {\n /**\n * Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.\n */\n blockCount: number\n /**\n * A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used.\n */\n rewardPercentiles: number[]\n} & (\n | {\n blockNumber?: undefined\n /**\n * Highest number block of the requested range.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n | {\n /** Highest number block of the requested range. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\nexport type GetFeeHistoryReturnType = FeeHistory\n\nexport type GetFeeHistoryErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | FormatFeeHistoryErrorType\n\n/**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param client - Client to use\n * @param parameters - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getFeeHistory } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await getFeeHistory(client, {\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\nexport async function getFeeHistory(\n client: Client,\n {\n blockCount,\n blockNumber,\n blockTag = 'latest',\n rewardPercentiles,\n }: GetFeeHistoryParameters,\n): Promise {\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const feeHistory = await client.request(\n {\n method: 'eth_feeHistory',\n params: [\n numberToHex(blockCount),\n blockNumberHex || blockTag,\n rewardPercentiles,\n ],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n return formatFeeHistory(feeHistory)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RpcFeeHistory } from '../../types/rpc.js'\n\nexport type FormatFeeHistoryErrorType = ErrorType\n\nexport function formatFeeHistory(feeHistory: RpcFeeHistory): FeeHistory {\n return {\n baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),\n gasUsedRatio: feeHistory.gasUsedRatio,\n oldestBlock: BigInt(feeHistory.oldestBlock),\n reward: feeHistory.reward?.map((reward) =>\n reward.map((value) => BigInt(value)),\n ),\n }\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterLogsParameters<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<'event', abi, eventName, any, strict, fromBlock, toBlock>\n}\nexport type GetFilterLogsReturnType<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetFilterLogsErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterLogs(client, { filter })\n */\nexport async function getFilterLogs<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterLogsParameters,\n): Promise<\n GetFilterLogsReturnType\n> {\n const strict = filter.strict ?? false\n\n const logs = await filter.request({\n method: 'eth_getFilterLogs',\n params: [filter.id],\n })\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!filter.abi)\n return formattedLogs as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Address } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatProofErrorType,\n formatProof,\n} from '../../utils/formatters/proof.js'\n\nexport type GetProofParameters = {\n /** Account address. */\n address: Address\n /** Array of storage-keys that should be proofed and included. */\n storageKeys: Hash[]\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetProofReturnType = Proof\n\nexport type GetProofErrorType =\n | NumberToHexErrorType\n | FormatProofErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getProof } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getProof(client, {\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\nexport async function getProof(\n client: Client,\n {\n address,\n blockNumber,\n blockTag: blockTag_,\n storageKeys,\n }: GetProofParameters,\n): Promise {\n const blockTag = blockTag_ ?? 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n const proof = await client.request({\n method: 'eth_getProof',\n params: [address, storageKeys, blockNumberHex || blockTag],\n })\n\n return formatProof(proof)\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type GetAddressErrorType, getAddress } from '../address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../address/isAddressEqual.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n recoverAuthorizationAddress,\n} from './recoverAuthorizationAddress.js'\n\nexport type VerifyAuthorizationParameters =\n RecoverAuthorizationAddressParameters & {\n /** The address that signed the Authorization object. */\n address: Address\n }\n\nexport type VerifyAuthorizationReturnType = boolean\n\nexport type VerifyAuthorizationErrorType =\n | IsAddressEqualErrorType\n | GetAddressErrorType\n | RecoverAuthorizationAddressErrorType\n | ErrorType\n\n/**\n * Verify that an Authorization object was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/utilities/verifyAuthorization}\n *\n * @param parameters - {@link VerifyAuthorizationParameters}\n * @returns Whether or not the signature is valid. {@link VerifyAuthorizationReturnType}\n */\nexport async function verifyAuthorization({\n address,\n authorization,\n signature,\n}: VerifyAuthorizationParameters): Promise {\n return isAddressEqual(\n getAddress(address),\n await recoverAuthorizationAddress({\n authorization,\n signature,\n }),\n )\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n WalletConnectSessionSettlementError,\n type WalletConnectSessionSettlementErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | AtomicityNotSupportedErrorType\n | AtomicReadyWalletRejectedUpgradeErrorType\n | BundleTooLargeErrorType\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | DuplicateIdErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownBundleIdErrorType\n | UnknownRpcErrorType\n | UnsupportedChainIdErrorType\n | UnsupportedNonOptionalCapabilityErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WalletConnectSessionSettlementErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest Promise>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n methods,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n\n const { method } = args\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n\n const requestId = dedupe\n ? stringToHex(`${uid}.${stringify(args)}`)\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n\n // 5700\n case UnsupportedNonOptionalCapabilityError.code:\n throw new UnsupportedNonOptionalCapabilityError(err)\n // 5710\n case UnsupportedChainIdError.code:\n throw new UnsupportedChainIdError(err)\n // 5720\n case DuplicateIdError.code:\n throw new DuplicateIdError(err)\n // 5730\n case UnknownBundleIdError.code:\n throw new UnknownBundleIdError(err)\n // 5740\n case BundleTooLargeError.code:\n throw new BundleTooLargeError(err)\n // 5750\n case AtomicReadyWalletRejectedUpgradeError.code:\n throw new AtomicReadyWalletRejectedUpgradeError(err)\n // 5760\n case AtomicityNotSupportedError.code:\n throw new AtomicityNotSupportedError(err)\n\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n\n // WalletConnect: Session Settlement Failed\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n case WalletConnectSessionSettlementError.code:\n throw new WalletConnectSessionSettlementError(err)\n\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter, 10) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe(\n fn: () => Promise,\n { enabled = true, id }: WithDedupeOptions,\n): Promise {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport type DefineChainReturnType = Prettify<\n chain &\n (chain['extendSchema'] extends Record\n ? {\n extend: (\n extended: extended,\n ) => Assign\n }\n : {})\n>\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain,\n>(chain: chain): DefineChainReturnType, chain>> {\n const chainInstance = {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign, chain>\n\n function extend(base: typeof chainInstance) {\n type ExtendFn = (base: typeof chainInstance) => unknown\n return (fnOrExtended: ExtendFn | Record) => {\n const properties = (\n typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended\n ) as (typeof chainInstance)['extendSchema']\n const combined = { ...base, ...properties }\n return Object.assign(combined, { extend: extend(combined) })\n }\n }\n\n return Object.assign(chainInstance, {\n extend: extend(chainInstance),\n }) as never\n}\n\nexport function extendSchema>(): schema {\n return {} as schema\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n} from 'abitype'\nexport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nexport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from '../accounts/utils/publicKeyToAddress.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './abi/decodeAbiParameters.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n encodeDeployData,\n} from './abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n encodeErrorResult,\n} from './abi/encodeErrorResult.js'\nexport {\n type EncodeArgErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from './abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n encodeFunctionResult,\n} from './abi/encodeFunctionResult.js'\nexport { type EncodePackedErrorType, encodePacked } from './abi/encodePacked.js'\nexport {\n type FormatAbiItemErrorType,\n type FormatAbiParamErrorType,\n type FormatAbiParamsErrorType,\n formatAbiItem,\n formatAbiParams,\n} from './abi/formatAbiItem.js'\nexport {\n type FormatAbiItemWithArgsErrorType,\n formatAbiItemWithArgs,\n} from './abi/formatAbiItemWithArgs.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './abi/parseEventLogs.js'\nexport {\n type ChecksumAddressErrorType,\n getAddress,\n} from './address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './address/getContractAddress.js'\nexport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from './address/isAddressEqual.js'\nexport {\n type HashAuthorizationErrorType,\n type HashAuthorizationParameters,\n type HashAuthorizationReturnType,\n hashAuthorization,\n} from './authorization/hashAuthorization.js'\nexport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n type RecoverAuthorizationAddressReturnType,\n recoverAuthorizationAddress,\n} from './authorization/recoverAuthorizationAddress.js'\nexport {\n type SerializeAuthorizationListErrorType,\n type SerializeAuthorizationListReturnType,\n serializeAuthorizationList,\n} from './authorization/serializeAuthorizationList.js'\nexport {\n type VerifyAuthorizationErrorType,\n type VerifyAuthorizationParameters,\n type VerifyAuthorizationReturnType,\n verifyAuthorization,\n} from './authorization/verifyAuthorization.js'\nexport {\n buildRequest,\n type RequestErrorType,\n} from './buildRequest.js'\nexport {\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './chain/assertCurrentChain.js'\nexport { defineChain } from './chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n concat,\n concatBytes,\n concatHex,\n} from './data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n pad,\n padBytes,\n padHex,\n} from './data/pad.js'\nexport { type SizeErrorType, size } from './data/size.js'\nexport {\n type AssertEndOffsetErrorType,\n type AssertStartOffsetErrorType,\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n type SliceReturnType,\n slice,\n sliceBytes,\n sliceHex,\n} from './data/slice.js'\nexport { type TrimErrorType, type TrimReturnType, trim } from './data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBigInt as bytesToBigint,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n type FromBytesReturnType,\n fromBytes,\n} from './encoding/fromBytes.js'\nexport {\n type AssertSizeErrorType,\n type FromHexErrorType,\n type FromHexParameters,\n type FromHexReturnType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBigIntOpts,\n type HexToBoolErrorType,\n type HexToBoolOpts,\n type HexToNumberErrorType,\n type HexToNumberOpts,\n type HexToStringErrorType,\n type HexToStringOpts,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n fromRlp,\n} from './encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n type HexToRlpErrorType,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './encoding/toRlp.js'\nexport {\n type GetCallErrorReturnType,\n getCallError,\n} from './errors/getCallError.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './errors/getContractError.js'\nexport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from './errors/getEstimateGasError.js'\nexport {\n containsNodeError,\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './errors/getNodeError.js'\nexport {\n type GetTransactionErrorParameters,\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from './errors/getTransactionError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './formatters/block.js'\nexport { type ExtractErrorType, extract } from './formatters/extract.js'\nexport {\n type DefineFormatterErrorType,\n defineFormatter,\n} from './formatters/formatter.js'\nexport { type FormatLogErrorType, formatLog } from './formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n} from './formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from './formatters/transactionRequest.js'\nexport { getAction } from './getAction.js'\nexport { type IsHashErrorType, isHash } from './hash/isHash.js'\nexport { type Keccak256ErrorType, keccak256 } from './hash/keccak256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './hash/ripemd160.js'\nexport { type Sha256ErrorType, sha256 } from './hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './hash/toFunctionSignature.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './nonceManager.js'\nexport { arrayRegex, bytesRegex, integerRegex } from './regex.js'\nexport {\n getSocket,\n rpc,\n type WebSocketAsyncErrorType,\n type WebSocketAsyncOptions,\n type WebSocketAsyncReturnType,\n type WebSocketErrorType,\n type WebSocketOptions,\n type WebSocketReturnType,\n} from './rpc/compat.js'\nexport {\n getHttpRpcClient,\n type HttpRequestErrorType,\n type HttpRequestParameters,\n type HttpRequestReturnType,\n type HttpRpcClient,\n type HttpRpcClientOptions,\n} from './rpc/http.js'\nexport {\n type GetSocketParameters,\n type GetSocketRpcClientErrorType,\n type GetSocketRpcClientParameters,\n getSocketRpcClient,\n type Socket,\n type SocketRpcClient,\n socketClientCache,\n} from './rpc/socket.js'\nexport { getWebSocketRpcClient } from './rpc/webSocket.js'\nexport {\n type HashMessageErrorType,\n type HashMessageReturnType,\n hashMessage,\n} from './signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashStruct,\n hashTypedData,\n} from './signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './signature/isErc8010Signature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './signature/parseErc8010Signature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './signature/recoverPublicKey.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './signature/recoverTypedDataAddress.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './signature/serializeErc8010Signature.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n parseTransaction,\n} from './transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './transaction/serializeAccessList.js'\nexport {\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './typedData.js'\nexport { type FormatEtherErrorType, formatEther } from './unit/formatEther.js'\nexport { type FormatGweiErrorType, formatGwei } from './unit/formatGwei.js'\nexport { type FormatUnitsErrorType, formatUnits } from './unit/formatUnits.js'\nexport { type ParseEtherErrorType, parseEther } from './unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './unit/parseGwei.js'\nexport { type ParseUnitsErrorType, parseUnits } from './unit/parseUnits.js'\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport type { MaybePromise } from '../../types/utils.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Override for the fetch function used to make requests. */\n fetchFn?:\n | ((input: string | URL | Request, init?: RequestInit) => Promise)\n | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit | undefined\n /** A callback to handle the request. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Override for the fetch function used to make requests. */\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request(\n params: HttpRequestParameters,\n ): Promise>\n}\n\nexport function getHttpRpcClient(\n url_: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n const { url, headers: headers_url } = parseUrl(url_)\n\n return {\n async request(params) {\n const {\n body,\n fetchFn = options.fetchFn ?? fetch,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n ...headers_url,\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n const args = (await onRequest?.(request, init)) ?? { ...init, url }\n const response = await fetchFn(args.url ?? url, args)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n\n/** @internal */\nexport function parseUrl(url_: string) {\n try {\n const url = new URL(url_)\n\n const result = (() => {\n // Handle Basic authentication credentials\n if (url.username) {\n const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`\n url.username = ''\n url.password = ''\n\n return {\n url: url.toString(),\n headers: { Authorization: `Basic ${btoa(credentials)}` },\n }\n }\n\n return\n })()\n\n return { url: url.toString(), ...result }\n } catch {\n return { url: url_ }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout(\n fn: ({\n signal,\n }: {\n signal: AbortController['signal'] | null\n }) => Promise,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\n","import * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Authorization from '../core/Authorization.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport * as Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-8010 signature. */\nexport type Unwrapped = {\n /** Authorization signed by the delegatee. */\n authorization: Authorization.Authorization\n /** Data to initialize the delegation. */\n data?: Hex.Hex | undefined\n /** The original signature. */\n signature: Hex.Hex\n /** Address of the initializer. */\n to?: Address.Address | undefined\n}\n\n/** Wrapped ERC-8010 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-8010 wrapped signatures.\n */\nexport const magicBytes =\n '0x8010801080108010801080108010801080108010801080108010801080108010' as const\n\n/** Suffix ABI parameters for the ERC-8010 wrapped signature. */\nexport const suffixParameters = AbiParameters.from(\n '(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data',\n)\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * SignatureErc8010.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-8010 wrapped signature.\n * ```\n *\n * @param value - The value to assert.\n */\nexport function assert(value: Unwrapped | Wrapped) {\n if (typeof value === 'string') {\n if (Hex.slice(value, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(value)\n } else Signature.assert(value.authorization)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc8010.from('0x...') // [!code focus]\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc8010.from({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * })\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } }\n * ```\n *\n * @param value - Value to parse.\n * @returns Parsed value.\n */\nexport function from(value: Unwrapped | Wrapped): Unwrapped {\n if (typeof value === 'string') return unwrap(value)\n return value\n}\n\nexport declare namespace from {\n type ErrorType = unwrap.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Unwraps an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const { authorization, data, signature } = SignatureErc8010.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to unwrap.\n * @returns Unwrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const suffixLength = Hex.toNumber(Hex.slice(wrapped, -64, -32))\n const suffix = Hex.slice(wrapped, -suffixLength - 64, -64)\n const signature = Hex.slice(wrapped, 0, -suffixLength - 64)\n\n const [auth, to, data] = AbiParameters.decode(suffixParameters, suffix)\n\n const authorization = Authorization.from({\n address: auth.delegation,\n chainId: Number(auth.chainId),\n nonce: auth.nonce,\n yParity: auth.yParity,\n r: auth.r,\n s: auth.s,\n })\n\n return {\n authorization,\n signature,\n ...(data && data !== '0x' ? { data, to } : {}),\n }\n}\n\nexport declare namespace unwrap {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Wraps a signature into [ERC-8010 format](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md).\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc8010.wrap({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Values to wrap.\n * @returns Wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature } = value\n\n assert(value)\n\n const self = Secp256k1.recoverAddress({\n payload: Authorization.getSignPayload(value.authorization),\n signature: Signature.from(value.authorization),\n })\n\n const suffix = AbiParameters.encode(suffixParameters, [\n {\n ...value.authorization,\n delegation: value.authorization.address,\n chainId: BigInt(value.authorization.chainId),\n },\n value.to ?? self,\n data ?? '0x',\n ])\n const suffixLength = Hex.fromNumber(Hex.size(suffix), { size: 32 })\n return Hex.concat(signature, suffix, suffixLength, magicBytes)\n}\n\nexport declare namespace wrap {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const valid = SignatureErc8010.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param value - The value to validate.\n * @returns `true` if the value is valid, `false` otherwise.\n */\nexport function validate(value: Unwrapped | Wrapped): boolean {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-8010 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc8010.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-8010 wrapped signature.`)\n }\n}\n","import * as abitype from 'abitype'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiParameters.js'\nimport * as Cursor from './internal/cursor.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for ABI parameters. */\nexport type AbiParameters = readonly abitype.AbiParameter[]\n\n/** A parameter on an {@link ox#AbiParameters.AbiParameters}. */\nexport type Parameter = abitype.AbiParameter\n\n/** A packed ABI type. */\nexport type PackedAbiType =\n | abitype.SolidityAddress\n | abitype.SolidityBool\n | abitype.SolidityBytes\n | abitype.SolidityInt\n | abitype.SolidityString\n | abitype.SolidityArrayWithoutTuple\n\n/**\n * Decodes ABI-encoded data into its respective primitive values based on ABI Parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * You can pass **JSON ABI** Parameters:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' },\n * ],\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @param parameters - The set of ABI parameters to decode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param data - ABI encoded data.\n * @param options - Decoding options.\n * @returns Array of decoded values.\n */\nexport function decode<\n const parameters extends AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n>(\n parameters: parameters,\n data: Bytes.Bytes | Hex.Hex,\n options?: decode.Options,\n): decode.ReturnType\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n parameters: AbiParameters,\n data: Bytes.Bytes | Hex.Hex,\n options: {\n as?: 'Array' | 'Object' | undefined\n checksumAddress?: boolean | undefined\n } = {},\n): readonly unknown[] | Record {\n const { as = 'Array', checksumAddress = false } = options\n\n const bytes = typeof data === 'string' ? Bytes.fromHex(data) : data\n const cursor = Cursor.create(bytes)\n\n if (Bytes.size(bytes) === 0 && parameters.length > 0)\n throw new ZeroDataError()\n if (Bytes.size(bytes) && Bytes.size(bytes) < 32)\n throw new DataSizeTooSmallError({\n data: typeof data === 'string' ? data : Hex.fromBytes(data),\n parameters: parameters as readonly Parameter[],\n size: Bytes.size(bytes),\n })\n\n let consumed = 0\n const values: any = as === 'Array' ? [] : {}\n for (let i = 0; i < parameters.length; ++i) {\n const param = parameters[i] as Parameter\n cursor.setPosition(consumed)\n const [data, consumed_] = internal.decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: 0,\n })\n consumed += consumed_\n if (as === 'Array') values.push(data)\n else values[param.name ?? i] = data\n }\n return values\n}\n\nexport declare namespace decode {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Object' | 'Array' | undefined\n /**\n * Whether decoded addresses should be checksummed.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n\n type ReturnType<\n parameters extends AbiParameters = AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n > = parameters extends readonly []\n ? as extends 'Object'\n ? {}\n : []\n : as extends 'Object'\n ? internal.ToObject\n : internal.ToPrimitiveTypes\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | internal.decodeParameter.ErrorType\n | ZeroDataError\n | DataSizeTooSmallError\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes primitive values into ABI encoded data as per the [Application Binary Interface (ABI) Specification](https://docs.soliditylang.org/en/latest/abi-spec).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * Specify **JSON ABI** Parameters as schema:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * [\n * { type: 'string', name: 'name' },\n * { type: 'uint', name: 'age' },\n * { type: 'bool', name: 'isOwner' },\n * ],\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @param parameters - The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param values - The set of primitive values that correspond to the ABI types defined in `parameters`.\n * @returns ABI encoded data.\n */\nexport function encode<\n const parameters extends AbiParameters | readonly unknown[],\n>(\n parameters: parameters,\n values: parameters extends AbiParameters\n ? internal.ToPrimitiveTypes\n : never,\n options?: encode.Options,\n): Hex.Hex {\n const { checksumAddress = false } = options ?? {}\n\n if (parameters.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: parameters.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParameters = internal.prepareParameters({\n checksumAddress,\n parameters: parameters as readonly Parameter[],\n values: values as any,\n })\n const data = internal.encode(preparedParameters)\n if (data.length === 0) return '0x'\n return data\n}\n\nexport declare namespace encode {\n type ErrorType =\n | LengthMismatchError\n | internal.encode.ErrorType\n | internal.prepareParameters.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /**\n * Whether addresses should be checked against their checksum.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n}\n\n/**\n * Encodes an array of primitive values to a [packed ABI encoding](https://docs.soliditylang.org/en/latest/abi-spec.html#non-standard-packed-mode).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const encoded = AbiParameters.encodePacked(\n * ['address', 'string'],\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 'hello world'],\n * )\n * // @log: '0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64'\n * ```\n *\n * @param types - Set of ABI types to pack encode.\n * @param values - The set of primitive values that correspond to the ABI types defined in `types`.\n * @returns The encoded packed data.\n */\nexport function encodePacked<\n const packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: packedAbiTypes, values: encodePacked.Values): Hex.Hex {\n if (types.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: types.length as number,\n givenLength: values.length as number,\n })\n\n const data: Hex.Hex[] = []\n for (let i = 0; i < (types as unknown[]).length; i++) {\n const type = types[i]\n const value = values[i]\n data.push(encodePacked.encode(type, value))\n }\n return Hex.concat(...data)\n}\n\nexport namespace encodePacked {\n export type ErrorType =\n | Hex.concat.ErrorType\n | LengthMismatchError\n | Errors.GlobalErrorType\n\n export type Values<\n packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n > = {\n [key in keyof packedAbiTypes]: packedAbiTypes[key] extends abitype.AbiType\n ? abitype.AbiParameterToPrimitiveType<{ type: packedAbiTypes[key] }>\n : unknown\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc\n export function encode(\n type: packedAbiType,\n value: Values<[packedAbiType]>[0],\n isArray = false,\n ): Hex.Hex {\n if (type === 'address') {\n const address = value as Address.Address\n Address.assert(address)\n return Hex.padLeft(\n address.toLowerCase() as Hex.Hex,\n isArray ? 32 : 0,\n ) as Address.Address\n }\n if (type === 'string') return Hex.fromString(value as string)\n if (type === 'bytes') return value as Hex.Hex\n if (type === 'bool')\n return Hex.padLeft(Hex.fromBoolean(value as boolean), isArray ? 32 : 1)\n\n const intMatch = (type as string).match(Solidity.integerRegex)\n if (intMatch) {\n const [_type, baseType, bits = '256'] = intMatch\n const size = Number.parseInt(bits, 10) / 8\n return Hex.fromNumber(value as number, {\n size: isArray ? 32 : size,\n signed: baseType === 'int',\n })\n }\n\n const bytesMatch = (type as string).match(Solidity.bytesRegex)\n if (bytesMatch) {\n const [_type, size] = bytesMatch\n if (Number.parseInt(size!, 10) !== ((value as Hex.Hex).length - 2) / 2)\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size!, 10),\n value: value as Hex.Hex,\n })\n return Hex.padRight(value as Hex.Hex, isArray ? 32 : 0) as Hex.Hex\n }\n\n const arrayMatch = (type as string).match(Solidity.arrayRegex)\n if (arrayMatch && Array.isArray(value)) {\n const [_type, childType] = arrayMatch\n const data: Hex.Hex[] = []\n for (let i = 0; i < value.length; i++) {\n data.push(encode(childType, value[i], true))\n }\n if (data.length === 0) return '0x'\n return Hex.concat(...data)\n }\n\n throw new InvalidTypeError(type as string)\n }\n}\n\n/**\n * Formats {@link ox#AbiParameters.AbiParameters} into **Human Readable ABI Parameters**.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const formatted = AbiParameters.format([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param parameters - The ABI Parameters to format.\n * @returns The formatted ABI Parameters .\n */\nexport function format<\n const parameters extends readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n>(\n parameters:\n | parameters\n | readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n): abitype.FormatAbiParameters {\n return abitype.formatAbiParameters(parameters)\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses arbitrary **JSON ABI Parameters** or **Human Readable ABI Parameters** into typed {@link ox#AbiParameters.AbiParameters}.\n *\n * @example\n * ### JSON Parameters\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable Parameters\n *\n * Human Readable ABI Parameters can be parsed into a typed {@link ox#AbiParameters.AbiParameters}:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from('address spender, uint256 amount')\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'Foo foo, address bar',\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param parameters - The ABI Parameters to parse.\n * @returns The typed ABI Parameters.\n */\nexport function from<\n const parameters extends AbiParameters | string | readonly string[],\n>(\n parameters: parameters | AbiParameters | string | readonly string[],\n): from.ReturnType {\n if (Array.isArray(parameters) && typeof parameters[0] === 'string')\n return abitype.parseAbiParameters(parameters) as never\n if (typeof parameters === 'string')\n return abitype.parseAbiParameters(parameters) as never\n return parameters as never\n}\n\nexport declare namespace from {\n type ReturnType<\n parameters extends AbiParameters | string | readonly string[],\n > = parameters extends string\n ? abitype.ParseAbiParameters\n : parameters extends readonly string[]\n ? abitype.ParseAbiParameters\n : parameters\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Throws when the data size is too small for the given parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x010f')\n * // ↑ ❌ 2 bytes\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass a valid data size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class DataSizeTooSmallError extends Errors.BaseError {\n override readonly name = 'AbiParameters.DataSizeTooSmallError'\n constructor({\n data,\n parameters,\n size,\n }: { data: Hex.Hex; parameters: readonly Parameter[]; size: number }) {\n super(`Data size of ${size} bytes is too small for given parameters.`, {\n metaMessages: [\n `Params: (${abitype.formatAbiParameters(parameters as readonly [Parameter])})`,\n `Data: ${data} (${size} bytes)`,\n ],\n })\n }\n}\n\n/**\n * Throws when zero data is provided, but data is expected.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x')\n * // ↑ ❌ zero data\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass valid data.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class ZeroDataError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\n/**\n * The length of the array value does not match the length specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('uint256[3]'), [[69n, 420n]])\n * // ↑ expected: 3 ↑ ❌ length: 2\n * // @error: AbiParameters.ArrayLengthMismatchError: ABI encoding array length mismatch\n * // @error: for type `uint256[3]`. Expected: `3`. Given: `2`.\n * ```\n *\n * ### Solution\n *\n * Pass an array of the correct length.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [[69n, 420n, 69n]])\n * // ↑ ✅ length: 3\n * ```\n */\nexport class ArrayLengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n `Array length mismatch for type \\`${type}\\`. Expected: \\`${expectedLength}\\`. Given: \\`${givenLength}\\`.`,\n )\n }\n}\n\n/**\n * The size of the bytes value does not match the size specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('bytes8'), [['0xdeadbeefdeadbeefdeadbeef']])\n * // ↑ expected: 8 bytes ↑ ❌ size: 12 bytes\n * // @error: BytesSizeMismatchError: Size of bytes \"0xdeadbeefdeadbeefdeadbeef\"\n * // @error: (bytes12) does not match expected size (bytes8).\n * ```\n *\n * ### Solution\n *\n * Pass a bytes value of the correct size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['bytes8']), ['0xdeadbeefdeadbeef'])\n * // ↑ ✅ size: 8 bytes\n * ```\n */\nexport class BytesSizeMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.BytesSizeMismatchError'\n constructor({\n expectedSize,\n value,\n }: { expectedSize: number; value: Hex.Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${Hex.size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\n/**\n * The length of the values to encode does not match the length of the ABI parameters.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['string', 'uint256']), ['hello'])\n * // @error: LengthMismatchError: ABI encoding params/values length mismatch.\n * // @error: Expected length (params): 2\n * // @error: Given length (values): 1\n * ```\n *\n * ### Solution\n *\n * Pass the correct number of values to encode.\n *\n * ### Solution\n *\n * Pass a [valid ABI type](https://docs.soliditylang.org/en/develop/abi-spec.html#types).\n */\nexport class LengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.LengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding parameters/values length mismatch.',\n `Expected length (parameters): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * The value provided is not a valid array as specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [69])\n * ```\n *\n * ### Solution\n *\n * Pass an array value.\n */\nexport class InvalidArrayError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidArrayError'\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is not a valid array.`)\n }\n}\n\n/**\n * Throws when the ABI parameter type is invalid.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'lol' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ❌ invalid type\n * // @error: AbiParameters.InvalidTypeError: Type `lol` is not a valid ABI Type.\n * ```\n */\nexport class InvalidTypeError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidTypeError'\n constructor(type: string) {\n super(`Type \\`${type}\\` is not a valid ABI Type.`)\n }\n}\n","import type { Address as abitype_Address } from 'abitype'\nimport * as Bytes from './Bytes.js'\nimport * as Caches from './Caches.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as PublicKey from './PublicKey.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** Root type for Address. */\nexport type Address = abitype_Address\n\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(\n value: string,\n options: assert.Options = {},\n): asserts value is Address {\n const { strict = true } = options\n\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n })\n\n if (strict) {\n if (value.toLowerCase() === value) return\n if (checksum(value as Address) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n })\n }\n}\n\nexport declare namespace assert {\n type Options = {\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\n type ErrorType = InvalidAddressError | Errors.GlobalErrorType\n}\n\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address: string): Address {\n if (Caches.checksum.has(address)) return Caches.checksum.get(address)!\n\n assert(address, { strict: false })\n\n const hexAddress = address.substring(2).toLowerCase()\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' })\n\n const characters = hexAddress.split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1]! >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i]!.toUpperCase()\n }\n if ((hash[i >> 1]! & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1]!.toUpperCase()\n }\n }\n\n const result = `0x${characters.join('')}` as const\n Caches.checksum.set(address, result)\n return result\n}\n\nexport declare namespace checksum {\n type ErrorType =\n | assert.ErrorType\n | Hash.keccak256.ErrorType\n | Bytes.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a stringified address to a typed (optionally checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: true\n * })\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address: string, options: from.Options = {}): Address {\n const { checksum: checksumVal = false } = options\n assert(address)\n if (checksumVal) return checksum(address)\n return address as Address\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | assert.ErrorType\n | checksum.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(\n publicKey: PublicKey.PublicKey,\n options: fromPublicKey.Options = {},\n): Address {\n const address = Hash.keccak256(\n `0x${PublicKey.toHex(publicKey).slice(4)}`,\n ).substring(26)\n return from(`0x${address}`, options)\n}\n\nexport declare namespace fromPublicKey {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA: Address, addressB: Address): boolean {\n assert(addressA, { strict: false })\n assert(addressB, { strict: false })\n return addressA.toLowerCase() === addressB.toLowerCase()\n}\n\nexport declare namespace isEqual {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(\n address: string,\n options: validate.Options = {},\n): address is Address {\n const { strict = true } = options ?? {}\n try {\n assert(address, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\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}\n\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError<\n cause extends InvalidInputError | InvalidChecksumError =\n | InvalidInputError\n | InvalidChecksumError,\n> extends Errors.BaseError {\n override readonly name = 'Address.InvalidAddressError'\n\n constructor({ address, cause }: { address: string; cause: cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n override readonly name = 'Address.InvalidInputError'\n\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.')\n }\n}\n\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n override readonly name = 'Address.InvalidChecksumError'\n\n constructor() {\n super('Address does not match its checksum counterpart.')\n }\n}\n","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see 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 * as Address from './Address.js'\nimport { LruMap } from './internal/lru.js'\n\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap(8192),\n}\n\nexport const checksum = caches.checksum\n\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches)) cache.clear()\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3'\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: keccak256.Options = {},\n): keccak256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_keccak256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace keccak256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [HMAC-SHA256](https://en.wikipedia.org/wiki/HMAC) of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `hmac` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef')\n * // @log: '0x...'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param key - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} key.\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns HMAC-SHA256 hash.\n */\nexport function hmac256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n key: Hex.Hex | Bytes.Bytes,\n value: value | Hex.Hex | Bytes.Bytes,\n options: hmac256.Options = {},\n): hmac256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = hmac(noble_sha256, Bytes.from(key), Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace hmac256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: ripemd160.Options = {},\n): ripemd160.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_ripemd160(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace ripemd160 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: sha256.Options = {},\n): sha256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_sha256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace sha256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value: string): value is Hex.Hex {\n return Hex.validate(value) && Hex.size(value) === 32\n}\n\nexport declare namespace validate {\n type ErrorType =\n | Hex.validate.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial } from './internal/types.js'\nimport * as Json from './Json.js'\n\n/** Root type for an ECDSA Public Key. */\nexport type PublicKey<\n compressed extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n compressed extends true\n ? {\n prefix: numberType\n x: bigintType\n y?: undefined\n }\n : {\n prefix: numberType\n x: bigintType\n y: bigintType\n }\n>\n\n/**\n * Asserts that a {@link ox#PublicKey.PublicKey} is valid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @error: PublicKey.InvalidError: Value \\`{\"y\":\"1\"}\\` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function assert(\n publicKey: ExactPartial,\n options: assert.Options = {},\n): asserts publicKey is PublicKey {\n const { compressed } = options\n const { prefix, x, y } = publicKey\n\n // Uncompressed\n if (\n compressed === false ||\n (typeof x === 'bigint' && typeof y === 'bigint')\n ) {\n if (prefix !== 4)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidUncompressedPrefixError(),\n })\n return\n }\n\n // Compressed\n if (\n compressed === true ||\n (typeof x === 'bigint' && typeof y === 'undefined')\n ) {\n if (prefix !== 3 && prefix !== 2)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidCompressedPrefixError(),\n })\n return\n }\n\n // Unknown/invalid\n throw new InvalidError({ publicKey })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = InvalidError | InvalidPrefixError | Errors.GlobalErrorType\n}\n\n/**\n * Compresses a {@link ox#PublicKey.PublicKey}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const compressed = PublicKey.compress(publicKey) // [!code focus]\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The public key to compress.\n * @returns The compressed public key.\n */\nexport function compress(publicKey: PublicKey): PublicKey {\n const { x, y } = publicKey\n return {\n prefix: y % 2n === 0n ? 2 : 3,\n x,\n }\n}\n\nexport declare namespace compress {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#PublicKey.PublicKey} object from a {@link ox#PublicKey.PublicKey}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from('0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param value - The public key value to instantiate.\n * @returns The instantiated {@link ox#PublicKey.PublicKey}.\n */\nexport function from<\n const publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes,\n>(value: from.Value): from.ReturnType {\n const publicKey = (() => {\n if (Hex.validate(value)) return fromHex(value)\n if (Bytes.validate(value)) return fromBytes(value)\n\n const { prefix, x, y } = value\n if (typeof x === 'bigint' && typeof y === 'bigint')\n return { prefix: prefix ?? 0x04, x, y }\n return { prefix, x }\n })()\n\n assert(publicKey)\n\n return publicKey as never\n}\n\n/** @internal */\ntype CompressedPublicKey = PublicKey\n\n/** @internal */\ntype UncompressedPublicKey = Omit, 'prefix'> & {\n prefix?: PublicKey['prefix'] | undefined\n}\n\nexport declare namespace from {\n type Value<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey | CompressedPublicKey | UncompressedPublicKey\n\n type ReturnType<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey extends CompressedPublicKey | UncompressedPublicKey\n ? publicKey extends UncompressedPublicKey\n ? Compute\n : publicKey\n : PublicKey\n\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromBytes(publicKey: Bytes.Bytes): PublicKey {\n return fromHex(Hex.fromBytes(publicKey))\n}\n\nexport declare namespace fromBytes {\n type ErrorType =\n | fromHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### Deserializing a Compressed Public Key\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75')\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromHex(publicKey: Hex.Hex): PublicKey {\n if (\n publicKey.length !== 132 &&\n publicKey.length !== 130 &&\n publicKey.length !== 68\n )\n throw new InvalidSerializedSizeError({ publicKey })\n\n if (publicKey.length === 130) {\n const x = BigInt(Hex.slice(publicKey, 0, 32))\n const y = BigInt(Hex.slice(publicKey, 32, 64))\n return {\n prefix: 4,\n x,\n y,\n } as never\n }\n\n if (publicKey.length === 132) {\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n const y = BigInt(Hex.slice(publicKey, 33, 65))\n return {\n prefix,\n x,\n y,\n } as never\n }\n\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n return {\n prefix,\n x,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType = Hex.slice.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const bytes = PublicKey.toBytes(publicKey) // [!code focus]\n * // @log: Uint8Array [128, 3, 131, ...]\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toBytes(\n publicKey: PublicKey,\n options: toBytes.Options = {},\n): Bytes.Bytes {\n return Bytes.fromHex(toHex(publicKey, options))\n}\n\nexport declare namespace toBytes {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const hex = PublicKey.toHex(publicKey) // [!code focus]\n * // @log: '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toHex(\n publicKey: PublicKey,\n options: toHex.Options = {},\n): Hex.Hex {\n assert(publicKey)\n\n const { prefix, x, y } = publicKey\n const { includePrefix = true } = options\n\n const publicKey_ = Hex.concat(\n includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x',\n Hex.fromNumber(x, { size: 32 }),\n // If the public key is not compressed, add the y coordinate.\n typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x',\n )\n\n return publicKey_\n}\n\nexport declare namespace toHex {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Validates a {@link ox#PublicKey.PublicKey}. Returns `true` if valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const valid = PublicKey.validate({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @log: false\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function validate(\n publicKey: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(publicKey, options)\n return true\n } catch (_error) {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a public key is invalid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({ y: 1n })\n * // @error: PublicKey.InvalidError: Value `{\"y\":1n}` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n */\nexport class InvalidError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidError'\n\n constructor({ publicKey }: { publicKey: unknown }) {\n super(`Value \\`${Json.stringify(publicKey)}\\` is not a valid public key.`, {\n metaMessages: [\n 'Public key must contain:',\n '- an `x` and `prefix` value (compressed)',\n '- an `x`, `y`, and `prefix` value (uncompressed)',\n ],\n })\n }\n}\n\n/** Thrown when a public key has an invalid prefix. */\nexport class InvalidPrefixError<\n cause extends InvalidCompressedPrefixError | InvalidUncompressedPrefixError =\n | InvalidCompressedPrefixError\n | InvalidUncompressedPrefixError,\n> extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidPrefixError'\n\n constructor({ prefix, cause }: { prefix: number | undefined; cause: cause }) {\n super(`Prefix \"${prefix}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when the public key has an invalid prefix for a compressed public key. */\nexport class InvalidCompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidCompressedPrefixError'\n\n constructor() {\n super('Prefix must be 2 or 3 for compressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid prefix for an uncompressed public key. */\nexport class InvalidUncompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidUncompressedPrefixError'\n\n constructor() {\n super('Prefix must be 4 for uncompressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid serialized size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidSerializedSizeError'\n\n constructor({ publicKey }: { publicKey: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${publicKey}\\` is an invalid public key size.`, {\n metaMessages: [\n 'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',\n `Received ${Hex.size(Hex.from(publicKey))} bytes.`,\n ],\n })\n }\n}\n","import type {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\n} from 'abitype'\nimport * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Bytes from '../Bytes.js'\nimport * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\nimport { integerRegex } from '../Solidity.js'\nimport type * as Cursor from './cursor.js'\nimport type { Compute, IsNarrowable, UnionToIntersection } from './types.js'\n\n/** @internal */\nexport type ParameterToPrimitiveType<\n abiParameter extends AbiParameter | { name: string; type: unknown },\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParameterToPrimitiveType\n\n/** @internal */\nexport type PreparedParameter = { dynamic: boolean; encoded: Hex.Hex }\n\n/** @internal */\nexport type ToObject<\n parameters extends readonly AbiParameter[],\n kind extends AbiParameterKind = AbiParameterKind,\n> = IsNarrowable extends true\n ? Compute<\n UnionToIntersection<\n {\n [index in keyof parameters]: parameters[index] extends {\n name: infer name extends string\n }\n ? {\n [key in name]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n : {\n [key in index]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n }[number]\n >\n >\n : unknown\n\n/** @internal */\nexport type ToPrimitiveTypes<\n abiParameters extends readonly AbiParameter[],\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParametersToPrimitiveTypes\n\n/** @internal */\nexport type Tuple = ParameterToPrimitiveType\n\n/** @internal */\nexport function decodeParameter(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(\n cursor,\n { ...param, type },\n { checksumAddress, length, staticPosition },\n )\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, {\n checksumAddress,\n staticPosition,\n })\n if (param.type === 'address')\n return decodeAddress(cursor, { checksum: checksumAddress })\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 AbiParameters.InvalidTypeError(param.type)\n}\n\nexport declare namespace decodeParameter {\n type ErrorType =\n | decodeArray.ErrorType\n | decodeTuple.ErrorType\n | decodeAddress.ErrorType\n | decodeBool.ErrorType\n | decodeBytes.ErrorType\n | decodeNumber.ErrorType\n | decodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\n/** @internal */\nexport function decodeAddress(\n cursor: Cursor.Cursor,\n options: { checksum?: boolean | undefined } = {},\n) {\n const { checksum = false } = options\n const value = cursor.readBytes(32)\n const wrap = (address: Hex.Hex) =>\n checksum ? Address.checksum(address) : address\n return [wrap(Hex.fromBytes(Bytes.slice(value, -20))), 32]\n}\n\nexport declare namespace decodeAddress {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeArray(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n staticPosition: number\n },\n) {\n const { checksumAddress, length, staticPosition } = options\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 = Bytes.toNumber(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 = Bytes.toNumber(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 checksumAddress,\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeArray {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBool(cursor: Cursor.Cursor) {\n return [Bytes.toBoolean(cursor.readBytes(32), { size: 32 }), 32]\n}\n\nexport declare namespace decodeBool {\n type ErrorType = Bytes.toBoolean.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBytes(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\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 = Bytes.toNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = Bytes.toNumber(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 [Hex.fromBytes(data), 32]\n }\n\n const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))\n return [value, 32]\n}\n\nexport declare namespace decodeBytes {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeNumber(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10)\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? Bytes.toBigInt(value, { signed })\n : Bytes.toNumber(value, { signed }),\n 32,\n ]\n}\n\nexport declare namespace decodeNumber {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport type TupleAbiParameter = AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n}\n\n/** @internal */\nexport function decodeTuple(\n cursor: Cursor.Cursor,\n param: TupleAbiParameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeTuple {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeString(\n cursor: Cursor.Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = Bytes.toNumber(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 = Bytes.toNumber(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 = Bytes.toString(Bytes.trimLeft(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\nexport declare namespace decodeString {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toString.ErrorType\n | Bytes.trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameters<\n const parameters extends AbiParameters.AbiParameters,\n>({\n checksumAddress,\n parameters,\n values,\n}: {\n checksumAddress?: boolean | undefined\n parameters: parameters\n values: parameters extends AbiParameters.AbiParameters\n ? ToPrimitiveTypes\n : never\n}) {\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameters.length; i++) {\n preparedParameters.push(\n prepareParameter({\n checksumAddress,\n parameter: parameters[i]!,\n value: values[i],\n }),\n )\n }\n return preparedParameters\n}\n\n/** @internal */\nexport declare namespace prepareParameters {\n type ErrorType = prepareParameter.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameter<\n const parameter extends AbiParameters.Parameter,\n>({\n checksumAddress = false,\n parameter: parameter_,\n value,\n}: {\n parameter: parameter\n value: parameter extends AbiParameters.Parameter\n ? ParameterToPrimitiveType\n : never\n checksumAddress?: boolean | undefined\n}): PreparedParameter {\n const parameter = parameter_ as AbiParameters.Parameter\n\n const arrayComponents = getArrayComponents(parameter.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, {\n checksumAddress,\n length,\n parameter: {\n ...parameter,\n type,\n },\n })\n }\n if (parameter.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n checksumAddress,\n parameter: parameter as TupleAbiParameter,\n })\n }\n if (parameter.type === 'address') {\n return encodeAddress(value as unknown as Hex.Hex, {\n checksum: checksumAddress,\n })\n }\n if (parameter.type === 'bool') {\n return encodeBoolean(value as unknown as boolean)\n }\n if (parameter.type.startsWith('uint') || parameter.type.startsWith('int')) {\n const signed = parameter.type.startsWith('int')\n const [, , size = '256'] = integerRegex.exec(parameter.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\n }\n if (parameter.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex.Hex, { type: parameter.type })\n }\n if (parameter.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new AbiParameters.InvalidTypeError(parameter.type)\n}\n\n/** @internal */\nexport declare namespace prepareParameter {\n type ErrorType =\n | encodeArray.ErrorType\n | encodeTuple.ErrorType\n | encodeAddress.ErrorType\n | encodeBoolean.ErrorType\n | encodeBytes.ErrorType\n | encodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encode(preparedParameters: PreparedParameter[]): Hex.Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) staticSize += 32\n else staticSize += Hex.size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParameters: Hex.Hex[] = []\n const dynamicParameters: Hex.Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) {\n staticParameters.push(\n Hex.fromNumber(staticSize + dynamicSize, { size: 32 }),\n )\n dynamicParameters.push(encoded)\n dynamicSize += Hex.size(encoded)\n } else {\n staticParameters.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return Hex.concat(...staticParameters, ...dynamicParameters)\n}\n\n/** @internal */\nexport declare namespace encode {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeAddress(\n value: Hex.Hex,\n options: { checksum: boolean },\n): PreparedParameter {\n const { checksum = false } = options\n Address.assert(value, { strict: checksum })\n return {\n dynamic: false,\n encoded: Hex.padLeft(value.toLowerCase() as Hex.Hex),\n }\n}\n\n/** @internal */\nexport declare namespace encodeAddress {\n type ErrorType =\n | Address.assert.ErrorType\n | Hex.padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeArray(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, length, parameter } = options\n\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new AbiParameters.InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiParameters.ArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${parameter.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter,\n value: value[i],\n })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParameters.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encode(preparedParameters)\n if (dynamic) {\n const length = Hex.fromNumber(preparedParameters.length, { size: 32 })\n return {\n dynamic: true,\n encoded:\n preparedParameters.length > 0 ? Hex.concat(length, data) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeArray {\n type ErrorType =\n | AbiParameters.InvalidArrayError\n | AbiParameters.ArrayLengthMismatchError\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBytes(\n value: Hex.Hex,\n { type }: { type: string },\n): PreparedParameter {\n const [, parametersize] = type.split('bytes')\n const bytesSize = Hex.size(value)\n if (!parametersize) {\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_ = Hex.padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32)\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padLeft(Hex.fromNumber(bytesSize, { size: 32 })),\n value_,\n ),\n }\n }\n if (bytesSize !== Number.parseInt(parametersize, 10))\n throw new AbiParameters.BytesSizeMismatchError({\n expectedSize: Number.parseInt(parametersize, 10),\n value,\n })\n return { dynamic: false, encoded: Hex.padRight(value) }\n}\n\n/** @internal */\nexport declare namespace encodeBytes {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.padRight.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBoolean(value: boolean): PreparedParameter {\n if (typeof value !== 'boolean')\n throw new Errors.BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: Hex.padLeft(Hex.fromBoolean(value)) }\n}\n\n/** @internal */\nexport declare namespace encodeBoolean {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.fromBoolean.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeNumber(\n value: number,\n { signed, size }: { signed: boolean; size: number },\n): PreparedParameter {\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 Hex.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: Hex.fromNumber(value, {\n size: 32,\n signed,\n }),\n }\n}\n\n/** @internal */\nexport declare namespace encodeNumber {\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeString(value: string): PreparedParameter {\n const hexValue = Hex.fromString(value)\n const partsLength = Math.ceil(Hex.size(hexValue) / 32)\n const parts: Hex.Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(Hex.padRight(Hex.slice(hexValue, i * 32, (i + 1) * 32)))\n }\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padRight(Hex.fromNumber(Hex.size(hexValue), { size: 32 })),\n ...parts,\n ),\n }\n}\n\n/** @internal */\nexport declare namespace encodeString {\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Hex.padRight.ErrorType\n | Hex.slice.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeTuple<\n const parameter extends AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n },\n>(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, parameter } = options\n\n let dynamic = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameter.components.length; i++) {\n const param_ = parameter.components[i]!\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParameters.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encode(preparedParameters)\n : Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeTuple {\n type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\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\n/** @internal */\nexport function hasDynamicChild(param: AbiParameters.Parameter) {\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({\n ...param,\n type: arrayComponents[1],\n } as AbiParameters.Parameter)\n )\n return true\n\n return false\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\nexport 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 type { Bytes } from '../Bytes.js'\nimport * as Errors from '../Errors.js'\n\n/** @internal */\nexport type Cursor = {\n bytes: Bytes\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): Bytes[number]\n inspectBytes(length: number, position?: number): Bytes\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: Bytes[number]): void\n pushBytes(bytes: Bytes): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): Bytes[number]\n readBytes(length: number, size?: number): Bytes\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\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: Bytes[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: Bytes) {\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\n/** @internal */\nexport function create(\n bytes: Bytes,\n { recursiveReadLimit = 8_192 }: create.Config = {},\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\n/** @internal */\nexport declare namespace create {\n type Config = { recursiveReadLimit?: number | undefined }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport class NegativeOffsetError extends Errors.BaseError {\n override readonly name = 'Cursor.NegativeOffsetError'\n\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`)\n }\n}\n\n/** @internal */\nexport class PositionOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Cursor.PositionOutOfBoundsError'\n\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n )\n }\n}\n\n/** @internal */\nexport class RecursiveReadLimitExceededError extends Errors.BaseError {\n override readonly name = 'Cursor.RecursiveReadLimitExceededError'\n\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n )\n }\n}\n","import type * as Address from './Address.js'\nimport type * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, Mutable, Undefined } from './internal/types.js'\nimport * as Rlp from './Rlp.js'\nimport * as Signature from './Signature.js'\n\n/** Root type for an EIP-7702 Authorization. */\nexport type Authorization<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** Address of the contract to set as code for the Authority. */\n address: Address.Address\n /** Chain ID to authorize. */\n chainId: numberType\n /** Nonce of the Authority to authorize. */\n nonce: bigintType\n } & (signed extends true\n ? Signature.Signature\n : Undefined)\n>\n\n/** RPC representation of an {@link ox#Authorization.Authorization}. */\nexport type Rpc = Authorization\n\n/** List of {@link ox#Authorization.Authorization}. */\nexport type List<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute[]>\n\n/** RPC representation of an {@link ox#Authorization.List}. */\nexport type ListRpc = List\n\n/** Signed representation of a list of {@link ox#Authorization.Authorization}. */\nexport type ListSigned = List<\n true,\n bigintType,\n numberType\n>\n\n/** Signed representation of an {@link ox#Authorization.Authorization}. */\nexport type Signed = Authorization<\n true,\n bigintType,\n numberType\n>\n\n/** Tuple representation of an {@link ox#Authorization.Authorization}. */\nexport type Tuple = signed extends true\n ? readonly [\n chainId: Hex.Hex,\n address: Hex.Hex,\n nonce: Hex.Hex,\n yParity: Hex.Hex,\n r: Hex.Hex,\n s: Hex.Hex,\n ]\n : readonly [chainId: Hex.Hex, address: Hex.Hex, nonce: Hex.Hex]\n\n/** Tuple representation of a signed {@link ox#Authorization.Authorization}. */\nexport type TupleSigned = Tuple\n\n/** Tuple representation of a list of {@link ox#Authorization.Authorization}. */\nexport type TupleList =\n readonly Tuple[]\n\n/** Tuple representation of a list of signed {@link ox#Authorization.Authorization}. */\nexport type TupleListSigned = TupleList\n\n/**\n * Converts an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization object into a typed {@link ox#Authorization.Authorization}.\n *\n * @example\n * An Authorization can be instantiated from an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * A {@link ox#Signature.Signature} can be attached with the `signature` option. The example below demonstrates signing\n * an Authorization with {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: Authorization.getSignPayload(authorization),\n * privateKey: '0x...',\n * })\n *\n * const authorization_signed = Authorization.from(authorization, { signature }) // [!code focus]\n * ```\n *\n * @param authorization - An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n * @param options - Authorization options.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function from<\n const authorization extends Authorization | Rpc,\n const signature extends Signature.Signature | undefined = undefined,\n>(\n authorization: authorization | Authorization,\n options: from.Options = {},\n): from.ReturnType {\n if (typeof authorization.chainId === 'string')\n return fromRpc(authorization) as never\n return { ...authorization, ...options.signature } as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = {\n /** The {@link ox#Signature.Signature} to attach to the Authorization. */\n signature?: signature | Signature.Signature | undefined\n }\n\n type ReturnType<\n authorization extends Authorization | Rpc = Authorization,\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends Signature.Signature ? Readonly : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Rpc} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param authorization - The RPC-formatted Authorization.\n * @returns A signed {@link ox#Authorization.Authorization}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)!\n\n return {\n address,\n chainId: Number(chainId),\n nonce: BigInt(nonce),\n ...signature,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.ListRpc} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * }])\n * ```\n *\n * @param authorizationList - The RPC-formatted Authorization list.\n * @returns A signed {@link ox#Authorization.List}.\n */\nexport function fromRpcList(authorizationList: ListRpc): ListSigned {\n return authorizationList.map(fromRpc)\n}\n\nexport declare namespace fromRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Tuple} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3'\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: }\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3',\n * '0x1',\n * '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90',\n * '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: }\n * ```\n *\n * @param tuple - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function fromTuple(\n tuple: tuple,\n): fromTuple.ReturnType {\n const [chainId, address, nonce, yParity, r, s] = tuple\n let args = {\n address,\n chainId: chainId === '0x' ? 0 : Number(chainId),\n nonce: nonce === '0x' ? 0n : BigInt(nonce),\n }\n if (yParity && r && s)\n args = { ...args, ...Signature.fromTuple([yParity, r, s]) }\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType = Compute<\n Authorization ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.TupleList} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param tupleList - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n * @returns An {@link ox#Authorization.List}.\n */\nexport function fromTupleList(\n tupleList: tupleList,\n): fromTupleList.ReturnType {\n const list: Mutable = []\n for (const tuple of tupleList) list.push(fromTuple(tuple))\n return list as never\n}\n\nexport declare namespace fromTupleList {\n type ReturnType = Compute<\n TupleList ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * The example below demonstrates computing the sign payload for an {@link ox#Authorization.Authorization}. This payload\n * can then be passed to signing functions like {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = Authorization.getSignPayload(authorization) // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload,\n * privateKey: '0x...',\n * })\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: Authorization): Hex.Hex {\n return hash(authorization, { presign: true })\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const hash = Authorization.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The hash.\n */\nexport function hash(\n authorization: Authorization,\n options: hash.Options = {},\n): Hex.Hex {\n const { presign } = options\n return Hash.keccak256(\n Hex.concat(\n '0x05',\n Rlp.fromHex(\n toTuple(\n presign\n ? {\n address: authorization.address,\n chainId: authorization.chainId,\n nonce: authorization.nonce,\n }\n : authorization,\n ),\n ),\n ),\n )\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /** Whether to hash this authorization for signing. @default false */\n presign?: boolean | undefined\n }\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * })\n * ```\n *\n * @param authorization - An Authorization.\n * @returns An RPC-formatted Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, nonce, ...signature } = authorization\n\n return {\n address,\n chainId: Hex.fromNumber(chainId),\n nonce: Hex.fromNumber(nonce),\n ...Signature.toRpc(signature),\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.ListRpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * }])\n * ```\n *\n * @param authorizationList - An Authorization List.\n * @returns An RPC-formatted Authorization List.\n */\nexport function toRpcList(authorizationList: ListSigned): ListRpc {\n return authorizationList.map(toRpc)\n}\n\nexport declare namespace toRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const tuple = Authorization.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n */\nexport function toTuple(\n authorization: authorization,\n): toTuple.ReturnType {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)\n return [\n chainId ? Hex.fromNumber(chainId) : '0x',\n address,\n nonce ? Hex.fromNumber(nonce) : '0x',\n ...(signature ? Signature.toTuple(signature) : []),\n ] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType =\n Compute>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.TupleList}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization_1 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * const authorization_2 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 3,\n * nonce: 20n,\n * })\n *\n * const tuple = Authorization.toTupleList([authorization_1, authorization_2]) // [!code focus]\n * // @log: [\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ],\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param list - An {@link ox#Authorization.List}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n */\nexport function toTupleList<\n const list extends\n | readonly Authorization[]\n | readonly Authorization[],\n>(list?: list | undefined): toTupleList.ReturnType {\n if (!list || list.length === 0) return []\n\n const tupleList: Mutable = []\n for (const authorization of list) tupleList.push(toTuple(authorization))\n\n return tupleList as never\n}\n\nexport declare namespace toTupleList {\n type ReturnType<\n list extends\n | readonly Authorization[]\n | readonly Authorization[],\n > = Compute<\n TupleList[] ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Cursor from './internal/cursor.js'\nimport type { ExactPartial, RecursiveArray } from './internal/types.js'\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toBytes('0x8b68656c6c6f20776f726c64')\n * // Uint8Array([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Bytes.Bytes} value.\n */\nexport function toBytes(\n value: Bytes.Bytes | Hex.Hex,\n): RecursiveArray {\n return to(value, 'Bytes')\n}\n\nexport declare namespace toBytes {\n type ErrorType = to.ErrorType\n}\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toHex('0x8b68656c6c6f20776f726c64')\n * // 0x68656c6c6f20776f726c64\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes.Bytes | Hex.Hex): RecursiveArray {\n return to(value, 'Hex')\n}\n\nexport declare namespace toHex {\n type ErrorType = to.ErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\n/////////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport function to<\n value extends Bytes.Bytes | Hex.Hex,\n to extends 'Hex' | 'Bytes',\n>(value: value, to: to | 'Hex' | 'Bytes'): to.ReturnType {\n const to_ = to ?? (typeof value === 'string' ? 'Hex' : 'Bytes')\n\n const bytes = (() => {\n if (typeof value === 'string') {\n if (value.length > 3 && value.length % 2 !== 0)\n throw new Hex.InvalidLengthError(value)\n return Bytes.fromHex(value)\n }\n return value as Bytes.Bytes\n })()\n\n const cursor = Cursor.create(bytes, {\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n })\n const result = decodeRlpCursor(cursor, to_)\n\n return result as to.ReturnType\n}\n\n/** @internal */\nexport declare namespace to {\n type ReturnType =\n | (to extends 'Bytes' ? RecursiveArray : never)\n | (to extends 'Hex' ? RecursiveArray : never)\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | decodeRlpCursor.ErrorType\n | Cursor.create.ErrorType\n | Hex.InvalidLengthError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\n\n/** @internal */\nexport function decodeRlpCursor(\n cursor: Cursor.Cursor,\n to: to | 'Hex' | 'Bytes' | undefined = 'Hex',\n): decodeRlpCursor.ReturnType {\n if (cursor.bytes.length === 0)\n return (\n to === 'Hex' ? Hex.fromBytes(cursor.bytes) : cursor.bytes\n ) as decodeRlpCursor.ReturnType\n\n const prefix = cursor.readByte()\n if (prefix < 0x80) cursor.decrementPosition(1)\n\n // bytes\n if (prefix < 0xc0) {\n const length = readLength(cursor, prefix, 0x80)\n const bytes = cursor.readBytes(length)\n return (\n to === 'Hex' ? Hex.fromBytes(bytes) : bytes\n ) as decodeRlpCursor.ReturnType\n }\n\n // list\n const length = readLength(cursor, prefix, 0xc0)\n return readList(cursor, length, to) as {} as decodeRlpCursor.ReturnType\n}\n\n/** @internal */\nexport declare namespace decodeRlpCursor {\n type ReturnType = to.ReturnType\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | readLength.ErrorType\n | readList.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readLength(\n cursor: Cursor.Cursor,\n prefix: number,\n offset: number,\n) {\n if (offset === 0x80 && prefix < 0x80) return 1\n if (prefix <= offset + 55) return prefix - offset\n if (prefix === offset + 55 + 1) return cursor.readUint8()\n if (prefix === offset + 55 + 2) return cursor.readUint16()\n if (prefix === offset + 55 + 3) return cursor.readUint24()\n if (prefix === offset + 55 + 4) return cursor.readUint32()\n throw new Errors.BaseError('Invalid RLP prefix')\n}\n\n/** @internal */\nexport declare namespace readLength {\n type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readList(\n cursor: Cursor.Cursor,\n length: number,\n to: to | 'Hex' | 'Bytes',\n) {\n const position = cursor.position\n const value: decodeRlpCursor.ReturnType[] = []\n while (cursor.position - position < length)\n value.push(decodeRlpCursor(cursor, to))\n return value\n}\n\n/** @internal */\nexport declare namespace readList {\n type ErrorType = Errors.GlobalErrorType\n}\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor.Cursor): void\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.from('0x68656c6c6f20776f726c64', { as: 'Hex' })\n * // @log: 0x8b68656c6c6f20776f726c64\n *\n * Rlp.from(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), { as: 'Bytes' })\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function from(\n value: RecursiveArray | RecursiveArray,\n options: from.Options,\n): from.ReturnType {\n const { as } = options\n\n const encodable = getEncodable(value)\n const cursor = Cursor.create(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (as === 'Hex') return Hex.fromBytes(cursor.bytes) as from.ReturnType\n return cursor.bytes as from.ReturnType\n}\n\nexport declare namespace from {\n type Options = {\n /** The type to convert the RLP value to. */\n as: as | 'Hex' | 'Bytes'\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Cursor.create.ErrorType\n | Hex.fromBytes.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.fromBytes(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]))\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromBytes(\n bytes: RecursiveArray,\n options: fromBytes.Options = {},\n): fromBytes.ReturnType {\n const { as = 'Bytes' } = options\n return from(bytes, { as }) as never\n}\n\nexport declare namespace fromBytes {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n *\n * Rlp.fromHex('0x68656c6c6f20776f726c64')\n * // @log: 0x8b68656c6c6f20776f726c64\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromHex(\n hex: RecursiveArray,\n options: fromHex.Options = {},\n): fromHex.ReturnType {\n const { as = 'Hex' } = options\n return from(hex, { as }) as never\n}\n\nexport declare namespace fromHex {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\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.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: Bytes.Bytes | Hex.Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? Bytes.fromHex(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.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 <= 0xff) return 1\n if (length <= 0xff_ff) return 2\n if (length <= 0xff_ff_ff) return 3\n if (length <= 0xff_ff_ff_ff) return 4\n throw new Errors.BaseError('Length is too large.')\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial, OneOf } from './internal/types.js'\nimport * as Json from './Json.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for an ECDSA signature. */\nexport type Signature<\n recovered extends boolean = true,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n recovered extends true\n ? {\n r: bigintType\n s: bigintType\n yParity: numberType\n }\n : {\n r: bigintType\n s: bigintType\n yParity?: numberType | undefined\n }\n>\n\n/** RPC-formatted ECDSA signature. */\nexport type Rpc = Signature<\n recovered,\n Hex.Hex,\n Hex.Hex\n>\n\n/** (Legacy) ECDSA signature. */\nexport type Legacy = {\n r: bigintType\n s: bigintType\n v: numberType\n}\n\n/** RPC-formatted (Legacy) ECDSA signature. */\nexport type LegacyRpc = Legacy\n\nexport type Tuple = readonly [yParity: Hex.Hex, r: Hex.Hex, s: Hex.Hex]\n\n/**\n * Asserts that a Signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.assert({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @error: InvalidSignatureRError:\n * // @error: Value `-549...n` is an invalid r value.\n * // @error: r must be a positive integer less than 2^256.\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function assert(\n signature: ExactPartial,\n options: assert.Options = {},\n): asserts signature is Signature {\n const { recovered } = options\n if (typeof signature.r === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (typeof signature.s === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (recovered && typeof signature.yParity === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (signature.r < 0n || signature.r > Solidity.maxUint256)\n throw new InvalidRError({ value: signature.r })\n if (signature.s < 0n || signature.s > Solidity.maxUint256)\n throw new InvalidSError({ value: signature.s })\n if (\n typeof signature.yParity === 'number' &&\n signature.yParity !== 0 &&\n signature.yParity !== 1\n )\n throw new InvalidYParityError({ value: signature.yParity })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType =\n | MissingPropertiesError\n | InvalidRError\n | InvalidSError\n | InvalidYParityError\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Bytes.Bytes} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param signature - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromBytes(signature: Bytes.Bytes): Signature {\n return fromHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Hex.Hex} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.fromHex('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c')\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param serialized - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromHex(signature: Hex.Hex): Signature {\n if (signature.length !== 130 && signature.length !== 132)\n throw new InvalidSerializedSizeError({ signature })\n\n const r = BigInt(Hex.slice(signature, 0, 32))\n const s = BigInt(Hex.slice(signature, 32, 64))\n\n const yParity = (() => {\n const yParity = Number(`0x${signature.slice(130)}`)\n if (Number.isNaN(yParity)) return undefined\n try {\n return vToYParity(yParity)\n } catch {\n throw new InvalidYParityError({ value: yParity })\n }\n })()\n\n if (typeof yParity === 'undefined')\n return {\n r,\n s,\n } as never\n return {\n r,\n s,\n yParity,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType =\n | Hex.from.ErrorType\n | InvalidSerializedSizeError\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts a {@link ox#Signature.Signature} from an arbitrary object that may include signature properties.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.extract({\n * baz: 'barry',\n * foo: 'bar',\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * zebra: 'stripes',\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @param value - The arbitrary object to extract the signature from.\n * @returns The extracted {@link ox#Signature.Signature}.\n */\nexport function extract(value: extract.Value): Signature | undefined {\n if (typeof value.r === 'undefined') return undefined\n if (typeof value.s === 'undefined') return undefined\n return from(value as any)\n}\n\nexport declare namespace extract {\n type Value = {\n r?: bigint | Hex.Hex | undefined\n s?: bigint | Hex.Hex | undefined\n yParity?: number | Hex.Hex | undefined\n v?: number | Hex.Hex | undefined\n }\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#Signature.Signature} object from a {@link ox#Signature.Signature}, {@link ox#Signature.Legacy}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db801')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @example\n * ### From Legacy\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * v: 27,\n * })\n * // @log: {\n * // @log: r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * // @log: s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * // @log: yParity: 0\n * // @log: }\n * ```\n *\n * @param signature - The signature value to instantiate.\n * @returns The instantiated {@link ox#Signature.Signature}.\n */\nexport function from<\n const signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n>(\n signature:\n | signature\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n): from.ReturnType {\n const signature_ = (() => {\n if (typeof signature === 'string') return fromHex(signature)\n if (signature instanceof Uint8Array) return fromBytes(signature)\n if (typeof signature.r === 'string') return fromRpc(signature)\n if (signature.v) return fromLegacy(signature)\n return {\n r: signature.r,\n s: signature.s,\n ...(typeof signature.yParity !== 'undefined'\n ? { yParity: signature.yParity }\n : {}),\n }\n })()\n assert(signature_)\n return signature_ as never\n}\n\nexport declare namespace from {\n type ReturnType<\n signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n > = signature extends Signature & { v?: undefined }\n ? signature\n : Signature\n\n type ErrorType =\n | assert.ErrorType\n | fromBytes.ErrorType\n | fromHex.ErrorType\n | vToYParity.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerBytes(new Uint8Array([132, 51, 23, ...]))\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerBytes(signature: Bytes.Bytes): Signature {\n return fromDerHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerHex('0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerHex(signature: Hex.Hex): Signature {\n const { r, s } = secp256k1.Signature.fromDER(Hex.from(signature).slice(2))\n return { r, s }\n}\n\nexport declare namespace fromDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Legacy} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.fromLegacy({ r: 1n, s: 2n, v: 28 })\n * // @log: { r: 1n, s: 2n, yParity: 1 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Legacy} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromLegacy(signature: Legacy): Signature {\n return {\n r: signature.r,\n s: signature.s,\n yParity: vToYParity(signature.v),\n }\n}\n\nexport declare namespace fromLegacy {\n type ErrorType = vToYParity.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Rpc} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromRpc({\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Rpc} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromRpc(signature: {\n r: Hex.Hex\n s: Hex.Hex\n yParity?: Hex.Hex | undefined\n v?: Hex.Hex | undefined\n}): Signature {\n const yParity = (() => {\n const v = signature.v ? Number(signature.v) : undefined\n let yParity = signature.yParity ? Number(signature.yParity) : undefined\n if (typeof v === 'number' && typeof yParity !== 'number')\n yParity = vToYParity(v)\n if (typeof yParity !== 'number')\n throw new InvalidYParityError({ value: signature.yParity })\n return yParity\n })()\n\n return {\n r: BigInt(signature.r),\n s: BigInt(signature.s),\n yParity,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Tuple} to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromTuple(['0x01', '0x7b', '0x1c8'])\n * // @log: {\n * // @log: r: 123n,\n * // @log: s: 456n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @param tuple - The {@link ox#Signature.Tuple} to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromTuple(tuple: Tuple): Signature {\n const [yParity, r, s] = tuple\n return from({\n r: r === '0x' ? 0n : BigInt(r),\n s: s === '0x' ? 0n : BigInt(s),\n yParity: yParity === '0x' ? 0 : Number(yParity),\n })\n}\n\nexport declare namespace fromTuple {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toBytes({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: Uint8Array [102, 16, 10, ...]\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toBytes(signature: Signature): Bytes.Bytes {\n return Bytes.fromHex(toHex(signature))\n}\n\nexport declare namespace toBytes {\n type ErrorType =\n | toHex.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toHex({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c'\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toHex(signature: Signature): Hex.Hex {\n assert(signature)\n\n const r = signature.r\n const s = signature.s\n\n const signature_ = Hex.concat(\n Hex.fromNumber(r, { size: 32 }),\n Hex.fromNumber(s, { size: 32 }),\n // If the signature is recovered, add the recovery byte to the signature.\n typeof signature.yParity === 'number'\n ? Hex.fromNumber(yParityToV(signature.yParity), { size: 1 })\n : '0x',\n )\n\n return signature_\n}\n\nexport declare namespace toHex {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerBytes(signature)\n * // @log: Uint8Array [132, 51, 23, ...]\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerBytes(signature: Signature): Bytes.Bytes {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return sig.toDERRawBytes()\n}\n\nexport declare namespace toDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerHex(signature)\n * // @log: '0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8'\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerHex(signature: Signature): Hex.Hex {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return `0x${sig.toDERHex()}`\n}\n\nexport declare namespace toDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Legacy}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.toLegacy({ r: 1n, s: 2n, yParity: 1 })\n * // @log: { r: 1n, s: 2n, v: 28 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Legacy}.\n */\nexport function toLegacy(signature: Signature): Legacy {\n return {\n r: signature.r,\n s: signature.s,\n v: yParityToV(signature.yParity),\n }\n}\n\nexport declare namespace toLegacy {\n type ErrorType = yParityToV.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toRpc({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Rpc}.\n */\nexport function toRpc(signature: Signature): Rpc {\n const { r, s, yParity } = signature\n return {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity: yParity === 0 ? '0x0' : '0x1',\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to a serialized {@link ox#Signature.Tuple} to be used for signatures in Transaction Envelopes, EIP-7702 Authorization Lists, etc.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signatureTuple = Signature.toTuple({\n * r: 123n,\n * s: 456n,\n * yParity: 1,\n * })\n * // @log: [yParity: '0x01', r: '0x7b', s: '0x1c8']\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The {@link ox#Signature.Tuple}.\n */\nexport function toTuple(signature: Signature): Tuple {\n const { r, s, yParity } = signature\n\n return [\n yParity ? '0x01' : '0x',\n r === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(r!)),\n s === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(s!)),\n ] as const\n}\n\nexport declare namespace toTuple {\n type ErrorType =\n | Hex.trimLeft.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a Signature. Returns `true` if the signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const valid = Signature.validate({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: false\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function validate(\n signature: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(signature, options)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const yParity = Signature.vToYParity(28)\n * // @log: 1\n * ```\n *\n * @param v - The ECDSA `v` value to convert.\n * @returns The `yParity` value.\n */\nexport function vToYParity(v: number): Signature['yParity'] {\n if (v === 0 || v === 27) return 0\n if (v === 1 || v === 28) return 1\n if (v >= 35) return v % 2 === 0 ? 1 : 0\n throw new InvalidVError({ value: v })\n}\n\nexport declare namespace vToYParity {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const v = Signature.yParityToV(1)\n * // @log: 28\n * ```\n *\n * @param yParity - The ECDSA `yParity` value to convert.\n * @returns The `v` value.\n */\nexport function yParityToV(yParity: number): number {\n if (yParity === 0) return 27\n if (yParity === 1) return 28\n throw new InvalidYParityError({ value: yParity })\n}\n\nexport declare namespace yParityToV {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/** Thrown when the serialized signature is of an invalid size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSerializedSizeError'\n\n constructor({ signature }: { signature: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${signature}\\` is an invalid signature size.`, {\n metaMessages: [\n 'Expected: 64 bytes or 65 bytes.',\n `Received ${Hex.size(Hex.from(signature))} bytes.`,\n ],\n })\n }\n}\n\n/** Thrown when the signature is missing either an `r`, `s`, or `yParity` property. */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'Signature.MissingPropertiesError'\n\n constructor({ signature }: { signature: unknown }) {\n super(\n `Signature \\`${Json.stringify(signature)}\\` is missing either an \\`r\\`, \\`s\\`, or \\`yParity\\` property.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `r` value. */\nexport class InvalidRError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidRError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid r value. r must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `s` value. */\nexport class InvalidSError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid s value. s must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `yParity` value. */\nexport class InvalidYParityError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidYParityError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid y-parity value. Y-parity must be 0 or 1.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `v` value. */\nexport class InvalidVError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidVError'\n\n constructor({ value }: { value: number }) {\n super(`Value \\`${value}\\` is an invalid v value. v must be 27, 28 or >=35.`)\n }\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Entropy from './internal/entropy.js'\nimport type { OneOf } from './internal/types.js'\nimport * as PublicKey from './PublicKey.js'\nimport type * as Signature from './Signature.js'\n\n/** Re-export of noble/curves secp256k1 utilities. */\nexport const noble = secp256k1\n\n/**\n * Creates a new secp256k1 ECDSA key pair consisting of a private key and its corresponding public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey, publicKey } = Secp256k1.createKeyPair()\n * ```\n *\n * @param options - The options to generate the key pair.\n * @returns The generated key pair containing both private and public keys.\n */\nexport function createKeyPair(\n options: createKeyPair.Options = {},\n): createKeyPair.ReturnType {\n const { as = 'Hex' } = options\n const privateKey = randomPrivateKey({ as })\n const publicKey = getPublicKey({ privateKey })\n\n return {\n privateKey: privateKey as never,\n publicKey,\n }\n}\n\nexport declare namespace createKeyPair {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType = {\n privateKey:\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n publicKey: PublicKey.PublicKey\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the secp256k1 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const publicKey = Secp256k1.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(\n options: getPublicKey.Options,\n): PublicKey.PublicKey {\n const { privateKey } = options\n const point = secp256k1.ProjectivePoint.fromPrivateKey(\n Hex.from(privateKey).slice(2),\n )\n return PublicKey.from(point)\n}\n\nexport declare namespace getPublicKey {\n type Options = {\n /**\n * Private key to compute the public key from.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes a shared secret using ECDH (Elliptic Curve Diffie-Hellman) between a private key and a public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey: privateKeyA } = Secp256k1.createKeyPair()\n * const { publicKey: publicKeyB } = Secp256k1.createKeyPair()\n *\n * const sharedSecret = Secp256k1.getSharedSecret({\n * privateKey: privateKeyA,\n * publicKey: publicKeyB\n * })\n * ```\n *\n * @param options - The options to compute the shared secret.\n * @returns The computed shared secret.\n */\nexport function getSharedSecret(\n options: getSharedSecret.Options,\n): getSharedSecret.ReturnType {\n const { as = 'Hex', privateKey, publicKey } = options\n const point = secp256k1.ProjectivePoint.fromHex(\n PublicKey.toHex(publicKey).slice(2),\n )\n const sharedPoint = point.multiply(\n secp256k1.utils.normPrivateKeyToScalar(Hex.from(privateKey).slice(2)),\n )\n const sharedSecret = sharedPoint.toRawBytes(true) // compressed format\n if (as === 'Hex') return Hex.fromBytes(sharedSecret) as never\n return sharedSecret as never\n}\n\nexport declare namespace getSharedSecret {\n type Options = {\n /**\n * Format of the returned shared secret.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n /**\n * Private key to use for the shared secret computation.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n /**\n * Public key to use for the shared secret computation.\n */\n publicKey: PublicKey.PublicKey\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.toHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random ECDSA private key on the secp256k1 curve.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey(\n options: randomPrivateKey.Options = {},\n): randomPrivateKey.ReturnType {\n const { as = 'Hex' } = options\n const bytes = secp256k1.utils.randomPrivateKey()\n if (as === 'Hex') return Hex.fromBytes(bytes) as never\n return bytes as never\n}\n\nexport declare namespace randomPrivateKey {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing address from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const address = Secp256k1.recoverAddress({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered address.\n */\nexport function recoverAddress(\n options: recoverAddress.Options,\n): recoverAddress.ReturnType {\n return Address.fromPublicKey(recoverPublicKey(options))\n}\n\nexport declare namespace recoverAddress {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = Secp256k1.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(\n options: recoverPublicKey.Options,\n): PublicKey.PublicKey {\n const { payload, signature } = options\n const { r, s, yParity } = signature\n const signature_ = new secp256k1.Signature(\n BigInt(r),\n BigInt(s),\n ).addRecoveryBit(yParity)\n const point = signature_.recoverPublicKey(Hex.from(payload).substring(2))\n return PublicKey.from(point)\n}\n\nexport declare namespace recoverPublicKey {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ErrorType =\n | PublicKey.from.ErrorType\n | Hex.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs the payload with the provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options: sign.Options): Signature.Signature {\n const {\n extraEntropy = Entropy.extraEntropy,\n hash,\n payload,\n privateKey,\n } = options\n const { r, s, recovery } = secp256k1.sign(\n Bytes.from(payload),\n Bytes.from(privateKey),\n {\n extraEntropy:\n typeof extraEntropy === 'boolean'\n ? extraEntropy\n : Hex.from(extraEntropy).slice(2),\n lowS: true,\n ...(hash ? { prehash: true } : {}),\n },\n )\n return {\n r,\n s,\n yParity: recovery,\n }\n}\n\nexport declare namespace sign {\n type Options = {\n /**\n * Extra entropy to add to the signing process. Setting to `false` will disable it.\n * @default true\n */\n extraEntropy?: boolean | Hex.Hex | Bytes.Bytes | undefined\n /**\n * If set to `true`, the payload will be hashed (sha256) before being signed.\n */\n hash?: boolean | undefined\n /**\n * Payload to sign.\n */\n payload: Hex.Hex | Bytes.Bytes\n /**\n * ECDSA private key.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Bytes.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Verifies a payload was signed by the provided address.\n *\n * @example\n * ### Verify with Ethereum Address\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Verify with Public Key\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = '0x...'\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided address.\n */\nexport function verify(options: verify.Options): boolean {\n const { address, hash, payload, publicKey, signature } = options\n if (address)\n return Address.isEqual(address, recoverAddress({ payload, signature }))\n return secp256k1.verify(\n signature,\n Bytes.from(payload),\n PublicKey.toBytes(publicKey),\n ...(hash ? [{ prehash: true, lowS: true }] : []),\n )\n}\n\nexport declare namespace verify {\n type Options = {\n /** If set to `true`, the payload will be hashed (sha256) before being verified. */\n hash?: boolean | undefined\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Address that signed the payload. */\n address: Address.Address\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RpcProof } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../index.js'\n\nexport type FormatProofErrorType = ErrorType\n\nfunction formatStorageProof(storageProof: RpcProof['storageProof']) {\n return storageProof.map((proof) => ({\n ...proof,\n value: BigInt(proof.value),\n }))\n}\n\nexport function formatProof(proof: ExactPartial) {\n return {\n ...proof,\n balance: proof.balance ? BigInt(proof.balance) : undefined,\n nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined,\n storageProof: proof.storageProof\n ? formatStorageProof(proof.storageProof)\n : undefined,\n } as Proof\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetStorageAtParameters = {\n address: Address\n slot: Hex\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetStorageAtReturnType = Hex | undefined\n\nexport type GetStorageAtErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param client - Client to use\n * @param parameters - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getStorageAt(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\nexport async function getStorageAt(\n client: Client,\n { address, blockNumber, blockTag = 'latest', slot }: GetStorageAtParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const data = await client.request({\n method: 'eth_getStorageAt',\n params: [address, slot, blockNumberHex || blockTag],\n })\n return data\n}\n","import type { Address } from '../../accounts/index.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { OneOf, Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters =\n OneOf<\n // eth_getTransactionByBlockHashAndIndex\n | {\n /** The block hash */\n blockHash: Hash\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block number */\n blockNumber: bigint\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block tag. */\n blockTag: blockTag | BlockTag\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByHash\n | {\n /** The hash of the transaction. */\n hash: Hash\n }\n // eth_getTransactionBySenderAndNonce\n | {\n /** The sender of the transaction. */\n sender: Address\n /** The nonce of the transaction on the sender. */\n nonce: number\n }\n >\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetTransactionErrorType =\n | TransactionNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n sender,\n nonce,\n }: GetTransactionParameters,\n): Promise> {\n const blockTag = blockTag_ || 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let transaction: RpcTransaction | null = null\n if (hash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if ((blockNumberHex || blockTag) && typeof index === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n } else if (sender && typeof nonce === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionBySenderAndNonce',\n params: [sender, numberToHex(nonce)],\n },\n { dedupe: true },\n )\n }\n\n if (!transaction)\n throw new TransactionNotFoundError({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n })\n\n const format =\n client.chain?.formatters?.transaction?.format || formatTransaction\n return format(transaction, 'getTransaction')\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { FormattedTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetBlockNumberErrorType,\n getBlockNumber,\n} from './getBlockNumber.js'\nimport {\n type GetTransactionErrorType,\n getTransaction,\n} from './getTransaction.js'\n\nexport type GetTransactionConfirmationsParameters<\n chain extends Chain | undefined = Chain,\n> =\n | {\n /** The transaction hash. */\n hash: Hash\n transactionReceipt?: undefined\n }\n | {\n hash?: undefined\n /** The transaction receipt. */\n transactionReceipt: FormattedTransactionReceipt\n }\n\nexport type GetTransactionConfirmationsReturnType = bigint\n\nexport type GetTransactionConfirmationsErrorType =\n | GetBlockNumberErrorType\n | GetTransactionErrorType\n | ErrorType\n\n/**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionConfirmations } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await getTransactionConfirmations(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionConfirmations<\n chain extends Chain | undefined,\n>(\n client: Client,\n { hash, transactionReceipt }: GetTransactionConfirmationsParameters,\n): Promise {\n const [blockNumber, transaction] = await Promise.all([\n getAction(client, getBlockNumber, 'getBlockNumber')({}),\n hash\n ? getAction(client, getTransaction, 'getTransaction')({ hash })\n : undefined,\n ])\n const transactionBlockNumber =\n transactionReceipt?.blockNumber || transaction?.blockNumber\n if (!transactionBlockNumber) return 0n\n return blockNumber - transactionBlockNumber! + 1n\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n /** The hash of the transaction. */\n hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt(\n client: Client,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(\n receipt,\n 'getTransactionReceipt',\n ) as GetTransactionReceiptReturnType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { multicall3Bytecode } from '../../constants/contracts.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record\n } = {},\n> = Pick<\n CallParameters,\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'stateOverride'\n> & {\n /** The account to use for the multicall. */\n account?: Address | undefined\n /** Whether to allow failures. */\n allowFailure?: allowFailure | boolean | undefined\n /** The size of each batch of calls. */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The contracts to call. */\n contracts: MulticallContracts<\n Narrow,\n { mutability: AbiStateMutability } & options\n >\n /** The address of the multicall3 contract to use. */\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client,\n parameters: MulticallParameters,\n): Promise> {\n const {\n account,\n authorizationList,\n allowFailure = true,\n blockNumber,\n blockOverrides,\n blockTag,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const {\n batchSize = parameters.batchSize ?? 1024,\n deployless = parameters.deployless ?? false,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n\n const multicallAddress = (() => {\n if (parameters.multicallAddress) return parameters.multicallAddress\n if (deployless) return null\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n })()\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n sender: account,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress === null\n ? { code: multicall3Bytecode }\n : { address: multicallAddress }),\n abi: multicall3Abi,\n account,\n args: [calls],\n authorizationList,\n blockNumber,\n blockOverrides,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType\n}\n","import type { Abi, AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\n\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 { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.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 EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { concat } from '../../utils/data/concat.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getContractError } from '../../utils/errors/getContractError.js'\nimport {\n type GetNodeErrorReturnType,\n getNodeError,\n} from '../../utils/errors/getNodeError.js'\nimport {\n type FormatBlockErrorType,\n formatBlock,\n} from '../../utils/formatters/block.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport {\n type FormatTransactionRequestErrorType,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\n\ntype CallExtraProperties = ExactPartial<\n UnionOmit<\n TransactionRequest,\n 'blobs' | 'data' | 'kzg' | 'to' | 'sidecars' | 'value'\n >\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Recipient. `null` if contract deployment. */\n to?: Address | null | undefined\n}\n\nexport type SimulateBlocksParameters<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Blocks to simulate. */\n blocks: readonly {\n /** Block overrides. */\n blockOverrides?: BlockOverrides.BlockOverrides | undefined\n /** Calls to execute. */\n calls: Calls, CallExtraProperties>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n }[]\n /** Whether to return the full transactions. */\n returnFullTransactions?: boolean | undefined\n /** Whether to trace transfers. */\n traceTransfers?: boolean | undefined\n /** Whether to enable validation mode. */\n validation?: boolean | 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)\n\nexport type SimulateBlocksReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = readonly (Block & {\n calls: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n})[]\n\nexport type SimulateBlocksErrorType =\n | AssertRequestErrorType\n | DecodeFunctionResultErrorType\n | EncodeFunctionDataErrorType\n | FormatBlockErrorType\n | FormatTransactionRequestErrorType\n | GetNodeErrorReturnType\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createClient, http, parseEther } from 'viem'\n * import { simulate } from 'viem/actions'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulate(client, {\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateBlocksParameters}\n * @returns Simulated blocks. {@link SimulateBlocksReturnType}\n */\nexport async function simulateBlocks<\n chain extends Chain | undefined,\n const calls extends readonly unknown[],\n>(\n client: Client,\n parameters: SimulateBlocksParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n blocks,\n returnFullTransactions,\n traceTransfers,\n validation,\n } = parameters\n\n try {\n const blockStateCalls = []\n for (const block of blocks) {\n const blockOverrides = block.blockOverrides\n ? BlockOverrides.toRpc(block.blockOverrides)\n : undefined\n const calls = block.calls.map((call_) => {\n const call = call_ as Call\n const account = call.account ? parseAccount(call.account) : undefined\n const data = call.abi ? encodeFunctionData(call) : call.data\n const request = {\n ...call,\n account,\n data: call.dataSuffix\n ? concat([data || '0x', call.dataSuffix])\n : data,\n from: call.from ?? account?.address,\n } as const\n assertRequest(request)\n return formatTransactionRequest(request)\n })\n const stateOverrides = block.stateOverrides\n ? serializeStateOverride(block.stateOverrides)\n : undefined\n\n blockStateCalls.push({\n blockOverrides,\n calls,\n stateOverrides,\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const result = await client.request({\n method: 'eth_simulateV1',\n params: [\n { blockStateCalls, returnFullTransactions, traceTransfers, validation },\n block,\n ],\n })\n\n return result.map((block, i) => ({\n ...formatBlock(block),\n calls: block.calls.map((call, j) => {\n const { abi, args, functionName, to } = blocks[i].calls[j] as Call<\n unknown,\n CallExtraProperties\n >\n\n const data = call.error?.data ?? call.returnData\n const gasUsed = BigInt(call.gasUsed)\n const logs = call.logs?.map((log) => formatLog(log))\n const status = call.status === '0x1' ? 'success' : 'failure'\n\n const result =\n abi && status === 'success' && data !== '0x'\n ? decodeFunctionResult({\n abi,\n data,\n functionName,\n })\n : null\n\n const error = (() => {\n if (status === 'success') return undefined\n\n let error: Error | undefined\n if (data === '0x') error = new AbiDecodingZeroDataError()\n else if (data) error = new RawContractError({ data })\n\n if (!error) return undefined\n return getContractError(error, {\n abi: (abi ?? []) as Abi,\n address: to ?? '0x',\n args,\n functionName: functionName ?? '',\n })\n })()\n\n return {\n data,\n gasUsed,\n logs,\n status,\n ...(status === 'success'\n ? {\n result,\n }\n : {\n error,\n }),\n }\n }),\n })) as unknown as SimulateBlocksReturnType\n } catch (e) {\n const cause = e as BaseError\n const error = getNodeError(cause, {})\n if (error instanceof UnknownNodeError) throw cause\n throw error\n }\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiItem.js'\nimport type { UnionCompute } from './internal/types.js'\n\n/** Root type for an item on an {@link ox#Abi.Abi}. */\nexport type AbiItem = Abi.Abi[number]\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type Foo = AbiItem.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = Extract\n\n/**\n * Extracts the names of all {@link ox#AbiItem.AbiItem} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type names = AbiItem.Name\n * // ^?\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames = Extract<\n abi[number],\n { name: string }\n>['name']\n\n/**\n * Formats an {@link ox#AbiItem.AbiItem} into a **Human Readable ABI Item**.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const formatted = AbiItem.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiItem - The ABI Item to format.\n * @returns The formatted ABI Item .\n */\nexport function format(\n abiItem: abiItem | AbiItem,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiItem) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Item** or **Human Readable ABI Item** into a typed {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from({\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: [{ type: 'bool' }],\n * })\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiItem - The ABI Item to parse.\n * @returns The typed ABI Item.\n */\nexport function from<\n const abiItem extends AbiItem | string | readonly string[],\n>(\n abiItem: (abiItem | AbiItem | string | readonly string[]) &\n (\n | (abiItem extends string ? internal.Signature : never)\n | (abiItem extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiItem\n ),\n options: from.Options = {},\n): from.ReturnType {\n const { prepare = true } = options\n const item = (() => {\n if (Array.isArray(abiItem)) return abitype.parseAbiItem(abiItem)\n if (typeof abiItem === 'string')\n return abitype.parseAbiItem(abiItem as never)\n return abiItem\n })() as AbiItem\n return {\n ...item,\n ...(prepare ? { hash: getSignatureHash(item) } : {}),\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType =\n abiItem extends string\n ? abitype.ParseAbiItem\n : abiItem extends readonly string[]\n ? abitype.ParseAbiItem\n : abiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ABI Items can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiItem.fromAbi(abi, 'Transfer') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Items can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiItem.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Item from an `eth_call` RPC response,\n * a Transaction `input`, or from Event Log `topics`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends internal.ExtractArgs | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: fromAbi.Options,\n): fromAbi.ReturnType {\n const { args = [], prepare = true } = (options ??\n {}) as unknown as fromAbi.Options\n\n const isSelector = Hex.validate(name, { strict: false })\n const abiItems = (abi as Abi.Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function' || abiItem.type === 'error')\n return getSelector(abiItem) === Hex.slice(name, 0, 4)\n if (abiItem.type === 'event') return getSignatureHash(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0) throw new NotFoundError({ name: name as string })\n if (abiItems.length === 1)\n return {\n ...abiItems[0],\n ...(prepare ? { hash: getSignatureHash(abiItems[0]!) } : {}),\n } as never\n\n let matchedAbiItem: AbiItem | 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 {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\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 internal.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 = internal.getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AmbiguityError(\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 const abiItem = (() => {\n if (matchedAbiItem) return matchedAbiItem\n const [abiItem, ...overloads] = abiItems\n return { ...abiItem!, overloads }\n })()\n\n if (!abiItem) throw new NotFoundError({ name: name as string })\n return {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\n}\n\nexport declare namespace fromAbi {\n type Options<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n ///\n allArgs = internal.ExtractArgs,\n > = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n } & UnionCompute<\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.Abi\n ? args extends allArgs\n ? internal.Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (internal.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\n type ReturnType<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n fallback = AbiItem,\n > = abi extends Abi.Abi\n ? Abi.Abi extends abi\n ? fallback\n : internal.ExtractForArgs<\n abi,\n name,\n args extends internal.ExtractArgs\n ? args\n : internal.ExtractArgs\n >\n : fallback\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const selector = AbiItem.getSelector(erc20Abi, 'ownerOf')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for. Can be a signature or an ABI item for an error, event, function, etc.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSelector(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSelector(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n return Hex.slice(getSignatureHash(abiItem), 0, 4)\n}\n\nexport declare namespace getSelector {\n type ErrorType =\n | getSignatureHash.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the stringified signature for a given {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature('function ownerOf(uint256 tokenId)')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const signature = AbiItem.getSignature(erc20Abi, 'ownerOf')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature for.\n * @returns The stringified signature of the ABI Item.\n */\nexport function getSignature<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): string\nexport function getSignature(abiItem: string | AbiItem): string\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignature(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): string {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n const signature = (() => {\n if (typeof abiItem === 'string') return abiItem\n return abitype.formatAbiItem(abiItem)\n })()\n return internal.normalizeSignature(signature)\n}\n\nexport declare namespace getSignature {\n type ErrorType =\n | internal.normalizeSignature.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the signature hash for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing Event Topic values.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash('event Transfer(address indexed from, address indexed to, uint256 amount)')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const hash = AbiItem.getSignatureHash(erc20Abi, 'Transfer')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash({\n * name: 'Transfer',\n * type: 'event',\n * inputs: [\n * { name: 'from', type: 'address', indexed: true },\n * { name: 'to', type: 'address', indexed: true },\n * { name: 'amount', type: 'uint256', indexed: false },\n * ],\n * })\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature hash for.\n * @returns The {@link ox#Hash.(keccak256:function)} hash of the ABI item's signature.\n */\nexport function getSignatureHash<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSignatureHash(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignatureHash(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n if (typeof abiItem !== 'string' && 'hash' in abiItem && abiItem.hash)\n return abiItem.hash as Hex.Hex\n return Hash.keccak256(Hex.fromString(getSignature(abiItem)))\n}\n\nexport declare namespace getSignatureHash {\n type ErrorType =\n | getSignature.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Throws when ambiguous types are found on overloaded ABI items.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from(['function foo(address)', 'function foo(bytes20)'])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n *\n * ### Solution\n *\n * Remove one of the ambiguous types from the ABI.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function foo(bytes20)' // [!code --]\n * ])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n */\nexport class AmbiguityError extends Errors.BaseError {\n override readonly name = 'AbiItem.AmbiguityError'\n constructor(\n x: { abiItem: Abi.Abi[number]; type: string },\n y: { abiItem: Abi.Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI Items.', {\n metaMessages: [\n // TODO: abitype to add support for signature-formatted ABI items.\n `\\`${x.type}\\` in \\`${internal.normalizeSignature(abitype.formatAbiItem(x.abiItem))}\\`, and`,\n `\\`${y.type}\\` in \\`${internal.normalizeSignature(abitype.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 })\n }\n}\n\n/**\n * Throws when an ABI item is not found in the ABI.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * // @error: AbiItem.NotFoundError: ABI function with name \"baz\" not found.\n * ```\n *\n * ### Solution\n *\n * Ensure the ABI item exists on the ABI.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)',\n * 'function baz(bool)' // [!code ++]\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * ```\n */\nexport class NotFoundError extends Errors.BaseError {\n override readonly name = 'AbiItem.NotFoundError'\n constructor({\n name,\n data,\n type = 'item',\n }: {\n name?: string | undefined\n data?: Hex.Hex | undefined\n type?: string | undefined\n }) {\n const selector = (() => {\n if (name) return ` with name \"${name}\"`\n if (data) return ` with data \"${data}\"`\n return ''\n })()\n super(`ABI ${type}${selector} not found.`)\n }\n}\n\n/**\n * Throws when the selector size is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0xaaa')\n * // @error: AbiItem.InvalidSelectorSizeError: Selector size is invalid. Expected 4 bytes. Received 2 bytes (\"0xaaa\").\n * ```\n *\n * ### Solution\n *\n * Ensure the selector size is 4 bytes.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0x7af82b1a')\n * ```\n */\nexport class InvalidSelectorSizeError extends Errors.BaseError {\n override readonly name = 'AbiItem.InvalidSelectorSizeError'\n constructor({ data }: { data: Hex.Hex }) {\n super(\n `Selector size is invalid. Expected 4 bytes. Received ${Hex.size(data)} bytes (\"${data}\").`,\n )\n }\n}\n","import type * as abitype from 'abitype'\nimport type * as Abi from '../Abi.js'\nimport type * as AbiItem from '../AbiItem.js'\nimport type * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Errors from '../Errors.js'\nimport type {\n Compute,\n IsNever,\n IsUnion,\n TypeErrorMessage,\n UnionToTuple,\n} from './types.js'\n\n/** @internal */\nexport type ExtractArgs<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends AbiItem.Name = AbiItem.Name,\n> = abitype.AbiParametersToPrimitiveTypes<\n AbiItem.FromAbi['inputs'],\n 'inputs'\n> extends infer args\n ? [args] extends [never]\n ? readonly unknown[]\n : args\n : readonly unknown[]\n\n/** @internal */\nexport type ExtractForArgs<\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = IsUnion extends true\n ? {\n [key in keyof abi]: abi[key] extends { name: name } ? abi[key] : never\n }[number]\n : AbiItem.FromAbi extends infer abiItem extends AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n }\n ? IsUnion extends true // narrow overloads using `args` by converting to tuple and filtering out overloads that don't match\n ? UnionToTuple extends infer abiItems extends\n readonly (AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n })[]\n ? IsNever> extends true\n ? Compute<\n abiItems[0] & {\n readonly overloads: UnionToTuple<\n Exclude\n >\n }\n >\n : TupleToUnion // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)\n : never\n : abiItem\n : never\n\n/** @internal */\nexport type TupleToUnion<\n abiItems extends readonly {\n inputs: readonly abitype.AbiParameter[]\n }[],\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = {\n [k in keyof abiItems]: (\n readonly [] extends args\n ? readonly [] // fallback to `readonly []` if `args` has no value (e.g. `args` property not provided)\n : args\n ) extends abitype.AbiParametersToPrimitiveTypes<\n abiItems[k]['inputs'],\n 'inputs'\n >\n ? abiItems[k]\n : never\n}[number]\n\n/** @internal */\nexport type ErrorSignature<\n name extends string = string,\n parameters extends string = string,\n> = `error ${name}(${parameters})`\n\n/** @internal */\nexport type IsErrorSignature =\n signature extends ErrorSignature ? IsName : false\n\n/** @internal */\nexport type EventSignature<\n name extends string = string,\n parameters extends string = string,\n> = `event ${name}(${parameters})`\n\n/** @internal */\nexport type IsEventSignature =\n signature extends EventSignature ? IsName : false\n\n/** @internal */\nexport type FunctionSignature<\n name extends string = string,\n tail extends string = string,\n> = `function ${name}(${tail}`\nexport type IsFunctionSignature =\n signature extends FunctionSignature\n ? IsName extends true\n ? signature extends ValidFunctionSignatures\n ? true\n : // Check that `Parameters` is not absorbing other types (e.g. `returns`)\n signature extends `function ${string}(${infer parameters})`\n ? parameters extends InvalidFunctionParameters\n ? false\n : true\n : false\n : false\n : false\n/** @internal */\nexport type Scope = 'public' | 'external' // `internal` or `private` functions wouldn't make it to ABI so can ignore\n\n/** @internal */\nexport type Returns = `returns (${string})` | `returns(${string})`\n\n// Almost all valid function signatures, except `function ${string}(${infer parameters})` since `parameters` can absorb returns\n/** @internal */\nexport type ValidFunctionSignatures =\n | `function ${string}()`\n // basic\n | `function ${string}() ${Returns}`\n | `function ${string}() ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope}`\n // combinations\n | `function ${string}() ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}() ${Scope} ${Returns}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n // Parameters\n | `function ${string}(${string}) ${Returns}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n\n/** @internal */\nexport type StructSignature<\n name extends string = string,\n properties extends string = string,\n> = `struct ${name} {${properties}}`\n\n/** @internal */\nexport type IsStructSignature =\n signature extends StructSignature ? IsName : false\n\n/** @internal */\nexport type ConstructorSignature =\n `constructor(${tail}`\n\n/** @internal */\nexport type IsConstructorSignature =\n signature extends ConstructorSignature\n ? signature extends ValidConstructorSignatures\n ? true\n : false\n : false\n\n/** @internal */\nexport type ValidConstructorSignatures =\n | `constructor(${string})`\n | `constructor(${string}) payable`\n\n/** @internal */\nexport type FallbackSignature =\n `fallback() external${abiStateMutability}`\n\n/** @internal */\nexport type ReceiveSignature = 'receive() external payable'\n\n// TODO: Maybe use this for signature validation one day\n// https://twitter.com/devanshj__/status/1610423724708343808\n/** @internal */\nexport type IsSignature =\n | (IsErrorSignature extends true ? true : never)\n | (IsEventSignature extends true ? true : never)\n | (IsFunctionSignature extends true ? true : never)\n | (IsStructSignature extends true ? true : never)\n | (IsConstructorSignature extends true ? true : never)\n | (type extends FallbackSignature ? true : never)\n | (type extends ReceiveSignature ? true : never) extends infer condition\n ? [condition] extends [never]\n ? false\n : true\n : false\n\n/** @internal */\nexport type Signature<\n string1 extends string,\n string2 extends string | unknown = unknown,\n> = IsSignature extends true\n ? string1\n : string extends string1 // if exactly `string` (not narrowed), then pass through as valid\n ? string1\n : TypeErrorMessage<`Signature \"${string1}\" is invalid${string2 extends string\n ? ` at position ${string2}`\n : ''}.`>\n\n/** @internal */\nexport type Signatures = {\n [key in keyof signatures]: Signature\n}\n\n/** @internal */\nexport type IsName = name extends ''\n ? false\n : ValidateName extends name\n ? true\n : false\n\n/** @internal */\nexport type ValidateName<\n name extends string,\n checkCharacters extends boolean = false,\n> = name extends `${string}${' '}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot contain whitespace.`>\n : IsSolidityKeyword extends true\n ? TypeErrorMessage<`\"${name}\" is a protected Solidity keyword.`>\n : name extends `${number}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot be a number string.`>\n : name extends `${number}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot start with a number.`>\n : checkCharacters extends true\n ? IsValidCharacter extends true\n ? name\n : TypeErrorMessage<`\"${name}\" contains invalid character.`>\n : name\n\n/** @internal */\nexport type IsSolidityKeyword =\n type extends SolidityKeywords ? true : false\n\n/** @internal */\nexport type SolidityKeywords =\n | 'after'\n | 'alias'\n | 'anonymous'\n | 'apply'\n | 'auto'\n | 'byte'\n | 'calldata'\n | 'case'\n | 'catch'\n | 'constant'\n | 'copyof'\n | 'default'\n | 'defined'\n | 'error'\n | 'event'\n | 'external'\n | 'false'\n | 'final'\n | 'function'\n | 'immutable'\n | 'implements'\n | 'in'\n | 'indexed'\n | 'inline'\n | 'internal'\n | 'let'\n | 'mapping'\n | 'match'\n | 'memory'\n | 'mutable'\n | 'null'\n | 'of'\n | 'override'\n | 'partial'\n | 'private'\n | 'promise'\n | 'public'\n | 'pure'\n | 'reference'\n | 'relocatable'\n | 'return'\n | 'returns'\n | 'sizeof'\n | 'static'\n | 'storage'\n | 'struct'\n | 'super'\n | 'supports'\n | 'switch'\n | 'this'\n | 'true'\n | 'try'\n | 'typedef'\n | 'typeof'\n | 'var'\n | 'view'\n | 'virtual'\n | `address${`[${string}]` | ''}`\n | `bool${`[${string}]` | ''}`\n | `string${`[${string}]` | ''}`\n | `tuple${`[${string}]` | ''}`\n | `bytes${number | ''}${`[${string}]` | ''}`\n | `${'u' | ''}int${number | ''}${`[${string}]` | ''}`\n\n/** @internal */\nexport type IsValidCharacter =\n character extends `${ValidCharacters}${infer tail}`\n ? tail extends ''\n ? true\n : IsValidCharacter\n : false\n\n// biome-ignore format: no formatting\n/** @internal */\nexport type ValidCharacters =\n // uppercase letters\n | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'\n // lowercase letters\n | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'\n // numbers\n | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n // special characters\n | '_' | '$'\n\n// Template string inference can absorb `returns`:\n// type Result = `function foo(string) return s (uint256)` extends `function ${string}(${infer Parameters})` ? Parameters : never\n// // ^? type Result = \"string ) return s (uint256\"\n// So we need to validate against `returns` keyword with all combinations of whitespace\n/** @internal */\nexport type InvalidFunctionParameters =\n | `${string}${MangledReturns} (${string}`\n | `${string}) ${MangledReturns}${string}`\n | `${string})${string}${MangledReturns}${string}(${string}`\n\n// r_e_t_u_r_n_s\n/** @internal */\nexport type MangledReturns =\n // Single\n | `r${string}eturns`\n | `re${string}turns`\n | `ret${string}urns`\n | `retu${string}rns`\n | `retur${string}ns`\n | `return${string}s`\n // Double\n // `r_e*`\n | `r${string}e${string}turns`\n | `r${string}et${string}urns`\n | `r${string}etu${string}rns`\n | `r${string}etur${string}ns`\n | `r${string}eturn${string}s`\n // `re_t*`\n | `re${string}t${string}urns`\n | `re${string}tu${string}rns`\n | `re${string}tur${string}ns`\n | `re${string}turn${string}s`\n // `ret_u*`\n | `ret${string}u${string}rns`\n | `ret${string}ur${string}ns`\n | `ret${string}urn${string}s`\n // `retu_r*`\n | `retu${string}r${string}ns`\n | `retu${string}rn${string}s`\n // `retur_n*`\n | `retur${string}n${string}s`\n // Triple\n // `r_e_t*`\n | `r${string}e${string}t${string}urns`\n | `r${string}e${string}tu${string}rns`\n | `r${string}e${string}tur${string}ns`\n | `r${string}e${string}turn${string}s`\n // `re_t_u*`\n | `re${string}t${string}u${string}rns`\n | `re${string}t${string}ur${string}ns`\n | `re${string}t${string}urn${string}s`\n // `ret_u_r*`\n | `ret${string}u${string}r${string}ns`\n | `ret${string}u${string}rn${string}s`\n // `retu_r_n*`\n | `retu${string}r${string}n${string}s`\n // Quadruple\n // `r_e_t_u*`\n | `r${string}e${string}t${string}u${string}rns`\n | `r${string}e${string}t${string}ur${string}ns`\n | `r${string}e${string}t${string}urn${string}s`\n // `re_t_u_r*`\n | `re${string}t${string}u${string}r${string}ns`\n | `re${string}t${string}u${string}rn${string}s`\n // `ret_u_r_n*`\n | `ret${string}u${string}r${string}n${string}s`\n // Quintuple\n // `r_e_t_u_r*`\n | `r${string}e${string}t${string}u${string}r${string}ns`\n | `r${string}e${string}t${string}u${string}rn${string}s`\n // `re_t_u_r_n*`\n | `re${string}t${string}u${string}r${string}n${string}s`\n // Sextuple\n // `r_e_t_u_r_n_s`\n | `r${string}e${string}t${string}u${string}r${string}n${string}s`\n\n/** @internal */\nexport type Widen =\n | ([unknown] extends [type] ? unknown : never)\n | (type extends Function ? type : never)\n | (type extends abitype.ResolvedRegister['bigIntType'] ? bigint : never)\n | (type extends boolean ? boolean : never)\n | (type extends abitype.ResolvedRegister['intType'] ? number : never)\n | (type extends string\n ? type extends abitype.ResolvedRegister['addressType']\n ? abitype.ResolvedRegister['addressType']\n : type extends abitype.ResolvedRegister['bytesType']['inputs']\n ? abitype.ResolvedRegister['bytesType']\n : string\n : never)\n | (type extends readonly [] ? readonly [] : never)\n | (type extends Record\n ? { [K in keyof type]: Widen }\n : never)\n | (type extends { length: number }\n ? {\n [K in keyof type]: Widen\n } extends infer Val extends readonly unknown[]\n ? readonly [...Val]\n : never\n : never)\n\n/** @internal */\nexport function normalizeSignature(signature: string): string {\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', 'error', ''].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 Errors.BaseError('Unable to normalize signature.')\n\n return result\n}\n\n/** @internal */\nexport declare namespace normalizeSignature {\n export type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function isArgOfType(\n arg: unknown,\n abiParameter: AbiParameters.Parameter,\n): boolean {\n const argType = typeof arg\n const abiParameterType = abiParameter.type\n switch (abiParameterType) {\n case 'address':\n return Address.validate(arg as Address.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 AbiParameters.Parameter,\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 AbiParameters.Parameter),\n )\n )\n }\n\n return false\n }\n }\n}\n\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameters.Parameter[],\n targetParameters: readonly AbiParameters.Parameter[],\n args: ExtractArgs,\n): AbiParameters.Parameter['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 Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n if (types.includes('address') && types.includes('bytes'))\n return Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiConstructor.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `constructor` type. */\nexport type AbiConstructor = abitype.AbiConstructor\n\n/**\n * ABI-decodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const bytecode = '0x...'\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode,\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(constructor, { // [!code focus]\n * bytecode, // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.decode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param abiConstructor - The ABI Constructor to decode.\n * @param options - Decoding options.\n * @returns The decoded constructor inputs.\n */\nexport function decode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: decode.Options,\n): decode.ReturnType\nexport function decode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: decode.Options,\n): decode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: decode.Options]\n | [abiConstructor: AbiConstructor, options: decode.Options]\n): decode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n decode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, decode.Options]\n }\n return parameters as [AbiConstructor, decode.Options]\n })()\n\n const { bytecode } = options\n if (abiConstructor.inputs?.length === 0) return undefined\n const data = options.data.replace(bytecode, '0x') as Hex.Hex\n return AbiParameters.decode(abiConstructor.inputs, data)\n}\n\nexport declare namespace decode {\n interface Options {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The encoded constructor. */\n data: Hex.Hex\n }\n\n type ReturnType =\n | (abiConstructor['inputs']['length'] extends 0\n ? undefined\n : abitype.AbiParametersToPrimitiveTypes)\n | (IsNarrowable extends true\n ? never\n : undefined)\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.encode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n], // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiConstructor.encode` to encode the constructor of a contract and deploy it.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { AbiConstructor, Hex } from 'ox'\n *\n * // 1. Instantiate the ABI Constructor.\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner, uint256 amount)',\n * )\n *\n * // 2. Encode the ABI Constructor.\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * // 3. Deploy the contract.\n * const hash = await window.ethereum!.request({\n * method: 'eth_sendTransaction',\n * params: [{ data }],\n * })\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiConstructor - The ABI Constructor to encode.\n * @param options - Encoding options.\n * @returns The encoded constructor.\n */\nexport function encode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: encode.Options,\n): encode.ReturnType\nexport function encode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: encode.Options,\n): encode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: encode.Options]\n | [abiConstructor: AbiConstructor, options: encode.Options]\n): encode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n encode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, encode.Options]\n }\n\n return parameters as [AbiConstructor, encode.Options]\n })()\n\n const { bytecode, args } = options\n return Hex.concat(\n bytecode,\n abiConstructor.inputs?.length && args?.length\n ? AbiParameters.encode(abiConstructor.inputs, args as readonly unknown[])\n : '0x',\n )\n}\n\nexport declare namespace encode {\n type Options<\n abiConstructor extends AbiConstructor = AbiConstructor,\n ///\n args extends abitype.AbiParametersToPrimitiveTypes<\n abiConstructor['inputs']\n > = abitype.AbiParametersToPrimitiveTypes,\n > = {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The constructor arguments to encode. */\n args?: args | undefined\n } & (readonly [] extends args\n ? {}\n : {\n /** The constructor arguments to encode. */\n args: args\n })\n\n type ReturnType = Hex.Hex\n\n type ErrorType =\n | Hex.concat.ErrorType\n | AbiParameters.encode.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function format(\n abiConstructor: abiConstructor,\n): format.ReturnType\n/**\n * Formats an {@link ox#AbiConstructor.AbiConstructor} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const formatted = AbiConstructor.format({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiConstructor - The ABI Constructor to format.\n * @returns The formatted ABI Constructor.\n */\nexport function format(abiConstructor: AbiConstructor): string\n/** @internal */\nexport function format(abiConstructor: AbiConstructor): format.ReturnType {\n return abitype.formatAbiItem(abiConstructor)\n}\n\nexport declare namespace format {\n type ReturnType =\n abitype.FormatAbiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function from<\n const abiConstructor extends AbiConstructor | string | readonly string[],\n>(\n abiConstructor: (abiConstructor | string | readonly string[]) &\n (\n | (abiConstructor extends string\n ? internal.Signature\n : never)\n | (abiConstructor extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiConstructor\n ),\n): from.ReturnType\n/**\n * Parses an arbitrary **JSON ABI Constructor** or **Human Readable ABI Constructor** into a typed {@link ox#AbiConstructor.AbiConstructor}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner)' // [!code hl]\n * )\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from([\n * 'struct Foo { address owner; uint256 amount; }', // [!code hl]\n * 'constructor(Foo foo)',\n * ])\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiConstructor - The ABI Constructor to parse.\n * @returns Typed ABI Constructor.\n */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): AbiConstructor\n/** @internal */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): from.ReturnType {\n return AbiItem.from(abiConstructor as AbiConstructor)\n}\n\nexport declare namespace from {\n type ReturnType<\n abiConstructor extends\n | AbiConstructor\n | string\n | readonly string[] = AbiConstructor,\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function fromAbi(\n abi: abi | Abi.Abi | readonly unknown[],\n): fromAbi.ReturnType\n/**\n * Extracts an {@link ox#AbiConstructor.AbiConstructor} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Events can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([\n * 'constructor(address owner)',\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiConstructor.fromAbi(abi) // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @returns The ABI constructor.\n */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): AbiConstructor\n/** @internal */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): fromAbi.ReturnType {\n const item = (abi as Abi.Abi).find((item) => item.type === 'constructor')\n if (!item) throw new AbiItem.NotFoundError({ name: 'constructor' })\n return item\n}\n\nexport declare namespace fromAbi {\n type ReturnType = Extract<\n abi[number],\n { type: 'constructor' }\n >\n\n type ErrorType = AbiItem.NotFoundError | Errors.GlobalErrorType\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiFunction.js'\nimport type * as AbiItem_internal from './internal/abiItem.js'\nimport type * as AbiParameters_internal from './internal/abiParameters.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `function` type. */\nexport type AbiFunction = abitype.AbiFunction & {\n hash?: Hex.Hex | undefined\n overloads?: readonly AbiFunction[] | undefined\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type Foo = AbiFunction.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = abitype.ExtractAbiFunction\n\n/**\n * Extracts the names of all {@link ox#AbiFunction.AbiFunction} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type names = AbiFunction.Name\n * // ^?\n *\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames<\n abi extends Abi.Abi,\n abiStateMutability extends\n abitype.AbiStateMutability = abitype.AbiStateMutability,\n> = abitype.ExtractAbiFunctionNames\n\n/**\n * ABI-decodes function arguments according to the ABI Item's input types (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n *\n * const input = AbiFunction.decodeData(approve, data) // [!code focus]\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n * const data = '0x...\n *\n * const input = AbiFunction.decodeData(\n * abi, // [!code focus]\n * 'approve', // [!code focus]\n * data\n * )\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @param abiFunction - The ABI Item to decode.\n * @param data - The data to decode.\n */\nexport function decodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n): decodeData.ReturnType\nexport function decodeData(\n abiFunction: abiItem | AbiFunction,\n data: Hex.Hex,\n): decodeData.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeData(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: Hex.Hex | string, data: Hex.Hex]\n | [abiFunction: AbiFunction, data: Hex.Hex]\n) {\n const [abiFunction, data] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n ]\n return [fromAbi(abi, name), data]\n }\n return parameters as [AbiFunction, Hex.Hex]\n })()\n\n const { overloads } = abiFunction\n\n if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })\n if (abiFunction.inputs?.length === 0) return undefined\n\n const item = overloads\n ? fromAbi([abiFunction, ...overloads], data as never)\n : abiFunction\n\n if (Hex.size(data) <= 4) return undefined\n return AbiParameters.decode(item.inputs, Hex.slice(data, 4))\n}\n\nexport declare namespace decodeData {\n type ReturnType = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ? abiFunction['inputs'] extends readonly []\n ? undefined\n :\n | AbiParameters_internal.ToPrimitiveTypes\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? AbiParameters_internal.ToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >\n : never)\n : unknown\n\n type ErrorType =\n | fromAbi.ErrorType\n | AbiParameters.decode.ErrorType\n | Hex.size.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * ABI-decodes a function's result according to the ABI Item's output types (`outputs`).\n *\n * :::tip\n *\n * This function is typically used to decode contract function return values (e.g. the response of an `eth_call` or the `input` property of a Transaction).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply') // [!code hl]\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const output = AbiFunction.decodeResult(\n * erc20Abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * data\n * )\n * // @log: 42n\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.decodeResult` to decode the result of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input.\n * const data = AbiFunction.encodeData(\n * balanceOf,\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B']\n * )\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output. // [!code focus]\n * const balance = AbiFunction.decodeResult(balanceOf, response) // [!code focus]\n * // @log: 42n\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to decode\n * @param data - ABI-encoded function output\n * @param options - Decoding options\n * @returns Decoded function output\n */\nexport function decodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\nexport function decodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, data, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), data, options]\n }\n return parameters as [\n AbiFunction,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n })()\n\n const values = AbiParameters.decode(abiFunction.outputs, data, options)\n if (values && Object.keys(values).length === 0) return undefined\n if (values && Object.keys(values).length === 1) {\n if (Array.isArray(values)) return values[0]\n return Object.values(values)[0]\n }\n return values\n}\n\nexport declare namespace decodeResult {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Array' | 'Object' | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = IsNarrowable extends true\n ? abiFunction['outputs'] extends readonly []\n ? undefined\n : abiFunction['outputs'] extends readonly [\n infer type extends abitype.AbiParameter,\n ]\n ? abitype.AbiParameterToPrimitiveType\n : AbiParameters.decode.ReturnType<\n abiFunction['outputs'],\n as\n > extends infer types\n ? types extends readonly []\n ? undefined\n : types extends readonly [infer type]\n ? type\n : types\n : never\n : unknown\n\n type ErrorType = AbiParameters.decode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes function arguments (`inputs`), prefixed with the 4 byte function selector.\n *\n * :::tip\n *\n * This function is typically used to encode a contract function and its arguments for contract calls (e.g. `data` parameter of an `eth_call` or `eth_sendTransaction`).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData( // [!code focus]\n * approve, // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] // [!code focus]\n * ) // [!code focus]\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const approve = AbiFunction.fromAbi(erc20Abi, 'approve') // [!code hl]\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeData(\n * erc20Abi, // [!code focus]\n * 'approve', // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.encodeData` to encode the input of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input. // [!code focus]\n * const data = AbiFunction.encodeData( // [!code focus]\n * balanceOf, // [!code focus]\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] // [!code focus]\n * ) // [!code focus]\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output.\n * const balance = AbiFunction.decodeResult(balanceOf, response)\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to encode\n * @param args - Function arguments\n * @returns ABI-encoded function name and arguments\n */\nexport function encodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n ...args: encodeData.Args\n): Hex.Hex\nexport function encodeData(\n abiFunction: abiFunction | AbiFunction,\n ...args: encodeData.Args\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeData(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n ...args: readonly unknown[],\n ]\n | [abiFunction: AbiFunction, ...args: readonly unknown[]]\n) {\n const [abiFunction, args = []] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, args] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n readonly unknown[],\n ]\n return [fromAbi(abi, name, { args }), args]\n }\n const [abiFunction, args] = parameters as [AbiFunction, readonly unknown[]]\n return [abiFunction, args]\n })()\n\n const { overloads } = abiFunction\n\n const item = overloads\n ? (fromAbi([abiFunction as AbiFunction, ...overloads], abiFunction.name, {\n args,\n }) as AbiFunction)\n : abiFunction\n\n const selector = getSelector(item)\n\n const data =\n args.length > 0 ? AbiParameters.encode(item.inputs, args) : undefined\n\n return data ? Hex.concat(selector, data) : selector\n}\n\nexport declare namespace encodeData {\n type Args = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ?\n | (abitype.AbiParametersToPrimitiveTypes<\n abiFunction['inputs']\n > extends readonly []\n ? []\n : [abitype.AbiParametersToPrimitiveTypes])\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? [\n abitype.AbiParametersToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >,\n ]\n : [])\n : readonly unknown[]\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes a function's result (`outputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n * const output = AbiFunction.decodeResult(totalSupply, '0x000000000000000000000000000000000000000000000000000000000000002a')\n * // 42n\n *\n * const data = AbiFunction.encodeResult(totalSupply, 42n) // [!code focus]\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeResult(\n * abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * 42n\n * )\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @param abiFunction - The ABI item to encode the function output for.\n * @param output - The function output to encode.\n * @param options - Encoding options.\n * @returns The encoded function output.\n */\nexport function encodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n as extends 'Object' | 'Array' = 'Array',\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\nexport function encodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, output, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, output, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n any,\n encodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), output, options]\n }\n return parameters as [\n AbiFunction,\n any,\n encodeResult.Options | undefined,\n ]\n })()\n\n const { as = 'Array' } = options\n\n const values = (() => {\n if (abiFunction.outputs.length === 1) return [output]\n if (Array.isArray(output)) return output\n if (as === 'Object') return Object.values(output as any)\n return [output]\n })()\n\n return AbiParameters.encode(abiFunction.outputs, values)\n}\n\nexport declare namespace encodeResult {\n type Output<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = abiFunction['outputs'] extends readonly []\n ? never\n : abiFunction['outputs']['length'] extends 1\n ? AbiParameters_internal.ToPrimitiveTypes[0]\n : as extends 'Object'\n ? AbiParameters_internal.ToObject\n : AbiParameters_internal.ToPrimitiveTypes\n\n type Options = {\n as?: as | 'Object' | 'Array' | undefined\n }\n\n type ErrorType = AbiParameters.encode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Formats an {@link ox#AbiFunction.AbiFunction} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const formatted = AbiFunction.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiFunction - The ABI Function to format.\n * @returns The formatted ABI Function.\n */\nexport function format(\n abiFunction: abiFunction | AbiFunction,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiFunction) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Function** or **Human Readable ABI Function** into a typed {@link ox#AbiFunction.AbiFunction}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from({\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: [{ type: 'bool' }],\n * })\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiFunction - The ABI Function to parse.\n * @returns Typed ABI Function.\n */\nexport function from<\n const abiFunction extends AbiFunction | string | readonly string[],\n>(\n abiFunction: (abiFunction | AbiFunction | string | readonly string[]) &\n (\n | (abiFunction extends string ? internal.Signature : never)\n | (abiFunction extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiFunction\n ),\n options: from.Options = {},\n): from.ReturnType {\n return AbiItem.from(abiFunction as AbiFunction, options) as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted function (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction | string | readonly string[],\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Functions can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiFunction.fromAbi(abi, 'foo') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Functions can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiFunction.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Function from an `eth_call` RPC response or\n * from a Transaction `input`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: AbiItem.fromAbi.Options<\n abi,\n name,\n args,\n AbiItem_internal.ExtractArgs\n >,\n): AbiItem.fromAbi.ReturnType {\n const item = AbiItem.fromAbi(abi, name, options as any)\n if (item.type !== 'function')\n throw new AbiItem.NotFoundError({ name, type: 'function' })\n return item as never\n}\n\nexport declare namespace fromAbi {\n type ErrorType = AbiItem.fromAbi.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiFunction.AbiFunction}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector(abiItem: string | AbiFunction): Hex.Hex {\n return AbiItem.getSelector(abiItem)\n}\n\nexport declare namespace getSelector {\n type ErrorType = AbiItem.getSelector.ErrorType | Errors.GlobalErrorType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as AbiConstructor from 'ox/AbiConstructor'\nimport * as AbiFunction from 'ox/AbiFunction'\n\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { ethAddress, zeroAddress } from '../../constants/address.js'\nimport { deploylessCallViaBytecodeBytecode } from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { Mutable } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { hexToBigInt } from '../../utils/index.js'\nimport {\n type CreateAccessListErrorType,\n createAccessList,\n} from './createAccessList.js'\nimport {\n type SimulateBlocksErrorType,\n type SimulateBlocksParameters,\n simulateBlocks,\n} from './simulateBlocks.js'\n\nconst getBalanceCode =\n '0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033'\n\nexport type SimulateCallsParameters<\n calls extends readonly unknown[] = readonly unknown[],\n account extends Account | Address | undefined = Account | Address | undefined,\n> = Omit & {\n /** Account attached to the calls (msg.sender). */\n account?: account | undefined\n /** Calls to simulate. */\n calls: Calls>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n /** Whether to trace asset changes. */\n traceAssetChanges?: boolean | undefined\n}\n\nexport type SimulateCallsReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Asset changes. */\n assetChanges: readonly {\n token: {\n address: Address\n decimals?: number | undefined\n symbol?: string | undefined\n }\n value: { pre: bigint; post: bigint; diff: bigint }\n }[]\n /** Block results. */\n block: Block\n /** Call results. */\n results: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n}\n\nexport type SimulateCallsErrorType =\n | AbiFunction.encodeData.ErrorType\n | AbiFunction.from.ErrorType\n | CreateAccessListErrorType\n | EncodeFunctionDataErrorType\n | SimulateBlocksErrorType\n | ErrorType\n\n/**\n * Simulates execution of a batch of calls.\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateCalls } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulateCalls(client, {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n */\nexport async function simulateCalls<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateCallsParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag,\n calls,\n stateOverrides,\n traceAssetChanges,\n traceTransfers,\n validation,\n } = parameters\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n\n if (traceAssetChanges && !account)\n throw new BaseError(\n '`account` is required when `traceAssetChanges` is true',\n )\n\n // Derive bytecode to extract ETH balance via a contract call.\n const getBalanceData = account\n ? AbiConstructor.encode(AbiConstructor.from('constructor(bytes, bytes)'), {\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [\n getBalanceCode,\n AbiFunction.encodeData(\n AbiFunction.from('function getBalance(address)'),\n [account.address],\n ),\n ],\n })\n : undefined\n\n // Fetch ERC20/721 addresses that were \"touched\" from the calls.\n const assetAddresses = traceAssetChanges\n ? await Promise.all(\n parameters.calls.map(async (call: any) => {\n if (!call.data && !call.abi) return\n const { accessList } = await createAccessList(client, {\n account: account!.address,\n ...call,\n data: call.abi ? encodeFunctionData(call) : call.data,\n })\n return accessList.map(({ address, storageKeys }) =>\n storageKeys.length > 0 ? address : null,\n )\n }),\n ).then((x) => x.flat().filter(Boolean))\n : []\n\n const blocks = await simulateBlocks(client, {\n blockNumber,\n blockTag: blockTag as undefined,\n blocks: [\n ...(traceAssetChanges\n ? [\n // ETH pre balances\n {\n calls: [{ data: getBalanceData }],\n stateOverrides,\n },\n\n // Asset pre balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n\n {\n calls: [...calls, {}].map((call) => ({\n ...(call as Call),\n from: account?.address,\n })) as any,\n stateOverrides,\n },\n\n ...(traceAssetChanges\n ? [\n // ETH post balances\n {\n calls: [{ data: getBalanceData }],\n },\n\n // Asset post balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Decimals\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from('function decimals() returns (uint256)'),\n ],\n functionName: 'decimals',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Token URI\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from(\n 'function tokenURI(uint256) returns (string)',\n ),\n ],\n functionName: 'tokenURI',\n args: [0n],\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Symbols\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [AbiFunction.from('function symbol() returns (string)')],\n functionName: 'symbol',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n ],\n traceTransfers,\n validation,\n })\n\n const block_results = traceAssetChanges ? blocks[2] : blocks[0]\n const [\n block_ethPre,\n block_assetsPre,\n ,\n block_ethPost,\n block_assetsPost,\n block_decimals,\n block_tokenURI,\n block_symbols,\n ] = traceAssetChanges ? blocks : []\n\n // Extract call results from the simulation.\n const { calls: block_calls, ...block } = block_results\n const results = block_calls.slice(0, -1) ?? []\n\n // Extract pre-execution ETH and asset balances.\n const ethPre = block_ethPre?.calls ?? []\n const assetsPre = block_assetsPre?.calls ?? []\n const balancesPre = [...ethPre, ...assetsPre].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract post-execution ETH and asset balances.\n const ethPost = block_ethPost?.calls ?? []\n const assetsPost = block_assetsPost?.calls ?? []\n const balancesPost = [...ethPost, ...assetsPost].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract asset symbols & decimals.\n const decimals = (block_decimals?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (number | null)[]\n const symbols = (block_symbols?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n const tokenURI = (block_tokenURI?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n\n const changes: Mutable['assetChanges']> = []\n for (const [i, balancePost] of balancesPost.entries()) {\n const balancePre = balancesPre[i]\n\n if (typeof balancePost !== 'bigint') continue\n if (typeof balancePre !== 'bigint') continue\n\n const decimals_ = decimals[i - 1]\n const symbol_ = symbols[i - 1]\n const tokenURI_ = tokenURI[i - 1]\n\n const token = (() => {\n if (i === 0)\n return {\n address: ethAddress,\n decimals: 18,\n symbol: 'ETH',\n }\n\n return {\n address: assetAddresses[i - 1]! as Address,\n decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined,\n symbol: symbol_ ?? undefined,\n }\n })()\n\n if (changes.some((change) => change.token.address === token.address))\n continue\n\n changes.push({\n token,\n value: {\n pre: balancePre,\n post: balancePost,\n diff: balancePost - balancePre,\n },\n })\n }\n\n return {\n assetChanges: changes,\n block,\n results,\n } as unknown as SimulateCallsReturnType\n}\n","export const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const\n\nexport const zeroAddress = '0x0000000000000000000000000000000000000000' as const\n","import type * as Abi from '../core/Abi.js'\nimport * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-6492 signature. */\nexport type Unwrapped = {\n /** Calldata to pass to the target address for counterfactual verification. */\n data: Hex.Hex\n /** The original signature. */\n signature: Hex.Hex\n /** The target address to use for counterfactual verification. */\n to: Address.Address\n}\n\n/** Wrapped ERC-6492 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-6492 wrapped signatures.\n */\nexport const magicBytes =\n '0x6492649264926492649264926492649264926492649264926492649264926492' as const\n\n/**\n * Deployless ERC-6492 signature verification bytecode.\n */\nexport const universalSignatureValidatorBytecode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\n/**\n * ABI for the ERC-6492 universal deployless signature validator contract.\n *\n * Constructor return value is `0x1` (valid) or `0x0` (invalid).\n */\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 satisfies Abi.Abi\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * SignatureErc6492.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-6492 wrapped signature.\n * ```\n *\n * @param wrapped - The wrapped signature to assert.\n */\nexport function assert(wrapped: Wrapped) {\n if (Hex.slice(wrapped, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(wrapped)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc6492.from('0x...') // [!code focus]\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc6492.from({ // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * to: '0x...', // [!code focus]\n * })\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', }\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function from(wrapped: Unwrapped | Wrapped): Unwrapped {\n if (typeof wrapped === 'string') return unwrap(wrapped)\n return wrapped\n}\n\nexport declare namespace from {\n type ReturnType = Unwrapped\n\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const { data, signature, to } = SignatureErc6492.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const [to, data, signature] = AbiParameters.decode(\n AbiParameters.from('address, bytes, bytes'),\n wrapped,\n )\n\n return { data, signature, to }\n}\n\nexport declare namespace unwrap {\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc6492.wrap({ // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * to: '0x00000000219ab540356cBB839Cbe05303d7705Fa', // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Wrapped signature to serialize.\n * @returns Serialized wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature, to } = value\n\n return Hex.concat(\n AbiParameters.encode(AbiParameters.from('address, bytes, bytes'), [\n to,\n data,\n signature,\n ]),\n magicBytes,\n )\n}\n\nexport declare namespace wrap {\n type ErrorType =\n | AbiParameters.encode.ErrorType\n | Hex.concat.ErrorType\n | Signature.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const valid = SignatureErc6492.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param wrapped - The wrapped signature to validate.\n * @returns `true` if the wrapped signature is valid, `false` otherwise.\n */\nexport function validate(wrapped: Wrapped): boolean {\n try {\n assert(wrapped)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-6492 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc6492.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-6492 wrapped signature.`)\n }\n}\n","import type { Address } from 'abitype'\nimport { SignatureErc6492 } from 'ox/erc6492'\nimport { SignatureErc8010 } from 'ox/erc8010'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n erc1271Abi,\n erc6492SignatureValidatorAbi,\n multicall3Abi,\n} from '../../constants/abis.js'\nimport {\n erc6492SignatureValidatorByteCode,\n multicall3Bytecode,\n} from '../../constants/contracts.js'\nimport {\n CallExecutionError,\n ContractFunctionExecutionError,\n} from '../../errors/contract.js'\nimport type { InvalidHexBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.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 {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../../utils/address/isAddressEqual.js'\nimport { verifyAuthorization } from '../../utils/authorization/verifyAuthorization.js'\nimport { type ConcatHexErrorType, concatHex } from '../../utils/data/concat.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { hexToBool } from '../../utils/encoding/fromHex.js'\nimport {\n type BytesToHexErrorType,\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../utils/signature/recoverAddress.js'\nimport {\n type SerializeSignatureErrorType,\n serializeSignature,\n} from '../../utils/signature/serializeSignature.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type VerifyHashParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n /** The address that signed the original message. */\n address: Address\n /** The chain to use. */\n chain?: Chain | null | undefined\n /** The address of the ERC-6492 signature verifier contract. */\n erc6492VerifierAddress?: Address | undefined\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n /** @deprecated use `erc6492VerifierAddress` instead. */\n universalSignatureVerifierAddress?: Address | undefined\n} & OneOf<{ factory: Address; factoryData: Hex } | {}>\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n | BytesToHexErrorType\n | CallErrorType\n | ConcatHexErrorType\n | EncodeDeployDataErrorType\n | EncodeFunctionDataErrorType\n | ErrorType\n | GetAddressErrorType\n | GetCodeErrorType\n | InvalidHexBooleanError\n | IsAddressEqualErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ReadContractErrorType\n | RecoverAddressErrorType\n | SerializeSignatureErrorType\n\n/**\n * Verifies a message hash onchain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash(\n client: Client,\n parameters: VerifyHashParameters,\n): Promise {\n const {\n address,\n chain = client.chain,\n hash,\n erc6492VerifierAddress:\n verifierAddress = parameters.universalSignatureVerifierAddress ??\n chain?.contracts?.erc6492Verifier?.address,\n multicallAddress = parameters.multicallAddress ??\n chain?.contracts?.multicall3?.address,\n } = parameters\n\n if (chain?.verifyHash) return await chain.verifyHash(client, parameters)\n\n const signature = (() => {\n const signature = parameters.signature\n if (isHex(signature)) return signature\n if (typeof signature === 'object' && 'r' in signature && 's' in signature)\n return serializeSignature(signature)\n return bytesToHex(signature)\n })()\n\n try {\n if (SignatureErc8010.validate(signature))\n return await verifyErc8010(client, {\n ...parameters,\n multicallAddress,\n signature,\n })\n return await verifyErc6492(client, {\n ...parameters,\n verifierAddress,\n signature,\n })\n } catch (error) {\n // Fallback attempt to verify the signature via ECDSA recovery.\n try {\n const verified = isAddressEqual(\n getAddress(address),\n await recoverAddress({ hash, signature }),\n )\n if (verified) return true\n } catch {}\n\n if (error instanceof VerificationError) {\n // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n // this can happen for many reasons, for example if signer can not be recovered from the signature\n // or if the signature has no valid format\n return false\n }\n\n throw error\n }\n}\n\n/** @internal */\nexport async function verifyErc8010(\n client: Client,\n parameters: verifyErc8010.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, multicallAddress } = parameters\n\n const {\n authorization: authorization_ox,\n data: initData,\n signature,\n to,\n } = SignatureErc8010.unwrap(parameters.signature)\n\n // Check if already delegated\n const code = await getCode(client, {\n address,\n blockNumber,\n blockTag,\n } as never)\n\n // If already delegated, perform standard ERC-1271 verification.\n if (code === concatHex(['0xef0100', authorization_ox.address]))\n return await verifyErc1271(client, {\n address,\n blockNumber,\n blockTag,\n hash,\n signature,\n })\n\n const authorization = {\n address: authorization_ox.address,\n chainId: Number(authorization_ox.chainId),\n nonce: Number(authorization_ox.nonce),\n r: numberToHex(authorization_ox.r, { size: 32 }),\n s: numberToHex(authorization_ox.s, { size: 32 }),\n yParity: authorization_ox.yParity,\n } as const\n\n const valid = await verifyAuthorization({\n address,\n authorization,\n })\n if (!valid) throw new VerificationError()\n\n // Deployless verification.\n const results = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress\n ? { address: multicallAddress }\n : { code: multicall3Bytecode }),\n authorizationList: [authorization],\n abi: multicall3Abi,\n blockNumber,\n blockTag: 'pending',\n functionName: 'aggregate3',\n args: [\n [\n ...(initData\n ? ([\n {\n allowFailure: true,\n target: to ?? address,\n callData: initData,\n },\n ] as const)\n : []),\n {\n allowFailure: true,\n target: address,\n callData: encodeFunctionData({\n abi: erc1271Abi,\n functionName: 'isValidSignature',\n args: [hash, signature],\n }),\n },\n ],\n ],\n })\n\n const data = results[results.length - 1]?.returnData\n\n if (data?.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc8010 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nasync function verifyErc6492(\n client: Client,\n parameters: verifyErc6492.Parameters,\n) {\n const {\n address,\n factory,\n factoryData,\n hash,\n signature,\n verifierAddress,\n ...rest\n } = parameters\n\n const wrappedSignature = await (async () => {\n // If no `factory` or `factoryData` is provided, it is assumed that the\n // address is not a Smart Account, or the Smart Account is already deployed.\n if (!factory && !factoryData) return signature\n\n // If the signature is already wrapped, return the signature.\n if (SignatureErc6492.validate(signature)) return signature\n\n // If the Smart Account is not deployed, wrap the signature with a 6492 wrapper\n // to perform counterfactual validation.\n return SignatureErc6492.wrap({\n data: factoryData!,\n signature,\n to: factory!,\n })\n })()\n\n const args = verifierAddress\n ? ({\n to: verifierAddress,\n data: encodeFunctionData({\n abi: erc6492SignatureValidatorAbi,\n functionName: 'isValidSig',\n args: [address, hash, wrappedSignature],\n }),\n ...rest,\n } as unknown as CallParameters)\n : ({\n data: encodeDeployData({\n abi: erc6492SignatureValidatorAbi,\n args: [address, hash, wrappedSignature],\n bytecode: erc6492SignatureValidatorByteCode,\n }),\n ...rest,\n } as unknown as CallParameters)\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )(args).catch((error) => {\n if (error instanceof CallExecutionError) throw new VerificationError()\n throw error\n })\n\n if (hexToBool(data ?? '0x0')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc6492 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n /** The address of the ERC-6492 signature verifier contract. */\n verifierAddress?: Address | undefined\n } & OneOf<{ factory: Address; factoryData: Hex } | {}>\n}\n\n/** @internal */\nexport async function verifyErc1271(\n client: Client,\n parameters: verifyErc1271.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, signature } = parameters\n\n const result = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address,\n abi: erc1271Abi,\n args: [hash, signature],\n blockNumber,\n blockTag,\n functionName: 'isValidSignature',\n }).catch((error) => {\n if (error instanceof ContractFunctionExecutionError)\n throw new VerificationError()\n throw error\n })\n\n if (result.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc1271 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\nclass VerificationError extends Error {}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ByteArray,\n Hex,\n SignableMessage,\n Signature,\n} from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyMessageParameters = Prettify<\n Omit & {\n /** The address that signed the original message. */\n address: Address\n /** The message to be verified. */\n message: SignableMessage\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n }\n>\n\nexport type VerifyMessageReturnType = boolean\n\nexport type VerifyMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\nexport async function verifyMessage(\n client: Client,\n {\n address,\n message,\n factory,\n factoryData,\n signature,\n ...callRequest\n }: VerifyMessageParameters,\n): Promise {\n const hash = hashMessage(message)\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address, TypedData } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = Omit &\n TypedDataDefinition & {\n /** The address to verify the typed data for. */\n address: Address\n /** The signature to verify */\n signature: Hex | ByteArray | Signature\n }\n\nexport type VerifyTypedDataReturnType = boolean\n\nexport type VerifyTypedDataErrorType =\n | HashTypedDataErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\nexport async function verifyTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: VerifyTypedDataParameters,\n): Promise {\n const {\n address,\n factory,\n factoryData,\n signature,\n message,\n primaryType,\n types,\n domain,\n ...callRequest\n } = parameters as VerifyTypedDataParameters\n const hash = hashTypedData({ message, primaryType, types, domain })\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n TransactionNotFoundError,\n TransactionReceiptNotFoundError,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n type GetTransactionErrorType,\n type GetTransactionReturnType,\n getTransaction,\n} from './getTransaction.js'\nimport {\n type GetTransactionReceiptErrorType,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n type WatchBlockNumberErrorType,\n watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * Whether to check for transaction replacements.\n * @default true\n */\n checkReplacement?: boolean | undefined\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | WaitForTransactionReceiptTimeoutErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: WaitForTransactionReceiptParameters,\n): Promise> {\n const {\n checkReplacement = true,\n confirmations = 1,\n hash,\n onReplaced,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n } = parameters\n\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n const pollingInterval = (() => {\n if (parameters.pollingInterval) return parameters.pollingInterval\n if (client.chain?.experimental_preconfirmationTime)\n return client.chain.experimental_preconfirmationTime\n return client.pollingInterval\n })()\n\n let transaction: GetTransactionReturnType | undefined\n let replacedTransaction: GetTransactionReturnType | undefined\n let receipt: GetTransactionReceiptReturnType | undefined\n let retrying = false\n\n let _unobserve: () => void\n let _unwatch: () => void\n\n const { promise, resolve, reject } =\n withResolvers>()\n\n const timer = timeout\n ? setTimeout(() => {\n _unwatch?.()\n _unobserve?.()\n reject(new WaitForTransactionReceiptTimeoutError({ hash }))\n }, timeout)\n : undefined\n\n _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n async (emit) => {\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash }).catch(() => undefined)\n\n if (receipt && confirmations <= 1) {\n clearTimeout(timer)\n emit.resolve(receipt)\n _unobserve?.()\n return\n }\n\n _unwatch = getAction(\n client,\n watchBlockNumber,\n 'watchBlockNumber',\n )({\n emitMissed: true,\n emitOnBegin: true,\n poll: true,\n pollingInterval,\n async onBlockNumber(blockNumber_) {\n const done = (fn: () => void) => {\n clearTimeout(timer)\n _unwatch?.()\n fn()\n _unobserve?.()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\n\n try {\n // If we already have a valid receipt, let's check if we have enough\n // confirmations. If we do, then we can resolve.\n if (receipt) {\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n return\n }\n\n // Get the transaction to check if it's been replaced.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined transactions.\n if (checkReplacement && !transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\n },\n )\n retrying = false\n }\n\n // Get the receipt to check if it's been processed.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n } catch (err) {\n // If the receipt is not found, the transaction will be pending.\n // We need to check if it has potentially been replaced.\n if (\n err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\n\n try {\n replacedTransaction = transaction\n\n // Let's retrieve the transactions from the current block.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined blocks.\n retrying = true\n const block = await withRetry(\n () =>\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber,\n includeTransactions: true,\n }),\n {\n delay: retryDelay,\n retryCount,\n shouldRetry: ({ error }) =>\n error instanceof BlockNotFoundError,\n },\n )\n retrying = false\n\n const replacementTransaction = (\n block.transactions as {} as Transaction[]\n ).find(\n ({ from, nonce }) =>\n from === replacedTransaction!.from &&\n nonce === replacedTransaction!.nonce,\n )\n\n // If we couldn't find a replacement transaction, continue polling.\n if (!replacementTransaction) return\n\n // If we found a replacement transaction, return it's receipt.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({\n hash: replacementTransaction.hash,\n })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n let reason: ReplacementReason = 'replaced'\n if (\n replacementTransaction.to === replacedTransaction.to &&\n replacementTransaction.value === replacedTransaction.value &&\n replacementTransaction.input === replacedTransaction.input\n ) {\n reason = 'repriced'\n } else if (\n replacementTransaction.from === replacementTransaction.to &&\n replacementTransaction.value === 0n\n ) {\n reason = 'cancelled'\n }\n\n done(() => {\n emit.onReplaced?.({\n reason,\n replacedTransaction: replacedTransaction! as any,\n transaction: replacementTransaction,\n transactionReceipt: receipt!,\n })\n emit.resolve(receipt!)\n })\n } catch (err_) {\n done(() => emit.reject(err_))\n }\n } else {\n done(() => emit.reject(err))\n }\n }\n },\n })\n },\n )\n\n return promise\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n blockNumber: OnBlockNumberParameter,\n prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type WatchBlockNumberParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when a new block number is received. */\n onBlockNumber: OnBlockNumberFn\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n const pollBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) =>\n poll(\n async () => {\n try {\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({ cacheTime: 0 })\n\n if (prevBlockNumber !== undefined) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (blockNumber === prevBlockNumber) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n emit.onBlockNumber(i, prevBlockNumber)\n prevBlockNumber = i\n }\n }\n }\n\n // If the next block number is greater than the previous,\n // it is not in the past, and we can emit the new block number.\n if (\n prevBlockNumber === undefined ||\n blockNumber > prevBlockNumber\n ) {\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockReturnType, getBlock } from './getBlock.js'\n\nexport type OnBlockParameter<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = GetBlockReturnType\n\nexport type OnBlock<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = (\n block: OnBlockParameter,\n prevBlock: OnBlockParameter | undefined,\n) => void\n\nexport type WatchBlocksParameters<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** The callback to call when a new block is received. */\n onBlock: OnBlock\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n blockTag?: undefined\n emitMissed?: undefined\n emitOnBegin?: undefined\n includeTransactions?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** The block tag. Defaults to \"latest\". */\n blockTag?: blockTag | BlockTag | undefined\n /** Whether or not to emit the missed blocks to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the block to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to the client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlocksReturnType = () => void\n\nexport type WatchBlocksErrorType =\n | StringifyErrorType\n | PollErrorType\n | ErrorType\n\n/**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, watchBlocks, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlocks(client, {\n * onBlock: (block) => console.log(block),\n * })\n */\nexport function watchBlocks<\n transport extends Transport,\n chain extends Chain | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockTag = client.experimental_blockTag ?? 'latest',\n emitMissed = false,\n emitOnBegin = false,\n onBlock,\n onError,\n includeTransactions: includeTransactions_,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlocksParameters,\n): WatchBlocksReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const includeTransactions = includeTransactions_ ?? false\n\n let prevBlock:\n | GetBlockReturnType\n | undefined\n\n const pollBlocks = () => {\n const observerId = stringify([\n 'watchBlocks',\n client.uid,\n blockTag,\n emitMissed,\n emitOnBegin,\n includeTransactions,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlock, onError }, (emit) =>\n poll(\n async () => {\n try {\n const block = await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n if (block.number !== null && prevBlock?.number != null) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (block.number === prevBlock.number) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (block.number - prevBlock.number > 1 && emitMissed) {\n for (let i = prevBlock?.number + 1n; i < block.number; i++) {\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: i,\n includeTransactions,\n })) as GetBlockReturnType\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block\n }\n }\n }\n\n if (\n // If no previous block exists, emit.\n prevBlock?.number == null ||\n // If the block tag is \"pending\" with no block number, emit.\n (blockTag === 'pending' && block?.number == null) ||\n // If the next block number is greater than the previous block number, emit.\n // We don't want to emit blocks in the past.\n (block.number !== null && block.number > prevBlock.number)\n ) {\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block as any\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlocks = () => {\n let active = true\n let emitFetched = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n if (emitOnBegin) {\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n .then((block) => {\n if (!active) return\n if (!emitFetched) return\n onBlock(block as any, undefined)\n emitFetched = false\n })\n .catch(onError)\n }\n\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n async onData(data: any) {\n if (!active) return\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: data.result?.number,\n includeTransactions,\n }).catch(() => {})) as GetBlockReturnType\n if (!active) return\n onBlock(block as any, prevBlock as any)\n emitFetched = false\n prevBlock = block\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollBlocks() : subscribeBlocks()\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport {\n type CreateEventFilterParameters,\n createEventFilter,\n} from './createEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { type GetLogsParameters, getLogs } from './getLogs.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchEventOnLogsParameter<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n eventName extends string | undefined = MaybeAbiEventName,\n> = Log[]\nexport type WatchEventOnLogsFn<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = (\n logs: WatchEventOnLogsParameter,\n) => void\n\nexport type WatchEventParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchEventOnLogsFn\n} & GetPollOptions &\n (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: abiEvents | undefined\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n )\n\nexport type WatchEventReturnType = () => void\n\nexport type WatchEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchEvent } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchEvent(client, {\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchEvent<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n _eventName extends string | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n batch = true,\n event,\n events,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n }: WatchEventParameters,\n): WatchEventReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const strict = strict_ ?? false\n\n const pollEvent = () => {\n const observerId = stringify([\n 'watchEvent',\n address,\n args,\n batch,\n client.uid,\n event,\n pollingInterval,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abiEvents, _eventName, any>\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createEventFilter as any,\n 'createEventFilter',\n )({\n address,\n args,\n event: event!,\n events,\n strict,\n fromBlock,\n } as unknown as CreateEventFilterParameters)) as unknown as Filter<\n 'event',\n abiEvents,\n _eventName\n >\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n logs = await getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n event: event!,\n events,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n } as unknown as GetLogsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeEvent = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const events_ = events ?? (event ? [event] : undefined)\n let topics: LogTopic[] = []\n if (events_) {\n const encoded = (events_ as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: events_ ?? [],\n data: log.data,\n topics: log.topics,\n strict,\n })\n const formatted = formatLog(log, { args, eventName })\n onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollEvent() : subscribeEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { createPendingTransactionFilter } from './createPendingTransactionFilter.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type OnTransactionsParameter = Hash[]\nexport type OnTransactionsFn = (transactions: OnTransactionsParameter) => void\n\nexport type WatchPendingTransactionsParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new transactions are received. */\n onTransactions: OnTransactionsFn\n} & GetPollOptions\n\nexport type WatchPendingTransactionsReturnType = () => void\n\nexport type WatchPendingTransactionsErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param client - Client to use\n * @param parameters - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchPendingTransactions } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await watchPendingTransactions(client, {\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\nexport function watchPendingTransactions<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n {\n batch = true,\n onError,\n onTransactions,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchPendingTransactionsParameters,\n) {\n const enablePolling =\n typeof poll_ !== 'undefined'\n ? poll_\n : client.transport.type !== 'webSocket' && client.transport.type !== 'ipc'\n\n const pollPendingTransactions = () => {\n const observerId = stringify([\n 'watchPendingTransactions',\n client.uid,\n batch,\n pollingInterval,\n ])\n return observe(observerId, { onTransactions, onError }, (emit) => {\n let filter: Filter<'transaction'>\n\n const unwatch = poll(\n async () => {\n try {\n if (!filter) {\n try {\n filter = await getAction(\n client,\n createPendingTransactionFilter,\n 'createPendingTransactionFilter',\n )({})\n return\n } catch (err) {\n unwatch()\n throw err\n }\n }\n\n const hashes = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n if (hashes.length === 0) return\n if (batch) emit.onTransactions(hashes)\n else for (const hash of hashes) emit.onTransactions([hash])\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribePendingTransactions = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n params: ['newPendingTransactions'],\n onData(data: any) {\n if (!active) return\n const transaction = data.result\n onTransactions([transaction])\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling\n ? pollPendingTransactions()\n : subscribePendingTransactions()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport { parseSiweMessage } from '../../utils/siwe/parseSiweMessage.js'\nimport {\n type ValidateSiweMessageParameters,\n validateSiweMessage,\n} from '../../utils/siwe/validateSiweMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from '../public/verifyHash.js'\n\nexport type VerifySiweMessageParameters = Prettify<\n Pick &\n Pick<\n ValidateSiweMessageParameters,\n 'address' | 'domain' | 'nonce' | 'scheme' | 'time'\n > & {\n /**\n * EIP-4361 formatted message.\n */\n message: string\n /**\n * Signature to check against.\n */\n signature: Hex\n }\n>\n\nexport type VerifySiweMessageReturnType = boolean\n\nexport type VerifySiweMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\nexport async function verifySiweMessage(\n client: Client,\n parameters: VerifySiweMessageParameters,\n): Promise {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n ...callRequest\n } = parameters\n\n const parsed = parseSiweMessage(message)\n if (!parsed.address) return false\n\n const isValid = validateSiweMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n })\n if (!isValid) return false\n\n const hash = hashMessage(message)\n return verifyHash(client, {\n address: parsed.address,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\nimport type { SiweMessage } from './types.js'\n\n/**\n * @description Parses EIP-4361 formatted message into message fields object.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n *\n * @returns EIP-4361 fields object\n */\nexport function parseSiweMessage(\n message: string,\n): Prettify> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: Address\n domain: string\n scheme?: string\n statement?: string\n }\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string\n expirationTime?: string\n issuedAt?: string\n nonce: string\n notBefore?: string\n requestId?: string\n uri: string\n version: '1'\n }\n const resources = message.split('Resources:')[1]?.split('\\n- ').slice(1)\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n }\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\\n)(?
0x[a-fA-F0-9]{40})\\n\\n(?:(?.*)\\n\\n)?/\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?.+))\\n(?:Version: (?.+))\\n(?:Chain ID: (?\\d+))\\n(?:Nonce: (?[a-zA-Z0-9]+))\\n(?:Issued At: (?.+))(?:\\nExpiration Time: (?.+))?(?:\\nNot Before: (?.+))?(?:\\nRequest ID: (?.+))?/\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport type { SiweMessage } from './types.js'\n\nexport type ValidateSiweMessageParameters = {\n /**\n * Ethereum address to check against.\n */\n address?: Address | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined\n /**\n * EIP-4361 message fields.\n */\n message: ExactPartial\n /**\n * Random string to check against.\n */\n nonce?: string | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined\n}\n\nexport type ValidateSiweMessageReturnType = boolean\n\n/**\n * @description Validates EIP-4361 message.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n */\nexport function validateSiweMessage(\n parameters: ValidateSiweMessageParameters,\n): ValidateSiweMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters\n\n if (domain && message.domain !== domain) return false\n if (nonce && message.nonce !== nonce) return false\n if (scheme && message.scheme !== scheme) return false\n\n if (message.expirationTime && time >= message.expirationTime) return false\n if (message.notBefore && time < message.notBefore) return false\n\n try {\n if (!message.address) return false\n if (!isAddress(message.address, { strict: false })) return false\n if (address && !isAddressEqual(message.address, address)) return false\n } catch {\n return false\n }\n\n return true\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionReceiptRevertedError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { formatTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport type { FormattedTransactionReceipt } from '../../utils/index.js'\n\nexport type SendRawTransactionSyncParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n /** Whether to throw an error if the transaction was detected as reverted. @default true */\n throwOnReceiptRevert?: boolean | undefined\n /** The timeout for the transaction. */\n timeout?: number | undefined\n}\n\nexport type SendRawTransactionSyncReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type SendRawTransactionSyncErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network synchronously,\n * and waits for the transaction to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await sendRawTransactionSync(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransactionSync(\n client: Client,\n {\n serializedTransaction,\n throwOnReceiptRevert,\n timeout,\n }: SendRawTransactionSyncParameters,\n): Promise> {\n const receipt = await client.request(\n {\n method: 'eth_sendRawTransactionSync',\n params: timeout\n ? [serializedTransaction, timeout]\n : [serializedTransaction],\n },\n { retryCount: 0 },\n )\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n\n const formatted = format(receipt) as SendRawTransactionSyncReturnType\n if (formatted.status === 'reverted' && throwOnReceiptRevert)\n throw new TransactionReceiptRevertedError({ receipt: formatted })\n return formatted\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account, ParseAccount } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { PublicRpcSchema, RpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n} from './createClient.js'\nimport { type PublicActions, publicActions } from './decorators/public.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type PublicClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Pick<\n ClientConfig,\n | 'batch'\n | 'cacheTime'\n | 'ccipRead'\n | 'chain'\n | 'experimental_blockTag'\n | 'key'\n | 'name'\n | 'pollingInterval'\n | 'rpcSchema'\n | 'transport'\n >\n>\n\nexport type PublicClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Client<\n transport,\n chain,\n accountOrAddress,\n rpcSchema extends RpcSchema\n ? [...PublicRpcSchema, ...rpcSchema]\n : PublicRpcSchema,\n PublicActions\n >\n>\n\nexport type CreatePublicClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://viem.sh/docs/clients/public\n *\n * A Public Client is an interface to \"public\" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param config - {@link PublicClientConfig}\n * @returns A Public Client. {@link PublicClient}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: PublicClientConfig,\n): PublicClient, rpcSchema> {\n const { key = 'public', name = 'Public Client' } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n type: 'publicClient',\n })\n return client.extend(publicActions) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { OneOf } from '../../types/utils.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** Methods to include or exclude from executing RPC requests. */\n methods?:\n | OneOf<\n | {\n include?: string[] | undefined\n }\n | {\n exclude?: string[] | undefined\n }\n >\n | undefined\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = ({\n chain,\n}: {\n account?: Account | undefined\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record,\n>(\n {\n key,\n methods,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig,\n value?: rpcAttributes | undefined,\n): ReturnType> {\n const uid = uid_()\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\n value,\n }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { EIP1193RequestFn, RpcSchema } from '../../types/eip1193.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n getHttpRpcClient,\n type HttpRpcClientOptions,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './createTransport.js'\n\nexport type HttpTransportConfig<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** Methods to include or exclude from executing RPC requests. */\n methods?: TransportConfig['methods'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** Whether to return JSON RPC errors as responses instead of throwing. */\n raw?: raw | boolean | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** Typed JSON-RPC schema for the transport. */\n rpcSchema?: rpcSchema | RpcSchema | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n },\n EIP1193RequestFn\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n>(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig = {},\n): HttpTransport {\n const {\n batch,\n fetchFn,\n fetchOptions,\n key = 'http',\n methods,\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n raw,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchFn,\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n methods,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n\n if (raw) return { error, result }\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type AbiParameter,\n type AbiParameterKind,\n type AbiParameterToPrimitiveType,\n type AbiStateMutability,\n type Address,\n CircularReferenceError,\n InvalidAbiItemError,\n InvalidAbiParameterError,\n InvalidAbiParametersError,\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n InvalidParenthesisError,\n InvalidSignatureError,\n InvalidStructSignatureError,\n type Narrow,\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n SolidityProtectedKeywordError,\n type TypedData,\n type TypedDataDomain,\n type TypedDataParameter,\n UnknownSignatureError,\n UnknownTypeError,\n} from 'abitype'\nexport type {\n BlockOverrides,\n Rpc as RpcBlockOverrides,\n} from 'ox/BlockOverrides'\nexport type { EntryPointVersion } from './account-abstraction/types/entryPointVersion.js'\nexport type {\n RpcEstimateUserOperationGasReturnType,\n RpcGetUserOperationByHashReturnType,\n RpcUserOperation,\n RpcUserOperationReceipt,\n RpcUserOperationRequest,\n} from './account-abstraction/types/rpc.js'\nexport type {\n EstimateUserOperationGasReturnType,\n GetUserOperationByHashReturnType,\n PackedUserOperation,\n UserOperation,\n UserOperationReceipt,\n UserOperationRequest,\n} from './account-abstraction/types/userOperation.js'\nexport type {\n Account,\n AccountSource,\n CustomSource,\n HDAccount,\n HDOptions,\n JsonRpcAccount,\n LocalAccount,\n PrivateKeyAccount,\n} from './accounts/types.js'\nexport type {\n GetEnsAddressErrorType,\n GetEnsAddressParameters,\n GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n GetEnsAvatarErrorType,\n GetEnsAvatarParameters,\n GetEnsAvatarReturnType,\n} from './actions/ens/getEnsAvatar.js'\nexport type {\n GetEnsNameErrorType,\n GetEnsNameParameters,\n GetEnsNameReturnType,\n} from './actions/ens/getEnsName.js'\nexport type {\n GetEnsResolverErrorType,\n GetEnsResolverParameters,\n GetEnsResolverReturnType,\n} from './actions/ens/getEnsResolver.js'\nexport type {\n GetEnsTextErrorType,\n GetEnsTextParameters,\n GetEnsTextReturnType,\n} from './actions/ens/getEnsText.js'\nexport {\n type GetContractErrorType,\n type GetContractParameters,\n type GetContractReturnType,\n getContract,\n} from './actions/getContract.js'\nexport type {\n CallErrorType,\n CallParameters,\n CallReturnType,\n} from './actions/public/call.js'\nexport type {\n CreateAccessListErrorType,\n CreateAccessListParameters,\n CreateAccessListReturnType,\n} from './actions/public/createAccessList.js'\nexport type {\n CreateBlockFilterErrorType,\n CreateBlockFilterReturnType,\n} from './actions/public/createBlockFilter.js'\nexport type {\n CreateContractEventFilterErrorType,\n CreateContractEventFilterParameters,\n CreateContractEventFilterReturnType,\n} from './actions/public/createContractEventFilter.js'\nexport type {\n CreateEventFilterErrorType,\n CreateEventFilterParameters,\n CreateEventFilterReturnType,\n} from './actions/public/createEventFilter.js'\nexport type {\n CreatePendingTransactionFilterErrorType,\n CreatePendingTransactionFilterReturnType,\n} from './actions/public/createPendingTransactionFilter.js'\nexport type {\n EstimateContractGasErrorType,\n EstimateContractGasParameters,\n EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n EstimateFeesPerGasErrorType,\n EstimateFeesPerGasParameters,\n EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n EstimateGasErrorType,\n EstimateGasParameters,\n EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n EstimateMaxPriorityFeePerGasErrorType,\n EstimateMaxPriorityFeePerGasParameters,\n EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n FillTransactionErrorType,\n FillTransactionParameters,\n FillTransactionReturnType,\n} from './actions/public/fillTransaction.js'\nexport type {\n GetBalanceErrorType,\n GetBalanceParameters,\n GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n GetBlobBaseFeeErrorType,\n GetBlobBaseFeeReturnType,\n} from './actions/public/getBlobBaseFee.js'\nexport type {\n GetBlockErrorType,\n GetBlockParameters,\n GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n GetBlockNumberErrorType,\n GetBlockNumberParameters,\n GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n GetBlockTransactionCountErrorType,\n GetBlockTransactionCountParameters,\n GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n GetChainIdErrorType,\n GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n /** @deprecated Use `GetCodeErrorType` instead */\n GetCodeErrorType as GetBytecodeErrorType,\n GetCodeErrorType,\n /** @deprecated Use `GetCodeParameters` instead */\n GetCodeParameters as GetBytecodeParameters,\n GetCodeParameters,\n /** @deprecated Use `GetCodeReturnType` instead */\n GetCodeReturnType as GetBytecodeReturnType,\n GetCodeReturnType,\n} from './actions/public/getCode.js'\nexport type {\n GetContractEventsErrorType,\n GetContractEventsParameters,\n GetContractEventsReturnType,\n} from './actions/public/getContractEvents.js'\nexport type {\n GetDelegationErrorType,\n GetDelegationParameters,\n GetDelegationReturnType,\n} from './actions/public/getDelegation.js'\nexport type {\n GetEip712DomainErrorType,\n GetEip712DomainParameters,\n GetEip712DomainReturnType,\n} from './actions/public/getEip712Domain.js'\nexport type {\n GetFeeHistoryErrorType,\n GetFeeHistoryParameters,\n GetFeeHistoryReturnType,\n} from './actions/public/getFeeHistory.js'\nexport type {\n GetFilterChangesErrorType,\n GetFilterChangesParameters,\n GetFilterChangesReturnType,\n} from './actions/public/getFilterChanges.js'\nexport type {\n GetFilterLogsErrorType,\n GetFilterLogsParameters,\n GetFilterLogsReturnType,\n} from './actions/public/getFilterLogs.js'\nexport type {\n GetGasPriceErrorType,\n GetGasPriceReturnType,\n} from './actions/public/getGasPrice.js'\nexport type {\n GetLogsErrorType,\n GetLogsParameters,\n GetLogsReturnType,\n} from './actions/public/getLogs.js'\nexport type {\n GetProofErrorType,\n GetProofParameters,\n GetProofReturnType,\n} from './actions/public/getProof.js'\nexport type {\n GetStorageAtErrorType,\n GetStorageAtParameters,\n GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n GetTransactionErrorType,\n GetTransactionParameters,\n GetTransactionReturnType,\n} from './actions/public/getTransaction.js'\nexport type {\n GetTransactionConfirmationsErrorType,\n GetTransactionConfirmationsParameters,\n GetTransactionConfirmationsReturnType,\n} from './actions/public/getTransactionConfirmations.js'\nexport type {\n GetTransactionCountErrorType,\n GetTransactionCountParameters,\n GetTransactionCountReturnType,\n} from './actions/public/getTransactionCount.js'\nexport type {\n GetTransactionReceiptErrorType,\n GetTransactionReceiptParameters,\n GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n MulticallErrorType,\n MulticallParameters,\n MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n ReadContractErrorType,\n ReadContractParameters,\n ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n SimulateBlocksErrorType,\n SimulateBlocksParameters,\n SimulateBlocksReturnType,\n} from './actions/public/simulateBlocks.js'\nexport type {\n SimulateCallsErrorType,\n SimulateCallsParameters,\n SimulateCallsReturnType,\n} from './actions/public/simulateCalls.js'\nexport type {\n GetMutabilityAwareValue,\n SimulateContractErrorType,\n SimulateContractParameters,\n SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n UninstallFilterErrorType,\n UninstallFilterParameters,\n UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n VerifyHashErrorType as VerifyHashActionErrorType,\n VerifyHashParameters as VerifyHashActionParameters,\n VerifyHashReturnType as VerifyHashActionReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n VerifyMessageErrorType as VerifyMessageActionErrorType,\n VerifyMessageParameters as VerifyMessageActionParameters,\n VerifyMessageReturnType as VerifyMessageActionReturnType,\n} from './actions/public/verifyMessage.js'\nexport type {\n VerifyTypedDataErrorType as VerifyTypedDataActionErrorType,\n VerifyTypedDataParameters as VerifyTypedDataActionParameters,\n VerifyTypedDataReturnType as VerifyTypedDataActionReturnType,\n} from './actions/public/verifyTypedData.js'\nexport type {\n ReplacementReason,\n ReplacementReturnType,\n WaitForTransactionReceiptErrorType,\n WaitForTransactionReceiptParameters,\n WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n OnBlockNumberFn,\n OnBlockNumberParameter,\n WatchBlockNumberErrorType,\n WatchBlockNumberParameters,\n WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n OnBlock,\n OnBlockParameter,\n WatchBlocksErrorType,\n WatchBlocksParameters,\n WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n WatchContractEventErrorType,\n WatchContractEventOnLogsFn,\n WatchContractEventOnLogsParameter,\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n WatchEventErrorType,\n WatchEventOnLogsFn,\n WatchEventOnLogsParameter,\n WatchEventParameters,\n WatchEventReturnType,\n} from './actions/public/watchEvent.js'\nexport type {\n OnTransactionsFn,\n OnTransactionsParameter,\n WatchPendingTransactionsErrorType,\n WatchPendingTransactionsParameters,\n WatchPendingTransactionsReturnType,\n} from './actions/public/watchPendingTransactions.js'\nexport type {\n DropTransactionErrorType,\n DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n DumpStateErrorType,\n DumpStateReturnType,\n} from './actions/test/dumpState.js'\nexport type {\n GetAutomineErrorType,\n GetAutomineReturnType,\n} from './actions/test/getAutomine.js'\nexport type {\n GetTxpoolContentErrorType,\n GetTxpoolContentReturnType,\n} from './actions/test/getTxpoolContent.js'\nexport type {\n GetTxpoolStatusErrorType,\n GetTxpoolStatusReturnType,\n} from './actions/test/getTxpoolStatus.js'\nexport type {\n ImpersonateAccountErrorType,\n ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n IncreaseTimeErrorType,\n IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type {\n InspectTxpoolErrorType,\n InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type {\n LoadStateErrorType,\n LoadStateParameters,\n LoadStateReturnType,\n} from './actions/test/loadState.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type { RemoveBlockTimestampIntervalErrorType } from './actions/test/removeBlockTimestampInterval.js'\nexport type { ResetErrorType, ResetParameters } from './actions/test/reset.js'\nexport type {\n RevertErrorType,\n RevertParameters,\n} from './actions/test/revert.js'\nexport type {\n SendUnsignedTransactionErrorType,\n SendUnsignedTransactionParameters,\n SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type { SetAutomineErrorType } from './actions/test/setAutomine.js'\nexport type {\n SetBalanceErrorType,\n SetBalanceParameters,\n} from './actions/test/setBalance.js'\nexport type {\n SetBlockGasLimitErrorType,\n SetBlockGasLimitParameters,\n} from './actions/test/setBlockGasLimit.js'\nexport type {\n SetBlockTimestampIntervalErrorType,\n SetBlockTimestampIntervalParameters,\n} from './actions/test/setBlockTimestampInterval.js'\nexport type {\n SetCodeErrorType,\n SetCodeParameters,\n} from './actions/test/setCode.js'\nexport type {\n SetCoinbaseErrorType,\n SetCoinbaseParameters,\n} from './actions/test/setCoinbase.js'\nexport type {\n SetIntervalMiningErrorType,\n SetIntervalMiningParameters,\n} from './actions/test/setIntervalMining.js'\nexport type { SetLoggingEnabledErrorType } from './actions/test/setLoggingEnabled.js'\nexport type {\n SetMinGasPriceErrorType,\n SetMinGasPriceParameters,\n} from './actions/test/setMinGasPrice.js'\nexport type {\n SetNextBlockBaseFeePerGasErrorType,\n SetNextBlockBaseFeePerGasParameters,\n} from './actions/test/setNextBlockBaseFeePerGas.js'\nexport type {\n SetNextBlockTimestampErrorType,\n SetNextBlockTimestampParameters,\n} from './actions/test/setNextBlockTimestamp.js'\nexport type {\n SetNonceErrorType,\n SetNonceParameters,\n} from './actions/test/setNonce.js'\nexport type { SetRpcUrlErrorType } from './actions/test/setRpcUrl.js'\nexport type {\n SetStorageAtErrorType,\n SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type { SnapshotErrorType } from './actions/test/snapshot.js'\nexport type {\n StopImpersonatingAccountErrorType,\n StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n AddChainErrorType,\n AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport type {\n DeployContractErrorType,\n DeployContractParameters,\n DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n GetAddressesErrorType,\n GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n GetCallsStatusErrorType,\n GetCallsStatusParameters,\n GetCallsStatusReturnType,\n} from './actions/wallet/getCallsStatus.js'\nexport type {\n GetCapabilitiesErrorType,\n GetCapabilitiesParameters,\n GetCapabilitiesReturnType,\n} from './actions/wallet/getCapabilities.js'\nexport type {\n GetPermissionsErrorType,\n GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n PrepareAuthorizationErrorType,\n PrepareAuthorizationParameters,\n PrepareAuthorizationReturnType,\n} from './actions/wallet/prepareAuthorization.js'\nexport type {\n PrepareTransactionRequestErrorType,\n PrepareTransactionRequestParameters,\n PrepareTransactionRequestParameterType,\n PrepareTransactionRequestRequest,\n PrepareTransactionRequestReturnType,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n RequestAddressesErrorType,\n RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n RequestPermissionsErrorType,\n RequestPermissionsParameters,\n RequestPermissionsReturnType,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n SendCallsErrorType,\n SendCallsParameters,\n SendCallsReturnType,\n} from './actions/wallet/sendCalls.js'\nexport type {\n SendCallsSyncErrorType,\n SendCallsSyncParameters,\n SendCallsSyncReturnType,\n} from './actions/wallet/sendCallsSync.js'\nexport type {\n SendRawTransactionErrorType,\n SendRawTransactionParameters,\n SendRawTransactionReturnType,\n} from './actions/wallet/sendRawTransaction.js'\nexport type {\n SendRawTransactionSyncErrorType,\n SendRawTransactionSyncParameters,\n SendRawTransactionSyncReturnType,\n} from './actions/wallet/sendRawTransactionSync.js'\nexport type {\n SendTransactionErrorType,\n SendTransactionParameters,\n SendTransactionRequest,\n SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n SendTransactionSyncErrorType,\n SendTransactionSyncParameters,\n SendTransactionSyncRequest,\n SendTransactionSyncReturnType,\n} from './actions/wallet/sendTransactionSync.js'\nexport type {\n ShowCallsStatusErrorType,\n ShowCallsStatusParameters,\n ShowCallsStatusReturnType,\n} from './actions/wallet/showCallsStatus.js'\nexport type {\n SignAuthorizationErrorType,\n SignAuthorizationParameters,\n SignAuthorizationReturnType,\n} from './actions/wallet/signAuthorization.js'\nexport type {\n SignMessageErrorType,\n SignMessageParameters,\n SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n SignTransactionErrorType,\n SignTransactionParameters,\n SignTransactionRequest,\n SignTransactionReturnType,\n} from './actions/wallet/signTransaction.js'\nexport type {\n SignTypedDataErrorType,\n SignTypedDataParameters,\n SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n SwitchChainErrorType,\n SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n WaitForCallsStatusErrorType,\n WaitForCallsStatusParameters,\n WaitForCallsStatusReturnType,\n WaitForCallsStatusTimeoutErrorType,\n} from './actions/wallet/waitForCallsStatus.js'\nexport { WaitForCallsStatusTimeoutError } from './actions/wallet/waitForCallsStatus.js'\nexport type {\n WatchAssetErrorType,\n WatchAssetParameters,\n WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n WriteContractErrorType,\n WriteContractParameters,\n WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n WriteContractSyncErrorType,\n WriteContractSyncParameters,\n WriteContractSyncReturnType,\n} from './actions/wallet/writeContractSync.js'\nexport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n type MulticallBatchOptions,\n rpcSchema,\n} from './clients/createClient.js'\nexport {\n type CreatePublicClientErrorType,\n createPublicClient,\n type PublicClient,\n type PublicClientConfig,\n} from './clients/createPublicClient.js'\nexport {\n type CreateTestClientErrorType,\n createTestClient,\n type TestClient,\n type TestClientConfig,\n} from './clients/createTestClient.js'\nexport {\n type CreateWalletClientErrorType,\n createWalletClient,\n type WalletClient,\n type WalletClientConfig,\n} from './clients/createWalletClient.js'\nexport {\n type PublicActions,\n publicActions,\n} from './clients/decorators/public.js'\nexport {\n type TestActions,\n testActions,\n} from './clients/decorators/test.js'\nexport {\n type WalletActions,\n walletActions,\n} from './clients/decorators/wallet.js'\nexport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './clients/transports/createTransport.js'\nexport {\n type CustomTransport,\n type CustomTransportConfig,\n type CustomTransportErrorType,\n custom,\n} from './clients/transports/custom.js'\nexport {\n type FallbackTransport,\n type FallbackTransportConfig,\n type FallbackTransportErrorType,\n fallback,\n shouldThrow,\n} from './clients/transports/fallback.js'\nexport {\n type HttpTransport,\n type HttpTransportConfig,\n type HttpTransportErrorType,\n http,\n} from './clients/transports/http.js'\nexport {\n type WebSocketTransport,\n type WebSocketTransportConfig,\n type WebSocketTransportErrorType,\n webSocket,\n} from './clients/transports/webSocket.js'\nexport {\n erc20Abi,\n erc20Abi_bytes32,\n erc721Abi,\n erc1155Abi,\n erc4626Abi,\n erc6492SignatureValidatorAbi,\n /** @deprecated use `erc6492SignatureValidatorAbi` instead. */\n erc6492SignatureValidatorAbi as universalSignatureValidatorAbi,\n multicall3Abi,\n} from './constants/abis.js'\nexport { ethAddress, zeroAddress } from './constants/address.js'\nexport { zeroHash } from './constants/bytes.js'\nexport {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n erc6492SignatureValidatorByteCode,\n /** @deprecated use `erc6492SignatureValidatorByteCode` instead. */\n erc6492SignatureValidatorByteCode as universalSignatureValidatorByteCode,\n} from './constants/contracts.js'\nexport {\n maxInt8,\n maxInt16,\n maxInt24,\n maxInt32,\n maxInt40,\n maxInt48,\n maxInt56,\n maxInt64,\n maxInt72,\n maxInt80,\n maxInt88,\n maxInt96,\n maxInt104,\n maxInt112,\n maxInt120,\n maxInt128,\n maxInt136,\n maxInt144,\n maxInt152,\n maxInt160,\n maxInt168,\n maxInt176,\n maxInt184,\n maxInt192,\n maxInt200,\n maxInt208,\n maxInt216,\n maxInt224,\n maxInt232,\n maxInt240,\n maxInt248,\n maxInt256,\n maxUint8,\n maxUint16,\n maxUint24,\n maxUint32,\n maxUint40,\n maxUint48,\n maxUint56,\n maxUint64,\n maxUint72,\n maxUint80,\n maxUint88,\n maxUint96,\n maxUint104,\n maxUint112,\n maxUint120,\n maxUint128,\n maxUint136,\n maxUint144,\n maxUint152,\n maxUint160,\n maxUint168,\n maxUint176,\n maxUint184,\n maxUint192,\n maxUint200,\n maxUint208,\n maxUint216,\n maxUint224,\n maxUint232,\n maxUint240,\n maxUint248,\n maxUint256,\n minInt8,\n minInt16,\n minInt24,\n minInt32,\n minInt40,\n minInt48,\n minInt56,\n minInt64,\n minInt72,\n minInt80,\n minInt88,\n minInt96,\n minInt104,\n minInt112,\n minInt120,\n minInt128,\n minInt136,\n minInt144,\n minInt152,\n minInt160,\n minInt168,\n minInt176,\n minInt184,\n minInt192,\n minInt200,\n minInt208,\n minInt216,\n minInt224,\n minInt232,\n minInt240,\n minInt248,\n minInt256,\n} from './constants/number.js'\nexport { presignMessagePrefix } from './constants/strings.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.js'\nexport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n type AbiConstructorParamsNotFoundErrorType,\n AbiDecodingDataSizeInvalidError,\n type AbiDecodingDataSizeInvalidErrorType,\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiDecodingZeroDataError,\n type AbiDecodingZeroDataErrorType,\n AbiEncodingArrayLengthMismatchError,\n type AbiEncodingArrayLengthMismatchErrorType,\n AbiEncodingBytesSizeMismatchError,\n type AbiEncodingBytesSizeMismatchErrorType,\n AbiEncodingLengthMismatchError,\n type AbiEncodingLengthMismatchErrorType,\n AbiErrorInputsNotFoundError,\n type AbiErrorInputsNotFoundErrorType,\n AbiErrorNotFoundError,\n type AbiErrorNotFoundErrorType,\n AbiErrorSignatureNotFoundError,\n type AbiErrorSignatureNotFoundErrorType,\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n AbiFunctionSignatureNotFoundError,\n type AbiFunctionSignatureNotFoundErrorType,\n BytesSizeMismatchError,\n type BytesSizeMismatchErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n InvalidAbiEncodingTypeError,\n type InvalidAbiEncodingTypeErrorType,\n InvalidArrayError,\n type InvalidArrayErrorType,\n InvalidDefinitionTypeError,\n type InvalidDefinitionTypeErrorType,\n UnsupportedPackedAbiType,\n type UnsupportedPackedAbiTypeErrorType,\n} from './errors/abi.js'\nexport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from './errors/address.js'\nexport { BaseError, type BaseErrorType, setErrorConfig } from './errors/base.js'\nexport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n BundleFailedError,\n type BundleFailedErrorType,\n} from './errors/calls.js'\nexport {\n ChainDoesNotSupportContract,\n type ChainDoesNotSupportContractErrorType,\n ChainMismatchError,\n type ChainMismatchErrorType,\n ChainNotFoundError,\n type ChainNotFoundErrorType,\n ClientChainNotConfiguredError,\n type ClientChainNotConfiguredErrorType,\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from './errors/chain.js'\nexport {\n CallExecutionError,\n type CallExecutionErrorType,\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n CounterfactualDeploymentFailedError,\n type CounterfactualDeploymentFailedErrorType,\n RawContractError,\n type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n SliceOffsetOutOfBoundsError,\n type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n InvalidBytesBooleanError,\n type InvalidBytesBooleanErrorType,\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n InvalidHexValueError,\n type InvalidHexValueErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n type EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n EnsInvalidChainIdError,\n type EnsInvalidChainIdErrorType,\n} from './errors/ens.js'\nexport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n MaxFeePerGasTooLowError,\n type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from './errors/log.js'\nexport {\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'\nexport {\n HttpRequestError,\n type HttpRequestErrorType,\n RpcRequestError,\n type RpcRequestErrorType,\n SocketClosedError,\n type SocketClosedErrorType,\n TimeoutError,\n type TimeoutErrorType,\n WebSocketRequestError,\n type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n ProviderRpcError,\n type ProviderRpcErrorCode,\n type ProviderRpcErrorType,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from './errors/stateOverride.js'\nexport {\n FeeConflictError,\n type FeeConflictErrorType,\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n InvalidSerializedTransactionError,\n type InvalidSerializedTransactionErrorType,\n InvalidSerializedTransactionTypeError,\n type InvalidSerializedTransactionTypeErrorType,\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from './errors/transaction.js'\nexport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport {\n InvalidDomainError,\n type InvalidDomainErrorType,\n InvalidPrimaryTypeError,\n type InvalidPrimaryTypeErrorType,\n InvalidStructTypeError,\n type InvalidStructTypeErrorType,\n} from './errors/typedData.js'\nexport {\n InvalidDecimalNumberError,\n type InvalidDecimalNumberErrorType,\n} from './errors/unit.js'\nexport type {\n DeriveAccount,\n HDKey,\n ParseAccount,\n} from './types/account.js'\nexport type {\n Authorization,\n AuthorizationList,\n AuthorizationRequest,\n SerializedAuthorization,\n SerializedAuthorizationList,\n SignedAuthorization,\n SignedAuthorizationList,\n} from './types/authorization.js'\nexport type {\n Block,\n BlockIdentifier,\n BlockNumber,\n BlockTag,\n Uncle,\n} from './types/block.js'\nexport type { Call, Calls } from './types/calls.js'\nexport type {\n Capabilities,\n /** @deprecated Use `Capabilities` instead. */\n Capabilities as WalletCapabilities,\n CapabilitiesSchema,\n /** @deprecated Use `ChainIdToCapabilities` instead. */\n ChainIdToCapabilities as WalletCapabilitiesRecord,\n ChainIdToCapabilities,\n ExtractCapabilities,\n} from './types/capabilities.js'\nexport type {\n Chain,\n ChainConfig,\n ChainContract,\n ChainEstimateFeesPerGasFn,\n ChainEstimateFeesPerGasFnParameters,\n ChainFees,\n ChainFeesFnParameters,\n ChainFormatter,\n ChainFormatters,\n ChainMaxPriorityFeePerGasFn,\n ChainSerializers,\n DeriveChain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterParameters,\n ExtractChainFormatterReturnType,\n GetChainParameter,\n} from './types/chain.js'\nexport type {\n AbiEventParametersToPrimitiveTypes,\n AbiEventParameterToPrimitiveType,\n AbiEventTopicToPrimitiveType,\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ContractConstructorArgs,\n ContractErrorArgs,\n ContractErrorName,\n ContractEventArgs,\n ContractEventArgsFromTopics,\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n EventDefinition,\n ExtractAbiFunctionForArgs,\n ExtractAbiItem,\n ExtractAbiItemForArgs,\n ExtractAbiItemNames,\n GetEventArgs,\n GetValue,\n LogTopicType,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n UnionWiden,\n Widen,\n} from './types/contract.js'\nexport type { DataSuffix } from './types/dataSuffix.js'\nexport type {\n AddEthereumChainParameter,\n BundlerRpcSchema,\n DebugBundlerRpcSchema,\n EIP1193EventMap,\n EIP1193Events,\n EIP1193Parameters,\n EIP1193Provider,\n EIP1193RequestFn,\n EIP1474Methods,\n NetworkSync,\n PaymasterRpcSchema,\n ProviderConnectInfo,\n ProviderMessage,\n ProviderRpcErrorType as EIP1193ProviderRpcErrorType,\n PublicRpcSchema,\n RpcSchema,\n RpcSchemaOverride,\n TestRpcSchema,\n WalletCallReceipt,\n WalletGetAssetsParameters,\n WalletGetAssetsReturnType,\n WalletGetCallsStatusReturnType,\n WalletGrantPermissionsParameters,\n WalletGrantPermissionsReturnType,\n WalletPermission,\n WalletPermissionCaveat,\n WalletRpcSchema,\n WalletSendCallsParameters,\n WalletSendCallsReturnType,\n WatchAssetParams,\n} from './types/eip1193.js'\nexport { ProviderRpcError as EIP1193ProviderRpcError } from './types/eip1193.js'\nexport type { BlobSidecar, BlobSidecars } from './types/eip4844.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n FeeHistory,\n FeeValues,\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n FeeValuesType,\n} from './types/fee.js'\nexport type { Filter, FilterType } from './types/filter.js'\nexport type { GetTransactionRequestKzgParameter, Kzg } from './types/kzg.js'\nexport type { Log } from './types/log.js'\nexport type {\n ByteArray,\n CompactSignature,\n Hash,\n Hex,\n LogTopic,\n SignableMessage,\n Signature,\n} from './types/misc.js'\nexport type {\n MulticallContracts,\n MulticallResponse,\n MulticallResults,\n} from './types/multicall.js'\nexport type { Register, ResolvedRegister } from './types/register.js'\nexport type {\n Index,\n Quantity,\n RpcAccountStateOverride,\n RpcAuthorization,\n RpcAuthorizationList,\n RpcBlock,\n RpcBlockIdentifier,\n RpcBlockNumber,\n RpcFeeHistory,\n RpcFeeValues,\n RpcLog,\n RpcProof,\n RpcStateMapping,\n RpcStateOverride,\n RpcTransaction,\n RpcTransactionReceipt,\n RpcTransactionRequest,\n RpcUncle,\n Status,\n} from './types/rpc.js'\nexport type {\n StateMapping,\n StateOverride,\n} from './types/stateOverride.js'\nexport type {\n AccessList,\n Transaction,\n TransactionBase,\n TransactionEIP1559,\n TransactionEIP2930,\n TransactionEIP4844,\n TransactionEIP7702,\n TransactionLegacy,\n TransactionReceipt,\n TransactionRequest,\n TransactionRequestBase,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestGeneric,\n TransactionRequestLegacy,\n TransactionSerializable,\n TransactionSerializableBase,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionSerializedLegacy,\n TransactionType,\n} from './types/transaction.js'\nexport type { GetPollOptions, GetTransportConfig } from './types/transport.js'\nexport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from './types/typedData.js'\nexport type {\n Assign,\n Branded,\n Evaluate,\n ExactPartial,\n ExactRequired,\n IsNarrowable,\n IsNever,\n IsUndefined,\n IsUnion,\n LooseOmit,\n MaybePartial,\n MaybePromise,\n MaybeRequired,\n Mutable,\n NoInfer,\n NoUndefined,\n Omit,\n OneOf,\n Or,\n PartialBy,\n Prettify,\n RequiredBy,\n Some,\n UnionEvaluate,\n UnionLooseOmit,\n UnionOmit,\n UnionPartialBy,\n UnionPick,\n UnionRequiredBy,\n UnionToTuple,\n ValueOf,\n} from './types/utils.js'\nexport type { Withdrawal } from './types/withdrawal.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './utils/abi/decodeAbiParameters.js'\nexport {\n type DecodeDeployDataErrorType,\n type DecodeDeployDataParameters,\n type DecodeDeployDataReturnType,\n decodeDeployData,\n} from './utils/abi/decodeDeployData.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './utils/abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './utils/abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './utils/abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './utils/abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './utils/abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n type EncodeDeployDataReturnType,\n encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n type EncodeErrorResultReturnType,\n encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n type EncodeFunctionDataReturnType,\n encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n type EncodeFunctionResultReturnType,\n encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n type EncodePackedErrorType,\n encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n type GetAbiItemReturnType,\n getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './utils/abi/parseEventLogs.js'\nexport {\n type PrepareEncodeFunctionDataErrorType,\n type PrepareEncodeFunctionDataParameters,\n type PrepareEncodeFunctionDataReturnType,\n prepareEncodeFunctionData,\n} from './utils/abi/prepareEncodeFunctionData.js'\nexport {\n type ChecksumAddressErrorType,\n checksumAddress,\n type GetAddressErrorType,\n getAddress,\n} from './utils/address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n type IsAddressErrorType,\n type IsAddressOptions,\n isAddress,\n} from './utils/address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n type IsAddressEqualReturnType,\n isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport {\n type BlobsToCommitmentsErrorType,\n type BlobsToCommitmentsParameters,\n type BlobsToCommitmentsReturnType,\n blobsToCommitments,\n} from './utils/blob/blobsToCommitments.js'\nexport {\n blobsToProofs,\n type blobsToProofsErrorType,\n type blobsToProofsParameters,\n type blobsToProofsReturnType,\n} from './utils/blob/blobsToProofs.js'\nexport {\n type CommitmentsToVersionedHashesErrorType,\n type CommitmentsToVersionedHashesParameters,\n type CommitmentsToVersionedHashesReturnType,\n commitmentsToVersionedHashes,\n} from './utils/blob/commitmentsToVersionedHashes.js'\nexport {\n type CommitmentToVersionedHashErrorType,\n type CommitmentToVersionedHashParameters,\n type CommitmentToVersionedHashReturnType,\n commitmentToVersionedHash,\n} from './utils/blob/commitmentToVersionedHash.js'\nexport {\n type FromBlobsErrorType,\n type FromBlobsParameters,\n type FromBlobsReturnType,\n fromBlobs,\n} from './utils/blob/fromBlobs.js'\nexport {\n type SidecarsToVersionedHashesErrorType,\n type SidecarsToVersionedHashesParameters,\n type SidecarsToVersionedHashesReturnType,\n sidecarsToVersionedHashes,\n} from './utils/blob/sidecarsToVersionedHashes.js'\nexport {\n type ToBlobSidecarsErrorType,\n type ToBlobSidecarsParameters,\n type ToBlobSidecarsReturnType,\n toBlobSidecars,\n} from './utils/blob/toBlobSidecars.js'\nexport {\n type ToBlobsErrorType,\n type ToBlobsParameters,\n type ToBlobsReturnType,\n toBlobs,\n} from './utils/blob/toBlobs.js'\nexport {\n type CcipRequestErrorType,\n type CcipRequestParameters,\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport {\n type DefineChainReturnType,\n defineChain,\n extendSchema,\n} from './utils/chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './utils/chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './utils/chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n type ConcatReturnType,\n concat,\n concatBytes,\n concatHex,\n} from './utils/data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n type PadReturnType,\n pad,\n padBytes,\n padHex,\n} from './utils/data/pad.js'\nexport { type SizeErrorType, size } from './utils/data/size.js'\nexport {\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n slice,\n sliceBytes,\n sliceHex,\n} from './utils/data/slice.js'\nexport {\n type TrimErrorType,\n type TrimReturnType,\n trim,\n} from './utils/data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n type FromHexErrorType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBoolErrorType,\n type HexToNumberErrorType,\n type HexToStringErrorType,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './utils/encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n type FromRlpReturnType,\n fromRlp,\n} from './utils/encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './utils/encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './utils/encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n bytesToRlp,\n type HexToRlpErrorType,\n hexToRlp,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './utils/encoding/toRlp.js'\nexport { type LabelhashErrorType, labelhash } from './utils/ens/labelhash.js'\nexport { type NamehashErrorType, namehash } from './utils/ens/namehash.js'\nexport {\n type ToCoinTypeError,\n toCoinType,\n} from './utils/ens/toCoinType.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './utils/formatters/block.js'\nexport { type FormatLogErrorType, formatLog } from './utils/formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport {\n type Keccak256ErrorType,\n type Keccak256Hash,\n keccak256,\n} from './utils/hash/keccak256.js'\nexport {\n type Ripemd160ErrorType,\n type Ripemd160Hash,\n ripemd160,\n} from './utils/hash/ripemd160.js'\nexport {\n type Sha256ErrorType,\n type Sha256Hash,\n sha256,\n} from './utils/hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './utils/hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './utils/hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './utils/hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './utils/hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './utils/hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './utils/hash/toFunctionSignature.js'\nexport {\n type DefineKzgErrorType,\n type DefineKzgParameters,\n type DefineKzgReturnType,\n defineKzg,\n} from './utils/kzg/defineKzg.js'\nexport {\n type SetupKzgErrorType,\n type SetupKzgParameters,\n type SetupKzgReturnType,\n setupKzg,\n} from './utils/kzg/setupKzg.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './utils/nonceManager.js'\nexport { withCache } from './utils/promise/withCache.js'\nexport {\n type WithRetryErrorType,\n withRetry,\n} from './utils/promise/withRetry.js'\nexport {\n type WithTimeoutErrorType,\n withTimeout,\n} from './utils/promise/withTimeout.js'\nexport {\n type CompactSignatureToSignatureErrorType,\n compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n type HashMessageErrorType,\n hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashDomain,\n hashStruct,\n hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './utils/signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './utils/signature/isErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseCompactSignatureErrorType`. */\n type ParseCompactSignatureErrorType as HexToCompactSignatureErrorType,\n type ParseCompactSignatureErrorType,\n /** @deprecated Use `parseCompactSignature`. */\n parseCompactSignature as hexToCompactSignature,\n parseCompactSignature,\n} from './utils/signature/parseCompactSignature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './utils/signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './utils/signature/parseErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseSignatureErrorType`. */\n type ParseSignatureErrorType as HexToSignatureErrorType,\n type ParseSignatureErrorType,\n /** @deprecated Use `parseSignature`. */\n parseSignature as hexToSignature,\n parseSignature,\n} from './utils/signature/parseSignature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './utils/signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './utils/signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './utils/signature/recoverPublicKey.js'\nexport {\n type RecoverTransactionAddressErrorType,\n type RecoverTransactionAddressParameters,\n type RecoverTransactionAddressReturnType,\n recoverTransactionAddress,\n} from './utils/signature/recoverTransactionAddress.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeCompactSignatureErrorType as CompactSignatureToHexErrorType,\n type SerializeCompactSignatureErrorType,\n /** @deprecated Use `serializeCompactSignature` instead. */\n serializeCompactSignature as compactSignatureToHex,\n serializeCompactSignature,\n} from './utils/signature/serializeCompactSignature.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './utils/signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './utils/signature/serializeErc8010Signature.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n type SerializeSignatureParameters,\n type SerializeSignatureReturnType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from './utils/signature/serializeSignature.js'\nexport {\n type SignatureToCompactSignatureErrorType,\n signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n type ToPrefixedMessageErrorType,\n toPrefixedMessage,\n} from './utils/signature/toPrefixedMessage.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './utils/signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './utils/signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './utils/signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n type ParseTransactionReturnType,\n parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n type SerializedTransactionReturnType,\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './utils/transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n domainSeparator,\n type GetTypesForEIP712DomainErrorType,\n getTypesForEIP712Domain,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './utils/typedData.js'\nexport {\n type FormatEtherErrorType,\n formatEther,\n} from './utils/unit/formatEther.js'\nexport {\n type FormatGweiErrorType,\n formatGwei,\n} from './utils/unit/formatGwei.js'\nexport {\n type FormatUnitsErrorType,\n formatUnits,\n} from './utils/unit/formatUnits.js'\nexport {\n type ParseEtherErrorType,\n parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n type ParseUnitsErrorType,\n parseUnits,\n} from './utils/unit/parseUnits.js'\n","import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","export const x402Version = 2;\n","import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData {\n facilitator: T;\n networks: Set;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = (\n map: Map>,\n network: Network,\n): Map | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = (\n map: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = (\n schemeMap: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record = {};\n Object.keys(obj as Record)\n .sort()\n .forEach(key => {\n const value = (obj as Record)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n","import { x402ResourceServer } from \"../server\";\nimport {\n decodePaymentSignatureHeader,\n encodePaymentRequiredHeader,\n encodePaymentResponseHeader,\n} from \".\";\nimport {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n SettleError,\n Price,\n Network,\n PaymentRequirements,\n} from \"../types\";\nimport { x402Version } from \"..\";\n\n/**\n * Framework-agnostic HTTP adapter interface\n * Implementations provide framework-specific HTTP operations\n */\nexport interface HTTPAdapter {\n getHeader(name: string): string | undefined;\n getMethod(): string;\n getPath(): string;\n getUrl(): string;\n getAcceptHeader(): string;\n getUserAgent(): string;\n\n /**\n * Get query parameters from the request URL\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams?(): Record;\n\n /**\n * Get a specific query parameter by name\n *\n * @param name - The query parameter name\n * @returns The query parameter value(s) or undefined\n */\n getQueryParam?(name: string): string | string[] | undefined;\n\n /**\n * Get the parsed request body\n * Framework adapters should parse JSON/form data appropriately\n *\n * @returns The parsed request body\n */\n getBody?(): unknown;\n}\n\n/**\n * Paywall configuration for HTML responses\n */\nexport interface PaywallConfig {\n appName?: string;\n appLogo?: string;\n sessionTokenEndpoint?: string;\n currentUrl?: string;\n testnet?: boolean;\n}\n\n/**\n * Paywall provider interface for generating HTML\n */\nexport interface PaywallProvider {\n generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;\n}\n\n/**\n * Dynamic payTo function that receives HTTP request context\n */\nexport type DynamicPayTo = (context: HTTPRequestContext) => string | Promise;\n\n/**\n * Dynamic price function that receives HTTP request context\n */\nexport type DynamicPrice = (context: HTTPRequestContext) => Price | Promise;\n\n/**\n * Result of response body callbacks containing content type and body.\n */\nexport interface HTTPResponseBody {\n /**\n * The content type for the response (e.g., 'application/json', 'text/plain').\n */\n contentType: string;\n\n /**\n * The response body to include in the 402 response.\n */\n body: unknown;\n}\n\n/**\n * Dynamic function to generate a custom response for unpaid requests.\n * Receives the HTTP request context and returns the content type and body to include in the 402 response.\n */\nexport type UnpaidResponseBody = (\n context: HTTPRequestContext,\n) => HTTPResponseBody | Promise;\n\n/**\n * Dynamic function to generate a custom response for settlement failures.\n * Receives the HTTP request context and settle failure result, returns the content type and body.\n */\nexport type SettlementFailedResponseBody = (\n context: HTTPRequestContext,\n settleResult: Omit,\n) => HTTPResponseBody | Promise;\n\n/**\n * A single payment option for a route\n * Represents one way a client can pay for access to the resource\n */\nexport interface PaymentOption {\n scheme: string;\n payTo: string | DynamicPayTo;\n price: Price | DynamicPrice;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record;\n}\n\n/**\n * Route configuration for HTTP endpoints\n *\n * The 'accepts' field defines payment options for the route.\n * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.\n */\nexport interface RouteConfig {\n // Payment option(s): single or array\n accepts: PaymentOption | PaymentOption[];\n\n // HTTP-specific metadata\n resource?: string;\n description?: string;\n mimeType?: string;\n customPaywallHtml?: string;\n\n /**\n * Optional callback to generate a custom response for unpaid API requests.\n * This allows servers to return preview data, error messages, or other content\n * when a request lacks payment.\n *\n * For browser requests (Accept: text/html), the paywall HTML takes precedence.\n * This callback is only used for API clients.\n *\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @returns An object containing both contentType and body for the 402 response\n */\n unpaidResponseBody?: UnpaidResponseBody;\n\n /**\n * Optional callback to generate a custom response for settlement failures.\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @param settleResult - The settlement failure result\n * @returns An object containing both contentType and body for the 402 response\n */\n settlementFailedResponseBody?: SettlementFailedResponseBody;\n\n // Extensions\n extensions?: Record;\n}\n\n/**\n * Routes configuration - maps path patterns to route configs\n */\nexport type RoutesConfig = Record | RouteConfig;\n\n/**\n * Hook that runs on every request to a protected route, before payment processing.\n * Can grant access without payment, deny the request, or continue to payment flow.\n *\n * @returns\n * - `void` - Continue to payment processing (default behavior)\n * - `{ grantAccess: true }` - Grant access without requiring payment\n * - `{ abort: true; reason: string }` - Deny the request (returns 403)\n */\nexport type ProtectedRequestHook = (\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n) => Promise;\n\n/**\n * Compiled route for efficient matching\n */\nexport interface CompiledRoute {\n verb: string;\n regex: RegExp;\n config: RouteConfig;\n}\n\n/**\n * HTTP request context that encapsulates all request data\n */\nexport interface HTTPRequestContext {\n adapter: HTTPAdapter;\n path: string;\n method: string;\n paymentHeader?: string;\n}\n\n/**\n * HTTP transport context contains both request context and optional response data.\n */\nexport interface HTTPTransportContext {\n /** The HTTP request context */\n request: HTTPRequestContext;\n /** The response body buffer */\n responseBody?: Buffer;\n}\n\n/**\n * HTTP response instructions for the framework middleware\n */\nexport interface HTTPResponseInstructions {\n status: number;\n headers: Record;\n body?: unknown; // e.g. Paywall for web browser requests, but could be any other type\n isHtml?: boolean; // e.g. if body is a paywall, then isHtml is true\n}\n\n/**\n * Result of processing an HTTP request for payment\n */\nexport type HTTPProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n declaredExtensions?: Record;\n }\n | { type: \"payment-error\"; response: HTTPResponseInstructions };\n\n/**\n * Result of processSettlement\n */\nexport type ProcessSettleSuccessResponse = SettleResponse & {\n success: true;\n headers: Record;\n requirements: PaymentRequirements;\n};\n\nexport type ProcessSettleFailureResponse = SettleResponse & {\n success: false;\n errorReason: string;\n errorMessage?: string;\n headers: Record;\n response: HTTPResponseInstructions;\n};\n\nexport type ProcessSettleResultResponse =\n | ProcessSettleSuccessResponse\n | ProcessSettleFailureResponse;\n\n/**\n * Represents a validation error for a specific route's payment configuration.\n */\nexport interface RouteValidationError {\n /** The route pattern (e.g., \"GET /api/weather\") */\n routePattern: string;\n /** The payment scheme that failed validation */\n scheme: string;\n /** The network that failed validation */\n network: Network;\n /** The type of validation failure */\n reason: \"missing_scheme\" | \"missing_facilitator\";\n /** Human-readable error message */\n message: string;\n}\n\n/**\n * Error thrown when route configuration validation fails.\n */\nexport class RouteConfigurationError extends Error {\n /** The validation errors that caused this exception */\n public readonly errors: RouteValidationError[];\n\n /**\n * Creates a new RouteConfigurationError with the given validation errors.\n *\n * @param errors - The validation errors that caused this exception.\n */\n constructor(errors: RouteValidationError[]) {\n const message = `x402 Route Configuration Errors:\\n${errors.map(e => ` - ${e.message}`).join(\"\\n\")}`;\n super(message);\n this.name = \"RouteConfigurationError\";\n this.errors = errors;\n }\n}\n\n/**\n * HTTP-enhanced x402 resource server\n * Provides framework-agnostic HTTP protocol handling\n */\nexport class x402HTTPResourceServer {\n private ResourceServer: x402ResourceServer;\n private compiledRoutes: CompiledRoute[] = [];\n private routesConfig: RoutesConfig;\n private paywallProvider?: PaywallProvider;\n private protectedRequestHooks: ProtectedRequestHook[] = [];\n\n /**\n * Creates a new x402HTTPResourceServer instance.\n *\n * @param ResourceServer - The core x402ResourceServer instance to use\n * @param routes - Route configuration for payment-protected endpoints\n */\n constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig) {\n this.ResourceServer = ResourceServer;\n this.routesConfig = routes;\n\n // Handle both single route and multiple routes\n const normalizedRoutes =\n typeof routes === \"object\" && !(\"accepts\" in routes)\n ? (routes as Record)\n : { \"*\": routes as RouteConfig };\n\n for (const [pattern, config] of Object.entries(normalizedRoutes)) {\n const parsed = this.parseRoutePattern(pattern);\n this.compiledRoutes.push({\n verb: parsed.verb,\n regex: parsed.regex,\n config,\n });\n }\n }\n\n /**\n * Get the underlying x402ResourceServer instance.\n *\n * @returns The underlying x402ResourceServer instance\n */\n get server(): x402ResourceServer {\n return this.ResourceServer;\n }\n\n /**\n * Get the routes configuration.\n *\n * @returns The routes configuration\n */\n get routes(): RoutesConfig {\n return this.routesConfig;\n }\n\n /**\n * Initialize the HTTP resource server.\n *\n * This method initializes the underlying resource server (fetching facilitator support)\n * and then validates that all route payment configurations have corresponding\n * registered schemes and facilitator support.\n *\n * @throws RouteConfigurationError if any route's payment options don't have\n * corresponding registered schemes or facilitator support\n *\n * @example\n * ```typescript\n * const httpServer = new x402HTTPResourceServer(server, routes);\n * await httpServer.initialize();\n * ```\n */\n async initialize(): Promise {\n // First, initialize the underlying resource server (fetches facilitator support)\n await this.ResourceServer.initialize();\n\n // Then validate route configuration\n const errors = this.validateRouteConfiguration();\n if (errors.length > 0) {\n throw new RouteConfigurationError(errors);\n }\n }\n\n /**\n * Register a custom paywall provider for generating HTML\n *\n * @param provider - PaywallProvider instance\n * @returns This service instance for chaining\n */\n registerPaywallProvider(provider: PaywallProvider): this {\n this.paywallProvider = provider;\n return this;\n }\n\n /**\n * Register a hook that runs on every request to a protected route, before payment processing.\n * Hooks are executed in order of registration. The first hook to return a non-void result wins.\n *\n * @param hook - The request hook function\n * @returns The x402HTTPResourceServer instance for chaining\n */\n onProtectedRequest(hook: ProtectedRequestHook): this {\n this.protectedRequestHooks.push(hook);\n return this;\n }\n\n /**\n * Process HTTP request and return response instructions\n * This is the main entry point for framework middleware\n *\n * @param context - HTTP request context\n * @param paywallConfig - Optional paywall configuration\n * @returns Process result indicating next action for middleware\n */\n async processHTTPRequest(\n context: HTTPRequestContext,\n paywallConfig?: PaywallConfig,\n ): Promise {\n const { adapter, path, method } = context;\n\n // Find matching route\n const routeConfig = this.getRouteConfig(path, method);\n if (!routeConfig) {\n return { type: \"no-payment-required\" }; // No payment required for this route\n }\n\n // Execute request hooks before any payment processing\n for (const hook of this.protectedRequestHooks) {\n const result = await hook(context, routeConfig);\n if (result && \"grantAccess\" in result) {\n return { type: \"no-payment-required\" };\n }\n if (result && \"abort\" in result) {\n return {\n type: \"payment-error\",\n response: {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: result.reason },\n },\n };\n }\n }\n\n // Normalize accepts field to array of payment options\n const paymentOptions = this.normalizePaymentOptions(routeConfig);\n\n // Check for payment header (v1 or v2)\n const paymentPayload = this.extractPayment(adapter);\n\n // Create resource info, using config override if provided\n const resourceInfo = {\n url: routeConfig.resource || context.adapter.getUrl(),\n description: routeConfig.description || \"\",\n mimeType: routeConfig.mimeType || \"\",\n };\n\n // Build requirements from all payment options\n // (this method handles resolving dynamic functions internally)\n let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(\n paymentOptions,\n context,\n );\n\n let extensions = routeConfig.extensions;\n if (extensions) {\n extensions = this.ResourceServer.enrichExtensions(extensions, context);\n }\n\n // createPaymentRequiredResponse already handles extension enrichment in the core layer\n const transportContext: HTTPTransportContext = { request: context };\n const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n !paymentPayload ? \"Payment required\" : undefined,\n extensions,\n transportContext,\n );\n\n // If no payment provided\n if (!paymentPayload) {\n // Resolve custom unpaid response body if provided\n const unpaidBody = routeConfig.unpaidResponseBody\n ? await routeConfig.unpaidResponseBody(context)\n : undefined;\n\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(\n paymentRequired,\n this.isWebBrowser(adapter),\n paywallConfig,\n routeConfig.customPaywallHtml,\n unpaidBody,\n ),\n };\n }\n\n // Verify payment\n try {\n const matchingRequirements = this.ResourceServer.findMatchingRequirements(\n paymentRequired.accepts,\n paymentPayload,\n );\n\n if (!matchingRequirements) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const verifyResult = await this.ResourceServer.verifyPayment(\n paymentPayload,\n matchingRequirements,\n );\n\n if (!verifyResult.isValid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n verifyResult.invalidReason,\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n // Payment is valid, return data needed for settlement\n return {\n type: \"payment-verified\",\n paymentPayload,\n paymentRequirements: matchingRequirements,\n declaredExtensions: routeConfig.extensions,\n };\n } catch (error) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n error instanceof Error ? error.message : \"Payment verification failed\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n }\n\n /**\n * Process settlement after successful response\n *\n * @param paymentPayload - The verified payment payload\n * @param requirements - The matching payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional HTTP transport context\n * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure\n */\n async processSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record,\n transportContext?: HTTPTransportContext,\n ): Promise {\n try {\n const settleResponse = await this.ResourceServer.settlePayment(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n );\n\n if (!settleResponse.success) {\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason: settleResponse.errorReason || \"Settlement failed\",\n errorMessage:\n settleResponse.errorMessage || settleResponse.errorReason || \"Settlement failed\",\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n\n return {\n ...settleResponse,\n success: true,\n headers: this.createSettlementHeaders(settleResponse),\n requirements,\n };\n } catch (error) {\n if (error instanceof SettleError) {\n const errorReason = error.errorReason || error.message;\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: error.errorMessage || errorReason,\n payer: error.payer,\n network: error.network,\n transaction: error.transaction,\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n const errorReason = error instanceof Error ? error.message : \"Settlement failed\";\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: errorReason,\n network: requirements.network as Network,\n transaction: \"\",\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n }\n\n /**\n * Check if a request requires payment based on route configuration\n *\n * @param context - HTTP request context\n * @returns True if the route requires payment, false otherwise\n */\n requiresPayment(context: HTTPRequestContext): boolean {\n const routeConfig = this.getRouteConfig(context.path, context.method);\n return routeConfig !== undefined;\n }\n\n /**\n * Build HTTPResponseInstructions for settlement failure.\n * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.\n *\n * @param failure - Settlement failure result with headers\n * @param transportContext - Optional HTTP transport context for the request\n * @returns HTTP response instructions for the 402 settlement failure response\n */\n private async buildSettlementFailureResponse(\n failure: Omit,\n transportContext?: HTTPTransportContext,\n ): Promise {\n const settlementHeaders = failure.headers;\n const routeConfig = transportContext\n ? this.getRouteConfig(transportContext.request.path, transportContext.request.method)\n : undefined;\n\n const customBody = routeConfig?.settlementFailedResponseBody\n ? await routeConfig.settlementFailedResponseBody(transportContext!.request, failure)\n : undefined;\n\n const contentType = customBody ? customBody.contentType : \"application/json\";\n const body = customBody ? customBody.body : {};\n\n return {\n status: 402,\n headers: {\n \"Content-Type\": contentType,\n ...settlementHeaders,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n };\n }\n\n /**\n * Normalizes a RouteConfig's accepts field into an array of PaymentOptions\n * Handles both single PaymentOption and array formats\n *\n * @param routeConfig - Route configuration\n * @returns Array of payment options\n */\n private normalizePaymentOptions(routeConfig: RouteConfig): PaymentOption[] {\n return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];\n }\n\n /**\n * Validates that all payment options in routes have corresponding registered schemes\n * and facilitator support.\n *\n * @returns Array of validation errors (empty if all routes are valid)\n */\n private validateRouteConfiguration(): RouteValidationError[] {\n const errors: RouteValidationError[] = [];\n\n // Normalize routes to array of [pattern, config] pairs\n const normalizedRoutes =\n typeof this.routesConfig === \"object\" && !(\"accepts\" in this.routesConfig)\n ? Object.entries(this.routesConfig as Record)\n : [[\"*\", this.routesConfig as RouteConfig] as [string, RouteConfig]];\n\n for (const [pattern, config] of normalizedRoutes) {\n const paymentOptions = this.normalizePaymentOptions(config);\n\n for (const option of paymentOptions) {\n // Check 1: Is scheme registered?\n if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_scheme\",\n message: `Route \"${pattern}\": No scheme implementation registered for \"${option.scheme}\" on network \"${option.network}\"`,\n });\n // Skip facilitator check if scheme isn't registered\n continue;\n }\n\n // Check 2: Does facilitator support this scheme/network combination?\n const supportedKind = this.ResourceServer.getSupportedKind(\n x402Version,\n option.network,\n option.scheme,\n );\n\n if (!supportedKind) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_facilitator\",\n message: `Route \"${pattern}\": Facilitator does not support scheme \"${option.scheme}\" on network \"${option.network}\"`,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get route configuration for a request\n *\n * @param path - Request path\n * @param method - HTTP method\n * @returns Route configuration or undefined if no match\n */\n private getRouteConfig(path: string, method: string): RouteConfig | undefined {\n const normalizedPath = this.normalizePath(path);\n const upperMethod = method.toUpperCase();\n\n const matchingRoute = this.compiledRoutes.find(\n route =>\n route.regex.test(normalizedPath) && (route.verb === \"*\" || route.verb === upperMethod),\n );\n\n return matchingRoute?.config;\n }\n\n /**\n * Extract payment from HTTP headers (handles v1 and v2)\n *\n * @param adapter - HTTP adapter\n * @returns Decoded payment payload or null\n */\n private extractPayment(adapter: HTTPAdapter): PaymentPayload | null {\n // Check v2 header first (PAYMENT-SIGNATURE)\n const header = adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"PAYMENT-SIGNATURE\");\n\n if (header) {\n try {\n return decodePaymentSignatureHeader(header);\n } catch (error) {\n console.warn(\"Failed to decode PAYMENT-SIGNATURE header:\", error);\n }\n }\n\n return null;\n }\n\n /**\n * Check if request is from a web browser\n *\n * @param adapter - HTTP adapter\n * @returns True if request appears to be from a browser\n */\n private isWebBrowser(adapter: HTTPAdapter): boolean {\n const accept = adapter.getAcceptHeader();\n const userAgent = adapter.getUserAgent();\n return accept.includes(\"text/html\") && userAgent.includes(\"Mozilla\");\n }\n\n /**\n * Create HTTP response instructions from payment required\n *\n * @param paymentRequired - Payment requirements\n * @param isWebBrowser - Whether request is from browser\n * @param paywallConfig - Paywall configuration\n * @param customHtml - Custom HTML template\n * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests\n * @returns Response instructions\n */\n private createHTTPResponse(\n paymentRequired: PaymentRequired,\n isWebBrowser: boolean,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n unpaidResponse?: HTTPResponseBody,\n ): HTTPResponseInstructions {\n // Use 412 Precondition Failed for permit2_allowance_required error\n // This signals client needs to approve Permit2 before retrying\n const status = paymentRequired.error === \"permit2_allowance_required\" ? 412 : 402;\n\n if (isWebBrowser) {\n const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);\n return {\n status,\n headers: { \"Content-Type\": \"text/html\" },\n body: html,\n isHtml: true,\n };\n }\n\n const response = this.createHTTPPaymentRequiredResponse(paymentRequired);\n\n // Use callback result if provided, otherwise default to JSON with empty object\n const contentType = unpaidResponse ? unpaidResponse.contentType : \"application/json\";\n const body = unpaidResponse ? unpaidResponse.body : {};\n\n return {\n status,\n headers: {\n \"Content-Type\": contentType,\n ...response.headers,\n },\n body,\n };\n }\n\n /**\n * Create HTTP payment required response (v1 puts in body, v2 puts in header)\n *\n * @param paymentRequired - Payment required object\n * @returns Headers and body for the HTTP response\n */\n private createHTTPPaymentRequiredResponse(paymentRequired: PaymentRequired): {\n headers: Record;\n } {\n return {\n headers: {\n \"PAYMENT-REQUIRED\": encodePaymentRequiredHeader(paymentRequired),\n },\n };\n }\n\n /**\n * Create settlement response headers\n *\n * @param settleResponse - Settlement response\n * @returns Headers to add to response\n */\n private createSettlementHeaders(settleResponse: SettleResponse): Record {\n const encoded = encodePaymentResponseHeader(settleResponse);\n return { \"PAYMENT-RESPONSE\": encoded };\n }\n\n /**\n * Parse route pattern into verb and regex\n *\n * @param pattern - Route pattern like \"GET /api/*\", \"/api/[id]\", or \"/api/:id\"\n * @returns Parsed pattern with verb and regex\n */\n private parseRoutePattern(pattern: string): { verb: string; regex: RegExp } {\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n\n const regex = new RegExp(\n `^${\n path\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\") // Escape regex special chars\n .replace(/\\*/g, \".*?\") // Wildcards\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Parameters (Next.js style [param])\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, \"[^/]+\") // Parameters (Express style :param)\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n );\n\n return { verb: verb.toUpperCase(), regex };\n }\n\n /**\n * Normalize path for matching\n *\n * @param path - Raw path from request\n * @returns Normalized path\n */\n private normalizePath(path: string): string {\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n let decodedOrRawPath: string;\n try {\n decodedOrRawPath = decodeURIComponent(pathWithoutQuery);\n } catch {\n decodedOrRawPath = pathWithoutQuery;\n }\n\n return decodedOrRawPath\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/(.+?)\\/+$/, \"$1\");\n }\n\n /**\n * Generate paywall HTML for browser requests\n *\n * @param paymentRequired - Payment required response\n * @param paywallConfig - Optional paywall configuration\n * @param customHtml - Optional custom HTML template\n * @returns HTML string\n */\n private generatePaywallHTML(\n paymentRequired: PaymentRequired,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n ): string {\n if (customHtml) {\n return customHtml;\n }\n\n // Use custom paywall provider if set\n if (this.paywallProvider) {\n return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);\n }\n\n // Try to use @x402/paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@x402/paywall\");\n const displayAmount = this.getDisplayAmount(paymentRequired);\n const resource = paymentRequired.resource;\n\n return paywall.getPaywallHtml({\n amount: displayAmount,\n paymentRequired,\n currentUrl: resource?.url || paywallConfig?.currentUrl || \"\",\n testnet: paywallConfig?.testnet ?? true,\n appName: paywallConfig?.appName,\n appLogo: paywallConfig?.appLogo,\n sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint,\n });\n } catch {\n // @x402/paywall not installed, fall back to basic HTML\n }\n\n // Fallback: Basic HTML paywall\n const resource = paymentRequired.resource;\n const displayAmount = this.getDisplayAmount(paymentRequired);\n\n return `\n \n \n \n Payment Required\n \n \n \n \n
\n ${paywallConfig?.appLogo ? `\"${paywallConfig.appName` : \"\"}\n

Payment Required

\n ${resource ? `

Resource: ${resource.description || resource.url}

` : \"\"}\n

Amount: $${displayAmount.toFixed(2)} USDC

\n
\n \n

\n Note: Install @x402/paywall for full wallet connection and payment UI.\n

\n
\n
\n \n \n `;\n }\n\n /**\n * Extract display amount from payment requirements.\n *\n * @param paymentRequired - The payment required object\n * @returns The display amount in decimal format\n */\n private getDisplayAmount(paymentRequired: PaymentRequired): number {\n const accepts = paymentRequired.accepts;\n if (accepts && accepts.length > 0) {\n const firstReq = accepts[0];\n if (\"amount\" in firstReq) {\n // V2 format\n return parseFloat(firstReq.amount) / 1000000; // Assuming USDC with 6 decimals\n }\n }\n return 0;\n }\n}\n","import { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport {\n VerifyResponse,\n SettleResponse,\n SupportedResponse,\n VerifyError,\n SettleError,\n} from \"../types/facilitator\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://x402.org/facilitator\";\n\nexport interface FacilitatorConfig {\n url?: string;\n createAuthHeaders?: () => Promise<{\n verify: Record;\n settle: Record;\n supported: Record;\n }>;\n}\n\n/**\n * Interface for facilitator clients\n * Can be implemented for HTTP-based or local facilitators\n */\nexport interface FacilitatorClient {\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Get supported payment kinds and extensions from the facilitator\n *\n * @returns Supported payment kinds and extensions\n */\n getSupported(): Promise;\n}\n\n/** Number of retries for getSupported() on 429 rate limit errors */\nconst GET_SUPPORTED_RETRIES = 3;\n/** Base delay in ms for exponential backoff on retries */\nconst GET_SUPPORTED_RETRY_DELAY_MS = 1000;\n\n/**\n * HTTP-based client for interacting with x402 facilitator services\n * Handles HTTP communication with facilitator endpoints\n */\nexport class HTTPFacilitatorClient implements FacilitatorClient {\n readonly url: string;\n private readonly _createAuthHeaders?: FacilitatorConfig[\"createAuthHeaders\"];\n\n /**\n * Creates a new HTTPFacilitatorClient instance.\n *\n * @param config - Configuration options for the facilitator client\n */\n constructor(config?: FacilitatorConfig) {\n this.url = config?.url || DEFAULT_FACILITATOR_URL;\n this._createAuthHeaders = config?.createAuthHeaders;\n }\n\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n async verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"verify\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/verify`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n const verifyResponse = data as VerifyResponse;\n if (!response.ok) {\n throw new VerifyError(response.status, verifyResponse);\n }\n return verifyResponse;\n }\n\n throw new Error(`Facilitator verify failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n async settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"settle\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/settle`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n const settleResponse = data as SettleResponse;\n if (!response.ok) {\n throw new SettleError(response.status, settleResponse);\n }\n return settleResponse;\n }\n\n throw new Error(`Facilitator settle failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Get supported payment kinds and extensions from the facilitator.\n * Retries with exponential backoff on 429 rate limit errors.\n *\n * @returns Supported payment kinds and extensions\n */\n async getSupported(): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"supported\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {\n const response = await fetch(`${this.url}/supported`, {\n method: \"GET\",\n headers,\n });\n\n if (response.ok) {\n return (await response.json()) as SupportedResponse;\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(`Facilitator getSupported failed (${response.status}): ${errorText}`);\n\n // Retry on 429 rate limit errors with exponential backoff\n if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {\n const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n throw lastError;\n }\n\n throw lastError ?? new Error(\"Facilitator getSupported failed after retries\");\n }\n\n /**\n * Creates authentication headers for a specific path.\n *\n * @param path - The path to create authentication headers for (e.g., \"verify\", \"settle\", \"supported\")\n * @returns An object containing the authentication headers for the specified path\n */\n async createAuthHeaders(path: string): Promise<{\n headers: Record;\n }> {\n if (this._createAuthHeaders) {\n const authHeaders = (await this._createAuthHeaders()) as Record<\n string,\n Record\n >;\n return {\n headers: authHeaders[path] ?? {},\n };\n }\n return {\n headers: {},\n };\n }\n\n /**\n * Helper to convert objects to JSON-safe format.\n * Handles BigInt and other non-JSON types.\n *\n * @param obj - The object to convert\n * @returns The JSON-safe representation of the object\n */\n private toJsonSafe(obj: unknown): unknown {\n return JSON.parse(\n JSON.stringify(obj, (_, value) => (typeof value === \"bigint\" ? value.toString() : value)),\n );\n }\n}\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client } from \"../client/x402Client\";\n\n/**\n * Context provided to onPaymentRequired hooks.\n */\nexport interface PaymentRequiredContext {\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return headers to try before payment, or void to proceed directly to payment.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<{ headers: Record } | void>;\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n private paymentRequiredHooks: PaymentRequiredHook[] = [];\n\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Register a hook to handle 402 responses before payment.\n * Hooks run in order; first to return headers wins.\n *\n * @param hook - The hook function to register\n * @returns This instance for chaining\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Run hooks and return headers if any hook provides them.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Headers to use for retry, or null to proceed to payment\n */\n async handlePaymentRequired(\n paymentRequired: PaymentRequired,\n ): Promise | null> {\n for (const hook of this.paymentRequiredHooks) {\n const result = await hook({ paymentRequired });\n if (result?.headers) {\n return result.headers;\n }\n }\n return null;\n }\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequired): Promise {\n return this.client.createPaymentPayload(paymentRequired);\n }\n}\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(paymentResponse: SettleResponse): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPTransportContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n HTTPResponseBody,\n SettlementFailedResponseBody,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n ProtectedRequestHook,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { x402HTTPClient, PaymentRequiredContext, PaymentRequiredHook } from \"./x402HTTPClient\";\n","import { x402Version } from \"..\";\nimport { SchemeNetworkClient } from \"../types/mechanisms\";\nimport { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport { Network, PaymentRequired } from \"../types\";\nimport { findByNetworkAndScheme, findSchemesByNetwork } from \"../utils\";\n\n/**\n * Client Hook Context Interfaces\n */\n\nexport interface PaymentCreationContext {\n paymentRequired: PaymentRequired;\n selectedRequirements: PaymentRequirements;\n}\n\nexport interface PaymentCreatedContext extends PaymentCreationContext {\n paymentPayload: PaymentPayload;\n}\n\nexport interface PaymentCreationFailureContext extends PaymentCreationContext {\n error: Error;\n}\n\n/**\n * Client Hook Type Definitions\n */\n\nexport type BeforePaymentCreationHook = (\n context: PaymentCreationContext,\n) => Promise;\n\nexport type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise;\n\nexport type OnPaymentCreationFailureHook = (\n context: PaymentCreationFailureContext,\n) => Promise;\n\nexport type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;\n\n/**\n * Extension that can enrich payment payloads on the client side.\n *\n * Client extensions are invoked after the scheme creates the base payment payload\n * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612\n * permit signing) to enrich the payload's extensions data.\n */\nexport interface ClientExtension {\n /**\n * Unique key identifying this extension (e.g., \"eip2612GasSponsoring\").\n * Must match the extension key used in PaymentRequired.extensions.\n */\n key: string;\n\n /**\n * Called after payload creation when the extension key is present in\n * paymentRequired.extensions. Allows the extension to enrich the payload\n * with extension-specific data (e.g., signing an EIP-2612 permit).\n *\n * @param paymentPayload - The payment payload to enrich\n * @param paymentRequired - The original PaymentRequired response\n * @returns The enriched payment payload\n */\n enrichPaymentPayload?: (\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ) => Promise;\n}\n\n/**\n * A policy function that filters or transforms payment requirements.\n * Policies are applied in order before the selector chooses the final option.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of payment requirements to filter/transform\n * @returns Filtered array of payment requirements\n */\nexport type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];\n\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme client implementation for this network\n */\n client: SchemeNetworkClient;\n\n /**\n * The x402 protocol version to use for this scheme\n *\n * @default 2\n */\n x402Version?: number;\n}\n\n/**\n * Configuration options for the fetch wrapper\n */\nexport interface x402ClientConfig {\n /**\n * Array of scheme registrations defining which payment methods are supported\n */\n schemes: SchemeRegistration[];\n\n /**\n * Policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Custom payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n}\n\n/**\n * Core client for managing x402 payment schemes and creating payment payloads.\n *\n * Handles registration of payment schemes, policy-based filtering of payment requirements,\n * and creation of payment payloads based on server requirements.\n */\nexport class x402Client {\n private readonly paymentRequirementsSelector: SelectPaymentRequirements;\n private readonly registeredClientSchemes: Map>> = new Map();\n private readonly policies: PaymentPolicy[] = [];\n private readonly registeredExtensions: Map = new Map();\n\n private beforePaymentCreationHooks: BeforePaymentCreationHook[] = [];\n private afterPaymentCreationHooks: AfterPaymentCreationHook[] = [];\n private onPaymentCreationFailureHooks: OnPaymentCreationFailureHook[] = [];\n\n /**\n * Creates a new x402Client instance.\n *\n * @param paymentRequirementsSelector - Function to select payment requirements from available options\n */\n constructor(paymentRequirementsSelector?: SelectPaymentRequirements) {\n this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version, accepts) => accepts[0]);\n }\n\n /**\n * Creates a new x402Client instance from a configuration object.\n *\n * @param config - The client configuration including schemes, policies, and payment requirements selector\n * @returns A configured x402Client instance\n */\n static fromConfig(config: x402ClientConfig): x402Client {\n const client = new x402Client(config.paymentRequirementsSelector);\n config.schemes.forEach(scheme => {\n if (scheme.x402Version === 1) {\n client.registerV1(scheme.network, scheme.client);\n } else {\n client.register(scheme.network, scheme.client);\n }\n });\n config.policies?.forEach(policy => {\n client.registerPolicy(policy);\n });\n return client;\n }\n\n /**\n * Registers a scheme client for the current x402 version.\n *\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n register(network: Network, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(x402Version, network, client);\n }\n\n /**\n * Registers a scheme client for x402 version 1.\n *\n * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n registerV1(network: string, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(1, network as Network, client);\n }\n\n /**\n * Registers a policy to filter or transform payment requirements.\n *\n * Policies are applied in order after filtering by registered schemes\n * and before the selector chooses the final payment requirement.\n *\n * @param policy - Function to filter/transform payment requirements\n * @returns The x402Client instance for chaining\n *\n * @example\n * ```typescript\n * // Prefer cheaper options\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))\n * );\n *\n * // Prefer specific networks\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => r.network.startsWith('eip155:'))\n * );\n * ```\n */\n registerPolicy(policy: PaymentPolicy): x402Client {\n this.policies.push(policy);\n return this;\n }\n\n /**\n * Registers a client extension that can enrich payment payloads.\n *\n * Extensions are invoked after the scheme creates the base payload and the\n * payload is wrapped with extensions/resource/accepted data. If the extension's\n * key is present in `paymentRequired.extensions`, the extension's\n * `enrichPaymentPayload` hook is called to modify the payload.\n *\n * @param extension - The client extension to register\n * @returns The x402Client instance for chaining\n */\n registerExtension(extension: ClientExtension): x402Client {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Register a hook to execute before payment payload creation.\n * Can abort creation by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client {\n this.beforePaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment payload creation.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client {\n this.afterPaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment payload creation fails.\n * Can recover from failure by returning { recovered: true, payload: PaymentPayload }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client {\n this.onPaymentCreationFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Creates a payment payload based on a PaymentRequired response.\n *\n * Automatically extracts x402Version, resource, and extensions from the PaymentRequired\n * response and constructs a complete PaymentPayload with the accepted requirements.\n *\n * @param paymentRequired - The PaymentRequired response from the server\n * @returns Promise resolving to the complete payment payload\n */\n async createPaymentPayload(\n paymentRequired: PaymentRequired,\n ): Promise {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);\n }\n\n const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);\n\n const context: PaymentCreationContext = {\n paymentRequired,\n selectedRequirements: requirements,\n };\n\n // Execute beforePaymentCreation hooks\n for (const hook of this.beforePaymentCreationHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Payment creation aborted: ${result.reason}`);\n }\n }\n\n try {\n const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);\n if (!schemeNetworkClient) {\n throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);\n }\n\n const partialPayload = await schemeNetworkClient.createPaymentPayload(\n paymentRequired.x402Version,\n requirements,\n { extensions: paymentRequired.extensions },\n );\n\n let paymentPayload: PaymentPayload;\n if (partialPayload.x402Version == 1) {\n paymentPayload = partialPayload as PaymentPayload;\n } else {\n // Merge server-declared extensions with any scheme-provided extensions.\n // Scheme extensions overlay on top (e.g., EIP-2612 info enriches server declaration).\n const mergedExtensions = this.mergeExtensions(\n paymentRequired.extensions,\n partialPayload.extensions,\n );\n\n paymentPayload = {\n x402Version: partialPayload.x402Version,\n payload: partialPayload.payload,\n extensions: mergedExtensions,\n resource: paymentRequired.resource,\n accepted: requirements,\n };\n }\n\n // Enrich payload via registered client extensions (for non-scheme extensions)\n paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);\n\n // Execute afterPaymentCreation hooks\n const createdContext: PaymentCreatedContext = {\n ...context,\n paymentPayload,\n };\n\n for (const hook of this.afterPaymentCreationHooks) {\n await hook(createdContext);\n }\n\n return paymentPayload;\n } catch (error) {\n const failureContext: PaymentCreationFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onPaymentCreationFailure hooks\n for (const hook of this.onPaymentCreationFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.payload;\n }\n }\n\n throw error;\n }\n }\n\n\n\n /**\n * Merges server-declared extensions with scheme-provided extensions.\n * Scheme extensions overlay on top of server extensions at each key,\n * preserving server-provided schema while overlaying scheme-provided info.\n *\n * @param serverExtensions - Extensions declared by the server in the 402 response\n * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)\n * @returns The merged extensions object, or undefined if both inputs are undefined\n */\n private mergeExtensions(\n serverExtensions?: Record,\n schemeExtensions?: Record,\n ): Record | undefined {\n if (!schemeExtensions) return serverExtensions;\n if (!serverExtensions) return schemeExtensions;\n\n const merged = { ...serverExtensions };\n for (const [key, schemeValue] of Object.entries(schemeExtensions)) {\n const serverValue = merged[key];\n if (\n serverValue &&\n typeof serverValue === \"object\" &&\n schemeValue &&\n typeof schemeValue === \"object\"\n ) {\n // Deep merge: scheme info overlays server info, schema preserved\n merged[key] = { ...serverValue as Record, ...schemeValue as Record };\n } else {\n merged[key] = schemeValue;\n }\n }\n return merged;\n }\n\n /**\n * Enriches a payment payload by calling registered extension hooks.\n * For each extension key present in the PaymentRequired response,\n * invokes the corresponding extension's enrichPaymentPayload callback.\n *\n * @param paymentPayload - The payment payload to enrich with extension data\n * @param paymentRequired - The PaymentRequired response containing extension declarations\n * @returns The enriched payment payload with extension data applied\n */\n private async enrichPaymentPayloadWithExtensions(\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ): Promise {\n if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {\n return paymentPayload;\n }\n\n let enriched = paymentPayload;\n for (const [key, extension] of this.registeredExtensions) {\n if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {\n enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);\n }\n }\n\n return enriched;\n }\n\n /**\n * Selects appropriate payment requirements based on registered clients and policies.\n *\n * Selection process:\n * 1. Filter by registered schemes (network + scheme support)\n * 2. Apply all registered policies in order\n * 3. Use selector to choose final requirement\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of available payment requirements\n * @returns The selected payment requirements\n */\n private selectPaymentRequirements(x402Version: number, paymentRequirements: PaymentRequirements[]): PaymentRequirements {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${x402Version}`);\n }\n\n // Step 1: Filter by registered schemes\n const supportedPaymentRequirements = paymentRequirements.filter(requirement => {\n let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);\n if (!clientSchemes) {\n return false;\n }\n\n return clientSchemes.has(requirement.scheme);\n })\n\n if (supportedPaymentRequirements.length === 0) {\n throw new Error(`No network/scheme registered for x402 version: ${x402Version} which comply with the payment requirements. ${JSON.stringify({\n x402Version,\n paymentRequirements,\n x402Versions: Array.from(this.registeredClientSchemes.keys()),\n networks: Array.from(clientSchemesByNetwork.keys()),\n schemes: Array.from(clientSchemesByNetwork.values()).map(schemes => Array.from(schemes.keys())).flat(),\n })}`);\n }\n\n // Step 2: Apply all policies in order\n let filteredRequirements = supportedPaymentRequirements;\n for (const policy of this.policies) {\n filteredRequirements = policy(x402Version, filteredRequirements);\n\n if (filteredRequirements.length === 0) {\n throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version}`);\n }\n }\n\n // Step 3: Use selector to choose final requirement\n return this.paymentRequirementsSelector(x402Version, filteredRequirements);\n }\n\n /**\n * Internal method to register a scheme client.\n *\n * @param x402Version - The x402 protocol version\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n private _registerScheme(x402Version: number, network: Network, client: SchemeNetworkClient): x402Client {\n if (!this.registeredClientSchemes.has(x402Version)) {\n this.registeredClientSchemes.set(x402Version, new Map());\n }\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version)!;\n if (!clientSchemesByNetwork.has(network)) {\n clientSchemesByNetwork.set(network, new Map());\n }\n\n const clientByScheme = clientSchemesByNetwork.get(network)!;\n if (!clientByScheme.has(client.scheme)) {\n clientByScheme.set(client.scheme, client);\n }\n\n return this;\n }\n}\n","/**\n * Payment Pre-Auth Cache\n *\n * Wraps the @x402/fetch SDK with pre-authorization caching.\n * After the first 402 response, caches payment requirements per endpoint.\n * On subsequent requests, pre-signs payment and attaches it to the first\n * request, skipping the 402 round trip (~200ms savings per request).\n *\n * Falls back to normal 402 flow if pre-signed payment is rejected.\n */\n\nimport type { x402Client } from \"@x402/fetch\";\nimport { x402HTTPClient } from \"@x402/fetch\";\n\ntype PaymentRequired = Parameters[\"createPaymentPayload\"]>[0];\n\ninterface CachedEntry {\n paymentRequired: PaymentRequired;\n cachedAt: number;\n}\n\nconst DEFAULT_TTL_MS = 3_600_000; // 1 hour\n\ntype FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise;\n\nexport function createPayFetchWithPreAuth(\n baseFetch: FetchFn,\n client: x402Client,\n ttlMs = DEFAULT_TTL_MS,\n options?: { skipPreAuth?: boolean },\n): FetchFn {\n const httpClient = new x402HTTPClient(client);\n const cache = new Map();\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise => {\n const request = new Request(input, init);\n const urlPath = new URL(request.url).pathname;\n\n // Extract model from request body to create model-specific cache keys.\n // Without this, a cached payment from a paid model (e.g. sonnet) would be\n // incorrectly applied to a free model (nvidia/gpt-oss-120b), causing\n // payment errors even when the server wouldn't charge for the request.\n let requestModel = \"\";\n if (init?.body) {\n try {\n const bodyStr =\n init.body instanceof Uint8Array\n ? new TextDecoder().decode(init.body)\n : typeof init.body === \"string\"\n ? init.body\n : \"\";\n if (bodyStr) {\n const parsed = JSON.parse(bodyStr) as { model?: string };\n requestModel = parsed.model ?? \"\";\n }\n } catch {\n /* not JSON, use empty model */\n }\n }\n const cacheKey = `${urlPath}:${requestModel}`;\n\n // Try pre-auth if we have cached payment requirements\n // Skip for Solana: payments use per-tx blockhashes that expire ~60-90s,\n // making cached requirements useless and causing double charges.\n const cached = !options?.skipPreAuth ? cache.get(cacheKey) : undefined;\n if (cached && Date.now() - cached.cachedAt < ttlMs) {\n try {\n const payload = await client.createPaymentPayload(cached.paymentRequired);\n const headers = httpClient.encodePaymentSignatureHeader(payload);\n const preAuthRequest = request.clone();\n for (const [key, value] of Object.entries(headers)) {\n preAuthRequest.headers.set(key, value);\n }\n const response = await baseFetch(preAuthRequest);\n if (response.status !== 402) {\n return response; // Pre-auth worked — saved ~200ms\n }\n // Pre-auth rejected (params may have changed) — invalidate and fall through\n cache.delete(cacheKey);\n } catch {\n // Pre-auth signing failed — invalidate and fall through\n cache.delete(cacheKey);\n }\n }\n\n // Normal flow: make request, handle 402 if needed\n const clonedRequest = request.clone();\n const response = await baseFetch(request);\n if (response.status !== 402) {\n return response;\n }\n\n // Parse 402 response and cache for future pre-auth\n let paymentRequired: PaymentRequired;\n try {\n const getHeader = (name: string) => response.headers.get(name);\n let body: unknown;\n try {\n const responseText = await Promise.race([\n response.text(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Body read timeout\")), 30_000),\n ),\n ]);\n if (responseText) body = JSON.parse(responseText);\n } catch {\n /* empty body is fine */\n }\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n cache.set(cacheKey, { paymentRequired, cachedAt: Date.now() });\n } catch (error) {\n throw new Error(\n `Failed to parse payment requirements: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n { cause: error },\n );\n }\n\n // Sign payment and retry\n const payload = await client.createPaymentPayload(paymentRequired);\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(payload);\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n return baseFetch(clonedRequest);\n };\n}\n","import type { PaymentPayload } from \"@x402/core/types\";\nimport type { FacilitatorEvmSigner } from \"../signer\";\n\nexport const EIP2612_GAS_SPONSORING_KEY = \"eip2612GasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_KEY = \"erc20ApprovalGasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_VERSION = \"1\" as const;\n\nexport interface Eip2612GasSponsoringInfo {\n [key: string]: unknown;\n from: string;\n asset: string;\n spender: string;\n amount: string;\n nonce: string;\n deadline: string;\n signature: string;\n version: string;\n}\n\nexport interface Erc20ApprovalGasSponsoringInfo {\n [key: string]: unknown;\n from: `0x${string}`;\n asset: `0x${string}`;\n spender: `0x${string}`;\n amount: string;\n signedTransaction: `0x${string}`;\n version: string;\n}\n\n/**\n * A single transaction to be executed by the signer.\n * - `0x${string}`: a pre-signed serialized transaction (broadcast as-is via sendRawTransaction)\n * - `{ to, data, gas? }`: an unsigned call intent (signer signs and broadcasts)\n */\nexport type TransactionRequest =\n | `0x${string}`\n | { to: `0x${string}`; data: `0x${string}`; gas?: bigint };\n\nexport type Erc20ApprovalGasSponsoringSigner = FacilitatorEvmSigner & {\n sendTransactions(transactions: TransactionRequest[]): Promise<`0x${string}`[]>;\n simulateTransactions?(transactions: TransactionRequest[]): Promise;\n};\n\nexport interface Erc20ApprovalGasSponsoringFacilitatorExtension {\n key: typeof ERC20_APPROVAL_GAS_SPONSORING_KEY;\n signer?: Erc20ApprovalGasSponsoringSigner;\n signerForNetwork?: (network: string) => Erc20ApprovalGasSponsoringSigner | undefined;\n}\n\n/**\n * Extracts a typed `info` payload from an extension entry.\n *\n * @param payload - Payment payload containing optional extensions.\n * @param extensionKey - Extension key to extract.\n * @returns The extension `info` object when present; otherwise null.\n */\nfunction _extractInfo(\n payload: PaymentPayload,\n extensionKey: string,\n): Record | null {\n const extensions = payload.extensions;\n if (!extensions) return null;\n const extension = extensions[extensionKey] as { info?: Record } | undefined;\n if (!extension?.info) return null;\n return extension.info;\n}\n\n/**\n * Extracts and validates required EIP-2612 gas sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed EIP-2612 gas sponsoring info when available and complete.\n */\nexport function extractEip2612GasSponsoringInfo(\n payload: PaymentPayload,\n): Eip2612GasSponsoringInfo | null {\n const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.nonce ||\n !info.deadline ||\n !info.signature ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Eip2612GasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of EIP-2612 sponsoring info.\n *\n * @param info - EIP-2612 extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateEip2612GasSponsoringInfo(info: Eip2612GasSponsoringInfo): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n numericPattern.test(info.nonce) &&\n numericPattern.test(info.deadline) &&\n hexPattern.test(info.signature) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Extracts and validates required ERC-20 approval sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed ERC-20 approval sponsoring info when available and complete.\n */\nexport function extractErc20ApprovalGasSponsoringInfo(\n payload: PaymentPayload,\n): Erc20ApprovalGasSponsoringInfo | null {\n const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.signedTransaction ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Erc20ApprovalGasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of ERC-20 approval sponsoring info.\n *\n * @param info - ERC-20 approval extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateErc20ApprovalGasSponsoringInfo(\n info: Erc20ApprovalGasSponsoringInfo,\n): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n hexPattern.test(info.signedTransaction) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Resolves the ERC-20 approval extension signer for a specific network.\n *\n * @param extension - Optional facilitator extension config.\n * @param network - CAIP-2 network identifier.\n * @returns A network-specific signer when available, else the default signer.\n */\nexport function resolveErc20ApprovalExtensionSigner(\n extension: Erc20ApprovalGasSponsoringFacilitatorExtension | undefined,\n network: string,\n): Erc20ApprovalGasSponsoringSigner | undefined {\n if (!extension) return undefined;\n return extension.signerForNetwork?.(network) ?? extension.signer;\n}\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce } from \"../../../utils\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainIdV1(requirements.network as EvmNetworkV1);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Permit2 EIP-712 types for signing PermitWitnessTransferFrom.\n * Must match the exact format expected by the Permit2 contract.\n * Note: Types must be in ALPHABETICAL order after the primary type (TokenPermissions < Witness).\n */\nexport const permit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"Witness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n Witness: [\n { name: \"to\", type: \"address\" },\n { name: \"validAfter\", type: \"uint256\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"name\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"authorizer\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n name: \"authorizationState\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/**\n * EIP-2612 Permit EIP-712 types for signing token.permit().\n */\nexport const eip2612PermitTypes = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * EIP-2612 nonces ABI for querying current nonce.\n */\nexport const eip2612NoncesAbi = [\n {\n type: \"function\",\n name: \"nonces\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** ERC-20 approve(address,uint256) ABI for encoding/decoding approval calldata. */\nexport const erc20ApproveAbi = [\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n] as const;\n\n/** ERC-20 allowance(address,address) ABI for checking spender approval. */\nexport const erc20AllowanceAbi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** Gas limit for a standard ERC-20 approve() transaction. */\nexport const ERC20_APPROVE_GAS_LIMIT = 70_000n;\n\n/** Fallback max fee per gas (1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_FEE_PER_GAS = 1_000_000_000n;\n\n/** Fallback max priority fee per gas (0.1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100_000_000n;\n\n/**\n * Canonical Permit2 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/Uniswap/permit2\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\" as const;\n\n/**\n * x402ExactPermit2Proxy contract address.\n * Vanity address: 0x4020...0001 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0001\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402ExactPermit2ProxyAddress = \"0x402085c248EeA27D92E8b30b2C58ed07f9E20001\" as const;\n\n/**\n * x402UptoPermit2Proxy contract address.\n * Vanity address: 0x4020...0002 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0002\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402UptoPermit2ProxyAddress = \"0x402039b3d6E6BEC5A02c2C9fd937ac17A6940002\" as const;\n\n/**\n * Shared ABI components for the Permit2 witness tuple.\n * Used in both x402ExactPermit2ProxyABI and x402UptoPermit2ProxyABI to keep them in sync.\n * The upto contract's witness struct is identical to exact (both remove 'extra' post-audit).\n */\nconst permit2WitnessABIComponents = [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"validAfter\", type: \"uint256\", internalType: \"uint256\" },\n] as const;\n\n/**\n * x402UptoPermit2Proxy ABI - settle function for upto payment scheme (variable amounts).\n * Updated post-audit: 'extra' removed from witness struct, 'initialize()' removed (now\n * a constructor arg), and error names aligned with x402ExactPermit2Proxy.\n */\nexport const x402UptoPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n\n/**\n * x402ExactPermit2Proxy ABI - settle function for exact payment scheme.\n */\nexport const x402ExactPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n","import { toHex } from \"viem\";\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (network.startsWith(\"eip155:\")) {\n const idStr = network.split(\":\")[1];\n const chainId = parseInt(idStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n return chainId;\n }\n\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\nimport * as Errors from \"../../facilitator/errors\";\nimport {\n diagnoseEip3009SimulationFailure,\n executeTransferWithAuthorization,\n simulateEip3009Transfer,\n} from \"../../facilitator/eip3009-utils\";\n\nexport interface VerifyV1Options {\n /** Run onchain simulation. Defaults to true. */\n simulate?: boolean;\n}\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * If enabled, the facilitator will deploy ERC-4337 smart wallets\n * via EIP-6492 when encountering undeployed contract signatures.\n *\n * @default false\n */\n deployERC4337WithEIP6492?: boolean;\n /**\n * If enabled, simulates transaction before settling. Defaults to false, ie only simulate during verify.\n *\n * @default false\n */\n simulateInSettle?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n deployERC4337WithEIP6492: config?.deployERC4337WithEIP6492 ?? false,\n simulateInSettle: config?.simulateInSettle ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n return this._verify(payload, requirements);\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this._verify(payload, requirements, {\n simulate: this.config.simulateInSettle ?? false,\n });\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? Errors.ErrInvalidScheme,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable (for optional deployment)\n const { address: factoryAddress, data: factoryCalldata } = parseErc6492Signature(\n exactEvmPayload.signature!,\n );\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if configured and needed\n if (\n this.config.deployERC4337WithEIP6492 &&\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment transaction\n await this.signer.waitForTransactionReceipt({ hash: deployTx });\n }\n }\n\n const tx = await executeTransferWithAuthorization(\n this.signer,\n getAddress(requirements.asset),\n exactEvmPayload,\n );\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: Errors.ErrTransactionFailed,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n return {\n success: false,\n errorReason: error instanceof Error ? error.message : Errors.ErrTransactionFailed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n /**\n * Internal verify with optional simulation control.\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @param options - Verification options (e.g. simulate)\n * @returns Promise resolving to verification response\n */\n private async _verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n options?: VerifyV1Options,\n ): Promise {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n const payer = exactEvmPayload.authorization.from;\n let eip6492Deployment:\n | { factoryAddress: `0x${string}`; factoryCalldata: `0x${string}` }\n | undefined;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidScheme,\n payer,\n };\n }\n\n // Get chain configuration\n let chainId: number;\n try {\n chainId = getEvmChainIdV1(payloadV1.network as EvmNetworkV1);\n } catch {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: Errors.ErrMissingEip712Domain,\n payer,\n };\n }\n\n const { name, version } = requirements.extra;\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n // Verify signature (flatten EIP-6492 handling out of catch block)\n let isValid = false;\n try {\n isValid = await this.signer.verifyTypedData({\n address: payer,\n ...permitTypedData,\n signature: exactEvmPayload.signature!,\n });\n } catch {\n isValid = false;\n }\n\n const signature = exactEvmPayload.signature!;\n const sigLen = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n\n // Extract EIP-6492 deployment info (factory address + calldata) if present\n const erc6492Data = parseErc6492Signature(signature);\n const hasDeploymentInfo =\n erc6492Data.address &&\n erc6492Data.data &&\n !isAddressEqual(erc6492Data.address, \"0x0000000000000000000000000000000000000000\");\n\n if (hasDeploymentInfo) {\n eip6492Deployment = {\n factoryAddress: erc6492Data.address!,\n factoryCalldata: erc6492Data.data!,\n };\n }\n\n if (!isValid) {\n const isSmartWallet = sigLen > 130; // 65 bytes = 130 hex chars for EOA\n\n if (!isSmartWallet) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidSignature,\n payer,\n };\n }\n\n const bytecode = await this.signer.getCode({ address: payer });\n const isDeployed = bytecode && bytecode !== \"0x\";\n\n if (!isDeployed && !hasDeploymentInfo) {\n return {\n isValid: false,\n invalidReason: Errors.ErrUndeployedSmartWallet,\n payer,\n };\n }\n }\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrRecipientMismatch,\n payer,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidBeforeExpired,\n payer,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidAfterInFuture,\n payer,\n };\n }\n\n // Verify amount exactly matches requirements\n if (BigInt(exactEvmPayload.authorization.value) !== BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidAuthorizationValue,\n payer,\n };\n }\n\n // Transaction simulation\n if (options?.simulate !== false) {\n const simulationSucceeded = await simulateEip3009Transfer(\n this.signer,\n erc20Address,\n exactEvmPayload,\n eip6492Deployment,\n );\n if (!simulationSucceeded) {\n return diagnoseEip3009SimulationFailure(\n this.signer,\n erc20Address,\n exactEvmPayload,\n requirements,\n requirementsV1.maxAmountRequired,\n );\n }\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n }\n}\n","/**\n * Named error reason constants for the exact EVM facilitator.\n *\n * These strings must be character-for-character identical to the Go constants in\n * go/mechanisms/evm/exact/facilitator/errors.go to maintain cross-SDK parity.\n */\n\nexport const ErrInvalidScheme = \"invalid_exact_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_exact_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_exact_evm_missing_eip712_domain\";\nexport const ErrRecipientMismatch = \"invalid_exact_evm_recipient_mismatch\";\nexport const ErrInvalidSignature = \"invalid_exact_evm_signature\";\nexport const ErrValidBeforeExpired = \"invalid_exact_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture = \"invalid_exact_evm_payload_authorization_valid_after\";\nexport const ErrInvalidAuthorizationValue = \"invalid_exact_evm_authorization_value\";\nexport const ErrUndeployedSmartWallet = \"invalid_exact_evm_payload_undeployed_smart_wallet\";\nexport const ErrTransactionFailed = \"invalid_exact_evm_transaction_failed\";\n\n// EIP-3009 verify errors\nexport const ErrEip3009TokenNameMismatch = \"invalid_exact_evm_token_name_mismatch\";\nexport const ErrEip3009TokenVersionMismatch = \"invalid_exact_evm_token_version_mismatch\";\nexport const ErrEip3009NotSupported = \"invalid_exact_evm_eip3009_not_supported\";\nexport const ErrEip3009NonceAlreadyUsed = \"invalid_exact_evm_nonce_already_used\";\nexport const ErrEip3009InsufficientBalance = \"invalid_exact_evm_insufficient_balance\";\nexport const ErrEip3009SimulationFailed = \"invalid_exact_evm_transaction_simulation_failed\";\n\n// Permit2 verify errors\nexport const ErrPermit2InvalidSpender = \"invalid_permit2_spender\";\nexport const ErrPermit2RecipientMismatch = \"invalid_permit2_recipient_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"permit2_deadline_expired\";\nexport const ErrPermit2NotYetValid = \"permit2_not_yet_valid\";\nexport const ErrPermit2AmountMismatch = \"permit2_amount_mismatch\";\nexport const ErrPermit2TokenMismatch = \"permit2_token_mismatch\";\nexport const ErrPermit2InvalidSignature = \"invalid_permit2_signature\";\nexport const ErrPermit2AllowanceRequired = \"permit2_allowance_required\";\nexport const ErrPermit2SimulationFailed = \"permit2_simulation_failed\";\nexport const ErrPermit2InsufficientBalance = \"permit2_insufficient_balance\";\nexport const ErrPermit2ProxyNotDeployed = \"permit2_proxy_not_deployed\";\n\n// Permit2 settle errors (from contract reverts)\nexport const ErrPermit2InvalidAmount = \"permit2_invalid_amount\";\nexport const ErrPermit2InvalidDestination = \"permit2_invalid_destination\";\nexport const ErrPermit2InvalidOwner = \"permit2_invalid_owner\";\nexport const ErrPermit2PaymentTooEarly = \"permit2_payment_too_early\";\nexport const ErrPermit2InvalidNonce = \"permit2_invalid_nonce\";\nexport const ErrPermit2612AmountMismatch = \"permit2_2612_amount_mismatch\";\n\n// ERC-20 approval gas sponsoring verify errors\nexport const ErrErc20ApprovalInsufficientEthForGas = \"erc20_approval_insufficient_eth_for_gas\";\nexport const ErrErc20ApprovalInvalidFormat = \"invalid_erc20_approval_extension_format\";\nexport const ErrErc20ApprovalFromMismatch = \"erc20_approval_from_mismatch\";\nexport const ErrErc20ApprovalAssetMismatch = \"erc20_approval_asset_mismatch\";\nexport const ErrErc20ApprovalSpenderNotPermit2 = \"erc20_approval_spender_not_permit2\";\nexport const ErrErc20ApprovalTxWrongTarget = \"erc20_approval_tx_wrong_target\";\nexport const ErrErc20ApprovalTxWrongSelector = \"erc20_approval_tx_wrong_selector\";\nexport const ErrErc20ApprovalTxWrongSpender = \"erc20_approval_tx_wrong_spender\";\nexport const ErrErc20ApprovalTxInvalidCalldata = \"erc20_approval_tx_invalid_calldata\";\nexport const ErrErc20ApprovalTxSignerMismatch = \"erc20_approval_tx_signer_mismatch\";\nexport const ErrErc20ApprovalTxInvalidSignature = \"erc20_approval_tx_invalid_signature\";\nexport const ErrErc20ApprovalTxParseFailed = \"erc20_approval_tx_parse_failed\";\nexport const ErrErc20ApprovalTxFailed = \"erc20_approval_tx_failed\";\n\n// EIP-2612 gas sponsoring verify errors\nexport const ErrInvalidEip2612ExtensionFormat = \"invalid_eip2612_extension_format\";\nexport const ErrEip2612FromMismatch = \"eip2612_from_mismatch\";\nexport const ErrEip2612AssetMismatch = \"eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderNotPermit2 = \"eip2612_spender_not_permit2\";\nexport const ErrEip2612DeadlineExpired = \"eip2612_deadline_expired\";\n\n// Shared settle errors\nexport const ErrUnsupportedPayloadType = \"unsupported_payload_type\";\nexport const ErrInvalidTransactionState = \"invalid_transaction_state\";\n","import { PaymentRequirements, VerifyResponse } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress, Hex, parseErc6492Signature, parseSignature } from \"viem\";\nimport { eip3009ABI } from \"../../constants\";\nimport { multicall, ContractCall, RawContractCall } from \"../../multicall\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport * as Errors from \"./errors\";\n\nexport interface Eip6492Deployment {\n factoryAddress: `0x${string}`;\n factoryCalldata: `0x${string}`;\n}\n\n/**\n * Simulates transferWithAuthorization via eth_call.\n * Returns true if simulation succeeded, false if it failed.\n *\n * @param signer - EVM signer for contract reads\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param eip6492Deployment - Optional EIP-6492 factory info for undeployed smart wallets\n *\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulateEip3009Transfer(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n eip6492Deployment?: Eip6492Deployment,\n): Promise {\n const auth = payload.authorization;\n const transferArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (eip6492Deployment) {\n const { signature: innerSignature } = parseErc6492Signature(payload.signature!);\n const transferCalldata = encodeFunctionData({\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, innerSignature],\n });\n\n try {\n const results = await multicall(signer.readContract.bind(signer), [\n {\n address: getAddress(eip6492Deployment.factoryAddress),\n callData: eip6492Deployment.factoryCalldata,\n } satisfies RawContractCall,\n {\n address: erc20Address,\n callData: transferCalldata,\n } satisfies RawContractCall,\n ]);\n\n return results[1]?.status === \"success\";\n } catch {\n return false;\n }\n }\n\n const sig = payload.signature!;\n const sigLength = sig.startsWith(\"0x\") ? sig.length - 2 : sig.length;\n const isECDSA = sigLength === 130;\n\n try {\n if (isECDSA) {\n const parsedSig = parseSignature(sig);\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...transferArgs,\n (parsedSig.v as number | undefined) ?? parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, sig],\n });\n }\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * After simulation fails, runs a single diagnostic multicall to determine the most specific error reason.\n * Checks balanceOf, name, version and authorizationState in one RPC round-trip.\n *\n * @param signer - EVM signer used for the payment\n * @param erc20Address - Address of the ERC-20 token contract\n * @param payload - The EIP-3009 transfer authorization payload\n * @param requirements - Payment requirements to validate against\n * @param amountRequired - Required amount for the payment (balance check)\n *\n * @returns Promise resolving to the verification result with validity and optional invalid reason\n */\nexport async function diagnoseEip3009SimulationFailure(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n requirements: PaymentRequirements,\n amountRequired: string,\n): Promise {\n const payer = payload.authorization.from;\n\n const diagnosticCalls: ContractCall[] = [\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payload.authorization.from],\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"name\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"version\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"authorizationState\",\n args: [payload.authorization.from, payload.authorization.nonce],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [balanceResult, nameResult, versionResult, authStateResult] = results;\n\n if (authStateResult.status === \"failure\") {\n return { isValid: false, invalidReason: Errors.ErrEip3009NotSupported, payer };\n }\n\n if (authStateResult.status === \"success\" && authStateResult.result === true) {\n return { isValid: false, invalidReason: Errors.ErrEip3009NonceAlreadyUsed, payer };\n }\n\n if (\n nameResult.status === \"success\" &&\n requirements.extra?.name &&\n nameResult.result !== requirements.extra.name\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenNameMismatch, payer };\n }\n\n if (\n versionResult.status === \"success\" &&\n requirements.extra?.version &&\n versionResult.result !== requirements.extra.version\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenVersionMismatch, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrEip3009InsufficientBalance,\n payer,\n };\n }\n }\n } catch {\n // Diagnostic multicall failed — fall through to generic error\n }\n\n return { isValid: false, invalidReason: Errors.ErrEip3009SimulationFailed, payer };\n}\n\n/**\n * Executes transferWithAuthorization onchain.\n *\n * @param signer - EVM signer for contract writes\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n *\n * @returns Transaction hash\n */\nexport async function executeTransferWithAuthorization(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n): Promise {\n const { signature } = parseErc6492Signature(payload.signature!);\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n const auth = payload.authorization;\n const baseArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (isECDSA) {\n const parsedSig = parseSignature(signature);\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...baseArgs,\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n }\n\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...baseArgs, signature],\n });\n}\n","import { encodeFunctionData, decodeFunctionResult } from \"viem\";\n\n/**\n * Multicall3 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/mds1/multicall\n */\nexport const MULTICALL3_ADDRESS = \"0xcA11bde05977b3631167028862bE2a173976CA11\" as const;\n\n/** Multicall3 getEthBalance ABI for querying native token balance. */\nexport const multicall3GetEthBalanceAbi = [\n {\n name: \"getEthBalance\",\n inputs: [{ name: \"addr\", type: \"address\" }],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/** Multicall3 tryAggregate ABI for batching calls. */\nconst multicall3ABI = [\n {\n inputs: [\n { name: \"requireSuccess\", type: \"bool\" },\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n name: \"tryAggregate\",\n outputs: [\n {\n name: \"returnData\",\n type: \"tuple[]\",\n components: [\n { name: \"success\", type: \"bool\" },\n { name: \"returnData\", type: \"bytes\" },\n ],\n },\n ],\n stateMutability: \"payable\",\n type: \"function\",\n },\n] as const;\n\nexport type ContractCall = {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n};\n\nexport type RawContractCall = {\n address: `0x${string}`;\n callData: `0x${string}`;\n};\n\nexport type MulticallSuccess = { status: \"success\"; result: unknown };\nexport type MulticallFailure = { status: \"failure\"; error: Error };\nexport type MulticallResult = MulticallSuccess | MulticallFailure;\n\n/**\n * Batches contract calls via Multicall3 `tryAggregate(false, ...)`.\n *\n * Accepts a mix of typed ContractCall (ABI-encoded + decoded) and\n * RawContractCall (pre-encoded calldata, no decoding) entries.\n * Raw calls are useful for the EIP-6492 factory deployment case\n * where calldata is pre-encoded with no ABI available.\n */\ntype ReadContractFn = (args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n}) => Promise;\n\n/**\n * Executes multiple contract read calls in a single RPC round-trip using Multicall3.\n *\n * @param readContract - Function that performs a single contract read (e.g. viem readContract)\n * @param calls - Array of contract calls to batch (ContractCall or RawContractCall)\n * @returns A promise that resolves to an array of decoded results, one per call\n */\nexport async function multicall(\n readContract: ReadContractFn,\n calls: ReadonlyArray,\n): Promise {\n const aggregateCalls = calls.map(call => {\n if (\"callData\" in call) {\n return { target: call.address, callData: call.callData };\n }\n const callData = encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args as unknown[],\n });\n return { target: call.address, callData };\n });\n\n const rawResults = (await readContract({\n address: MULTICALL3_ADDRESS,\n abi: multicall3ABI,\n functionName: \"tryAggregate\",\n args: [false, aggregateCalls],\n })) as { success: boolean; returnData: `0x${string}` }[];\n\n return rawResults.map((raw, i) => {\n if (!raw.success) {\n return {\n status: \"failure\" as const,\n error: new Error(`multicall: call reverted (returnData: ${raw.returnData})`),\n };\n }\n\n const call = calls[i];\n if (\"callData\" in call) {\n return { status: \"success\" as const, result: undefined };\n }\n\n try {\n const decoded = decodeFunctionResult({\n abi: call.abi,\n functionName: call.functionName,\n data: raw.returnData,\n });\n return { status: \"success\" as const, result: decoded };\n } catch (err) {\n return {\n status: \"failure\" as const,\n error: err instanceof Error ? err : new Error(String(err)),\n };\n }\n });\n}\n","export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const EVM_NETWORK_CHAIN_ID_MAP = {\n ethereum: 1,\n sepolia: 11155111,\n abstract: 2741,\n \"abstract-testnet\": 11124,\n \"base-sepolia\": 84532,\n base: 8453,\n \"avalanche-fuji\": 43113,\n avalanche: 43114,\n iotex: 4689,\n sei: 1329,\n \"sei-testnet\": 1328,\n polygon: 137,\n \"polygon-amoy\": 80002,\n peaq: 3338,\n story: 1514,\n educhain: 41923,\n \"skale-base-sepolia\": 324705682,\n megaeth: 4326,\n monad: 143,\n} as const;\n\nexport type EvmNetworkV1 = keyof typeof EVM_NETWORK_CHAIN_ID_MAP;\n\nexport const NETWORKS: string[] = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);\n\n/**\n * Extract chain ID from a v1 legacy network name.\n *\n * @param network - The v1 network name (e.g., \"base-sepolia\", \"polygon\")\n * @returns The numeric chain ID\n * @throws Error if the network name is not a known v1 network\n */\nexport function getEvmChainIdV1(network: string): number {\n const chainId = EVM_NETWORK_CHAIN_ID_MAP[network as EvmNetworkV1];\n if (!chainId) {\n throw new Error(`Unsupported v1 network: ${network}`);\n }\n return chainId;\n}\n","import {\n SchemeNetworkClient,\n PaymentRequirements,\n PaymentPayloadResult,\n PaymentPayloadContext,\n} from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { AssetTransferMethod } from \"../../types\";\nimport { PERMIT2_ADDRESS, erc20AllowanceAbi } from \"../../constants\";\nimport { getAddress } from \"viem\";\nimport { getEvmChainId } from \"../../utils\";\nimport { EIP2612_GAS_SPONSORING_KEY, ERC20_APPROVAL_GAS_SPONSORING_KEY } from \"../extensions\";\nimport { createEIP3009Payload } from \"./eip3009\";\nimport { createPermit2Payload } from \"./permit2\";\nimport { signEip2612Permit } from \"./eip2612\";\nimport { signErc20ApprovalTransaction } from \"./erc20approval\";\nimport { ExactEvmSchemeOptions, resolveExtensionRpcCapabilities } from \"./rpc\";\n\n/**\n * EVM client implementation for the Exact payment scheme.\n * Supports both EIP-3009 (transferWithAuthorization) and Permit2 flows.\n *\n * Routes to the appropriate authorization method based on\n * `requirements.extra.assetTransferMethod`. Defaults to EIP-3009\n * for backward compatibility with older facilitators.\n *\n * When the server advertises `eip2612GasSponsoring` and the asset transfer\n * method is `permit2`, the scheme automatically signs an EIP-2612 permit\n * if the user lacks Permit2 approval. This requires `readContract` on the signer.\n */\nexport class ExactEvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClient instance.\n *\n * @param signer - The EVM signer for client operations.\n * Base flow only requires `address` + `signTypedData`.\n * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally\n * requires optional capabilities like `readContract` and tx signing helpers.\n * @param options - Optional RPC configuration used to backfill extension capabilities.\n */\n constructor(\n private readonly signer: ClientEvmSigner,\n private readonly options?: ExactEvmSchemeOptions,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.\n *\n * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the\n * signer supports `readContract`, automatically signs an EIP-2612 permit\n * when Permit2 allowance is insufficient.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @param context - Optional context with server-declared extensions\n * @returns Promise resolving to a payment payload result (with optional extensions)\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n context?: PaymentPayloadContext,\n ): Promise {\n const assetTransferMethod =\n (paymentRequirements.extra?.assetTransferMethod as AssetTransferMethod) ?? \"eip3009\";\n\n if (assetTransferMethod === \"permit2\") {\n const result = await createPermit2Payload(this.signer, x402Version, paymentRequirements);\n\n const eip2612Extensions = await this.trySignEip2612Permit(\n paymentRequirements,\n result,\n context,\n );\n\n if (eip2612Extensions) {\n return {\n ...result,\n extensions: eip2612Extensions,\n };\n }\n\n const erc20Extensions = await this.trySignErc20Approval(paymentRequirements, result, context);\n if (erc20Extensions) {\n return {\n ...result,\n extensions: erc20Extensions,\n };\n }\n\n return result;\n }\n\n return createEIP3009Payload(this.signer, x402Version, paymentRequirements);\n }\n\n /**\n * Attempts to sign an EIP-2612 permit for gasless Permit2 approval.\n *\n * Returns extension data if:\n * 1. Server advertises eip2612GasSponsoring\n * 2. Signer has readContract capability\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param result - The payment payload result from the scheme\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for EIP-2612 gas sponsoring, or undefined if not applicable\n */\n private async trySignEip2612Permit(\n requirements: PaymentRequirements,\n result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n const tokenName = requirements.extra?.name as string | undefined;\n const tokenVersion = requirements.extra?.version as string | undefined;\n if (!tokenName || !tokenVersion) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const permit2Auth = result.payload?.permit2Authorization as Record | undefined;\n const deadline =\n (permit2Auth?.deadline as string) ??\n Math.floor(Date.now() / 1000 + requirements.maxTimeoutSeconds).toString();\n\n const info = await signEip2612Permit(\n {\n address: this.signer.address,\n signTypedData: msg => this.signer.signTypedData(msg),\n readContract: capabilities.readContract,\n },\n tokenAddress,\n tokenName,\n tokenVersion,\n chainId,\n deadline,\n requirements.amount,\n );\n\n return {\n [EIP2612_GAS_SPONSORING_KEY]: { info },\n };\n }\n\n /**\n * Attempts to sign an ERC-20 approval transaction for gasless Permit2 approval.\n *\n * This is the fallback path when the token does not support EIP-2612. The client\n * signs (but does not broadcast) a raw `approve(Permit2, MaxUint256)` transaction.\n * The facilitator broadcasts it atomically before settling.\n *\n * Returns extension data if:\n * 1. Server advertises erc20ApprovalGasSponsoring\n * 2. Signer has signTransaction + getTransactionCount capabilities\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param _result - The payment payload result from the scheme (unused)\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for ERC-20 approval gas sponsoring, or undefined if not applicable\n */\n private async trySignErc20Approval(\n requirements: PaymentRequirements,\n _result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n if (!capabilities.signTransaction || !capabilities.getTransactionCount) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const info = await signErc20ApprovalTransaction(\n {\n address: this.signer.address,\n signTransaction: capabilities.signTransaction,\n getTransactionCount: capabilities.getTransactionCount,\n estimateFeesPerGas: capabilities.estimateFeesPerGas,\n },\n tokenAddress,\n chainId,\n );\n\n return {\n [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info },\n };\n }\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport { createNonce, getEvmChainId } from \"../../utils\";\n\n/**\n * Creates an EIP-3009 (transferWithAuthorization) payload.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createEIP3009Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEIP3009Payload[\"authorization\"] = {\n from: signer.address,\n to: getAddress(paymentRequirements.payTo),\n value: paymentRequirements.amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n const signature = await signEIP3009Authorization(signer, authorization, paymentRequirements);\n\n const payload: ExactEIP3009Payload = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the EIP-3009 authorization using EIP-712.\n *\n * @param signer - The EVM signer\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signEIP3009Authorization(\n signer: ClientEvmSigner,\n authorization: ExactEIP3009Payload[\"authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress } from \"viem\";\nimport {\n permit2WitnessTypes,\n PERMIT2_ADDRESS,\n x402ExactPermit2ProxyAddress,\n erc20ApproveAbi,\n erc20AllowanceAbi,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactPermit2Payload } from \"../../types\";\nimport { createPermit2Nonce, getEvmChainId } from \"../../utils\";\n\n/** Maximum uint256 value for unlimited approval. */\nconst MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\n/**\n * Creates a Permit2 payload using the x402Permit2Proxy witness pattern.\n * The spender is set to x402Permit2Proxy, which enforces that funds\n * can only be sent to the witness.to address.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createPermit2Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const now = Math.floor(Date.now() / 1000);\n const nonce = createPermit2Nonce();\n\n // Lower time bound - allow some clock skew\n const validAfter = (now - 600).toString();\n // Upper time bound is enforced by Permit2's deadline field\n const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();\n\n const permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"] = {\n from: signer.address,\n permitted: {\n token: getAddress(paymentRequirements.asset),\n amount: paymentRequirements.amount,\n },\n spender: x402ExactPermit2ProxyAddress,\n nonce,\n deadline,\n witness: {\n to: getAddress(paymentRequirements.payTo),\n validAfter,\n },\n };\n\n const signature = await signPermit2Authorization(\n signer,\n permit2Authorization,\n paymentRequirements,\n );\n\n const payload: ExactPermit2Payload = {\n signature,\n permit2Authorization,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the Permit2 authorization using EIP-712 with witness data.\n * The signature authorizes the x402Permit2Proxy to transfer tokens on behalf of the signer.\n *\n * @param signer - The EVM signer\n * @param permit2Authorization - The Permit2 authorization parameters\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signPermit2Authorization(\n signer: ClientEvmSigner,\n permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n const domain = {\n name: \"Permit2\",\n chainId,\n verifyingContract: PERMIT2_ADDRESS,\n };\n\n const message = {\n permitted: {\n token: getAddress(permit2Authorization.permitted.token),\n amount: BigInt(permit2Authorization.permitted.amount),\n },\n spender: getAddress(permit2Authorization.spender),\n nonce: BigInt(permit2Authorization.nonce),\n deadline: BigInt(permit2Authorization.deadline),\n witness: {\n to: getAddress(permit2Authorization.witness.to),\n validAfter: BigInt(permit2Authorization.witness.validAfter),\n },\n };\n\n return await signer.signTypedData({\n domain,\n types: permit2WitnessTypes,\n primaryType: \"PermitWitnessTransferFrom\",\n message,\n });\n}\n\n/**\n * Creates transaction data to approve Permit2 to spend tokens.\n * The user sends this transaction (paying gas) before using Permit2 flow.\n *\n * @param tokenAddress - The ERC20 token contract address\n * @returns Transaction data to send for approval\n *\n * @example\n * ```typescript\n * const tx = createPermit2ApprovalTx(\"0x...\");\n * await walletClient.sendTransaction({\n * to: tx.to,\n * data: tx.data,\n * });\n * ```\n */\nexport function createPermit2ApprovalTx(tokenAddress: `0x${string}`): {\n to: `0x${string}`;\n data: `0x${string}`;\n} {\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [PERMIT2_ADDRESS, MAX_UINT256],\n });\n\n return {\n to: getAddress(tokenAddress),\n data,\n };\n}\n\n/**\n * Parameters for checking Permit2 allowance.\n * Application provides these to check if approval is needed.\n */\nexport interface Permit2AllowanceParams {\n tokenAddress: `0x${string}`;\n ownerAddress: `0x${string}`;\n}\n\n/**\n * Returns contract read parameters for checking Permit2 allowance.\n * Use with a public client to check if the user has approved Permit2.\n *\n * @param params - The allowance check parameters\n * @returns Contract read parameters for checking allowance\n *\n * @example\n * ```typescript\n * const readParams = getPermit2AllowanceReadParams({\n * tokenAddress: \"0x...\",\n * ownerAddress: \"0x...\",\n * });\n *\n * const allowance = await publicClient.readContract(readParams);\n * const needsApproval = allowance < requiredAmount;\n * ```\n */\nexport function getPermit2AllowanceReadParams(params: Permit2AllowanceParams): {\n address: `0x${string}`;\n abi: typeof erc20AllowanceAbi;\n functionName: \"allowance\";\n args: [`0x${string}`, `0x${string}`];\n} {\n return {\n address: getAddress(params.tokenAddress),\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [getAddress(params.ownerAddress), PERMIT2_ADDRESS],\n };\n}\n","import { getAddress } from \"viem\";\nimport { eip2612PermitTypes, eip2612NoncesAbi, PERMIT2_ADDRESS } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport type { Eip2612GasSponsoringInfo } from \"../extensions\";\n\nexport type Eip2612PermitSigner = Pick & {\n readContract: NonNullable;\n};\n\n/**\n * Signs an EIP-2612 permit authorizing the Permit2 contract to spend tokens.\n *\n * This creates a gasless off-chain signature that the facilitator can submit\n * on-chain via `x402Permit2Proxy.settleWithPermit()`.\n *\n * The `permittedAmount` must match the Permit2 `permitted.amount` exactly, as the\n * proxy contract enforces `permit2612.value == permittedAmount`.\n *\n * @param signer - The client EVM signer (must support readContract for nonce query)\n * @param tokenAddress - The ERC-20 token contract address\n * @param tokenName - The token name (from paymentRequirements.extra.name)\n * @param tokenVersion - The token version (from paymentRequirements.extra.version)\n * @param chainId - The chain ID\n * @param deadline - The deadline for the permit (unix timestamp as string)\n * @param permittedAmount - The Permit2 permitted amount (must match exactly)\n * @returns The EIP-2612 gas sponsoring info object\n */\nexport async function signEip2612Permit(\n signer: Eip2612PermitSigner,\n tokenAddress: `0x${string}`,\n tokenName: string,\n tokenVersion: string,\n chainId: number,\n deadline: string,\n permittedAmount: string,\n): Promise {\n const owner = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Query the current EIP-2612 nonce from the token contract\n const nonce = (await signer.readContract({\n address: tokenAddress,\n abi: eip2612NoncesAbi,\n functionName: \"nonces\",\n args: [owner],\n })) as bigint;\n\n // Construct EIP-712 domain for the token's permit function\n const domain = {\n name: tokenName,\n version: tokenVersion,\n chainId,\n verifyingContract: tokenAddress,\n };\n\n const approvalAmount = BigInt(permittedAmount);\n\n const message = {\n owner,\n spender,\n value: approvalAmount,\n nonce,\n deadline: BigInt(deadline),\n };\n\n // Sign the EIP-2612 permit\n const signature = await signer.signTypedData({\n domain,\n types: eip2612PermitTypes,\n primaryType: \"Permit\",\n message,\n });\n\n return {\n from: owner,\n asset: tokenAddress,\n spender,\n amount: approvalAmount.toString(),\n nonce: nonce.toString(),\n deadline,\n signature,\n version: \"1\",\n };\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport {\n PERMIT2_ADDRESS,\n erc20ApproveAbi,\n ERC20_APPROVE_GAS_LIMIT,\n DEFAULT_MAX_FEE_PER_GAS,\n DEFAULT_MAX_PRIORITY_FEE_PER_GAS,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport {\n ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n type Erc20ApprovalGasSponsoringInfo,\n} from \"../extensions\";\n\nexport type Erc20ApprovalTxSigner = Pick & {\n signTransaction: NonNullable;\n getTransactionCount: NonNullable;\n estimateFeesPerGas?: NonNullable;\n};\n\n/**\n * Signs an EIP-1559 `approve(Permit2, MaxUint256)` transaction for the given token.\n *\n * The signed transaction is NOT broadcast here — the facilitator broadcasts it\n * atomically before settling the Permit2 payment. This enables Permit2 payments\n * for generic ERC-20 tokens that do NOT implement EIP-2612.\n *\n * Always approves MaxUint256 regardless of the payment amount.\n *\n * @param signer - The client EVM signer (must support signTransaction, getTransactionCount)\n * @param tokenAddress - The ERC-20 token contract address\n * @param chainId - The chain ID\n * @returns The ERC-20 approval gas sponsoring info object\n */\nexport async function signErc20ApprovalTransaction(\n signer: Erc20ApprovalTxSigner,\n tokenAddress: `0x${string}`,\n chainId: number,\n): Promise {\n const from = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Encode approve(PERMIT2_ADDRESS, MaxUint256) calldata\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [spender, maxUint256],\n });\n\n // Get current nonce for the sender\n const nonce = await signer.getTransactionCount({ address: from });\n\n // Get current fee estimates, with fallback values\n let maxFeePerGas: bigint;\n let maxPriorityFeePerGas: bigint;\n try {\n const fees = await signer.estimateFeesPerGas?.();\n if (!fees) {\n throw new Error(\"no fee estimates available\");\n }\n maxFeePerGas = fees.maxFeePerGas;\n maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n } catch {\n maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;\n maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;\n }\n\n // Sign the EIP-1559 transaction (not broadcast)\n const signedTransaction = await signer.signTransaction({\n to: tokenAddress,\n data,\n nonce,\n gas: ERC20_APPROVE_GAS_LIMIT,\n maxFeePerGas,\n maxPriorityFeePerGas,\n chainId,\n });\n\n return {\n from,\n asset: tokenAddress,\n spender,\n amount: maxUint256.toString(),\n signedTransaction,\n version: ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n };\n}\n","import { createPublicClient, http } from \"viem\";\nimport type { ClientEvmSigner } from \"../../signer\";\nimport { getEvmChainId } from \"../../utils\";\n\nexport type ExactEvmSchemeConfig = {\n rpcUrl?: string;\n};\n\nexport type ExactEvmSchemeConfigByChainId = Record;\n\nexport type ExactEvmSchemeOptions = ExactEvmSchemeConfig | ExactEvmSchemeConfigByChainId;\n\ntype ExtensionRpcCapabilities = Pick<\n ClientEvmSigner,\n \"readContract\" | \"signTransaction\" | \"getTransactionCount\" | \"estimateFeesPerGas\"\n>;\n\nconst rpcClientCache = new Map>();\n\n/**\n * Determines whether scheme options are keyed by numeric chain id.\n *\n * @param options - Exact EVM scheme options provided by the client.\n * @returns True when options are a chainId-to-config mapping.\n */\nfunction isConfigByChainId(\n options: ExactEvmSchemeOptions,\n): options is ExactEvmSchemeConfigByChainId {\n const keys = Object.keys(options);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n\n/**\n * Returns a cached viem public client for a specific RPC URL.\n *\n * @param rpcUrl - The RPC endpoint URL used to construct the client.\n * @returns A cached or newly created viem public client instance.\n */\nfunction getRpcClient(rpcUrl: string): ReturnType {\n const existing = rpcClientCache.get(rpcUrl);\n if (existing) {\n return existing;\n }\n\n const client = createPublicClient({\n transport: http(rpcUrl),\n });\n rpcClientCache.set(rpcUrl, client);\n return client;\n}\n\n/**\n * Resolves the RPC URL for a given CAIP-2 network from scheme options.\n *\n * @param network - CAIP-2 network identifier.\n * @param options - Optional scheme configuration (single config or chain map).\n * @returns The configured RPC URL for the network, if available.\n */\nexport function resolveRpcUrl(\n network: string,\n options?: ExactEvmSchemeOptions,\n): string | undefined {\n if (!options) {\n return undefined;\n }\n\n if (isConfigByChainId(options)) {\n const chainId = getEvmChainId(network);\n const optionsByChainId = options as ExactEvmSchemeConfigByChainId;\n return optionsByChainId[chainId]?.rpcUrl;\n }\n\n return (options as ExactEvmSchemeConfig).rpcUrl;\n}\n\n/**\n * Resolves extension RPC capabilities from signer methods and optional RPC backfill.\n *\n * @param network - CAIP-2 network identifier for chain resolution.\n * @param signer - Client signer with optional RPC-like methods.\n * @param options - Optional scheme configuration used for RPC backfill.\n * @returns The best available capability set for extension enrichment flows.\n */\nexport function resolveExtensionRpcCapabilities(\n network: string,\n signer: ClientEvmSigner,\n options?: ExactEvmSchemeOptions,\n): ExtensionRpcCapabilities {\n const capabilities: ExtensionRpcCapabilities = {\n signTransaction: signer.signTransaction,\n readContract: signer.readContract,\n getTransactionCount: signer.getTransactionCount,\n estimateFeesPerGas: signer.estimateFeesPerGas,\n };\n\n const needsRpcBackfill =\n !capabilities.readContract ||\n !capabilities.getTransactionCount ||\n !capabilities.estimateFeesPerGas;\n if (!needsRpcBackfill) {\n return capabilities;\n }\n\n const rpcUrl = resolveRpcUrl(network, options);\n if (!rpcUrl) {\n return capabilities;\n }\n const rpcClient = getRpcClient(rpcUrl);\n if (!capabilities.readContract) {\n capabilities.readContract = args => rpcClient.readContract(args as never) as Promise;\n }\n if (!capabilities.getTransactionCount) {\n capabilities.getTransactionCount = async args =>\n rpcClient.getTransactionCount({ address: args.address });\n }\n if (!capabilities.estimateFeesPerGas) {\n capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();\n }\n\n return capabilities;\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeOptions } from \"./rpc\";\nimport { ExactEvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Client\n */\nexport interface EvmClientConfig {\n /**\n * The EVM signer to use for creating payment payloads\n */\n signer: ClientEvmSigner;\n\n /**\n * Optional payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional Exact EVM client scheme options.\n * Supports either a single config ({ rpcUrl }) or per-chain configs\n * keyed by EVM chain ID ({ 8453: { rpcUrl: \"...\" } }).\n */\n schemeOptions?: ExactEvmSchemeOptions;\n\n /**\n * Optional specific networks to register.\n * If not provided, registers wildcard support (eip155:*).\n */\n networks?: Network[];\n}\n\n/**\n * Registers EVM exact payment schemes to an x402Client instance.\n *\n * This function registers:\n * - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for EVM client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@x402/evm/exact/client/register\";\n * import { x402Client } from \"@x402/core/client\";\n * import { privateKeyToAccount } from \"viem/accounts\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const client = new x402Client();\n * registerExactEvmScheme(client, { signer: account });\n * ```\n */\nexport function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client {\n const evmScheme = new ExactEvmScheme(config.signer, config.schemeOptions);\n\n // Register V2 scheme\n // EIP-2612 gas sponsoring is handled internally by the scheme when the\n // server advertises support - no separate extension registration needed.\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach(network => {\n client.register(network, evmScheme);\n });\n } else {\n // Register wildcard for all EVM chains\n client.register(\"eip155:*\", evmScheme);\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactEvmSchemeV1(config.signer));\n });\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * ClientEvmSigner - Used by x402 clients to sign payment authorizations.\n *\n * Typically a viem WalletClient extended with publicActions:\n * ```typescript\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * Or composed via `toClientEvmSigner(account, publicClient)`.\n */\nexport type ClientEvmSigner = {\n readonly address: `0x${string}`;\n signTypedData(message: {\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n }): Promise<`0x${string}`>;\n /**\n * Optional on-chain reads.\n * Required only for extension enrichment (EIP-2612 / ERC-20 approval).\n */\n readContract?(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n /**\n * Optional: Signs a raw EIP-1559 transaction without broadcasting.\n * Required for ERC-20 approval gas sponsoring when the token lacks EIP-2612.\n */\n signTransaction?(args: {\n to: `0x${string}`;\n data: `0x${string}`;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n chainId: number;\n }): Promise<`0x${string}`>;\n /**\n * Optional: Gets the current transaction count (nonce) for an address.\n * Required for ERC-20 approval gas sponsoring.\n */\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n /**\n * Optional: Estimates current gas fees per gas.\n * Required for ERC-20 approval gas sponsoring.\n */\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n};\n\n/**\n * FacilitatorEvmSigner - Used by x402 facilitators to verify and settle payments\n * This is typically a viem PublicClient + WalletClient combination that can\n * read contract state, verify signatures, write transactions, and wait for receipts\n *\n * Supports multiple addresses for load balancing, key rotation, and high availability\n */\nexport type FacilitatorEvmSigner = {\n /**\n * Get all addresses this facilitator can use for signing\n * Enables dynamic address selection for load balancing and key rotation\n */\n getAddresses(): readonly `0x${string}`[];\n\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n verifyTypedData(args: {\n address: `0x${string}`;\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n signature: `0x${string}`;\n }): Promise;\n writeContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n /** Optional gas limit. When provided, skips eth_estimateGas simulation. */\n gas?: bigint;\n }): Promise<`0x${string}`>;\n sendTransaction(args: { to: `0x${string}`; data: `0x${string}` }): Promise<`0x${string}`>;\n waitForTransactionReceipt(args: { hash: `0x${string}` }): Promise<{ status: string }>;\n getCode(args: { address: `0x${string}` }): Promise<`0x${string}` | undefined>;\n};\n\n/**\n * Composes a ClientEvmSigner from a local account and a public client.\n *\n * Use this when your signer (e.g., `privateKeyToAccount`) doesn't have\n * `readContract`. The `publicClient` provides the on-chain read capability.\n *\n * Alternatively, use a WalletClient extended with publicActions directly:\n * ```typescript\n * const signer = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * @param signer - A signer with `address` and `signTypedData` (and optionally `readContract`)\n * @param publicClient - A client with optional read/nonce/fee helpers\n * @param publicClient.readContract - The readContract method from the public client\n * @param publicClient.getTransactionCount - Optional getTransactionCount for ERC-20 approval\n * @param publicClient.estimateFeesPerGas - Optional estimateFeesPerGas for ERC-20 approval\n * @returns A ClientEvmSigner with any available optional capabilities\n *\n * @example\n * ```typescript\n * const account = privateKeyToAccount(\"0x...\");\n * const publicClient = createPublicClient({ chain: baseSepolia, transport: http() });\n * const signer = toClientEvmSigner(account, publicClient);\n * ```\n */\nexport function toClientEvmSigner(\n signer: Omit & {\n readContract?: ClientEvmSigner[\"readContract\"];\n },\n publicClient?: {\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n },\n): ClientEvmSigner {\n const readContract = signer.readContract ?? publicClient?.readContract.bind(publicClient);\n\n const result: ClientEvmSigner = {\n address: signer.address,\n signTypedData: msg => signer.signTypedData(msg),\n };\n\n if (readContract) {\n result.readContract = readContract;\n }\n\n // Forward optional capabilities from signer or publicClient\n const signTransaction = signer.signTransaction;\n if (signTransaction) {\n result.signTransaction = args => signTransaction(args);\n }\n\n const getTransactionCount =\n signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);\n if (getTransactionCount) {\n result.getTransactionCount = args => getTransactionCount(args);\n }\n\n const estimateFeesPerGas =\n signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);\n if (estimateFeesPerGas) {\n result.estimateFeesPerGas = () => estimateFeesPerGas();\n }\n\n return result;\n}\n\n/**\n * Converts a viem client with single address to a FacilitatorEvmSigner\n * Wraps the single address in a getAddresses() function for compatibility\n *\n * @param client - The client to convert (must have 'address' property)\n * @returns FacilitatorEvmSigner with getAddresses() support\n */\nexport function toFacilitatorEvmSigner(\n client: Omit & { address: `0x${string}` },\n): FacilitatorEvmSigner {\n return {\n ...client,\n getAddresses: () => [client.address],\n };\n}\n","/**\n * Rule-Based Classifier (v2 — Weighted Scoring)\n *\n * Scores a request across 14 weighted dimensions and maps the aggregate\n * score to a tier using configurable boundaries. Confidence is calibrated\n * via sigmoid — low confidence triggers the fallback classifier.\n *\n * Handles 70-80% of requests in < 1ms with zero cost.\n */\n\nimport type { Tier, ScoringResult, ScoringConfig } from \"./types.js\";\n\ntype DimensionScore = { name: string; score: number; signal: string | null };\n\n// ─── Dimension Scorers ───\n// Each returns a score in [-1, 1] and an optional signal string.\n\nfunction scoreTokenCount(\n estimatedTokens: number,\n thresholds: { simple: number; complex: number },\n): DimensionScore {\n if (estimatedTokens < thresholds.simple) {\n return { name: \"tokenCount\", score: -1.0, signal: `short (${estimatedTokens} tokens)` };\n }\n if (estimatedTokens > thresholds.complex) {\n return { name: \"tokenCount\", score: 1.0, signal: `long (${estimatedTokens} tokens)` };\n }\n return { name: \"tokenCount\", score: 0, signal: null };\n}\n\nfunction scoreKeywordMatch(\n text: string,\n keywords: string[],\n name: string,\n signalLabel: string,\n thresholds: { low: number; high: number },\n scores: { none: number; low: number; high: number },\n): DimensionScore {\n const matches = keywords.filter((kw) => text.includes(kw.toLowerCase()));\n if (matches.length >= thresholds.high) {\n return {\n name,\n score: scores.high,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n if (matches.length >= thresholds.low) {\n return {\n name,\n score: scores.low,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n return { name, score: scores.none, signal: null };\n}\n\nfunction scoreMultiStep(text: string): DimensionScore {\n const patterns = [/first.*then/i, /step \\d/i, /\\d\\.\\s/];\n const hits = patterns.filter((p) => p.test(text));\n if (hits.length > 0) {\n return { name: \"multiStepPatterns\", score: 0.5, signal: \"multi-step\" };\n }\n return { name: \"multiStepPatterns\", score: 0, signal: null };\n}\n\nfunction scoreQuestionComplexity(prompt: string): DimensionScore {\n const count = (prompt.match(/\\?/g) || []).length;\n if (count > 3) {\n return { name: \"questionComplexity\", score: 0.5, signal: `${count} questions` };\n }\n return { name: \"questionComplexity\", score: 0, signal: null };\n}\n\n/**\n * Score agentic task indicators.\n * Returns agenticScore (0-1) based on keyword matches:\n * - 4+ matches = 1.0 (high agentic)\n * - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)\n * - 1-2 matches = 0.2 (low agentic)\n *\n * Thresholds raised because common keywords were pruned from the list.\n */\nfunction scoreAgenticTask(\n text: string,\n keywords: string[],\n): { dimensionScore: DimensionScore; agenticScore: number } {\n let matchCount = 0;\n const signals: string[] = [];\n\n for (const keyword of keywords) {\n if (text.includes(keyword.toLowerCase())) {\n matchCount++;\n if (signals.length < 3) {\n signals.push(keyword);\n }\n }\n }\n\n // Threshold-based scoring (raised thresholds after keyword pruning)\n if (matchCount >= 4) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 1.0,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 1.0,\n };\n } else if (matchCount >= 3) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.6,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 0.6,\n };\n } else if (matchCount >= 1) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.2,\n signal: `agentic-light (${signals.join(\", \")})`,\n },\n agenticScore: 0.2,\n };\n }\n\n return {\n dimensionScore: { name: \"agenticTask\", score: 0, signal: null },\n agenticScore: 0,\n };\n}\n\n// ─── Main Classifier ───\n\nexport function classifyByRules(\n prompt: string,\n systemPrompt: string | undefined,\n estimatedTokens: number,\n config: ScoringConfig,\n): ScoringResult {\n // Score against user prompt only — system prompts contain boilerplate keywords\n // (tool definitions, skill descriptions, behavioral rules) that dominate scoring\n // and make every request score identically. See GitHub issue #50.\n const userText = prompt.toLowerCase();\n\n // Score all 14 dimensions against user text only\n const dimensions: DimensionScore[] = [\n // Token count uses total estimated tokens (system + user) — context size matters for model selection\n scoreTokenCount(estimatedTokens, config.tokenCountThresholds),\n scoreKeywordMatch(\n userText,\n config.codeKeywords,\n \"codePresence\",\n \"code\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.reasoningKeywords,\n \"reasoningMarkers\",\n \"reasoning\",\n { low: 1, high: 2 },\n { none: 0, low: 0.7, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.technicalKeywords,\n \"technicalTerms\",\n \"technical\",\n { low: 2, high: 4 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.creativeKeywords,\n \"creativeMarkers\",\n \"creative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.simpleKeywords,\n \"simpleIndicators\",\n \"simple\",\n { low: 1, high: 2 },\n { none: 0, low: -1.0, high: -1.0 },\n ),\n scoreMultiStep(userText),\n scoreQuestionComplexity(prompt),\n\n // 6 new dimensions\n scoreKeywordMatch(\n userText,\n config.imperativeVerbs,\n \"imperativeVerbs\",\n \"imperative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.constraintIndicators,\n \"constraintCount\",\n \"constraints\",\n { low: 1, high: 3 },\n { none: 0, low: 0.3, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.outputFormatKeywords,\n \"outputFormat\",\n \"format\",\n { low: 1, high: 2 },\n { none: 0, low: 0.4, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.referenceKeywords,\n \"referenceComplexity\",\n \"references\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.negationKeywords,\n \"negationComplexity\",\n \"negation\",\n { low: 2, high: 3 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.domainSpecificKeywords,\n \"domainSpecificity\",\n \"domain-specific\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.8 },\n ),\n ];\n\n // Score agentic task indicators — user prompt only\n // System prompt describes assistant behavior, not user's intent.\n // e.g. a coding assistant system prompt with \"edit files\" / \"fix bugs\" should NOT\n // force every request into agentic mode.\n const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);\n dimensions.push(agenticResult.dimensionScore);\n const agenticScore = agenticResult.agenticScore;\n\n // Collect signals\n const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);\n\n // Compute weighted score\n const weights = config.dimensionWeights;\n let weightedScore = 0;\n for (const d of dimensions) {\n const w = weights[d.name] ?? 0;\n weightedScore += d.score * w;\n }\n\n // Count reasoning markers for override — only check USER prompt, not system prompt\n // This prevents system prompts with \"step by step\" from triggering REASONING for simple queries\n const reasoningMatches = config.reasoningKeywords.filter((kw) =>\n userText.includes(kw.toLowerCase()),\n );\n\n // Direct reasoning override: 2+ reasoning markers = high confidence REASONING\n if (reasoningMatches.length >= 2) {\n const confidence = calibrateConfidence(\n Math.max(weightedScore, 0.3), // ensure positive for confidence calc\n config.confidenceSteepness,\n );\n return {\n score: weightedScore,\n tier: \"REASONING\",\n confidence: Math.max(confidence, 0.85),\n signals,\n agenticScore,\n dimensions,\n };\n }\n\n // Map weighted score to tier using boundaries\n const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;\n let tier: Tier;\n let distanceFromBoundary: number;\n\n if (weightedScore < simpleMedium) {\n tier = \"SIMPLE\";\n distanceFromBoundary = simpleMedium - weightedScore;\n } else if (weightedScore < mediumComplex) {\n tier = \"MEDIUM\";\n distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);\n } else if (weightedScore < complexReasoning) {\n tier = \"COMPLEX\";\n distanceFromBoundary = Math.min(\n weightedScore - mediumComplex,\n complexReasoning - weightedScore,\n );\n } else {\n tier = \"REASONING\";\n distanceFromBoundary = weightedScore - complexReasoning;\n }\n\n // Calibrate confidence via sigmoid of distance from nearest boundary\n const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);\n\n // If confidence is below threshold → ambiguous\n if (confidence < config.confidenceThreshold) {\n return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };\n }\n\n return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };\n}\n\n/**\n * Sigmoid confidence calibration.\n * Maps distance from tier boundary to [0.5, 1.0] confidence range.\n */\nfunction calibrateConfidence(distance: number, steepness: number): number {\n return 1 / (1 + Math.exp(-steepness * distance));\n}\n","/**\n * Tier → Model Selection\n *\n * Maps a classification tier to the cheapest capable model.\n * Builds RoutingDecision metadata with cost estimates and savings.\n */\n\nimport type { Tier, TierConfig, RoutingDecision } from \"./types.js\";\n\nexport type ModelPricing = {\n inputPrice: number; // per 1M tokens\n outputPrice: number; // per 1M tokens\n};\n\nconst BASELINE_MODEL_ID = \"anthropic/claude-opus-4.6\";\n\n// Hardcoded fallback: Claude Opus 4.6 pricing (per 1M tokens)\n// Used when baseline model not found in dynamic pricing map\nconst BASELINE_INPUT_PRICE = 5.0;\nconst BASELINE_OUTPUT_PRICE = 25.0;\n\n/**\n * Select the primary model for a tier and build the RoutingDecision.\n */\nexport function selectModel(\n tier: Tier,\n confidence: number,\n method: \"rules\" | \"llm\",\n reasoning: string,\n tierConfigs: Record,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n agenticScore?: number,\n): RoutingDecision {\n const tierConfig = tierConfigs[tier];\n const model = tierConfig.primary;\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n const costEstimate = inputCost + outputCost;\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return {\n model,\n tier,\n confidence,\n method,\n reasoning,\n costEstimate,\n baselineCost,\n savings,\n ...(agenticScore !== undefined && { agenticScore }),\n };\n}\n\n/**\n * Get the ordered fallback chain for a tier: [primary, ...fallbacks].\n */\nexport function getFallbackChain(tier: Tier, tierConfigs: Record): string[] {\n const config = tierConfigs[tier];\n return [config.primary, ...config.fallback];\n}\n\n/**\n * Calculate cost for a specific model (used when fallback model is used).\n * Returns updated cost fields for RoutingDecision.\n */\n// Server-side margin applied to all x402 payments (must match blockrun server's MARGIN_PERCENT)\nconst SERVER_MARGIN_PERCENT = 5;\n// Minimum payment enforced by CDP Facilitator (must match blockrun server's MIN_PAYMENT_USD)\nconst MIN_PAYMENT_USD = 0.001;\n\nexport function calculateModelCost(\n model: string,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n): { costEstimate: number; baselineCost: number; savings: number } {\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n // Include server margin + minimum payment to match actual x402 charge\n const costEstimate = Math.max(\n (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100),\n MIN_PAYMENT_USD,\n );\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return { costEstimate, baselineCost, savings };\n}\n\n/**\n * Filter a model list to only those that support tool calling.\n * When hasTools is false, returns the list unchanged.\n * When all models lack tool calling support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByToolCalling(\n models: string[],\n hasTools: boolean,\n supportsToolCalling: (modelId: string) => boolean,\n): string[] {\n if (!hasTools) return models;\n const filtered = models.filter(supportsToolCalling);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to only those that support vision (image inputs).\n * When hasVision is false, returns the list unchanged.\n * When all models lack vision support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByVision(\n models: string[],\n hasVision: boolean,\n supportsVision: (modelId: string) => boolean,\n): string[] {\n if (!hasVision) return models;\n const filtered = models.filter(supportsVision);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to remove user-excluded models.\n * When all models are excluded, returns the full list as a fallback\n * (same safety pattern as filterByToolCalling/filterByVision).\n */\nexport function filterByExcludeList(models: string[], excludeList: Set): string[] {\n if (excludeList.size === 0) return models;\n const filtered = models.filter((m) => !excludeList.has(m));\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Get the fallback chain filtered by context length.\n * Only returns models that can handle the estimated total context.\n *\n * @param tier - The tier to get fallback chain for\n * @param tierConfigs - Tier configurations\n * @param estimatedTotalTokens - Estimated total context (input + output)\n * @param getContextWindow - Function to get context window for a model ID\n * @returns Filtered list of models that can handle the context\n */\nexport function getFallbackChainFiltered(\n tier: Tier,\n tierConfigs: Record,\n estimatedTotalTokens: number,\n getContextWindow: (modelId: string) => number | undefined,\n): string[] {\n const fullChain = getFallbackChain(tier, tierConfigs);\n\n // Filter to models that can handle the context\n const filtered = fullChain.filter((modelId) => {\n const contextWindow = getContextWindow(modelId);\n if (contextWindow === undefined) {\n // Unknown model - include it (let API reject if needed)\n return true;\n }\n // Add 10% buffer for safety\n return contextWindow >= estimatedTotalTokens * 1.1;\n });\n\n // If all models filtered out, return the original chain\n // (let the API error out - better than no options)\n if (filtered.length === 0) {\n return fullChain;\n }\n\n return filtered;\n}\n","/**\n * Router Strategy Registry\n *\n * Pluggable strategy system for request routing.\n * Default: RulesStrategy — identical to the original inline route() logic, <1ms.\n */\n\nimport type { Tier, RoutingDecision, RouterStrategy, RouterOptions } from \"./types.js\";\nimport { classifyByRules } from \"./rules.js\";\nimport { selectModel } from \"./selector.js\";\n\n/**\n * Rules-based routing strategy.\n * Extracted from the original route() in index.ts — logic is identical.\n * Attaches tierConfigs and profile to the decision for downstream use.\n */\nexport class RulesStrategy implements RouterStrategy {\n readonly name = \"rules\";\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ): RoutingDecision {\n const { config, modelPricing } = options;\n\n // Estimate input tokens (~4 chars per token)\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // --- Rule-based classification (runs first to get agenticScore) ---\n const ruleResult = classifyByRules(prompt, systemPrompt, estimatedTokens, config.scoring);\n\n // --- Select tier configs based on routing profile ---\n const { routingProfile } = options;\n let tierConfigs: Record;\n let profileSuffix: string;\n let profile: RoutingDecision[\"profile\"];\n\n if (routingProfile === \"eco\" && config.ecoTiers) {\n tierConfigs = config.ecoTiers;\n profileSuffix = \" | eco\";\n profile = \"eco\";\n } else if (routingProfile === \"premium\" && config.premiumTiers) {\n tierConfigs = config.premiumTiers;\n profileSuffix = \" | premium\";\n profile = \"premium\";\n } else {\n // Auto profile (or undefined): intelligent routing with agentic detection\n const agenticScore = ruleResult.agenticScore ?? 0;\n const isAutoAgentic = agenticScore >= 0.5;\n const isExplicitAgentic = config.overrides.agenticMode ?? false;\n const hasToolsInRequest = options.hasTools ?? false;\n const useAgenticTiers =\n (hasToolsInRequest || isAutoAgentic || isExplicitAgentic) && config.agenticTiers != null;\n tierConfigs = useAgenticTiers ? config.agenticTiers! : config.tiers;\n profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? \" (tools)\" : \"\"}` : \"\";\n profile = useAgenticTiers ? \"agentic\" : \"auto\";\n }\n\n const agenticScoreValue = ruleResult.agenticScore;\n\n // --- Override: large context → force COMPLEX ---\n if (estimatedTokens > config.overrides.maxTokensForceComplex) {\n const decision = selectModel(\n \"COMPLEX\",\n 0.95,\n \"rules\",\n `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n\n // Structured output detection\n const hasStructuredOutput = systemPrompt ? /json|structured|schema/i.test(systemPrompt) : false;\n\n let tier: Tier;\n let confidence: number;\n const method: \"rules\" | \"llm\" = \"rules\";\n let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(\", \")}`;\n\n if (ruleResult.tier !== null) {\n tier = ruleResult.tier;\n confidence = ruleResult.confidence;\n } else {\n // Ambiguous — default to configurable tier (no external API call)\n tier = config.overrides.ambiguousDefaultTier;\n confidence = 0.5;\n reasoning += ` | ambiguous -> default: ${tier}`;\n }\n\n // Apply structured output minimum tier\n if (hasStructuredOutput) {\n const tierRank: Record = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };\n const minTier = config.overrides.structuredOutputMinTier;\n if (tierRank[tier] < tierRank[minTier]) {\n reasoning += ` | upgraded to ${minTier} (structured output)`;\n tier = minTier;\n }\n }\n\n // Add routing profile suffix to reasoning\n reasoning += profileSuffix;\n\n const decision = selectModel(\n tier,\n confidence,\n method,\n reasoning,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n}\n\n// --- Strategy Registry ---\n\nconst registry = new Map();\nregistry.set(\"rules\", new RulesStrategy());\n\nexport function getStrategy(name: string): RouterStrategy {\n const strategy = registry.get(name);\n if (!strategy) {\n throw new Error(`Unknown routing strategy: ${name}`);\n }\n return strategy;\n}\n\nexport function registerStrategy(strategy: RouterStrategy): void {\n registry.set(strategy.name, strategy);\n}\n","/**\n * Default Routing Config\n *\n * All routing parameters as a TypeScript constant.\n * Operators override via openclaw.yaml plugin config.\n *\n * Scoring uses 14 weighted dimensions with sigmoid confidence calibration.\n */\n\nimport type { RoutingConfig } from \"./types.js\";\n\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n version: \"2.0\",\n\n classifier: {\n llmModel: \"google/gemini-2.5-flash\",\n llmMaxTokens: 10,\n llmTemperature: 0,\n promptTruncationChars: 500,\n cacheTtlMs: 3_600_000, // 1 hour\n },\n\n scoring: {\n tokenCountThresholds: { simple: 50, complex: 500 },\n\n // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR\n codeKeywords: [\n // English\n \"function\",\n \"class\",\n \"import\",\n \"def\",\n \"SELECT\",\n \"async\",\n \"await\",\n \"const\",\n \"let\",\n \"var\",\n \"return\",\n \"```\",\n // Chinese\n \"函数\",\n \"类\",\n \"导入\",\n \"定义\",\n \"查询\",\n \"异步\",\n \"等待\",\n \"常量\",\n \"变量\",\n \"返回\",\n // Japanese\n \"関数\",\n \"クラス\",\n \"インポート\",\n \"非同期\",\n \"定数\",\n \"変数\",\n // Russian\n \"функция\",\n \"класс\",\n \"импорт\",\n \"определ\",\n \"запрос\",\n \"асинхронный\",\n \"ожидать\",\n \"константа\",\n \"переменная\",\n \"вернуть\",\n // German\n \"funktion\",\n \"klasse\",\n \"importieren\",\n \"definieren\",\n \"abfrage\",\n \"asynchron\",\n \"erwarten\",\n \"konstante\",\n \"variable\",\n \"zurückgeben\",\n // Spanish\n \"función\",\n \"clase\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"asíncrono\",\n \"esperar\",\n \"constante\",\n \"variable\",\n \"retornar\",\n // Portuguese\n \"função\",\n \"classe\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"assíncrono\",\n \"aguardar\",\n \"constante\",\n \"variável\",\n \"retornar\",\n // Korean\n \"함수\",\n \"클래스\",\n \"가져오기\",\n \"정의\",\n \"쿼리\",\n \"비동기\",\n \"대기\",\n \"상수\",\n \"변수\",\n \"반환\",\n // Arabic\n \"دالة\",\n \"فئة\",\n \"استيراد\",\n \"تعريف\",\n \"استعلام\",\n \"غير متزامن\",\n \"انتظار\",\n \"ثابت\",\n \"متغير\",\n \"إرجاع\",\n ],\n reasoningKeywords: [\n // English\n \"prove\",\n \"theorem\",\n \"derive\",\n \"step by step\",\n \"chain of thought\",\n \"formally\",\n \"mathematical\",\n \"proof\",\n \"logically\",\n // Chinese\n \"证明\",\n \"定理\",\n \"推导\",\n \"逐步\",\n \"思维链\",\n \"形式化\",\n \"数学\",\n \"逻辑\",\n // Japanese\n \"証明\",\n \"定理\",\n \"導出\",\n \"ステップバイステップ\",\n \"論理的\",\n // Russian\n \"доказать\",\n \"докажи\",\n \"доказательств\",\n \"теорема\",\n \"вывести\",\n \"шаг за шагом\",\n \"пошагово\",\n \"поэтапно\",\n \"цепочка рассуждений\",\n \"рассуждени\",\n \"формально\",\n \"математически\",\n \"логически\",\n // German\n \"beweisen\",\n \"beweis\",\n \"theorem\",\n \"ableiten\",\n \"schritt für schritt\",\n \"gedankenkette\",\n \"formal\",\n \"mathematisch\",\n \"logisch\",\n // Spanish\n \"demostrar\",\n \"teorema\",\n \"derivar\",\n \"paso a paso\",\n \"cadena de pensamiento\",\n \"formalmente\",\n \"matemático\",\n \"prueba\",\n \"lógicamente\",\n // Portuguese\n \"provar\",\n \"teorema\",\n \"derivar\",\n \"passo a passo\",\n \"cadeia de pensamento\",\n \"formalmente\",\n \"matemático\",\n \"prova\",\n \"logicamente\",\n // Korean\n \"증명\",\n \"정리\",\n \"도출\",\n \"단계별\",\n \"사고의 연쇄\",\n \"형식적\",\n \"수학적\",\n \"논리적\",\n // Arabic\n \"إثبات\",\n \"نظرية\",\n \"اشتقاق\",\n \"خطوة بخطوة\",\n \"سلسلة التفكير\",\n \"رسمياً\",\n \"رياضي\",\n \"برهان\",\n \"منطقياً\",\n ],\n simpleKeywords: [\n // English\n \"what is\",\n \"define\",\n \"translate\",\n \"hello\",\n \"yes or no\",\n \"capital of\",\n \"how old\",\n \"who is\",\n \"when was\",\n // Chinese\n \"什么是\",\n \"定义\",\n \"翻译\",\n \"你好\",\n \"是否\",\n \"首都\",\n \"多大\",\n \"谁是\",\n \"何时\",\n // Japanese\n \"とは\",\n \"定義\",\n \"翻訳\",\n \"こんにちは\",\n \"はいかいいえ\",\n \"首都\",\n \"誰\",\n // Russian\n \"что такое\",\n \"определение\",\n \"перевести\",\n \"переведи\",\n \"привет\",\n \"да или нет\",\n \"столица\",\n \"сколько лет\",\n \"кто такой\",\n \"когда\",\n \"объясни\",\n // German\n \"was ist\",\n \"definiere\",\n \"übersetze\",\n \"hallo\",\n \"ja oder nein\",\n \"hauptstadt\",\n \"wie alt\",\n \"wer ist\",\n \"wann\",\n \"erkläre\",\n // Spanish\n \"qué es\",\n \"definir\",\n \"traducir\",\n \"hola\",\n \"sí o no\",\n \"capital de\",\n \"cuántos años\",\n \"quién es\",\n \"cuándo\",\n // Portuguese\n \"o que é\",\n \"definir\",\n \"traduzir\",\n \"olá\",\n \"sim ou não\",\n \"capital de\",\n \"quantos anos\",\n \"quem é\",\n \"quando\",\n // Korean\n \"무엇\",\n \"정의\",\n \"번역\",\n \"안녕하세요\",\n \"예 또는 아니오\",\n \"수도\",\n \"누구\",\n \"언제\",\n // Arabic\n \"ما هو\",\n \"تعريف\",\n \"ترجم\",\n \"مرحبا\",\n \"نعم أو لا\",\n \"عاصمة\",\n \"من هو\",\n \"متى\",\n ],\n technicalKeywords: [\n // English\n \"algorithm\",\n \"optimize\",\n \"architecture\",\n \"distributed\",\n \"kubernetes\",\n \"microservice\",\n \"database\",\n \"infrastructure\",\n // Chinese\n \"算法\",\n \"优化\",\n \"架构\",\n \"分布式\",\n \"微服务\",\n \"数据库\",\n \"基础设施\",\n // Japanese\n \"アルゴリズム\",\n \"最適化\",\n \"アーキテクチャ\",\n \"分散\",\n \"マイクロサービス\",\n \"データベース\",\n // Russian\n \"алгоритм\",\n \"оптимизировать\",\n \"оптимизаци\",\n \"оптимизируй\",\n \"архитектура\",\n \"распределённый\",\n \"микросервис\",\n \"база данных\",\n \"инфраструктура\",\n // German\n \"algorithmus\",\n \"optimieren\",\n \"architektur\",\n \"verteilt\",\n \"kubernetes\",\n \"mikroservice\",\n \"datenbank\",\n \"infrastruktur\",\n // Spanish\n \"algoritmo\",\n \"optimizar\",\n \"arquitectura\",\n \"distribuido\",\n \"microservicio\",\n \"base de datos\",\n \"infraestructura\",\n // Portuguese\n \"algoritmo\",\n \"otimizar\",\n \"arquitetura\",\n \"distribuído\",\n \"microsserviço\",\n \"banco de dados\",\n \"infraestrutura\",\n // Korean\n \"알고리즘\",\n \"최적화\",\n \"아키텍처\",\n \"분산\",\n \"마이크로서비스\",\n \"데이터베이스\",\n \"인프라\",\n // Arabic\n \"خوارزمية\",\n \"تحسين\",\n \"بنية\",\n \"موزع\",\n \"خدمة مصغرة\",\n \"قاعدة بيانات\",\n \"بنية تحتية\",\n ],\n creativeKeywords: [\n // English\n \"story\",\n \"poem\",\n \"compose\",\n \"brainstorm\",\n \"creative\",\n \"imagine\",\n \"write a\",\n // Chinese\n \"故事\",\n \"诗\",\n \"创作\",\n \"头脑风暴\",\n \"创意\",\n \"想象\",\n \"写一个\",\n // Japanese\n \"物語\",\n \"詩\",\n \"作曲\",\n \"ブレインストーム\",\n \"創造的\",\n \"想像\",\n // Russian\n \"история\",\n \"рассказ\",\n \"стихотворение\",\n \"сочинить\",\n \"сочини\",\n \"мозговой штурм\",\n \"творческий\",\n \"представить\",\n \"придумай\",\n \"напиши\",\n // German\n \"geschichte\",\n \"gedicht\",\n \"komponieren\",\n \"brainstorming\",\n \"kreativ\",\n \"vorstellen\",\n \"schreibe\",\n \"erzählung\",\n // Spanish\n \"historia\",\n \"poema\",\n \"componer\",\n \"lluvia de ideas\",\n \"creativo\",\n \"imaginar\",\n \"escribe\",\n // Portuguese\n \"história\",\n \"poema\",\n \"compor\",\n \"criativo\",\n \"imaginar\",\n \"escreva\",\n // Korean\n \"이야기\",\n \"시\",\n \"작곡\",\n \"브레인스토밍\",\n \"창의적\",\n \"상상\",\n \"작성\",\n // Arabic\n \"قصة\",\n \"قصيدة\",\n \"تأليف\",\n \"عصف ذهني\",\n \"إبداعي\",\n \"تخيل\",\n \"اكتب\",\n ],\n\n // New dimension keyword lists (multilingual)\n imperativeVerbs: [\n // English\n \"build\",\n \"create\",\n \"implement\",\n \"design\",\n \"develop\",\n \"construct\",\n \"generate\",\n \"deploy\",\n \"configure\",\n \"set up\",\n // Chinese\n \"构建\",\n \"创建\",\n \"实现\",\n \"设计\",\n \"开发\",\n \"生成\",\n \"部署\",\n \"配置\",\n \"设置\",\n // Japanese\n \"構築\",\n \"作成\",\n \"実装\",\n \"設計\",\n \"開発\",\n \"生成\",\n \"デプロイ\",\n \"設定\",\n // Russian\n \"построить\",\n \"построй\",\n \"создать\",\n \"создай\",\n \"реализовать\",\n \"реализуй\",\n \"спроектировать\",\n \"разработать\",\n \"разработай\",\n \"сконструировать\",\n \"сгенерировать\",\n \"сгенерируй\",\n \"развернуть\",\n \"разверни\",\n \"настроить\",\n \"настрой\",\n // German\n \"erstellen\",\n \"bauen\",\n \"implementieren\",\n \"entwerfen\",\n \"entwickeln\",\n \"konstruieren\",\n \"generieren\",\n \"bereitstellen\",\n \"konfigurieren\",\n \"einrichten\",\n // Spanish\n \"construir\",\n \"crear\",\n \"implementar\",\n \"diseñar\",\n \"desarrollar\",\n \"generar\",\n \"desplegar\",\n \"configurar\",\n // Portuguese\n \"construir\",\n \"criar\",\n \"implementar\",\n \"projetar\",\n \"desenvolver\",\n \"gerar\",\n \"implantar\",\n \"configurar\",\n // Korean\n \"구축\",\n \"생성\",\n \"구현\",\n \"설계\",\n \"개발\",\n \"배포\",\n \"설정\",\n // Arabic\n \"بناء\",\n \"إنشاء\",\n \"تنفيذ\",\n \"تصميم\",\n \"تطوير\",\n \"توليد\",\n \"نشر\",\n \"إعداد\",\n ],\n constraintIndicators: [\n // English\n \"under\",\n \"at most\",\n \"at least\",\n \"within\",\n \"no more than\",\n \"o(\",\n \"maximum\",\n \"minimum\",\n \"limit\",\n \"budget\",\n // Chinese\n \"不超过\",\n \"至少\",\n \"最多\",\n \"在内\",\n \"最大\",\n \"最小\",\n \"限制\",\n \"预算\",\n // Japanese\n \"以下\",\n \"最大\",\n \"最小\",\n \"制限\",\n \"予算\",\n // Russian\n \"не более\",\n \"не менее\",\n \"как минимум\",\n \"в пределах\",\n \"максимум\",\n \"минимум\",\n \"ограничение\",\n \"бюджет\",\n // German\n \"höchstens\",\n \"mindestens\",\n \"innerhalb\",\n \"nicht mehr als\",\n \"maximal\",\n \"minimal\",\n \"grenze\",\n \"budget\",\n // Spanish\n \"como máximo\",\n \"al menos\",\n \"dentro de\",\n \"no más de\",\n \"máximo\",\n \"mínimo\",\n \"límite\",\n \"presupuesto\",\n // Portuguese\n \"no máximo\",\n \"pelo menos\",\n \"dentro de\",\n \"não mais que\",\n \"máximo\",\n \"mínimo\",\n \"limite\",\n \"orçamento\",\n // Korean\n \"이하\",\n \"이상\",\n \"최대\",\n \"최소\",\n \"제한\",\n \"예산\",\n // Arabic\n \"على الأكثر\",\n \"على الأقل\",\n \"ضمن\",\n \"لا يزيد عن\",\n \"أقصى\",\n \"أدنى\",\n \"حد\",\n \"ميزانية\",\n ],\n outputFormatKeywords: [\n // English\n \"json\",\n \"yaml\",\n \"xml\",\n \"table\",\n \"csv\",\n \"markdown\",\n \"schema\",\n \"format as\",\n \"structured\",\n // Chinese\n \"表格\",\n \"格式化为\",\n \"结构化\",\n // Japanese\n \"テーブル\",\n \"フォーマット\",\n \"構造化\",\n // Russian\n \"таблица\",\n \"форматировать как\",\n \"структурированный\",\n // German\n \"tabelle\",\n \"formatieren als\",\n \"strukturiert\",\n // Spanish\n \"tabla\",\n \"formatear como\",\n \"estructurado\",\n // Portuguese\n \"tabela\",\n \"formatar como\",\n \"estruturado\",\n // Korean\n \"테이블\",\n \"형식\",\n \"구조화\",\n // Arabic\n \"جدول\",\n \"تنسيق\",\n \"منظم\",\n ],\n referenceKeywords: [\n // English\n \"above\",\n \"below\",\n \"previous\",\n \"following\",\n \"the docs\",\n \"the api\",\n \"the code\",\n \"earlier\",\n \"attached\",\n // Chinese\n \"上面\",\n \"下面\",\n \"之前\",\n \"接下来\",\n \"文档\",\n \"代码\",\n \"附件\",\n // Japanese\n \"上記\",\n \"下記\",\n \"前の\",\n \"次の\",\n \"ドキュメント\",\n \"コード\",\n // Russian\n \"выше\",\n \"ниже\",\n \"предыдущий\",\n \"следующий\",\n \"документация\",\n \"код\",\n \"ранее\",\n \"вложение\",\n // German\n \"oben\",\n \"unten\",\n \"vorherige\",\n \"folgende\",\n \"dokumentation\",\n \"der code\",\n \"früher\",\n \"anhang\",\n // Spanish\n \"arriba\",\n \"abajo\",\n \"anterior\",\n \"siguiente\",\n \"documentación\",\n \"el código\",\n \"adjunto\",\n // Portuguese\n \"acima\",\n \"abaixo\",\n \"anterior\",\n \"seguinte\",\n \"documentação\",\n \"o código\",\n \"anexo\",\n // Korean\n \"위\",\n \"아래\",\n \"이전\",\n \"다음\",\n \"문서\",\n \"코드\",\n \"첨부\",\n // Arabic\n \"أعلاه\",\n \"أدناه\",\n \"السابق\",\n \"التالي\",\n \"الوثائق\",\n \"الكود\",\n \"مرفق\",\n ],\n negationKeywords: [\n // English\n \"don't\",\n \"do not\",\n \"avoid\",\n \"never\",\n \"without\",\n \"except\",\n \"exclude\",\n \"no longer\",\n // Chinese\n \"不要\",\n \"避免\",\n \"从不\",\n \"没有\",\n \"除了\",\n \"排除\",\n // Japanese\n \"しないで\",\n \"避ける\",\n \"決して\",\n \"なしで\",\n \"除く\",\n // Russian\n \"не делай\",\n \"не надо\",\n \"нельзя\",\n \"избегать\",\n \"никогда\",\n \"без\",\n \"кроме\",\n \"исключить\",\n \"больше не\",\n // German\n \"nicht\",\n \"vermeide\",\n \"niemals\",\n \"ohne\",\n \"außer\",\n \"ausschließen\",\n \"nicht mehr\",\n // Spanish\n \"no hagas\",\n \"evitar\",\n \"nunca\",\n \"sin\",\n \"excepto\",\n \"excluir\",\n // Portuguese\n \"não faça\",\n \"evitar\",\n \"nunca\",\n \"sem\",\n \"exceto\",\n \"excluir\",\n // Korean\n \"하지 마\",\n \"피하다\",\n \"절대\",\n \"없이\",\n \"제외\",\n // Arabic\n \"لا تفعل\",\n \"تجنب\",\n \"أبداً\",\n \"بدون\",\n \"باستثناء\",\n \"استبعاد\",\n ],\n domainSpecificKeywords: [\n // English\n \"quantum\",\n \"fpga\",\n \"vlsi\",\n \"risc-v\",\n \"asic\",\n \"photonics\",\n \"genomics\",\n \"proteomics\",\n \"topological\",\n \"homomorphic\",\n \"zero-knowledge\",\n \"lattice-based\",\n // Chinese\n \"量子\",\n \"光子学\",\n \"基因组学\",\n \"蛋白质组学\",\n \"拓扑\",\n \"同态\",\n \"零知识\",\n \"格密码\",\n // Japanese\n \"量子\",\n \"フォトニクス\",\n \"ゲノミクス\",\n \"トポロジカル\",\n // Russian\n \"квантовый\",\n \"фотоника\",\n \"геномика\",\n \"протеомика\",\n \"топологический\",\n \"гомоморфный\",\n \"с нулевым разглашением\",\n \"на основе решёток\",\n // German\n \"quanten\",\n \"photonik\",\n \"genomik\",\n \"proteomik\",\n \"topologisch\",\n \"homomorph\",\n \"zero-knowledge\",\n \"gitterbasiert\",\n // Spanish\n \"cuántico\",\n \"fotónica\",\n \"genómica\",\n \"proteómica\",\n \"topológico\",\n \"homomórfico\",\n // Portuguese\n \"quântico\",\n \"fotônica\",\n \"genômica\",\n \"proteômica\",\n \"topológico\",\n \"homomórfico\",\n // Korean\n \"양자\",\n \"포토닉스\",\n \"유전체학\",\n \"위상\",\n \"동형\",\n // Arabic\n \"كمي\",\n \"ضوئيات\",\n \"جينوميات\",\n \"طوبولوجي\",\n \"تماثلي\",\n ],\n\n // Agentic task keywords - file ops, execution, multi-step, iterative work\n // Pruned: removed overly common words like \"then\", \"first\", \"run\", \"test\", \"build\"\n agenticTaskKeywords: [\n // English - File operations (clearly agentic)\n \"read file\",\n \"read the file\",\n \"look at\",\n \"check the\",\n \"open the\",\n \"edit\",\n \"modify\",\n \"update the\",\n \"change the\",\n \"write to\",\n \"create file\",\n // English - Execution (specific commands only)\n \"execute\",\n \"deploy\",\n \"install\",\n \"npm\",\n \"pip\",\n \"compile\",\n // English - Multi-step patterns (specific only)\n \"after that\",\n \"and also\",\n \"once done\",\n \"step 1\",\n \"step 2\",\n // English - Iterative work\n \"fix\",\n \"debug\",\n \"until it works\",\n \"keep trying\",\n \"iterate\",\n \"make sure\",\n \"verify\",\n \"confirm\",\n // Chinese (keep specific ones)\n \"读取文件\",\n \"查看\",\n \"打开\",\n \"编辑\",\n \"修改\",\n \"更新\",\n \"创建\",\n \"执行\",\n \"部署\",\n \"安装\",\n \"第一步\",\n \"第二步\",\n \"修复\",\n \"调试\",\n \"直到\",\n \"确认\",\n \"验证\",\n // Spanish\n \"leer archivo\",\n \"editar\",\n \"modificar\",\n \"actualizar\",\n \"ejecutar\",\n \"desplegar\",\n \"instalar\",\n \"paso 1\",\n \"paso 2\",\n \"arreglar\",\n \"depurar\",\n \"verificar\",\n // Portuguese\n \"ler arquivo\",\n \"editar\",\n \"modificar\",\n \"atualizar\",\n \"executar\",\n \"implantar\",\n \"instalar\",\n \"passo 1\",\n \"passo 2\",\n \"corrigir\",\n \"depurar\",\n \"verificar\",\n // Korean\n \"파일 읽기\",\n \"편집\",\n \"수정\",\n \"업데이트\",\n \"실행\",\n \"배포\",\n \"설치\",\n \"단계 1\",\n \"단계 2\",\n \"디버그\",\n \"확인\",\n // Arabic\n \"قراءة ملف\",\n \"تحرير\",\n \"تعديل\",\n \"تحديث\",\n \"تنفيذ\",\n \"نشر\",\n \"تثبيت\",\n \"الخطوة 1\",\n \"الخطوة 2\",\n \"إصلاح\",\n \"تصحيح\",\n \"تحقق\",\n ],\n\n // Dimension weights (sum to 1.0)\n dimensionWeights: {\n tokenCount: 0.08,\n codePresence: 0.15,\n reasoningMarkers: 0.18,\n technicalTerms: 0.1,\n creativeMarkers: 0.05,\n simpleIndicators: 0.02, // Reduced from 0.12 to make room for agenticTask\n multiStepPatterns: 0.12,\n questionComplexity: 0.05,\n imperativeVerbs: 0.03,\n constraintCount: 0.04,\n outputFormat: 0.03,\n referenceComplexity: 0.02,\n negationComplexity: 0.01,\n domainSpecificity: 0.02,\n agenticTask: 0.04, // Reduced - agentic signals influence tier selection, not dominate it\n },\n\n // Tier boundaries on weighted score axis\n tierBoundaries: {\n simpleMedium: 0.0,\n mediumComplex: 0.3, // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier\n complexReasoning: 0.5, // Raised from 0.4 - reserve for true reasoning tasks\n },\n\n // Sigmoid steepness for confidence calibration\n confidenceSteepness: 12,\n // Below this confidence → ambiguous (null tier)\n confidenceThreshold: 0.7,\n },\n\n // Auto (balanced) tier configs - current default smart routing\n // Benchmark-tuned 2026-03-16: balancing quality (retention) + latency\n tiers: {\n SIMPLE: {\n primary: \"google/gemini-2.5-flash\", // 1,238ms, IQ 20, 60% retention (best) — fast AND quality\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — smarter fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, strong quality\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context — newest flash-lite\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"openai/gpt-5.4-nano\", // $0.20/$1.25, 1M context\n \"xai/grok-4-fast-non-reasoning\", // 1,143ms, $0.20/$0.50 — fast fallback\n \"free/gpt-oss-120b\", // 1,252ms, FREE fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, $0.60/$3.00 — strong tool use, quality output\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — nearly same IQ, faster + cheaper\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"google/gemini-2.5-flash\", // 1,238ms, 60% retention\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"xai/grok-3-mini\", // 1,202ms, $0.30/$0.50\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-pro\", // 1,609ms, IQ 57 — fast flagship quality\n fallback: [\n \"google/gemini-3-pro-preview\", // 1,352ms, IQ 48 — quality-first fallback\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — fast + smart\n \"xai/grok-4-0709\", // 1,348ms, IQ 41\n \"google/gemini-2.5-pro\", // 1,294ms\n \"anthropic/claude-sonnet-4.6\", // 2,110ms, IQ 52 — quality fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32\n \"google/gemini-2.5-flash\", // 1,238ms, IQ 20 — cheap last resort\n \"openai/gpt-5.4\", // 6,213ms, IQ 57 — slowest but highest quality\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // 1,454ms, $0.20/$0.50\n fallback: [\n \"xai/grok-4-fast-reasoning\", // 1,298ms, $0.20/$0.50\n \"deepseek/deepseek-reasoner\", // 1,454ms, cheap reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Eco tier configs - absolute cheapest (blockrun/eco)\n ecoTiers: {\n SIMPLE: {\n primary: \"free/gpt-oss-120b\", // FREE! $0.00/$0.00\n fallback: [\n \"free/gpt-oss-20b\", // FREE — smaller, faster\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n \"openai/gpt-5.4-nano\", // $0.20/$1.25 — fast nano\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\", // $0.20/$0.50\n ],\n },\n MEDIUM: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n fallback: [\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\",\n \"google/gemini-2.5-flash\",\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n fallback: [\n \"google/gemini-2.5-flash-lite\",\n \"xai/grok-4-0709\",\n \"google/gemini-2.5-flash\",\n \"deepseek/deepseek-chat\",\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // $0.20/$0.50\n fallback: [\"xai/grok-4-fast-reasoning\", \"deepseek/deepseek-reasoner\"],\n },\n },\n\n // Premium tier configs - best quality (blockrun/premium)\n // codex=complex coding, kimi=simple coding, sonnet=reasoning/instructions, opus=architecture/PM/audits\n premiumTiers: {\n SIMPLE: {\n primary: \"moonshot/kimi-k2.5\", // $0.60/$3.00 - good for simple coding\n fallback: [\n \"google/gemini-2.5-flash\", // 60% retention, fast growth\n \"anthropic/claude-haiku-4.5\",\n \"google/gemini-2.5-flash-lite\",\n \"deepseek/deepseek-chat\",\n ],\n },\n MEDIUM: {\n primary: \"openai/gpt-5.3-codex\", // $1.75/$14 - 400K context, 128K output, replaces 5.2\n fallback: [\n \"moonshot/kimi-k2.5\",\n \"google/gemini-2.5-flash\", // 60% retention, good coding capability\n \"google/gemini-2.5-pro\",\n \"xai/grok-4-0709\",\n \"anthropic/claude-sonnet-4.6\",\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-opus-4.6\", // Best quality for complex tasks\n fallback: [\n \"openai/gpt-5.4\", // Newest flagship\n \"openai/gpt-5.3-codex\",\n \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-sonnet-4.6\",\n \"google/gemini-3.1-pro\", // Newest Gemini\n \"google/gemini-3-pro-preview\",\n \"moonshot/kimi-k2.5\",\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms, $3/$15 - best for reasoning/instructions\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms, cheap fast reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Agentic tier configs - models that excel at multi-step autonomous tasks\n agenticTiers: {\n SIMPLE: {\n primary: \"openai/gpt-4o-mini\", // $0.15/$0.60 - best tool compliance at lowest cost\n fallback: [\n \"moonshot/kimi-k2.5\", // 1,646ms, strong tool use quality\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, $0.60/$3.00 - strong tool use, proper function calls\n fallback: [\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"openai/gpt-4o-mini\", // 2,764ms, reliable tool calling\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"deepseek/deepseek-chat\", // 1,431ms\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — best agentic quality\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms — top quality\n \"google/gemini-3.1-pro\", // 1,609ms\n \"xai/grok-4-0709\", // 1,348ms\n \"openai/gpt-5.4\", // 6,213ms — slow but highest quality fallback\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — strong tool use + reasoning\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms\n \"deepseek/deepseek-reasoner\", // 1,454ms\n ],\n },\n },\n\n overrides: {\n maxTokensForceComplex: 100_000,\n structuredOutputMinTier: \"MEDIUM\",\n ambiguousDefaultTier: \"MEDIUM\",\n agenticMode: false,\n },\n};\n","/**\n * Smart Router Entry Point\n *\n * Classifies requests and routes to the cheapest capable model.\n * Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).\n */\n\nimport type { RoutingDecision, RouterOptions } from \"./types.js\";\nimport { getStrategy } from \"./strategy.js\";\n\n/**\n * Route a request to the cheapest capable model.\n * Delegates to the registered \"rules\" strategy by default.\n */\nexport function route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n): RoutingDecision {\n const strategy = getStrategy(\"rules\");\n return strategy.route(prompt, systemPrompt, maxOutputTokens, options);\n}\n\nexport { getStrategy, registerStrategy } from \"./strategy.js\";\nexport {\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n} from \"./selector.js\";\nexport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nexport type {\n RoutingDecision,\n Tier,\n RoutingConfig,\n RouterOptions,\n RouterStrategy,\n} from \"./types.js\";\nexport type { ModelPricing } from \"./selector.js\";\n","/**\n * Usage Logger\n *\n * Logs every LLM request as a JSON line to a daily log file.\n * Files: ~/.openclaw/blockrun/logs/usage-YYYY-MM-DD.jsonl\n *\n * MVP: append-only JSON lines. No rotation, no cleanup.\n * Logging never breaks the request flow — all errors are swallowed.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport type UsageEntry = {\n timestamp: string;\n model: string;\n tier: string;\n cost: number;\n baselineCost: number;\n savings: number; // 0-1 percentage\n latencyMs: number;\n /** Input (prompt) tokens reported by the provider */\n inputTokens?: number;\n /** Output (completion) tokens reported by the provider */\n outputTokens?: number;\n /** Partner service ID (e.g., \"x_users_lookup\") — only set for partner API calls */\n partnerId?: string;\n /** Partner service name (e.g., \"AttentionVC\") — only set for partner API calls */\n service?: string;\n};\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\nlet dirReady = false;\n\nasync function ensureDir(): Promise {\n if (dirReady) return;\n await mkdir(LOG_DIR, { recursive: true });\n dirReady = true;\n}\n\n/**\n * Log a usage entry as a JSON line.\n */\nexport async function logUsage(entry: UsageEntry): Promise {\n try {\n await ensureDir();\n const date = entry.timestamp.slice(0, 10); // YYYY-MM-DD\n const file = join(LOG_DIR, `usage-${date}.jsonl`);\n await appendFile(file, JSON.stringify(entry) + \"\\n\");\n } catch {\n // Never break the request flow\n }\n}\n","/**\n * Usage Statistics Aggregator\n *\n * Reads usage log files and aggregates statistics for terminal display.\n * Supports filtering by date range and provides multiple aggregation views.\n */\n\nimport { readdir, unlink } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type { UsageEntry } from \"./logger.js\";\nimport { VERSION } from \"./version.js\";\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\n\nexport type DailyStats = {\n date: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n avgLatencyMs: number;\n byTier: Record;\n byModel: Record;\n};\n\nexport type AggregatedStats = {\n period: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n savingsPercentage: number;\n avgLatencyMs: number;\n avgCostPerRequest: number;\n byTier: Record;\n byModel: Record;\n dailyBreakdown: DailyStats[];\n entriesWithBaseline: number; // Entries with valid baseline tracking\n};\n\n/**\n * Parse a JSONL log file into usage entries.\n * Handles both old format (without tier/baselineCost) and new format.\n */\nasync function parseLogFile(filePath: string): Promise {\n try {\n const content = await readTextFile(filePath);\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n const entries: UsageEntry[] = [];\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Partial;\n entries.push({\n timestamp: entry.timestamp || new Date().toISOString(),\n model: entry.model || \"unknown\",\n tier: entry.tier || \"UNKNOWN\",\n cost: entry.cost || 0,\n baselineCost: entry.baselineCost || entry.cost || 0,\n savings: entry.savings || 0,\n latencyMs: entry.latencyMs || 0,\n });\n } catch {\n // Skip malformed lines, keep valid ones\n }\n }\n return entries;\n } catch {\n return [];\n }\n}\n\n/**\n * Get list of available log files sorted by date (newest first).\n */\nasync function getLogFiles(): Promise {\n try {\n const files = await readdir(LOG_DIR);\n return files\n .filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\n/**\n * Aggregate stats for a single day.\n */\nfunction aggregateDay(date: string, entries: UsageEntry[]): DailyStats {\n const byTier: Record = {};\n const byModel: Record = {};\n let totalLatency = 0;\n\n for (const entry of entries) {\n // By tier\n if (!byTier[entry.tier]) byTier[entry.tier] = { count: 0, cost: 0 };\n byTier[entry.tier].count++;\n byTier[entry.tier].cost += entry.cost;\n\n // By model\n if (!byModel[entry.model]) byModel[entry.model] = { count: 0, cost: 0 };\n byModel[entry.model].count++;\n byModel[entry.model].cost += entry.cost;\n\n totalLatency += entry.latencyMs;\n }\n\n const totalCost = entries.reduce((sum, e) => sum + e.cost, 0);\n const totalBaselineCost = entries.reduce((sum, e) => sum + e.baselineCost, 0);\n\n return {\n date,\n totalRequests: entries.length,\n totalCost,\n totalBaselineCost,\n totalSavings: totalBaselineCost - totalCost,\n avgLatencyMs: entries.length > 0 ? totalLatency / entries.length : 0,\n byTier,\n byModel,\n };\n}\n\n/**\n * Get aggregated statistics for the last N days.\n */\nexport async function getStats(days: number = 7): Promise {\n const logFiles = await getLogFiles();\n const filesToRead = logFiles.slice(0, days);\n\n const dailyBreakdown: DailyStats[] = [];\n const allByTier: Record = {};\n const allByModel: Record = {};\n let totalRequests = 0;\n let totalCost = 0;\n let totalBaselineCost = 0;\n let totalLatency = 0;\n\n for (const file of filesToRead) {\n const date = file.replace(\"usage-\", \"\").replace(\".jsonl\", \"\");\n const filePath = join(LOG_DIR, file);\n const entries = await parseLogFile(filePath);\n\n if (entries.length === 0) continue;\n\n const dayStats = aggregateDay(date, entries);\n dailyBreakdown.push(dayStats);\n\n totalRequests += dayStats.totalRequests;\n totalCost += dayStats.totalCost;\n totalBaselineCost += dayStats.totalBaselineCost;\n totalLatency += dayStats.avgLatencyMs * dayStats.totalRequests;\n\n // Merge tier stats\n for (const [tier, stats] of Object.entries(dayStats.byTier)) {\n if (!allByTier[tier]) allByTier[tier] = { count: 0, cost: 0 };\n allByTier[tier].count += stats.count;\n allByTier[tier].cost += stats.cost;\n }\n\n // Merge model stats\n for (const [model, stats] of Object.entries(dayStats.byModel)) {\n if (!allByModel[model]) allByModel[model] = { count: 0, cost: 0 };\n allByModel[model].count += stats.count;\n allByModel[model].cost += stats.cost;\n }\n }\n\n // Calculate percentages\n const byTierWithPercentage: Record =\n {};\n for (const [tier, stats] of Object.entries(allByTier)) {\n byTierWithPercentage[tier] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const byModelWithPercentage: Record =\n {};\n for (const [model, stats] of Object.entries(allByModel)) {\n byModelWithPercentage[model] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const totalSavings = totalBaselineCost - totalCost;\n const savingsPercentage = totalBaselineCost > 0 ? (totalSavings / totalBaselineCost) * 100 : 0;\n\n // Count entries with valid baseline tracking (baseline != cost means tracking was active)\n let entriesWithBaseline = 0;\n for (const day of dailyBreakdown) {\n if (day.totalBaselineCost !== day.totalCost) {\n entriesWithBaseline += day.totalRequests;\n }\n }\n\n return {\n period: days === 1 ? \"today\" : `last ${days} days`,\n totalRequests,\n totalCost,\n totalBaselineCost,\n totalSavings,\n savingsPercentage,\n avgLatencyMs: totalRequests > 0 ? totalLatency / totalRequests : 0,\n avgCostPerRequest: totalRequests > 0 ? totalCost / totalRequests : 0,\n byTier: byTierWithPercentage,\n byModel: byModelWithPercentage,\n dailyBreakdown: dailyBreakdown.reverse(), // Oldest first for charts\n entriesWithBaseline, // How many entries have valid baseline tracking\n };\n}\n\n/**\n * Format stats as ASCII table for terminal display.\n */\nexport function formatStatsAscii(stats: AggregatedStats): string {\n const lines: string[] = [];\n\n // Header\n lines.push(\"╔════════════════════════════════════════════════════════════╗\");\n lines.push(`║ ClawRouter by BlockRun v${VERSION}`.padEnd(61) + \"║\");\n lines.push(\"║ Usage Statistics ║\");\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n\n // Summary\n lines.push(`║ Period: ${stats.period.padEnd(49)}║`);\n lines.push(`║ Total Requests: ${stats.totalRequests.toString().padEnd(41)}║`);\n lines.push(`║ Total Cost: $${stats.totalCost.toFixed(4).padEnd(43)}║`);\n lines.push(`║ Baseline Cost (Opus 4.5): $${stats.totalBaselineCost.toFixed(4).padEnd(30)}║`);\n\n // Show savings with note if some entries lack baseline tracking\n const savingsLine = `║ 💰 Total Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(1)}%)`;\n if (stats.entriesWithBaseline < stats.totalRequests && stats.entriesWithBaseline > 0) {\n lines.push(savingsLine.padEnd(61) + \"║\");\n const note = `║ (based on ${stats.entriesWithBaseline}/${stats.totalRequests} tracked requests)`;\n lines.push(note.padEnd(61) + \"║\");\n } else {\n lines.push(savingsLine.padEnd(61) + \"║\");\n }\n lines.push(`║ Avg Latency: ${stats.avgLatencyMs.toFixed(0)}ms`.padEnd(61) + \"║\");\n\n // Tier breakdown\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Routing by Tier: ║\");\n\n // Show all tiers found in data, ordered by known tiers first then others\n const knownTiers = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\", \"DIRECT\"];\n const allTiers = Object.keys(stats.byTier);\n const otherTiers = allTiers.filter((t) => !knownTiers.includes(t));\n const tierOrder = [...knownTiers.filter((t) => stats.byTier[t]), ...otherTiers];\n\n for (const tier of tierOrder) {\n const data = stats.byTier[tier];\n if (data) {\n const bar = \"█\".repeat(Math.min(20, Math.round(data.percentage / 5)));\n const displayTier = tier === \"UNKNOWN\" ? \"OTHER\" : tier;\n const line = `║ ${displayTier.padEnd(10)} ${bar.padEnd(20)} ${data.percentage.toFixed(1).padStart(5)}% (${data.count})`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n // Top models\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Top Models: ║\");\n\n const sortedModels = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 5);\n\n for (const [model, data] of sortedModels) {\n const shortModel = model.length > 25 ? model.slice(0, 22) + \"...\" : model;\n const line = `║ ${shortModel.padEnd(25)} ${data.count.toString().padStart(5)} reqs $${data.cost.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n\n // Daily breakdown (last 7 days)\n if (stats.dailyBreakdown.length > 0) {\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Daily Breakdown: ║\");\n lines.push(\"║ Date Requests Cost Saved ║\");\n\n for (const day of stats.dailyBreakdown.slice(-7)) {\n const saved = day.totalBaselineCost - day.totalCost;\n const line = `║ ${day.date} ${day.totalRequests.toString().padStart(6)} $${day.totalCost.toFixed(4).padStart(8)} $${saved.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n lines.push(\"╚════════════════════════════════════════════════════════════╝\");\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Delete all usage log files, resetting stats to zero.\n */\nexport async function clearStats(): Promise<{ deletedFiles: number }> {\n try {\n const files = await readdir(LOG_DIR);\n const logFiles = files.filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"));\n\n await Promise.all(logFiles.map((f) => unlink(join(LOG_DIR, f))));\n\n return { deletedFiles: logFiles.length };\n } catch {\n return { deletedFiles: 0 };\n }\n}\n","/**\n * Scanner-safe file reading utilities.\n *\n * Uses open() + read() to avoid false positives from openclaw's\n * potential-exfiltration heuristic in bundled output.\n */\n\nimport { open } from \"node:fs/promises\";\nimport { openSync, readSync, closeSync, fstatSync } from \"node:fs\";\n\n/** Read file contents as UTF-8 string (async). */\nexport async function readTextFile(filePath: string): Promise {\n const fh = await open(filePath, \"r\");\n try {\n const size = (await fh.stat()).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const { bytesRead } = await fh.read(buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n await fh.close();\n }\n}\n\n/** Read file contents as UTF-8 string (sync). */\nexport function readTextFileSync(filePath: string): string {\n const fd = openSync(filePath, \"r\");\n try {\n const size = fstatSync(fd).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const bytesRead = readSync(fd, buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n closeSync(fd);\n }\n}\n","/**\n * Single source of truth for version.\n * Reads from package.json at build time via tsup's define.\n */\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\n\n// Read package.json at runtime\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// In dist/, go up one level to find package.json\nconst require = createRequire(import.meta.url);\nconst pkg = require(join(__dirname, \"..\", \"package.json\")) as { version: string };\n\nexport const VERSION = pkg.version;\nexport const USER_AGENT = `clawrouter/${VERSION}`;\n","/**\n * Request Deduplication\n *\n * Prevents double-charging when OpenClaw retries a request after timeout.\n * Tracks in-flight requests and caches completed responses for a short TTL.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedResponse = {\n status: number;\n headers: Record;\n body: Buffer;\n completedAt: number;\n};\n\ntype InflightEntry = {\n resolvers: Array<(result: CachedResponse) => void>;\n};\n\nconst DEFAULT_TTL_MS = 30_000; // 30 seconds\nconst MAX_BODY_SIZE = 1_048_576; // 1MB\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical string regardless of field order.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip OpenClaw-injected timestamps from message content.\n * Format: [DAY YYYY-MM-DD HH:MM TZ] at the start of messages.\n * Example: [SUN 2026-02-07 13:30 PST] Hello world\n *\n * This ensures requests with different timestamps but same content hash identically.\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction stripTimestamps(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stripTimestamps);\n }\n const result: Record = {};\n for (const [key, value] of Object.entries(obj as Record)) {\n if (key === \"content\" && typeof value === \"string\") {\n // Strip timestamp prefix from message content\n result[key] = value.replace(TIMESTAMP_PATTERN, \"\");\n } else {\n result[key] = stripTimestamps(value);\n }\n }\n return result;\n}\n\nexport class RequestDeduplicator {\n private inflight = new Map();\n private completed = new Map();\n private ttlMs: number;\n\n constructor(ttlMs = DEFAULT_TTL_MS) {\n this.ttlMs = ttlMs;\n }\n\n /** Hash request body to create a dedup key. */\n static hash(body: Buffer): string {\n // Canonicalize JSON to ensure consistent hashing regardless of field order.\n // Also strip OpenClaw-injected timestamps so retries with different timestamps\n // still match the same dedup key.\n let content = body;\n try {\n const parsed = JSON.parse(body.toString());\n const stripped = stripTimestamps(parsed);\n const canonical = canonicalize(stripped);\n content = Buffer.from(JSON.stringify(canonical));\n } catch {\n // Not valid JSON, use raw bytes\n }\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 16);\n }\n\n /** Check if a response is cached for this key. */\n getCached(key: string): CachedResponse | undefined {\n const entry = this.completed.get(key);\n if (!entry) return undefined;\n if (Date.now() - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n return undefined;\n }\n return entry;\n }\n\n /** Check if a request with this key is currently in-flight. Returns a promise to wait on. */\n getInflight(key: string): Promise | undefined {\n const entry = this.inflight.get(key);\n if (!entry) return undefined;\n return new Promise((resolve) => {\n entry.resolvers.push(resolve);\n });\n }\n\n /** Mark a request as in-flight. */\n markInflight(key: string): void {\n this.inflight.set(key, {\n resolvers: [],\n });\n }\n\n /** Complete an in-flight request — cache result and notify waiters. */\n complete(key: string, result: CachedResponse): void {\n // Only cache responses within size limit\n if (result.body.length <= MAX_BODY_SIZE) {\n this.completed.set(key, result);\n }\n\n const entry = this.inflight.get(key);\n if (entry) {\n for (const resolve of entry.resolvers) {\n resolve(result);\n }\n this.inflight.delete(key);\n }\n\n this.prune();\n }\n\n /** Remove an in-flight entry on error (don't cache failures).\n * Also rejects any waiters so they can retry independently. */\n removeInflight(key: string): void {\n const entry = this.inflight.get(key);\n if (entry) {\n // Resolve waiters with a sentinel error response so they don't hang forever.\n // Waiters will see a 503 and can retry on their own.\n const errorBody = Buffer.from(\n JSON.stringify({\n error: { message: \"Original request failed, please retry\", type: \"dedup_origin_failed\" },\n }),\n );\n for (const resolve of entry.resolvers) {\n resolve({\n status: 503,\n headers: { \"content-type\": \"application/json\" },\n body: errorBody,\n completedAt: Date.now(),\n });\n }\n this.inflight.delete(key);\n }\n }\n\n /** Prune expired completed entries. */\n private prune(): void {\n const now = Date.now();\n for (const [key, entry] of this.completed) {\n if (now - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n }\n }\n }\n}\n","/**\n * Response Cache for LLM Completions\n *\n * Caches LLM responses by request hash (model + messages + params).\n * Inspired by LiteLLM's caching system. Returns cached responses for\n * identical requests, saving both cost and latency.\n *\n * Features:\n * - TTL-based expiration (default 10 minutes)\n * - LRU eviction when cache is full\n * - Size limits per item (1MB max)\n * - Heap-based expiration tracking for efficient pruning\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedLLMResponse = {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n cachedAt: number;\n expiresAt: number;\n};\n\nexport type ResponseCacheConfig = {\n /** Maximum number of cached responses. Default: 200 */\n maxSize?: number;\n /** Default TTL in seconds. Default: 600 (10 minutes) */\n defaultTTL?: number;\n /** Maximum size per cached item in bytes. Default: 1MB */\n maxItemSize?: number;\n /** Enable/disable cache. Default: true */\n enabled?: boolean;\n};\n\nconst DEFAULT_CONFIG: Required = {\n maxSize: 200,\n defaultTTL: 600,\n maxItemSize: 1_048_576, // 1MB\n enabled: true,\n};\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical hash.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip fields that shouldn't affect cache key:\n * - stream (we handle streaming separately)\n * - timestamps injected by OpenClaw\n * - request IDs\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction normalizeForCache(obj: Record): Record {\n const result: Record = {};\n\n for (const [key, value] of Object.entries(obj)) {\n // Skip fields that don't affect response content\n if ([\"stream\", \"user\", \"request_id\", \"x-request-id\"].includes(key)) {\n continue;\n }\n\n if (key === \"messages\" && Array.isArray(value)) {\n // Strip timestamps from message content\n result[key] = value.map((msg: unknown) => {\n if (typeof msg === \"object\" && msg !== null) {\n const m = msg as Record;\n if (typeof m.content === \"string\") {\n return { ...m, content: m.content.replace(TIMESTAMP_PATTERN, \"\") };\n }\n }\n return msg;\n });\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nexport class ResponseCache {\n private cache = new Map();\n private expirationHeap: Array<{ expiresAt: number; key: string }> = [];\n private config: Required;\n\n // Stats for monitoring\n private stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n };\n\n constructor(config: ResponseCacheConfig = {}) {\n // Filter out undefined values so they don't override defaults\n const filtered = Object.fromEntries(\n Object.entries(config).filter(([, v]) => v !== undefined),\n ) as ResponseCacheConfig;\n this.config = { ...DEFAULT_CONFIG, ...filtered };\n }\n\n /**\n * Generate cache key from request body.\n * Hashes: model + messages + temperature + max_tokens + other params\n */\n static generateKey(body: Buffer | string): string {\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n const normalized = normalizeForCache(parsed);\n const canonical = canonicalize(normalized);\n const keyContent = JSON.stringify(canonical);\n return createHash(\"sha256\").update(keyContent).digest(\"hex\").slice(0, 32);\n } catch {\n // Fallback: hash raw body\n const content = typeof body === \"string\" ? body : body.toString();\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 32);\n }\n }\n\n /**\n * Check if caching is enabled for this request.\n * Respects cache control headers and request params.\n */\n shouldCache(body: Buffer | string, headers?: Record): boolean {\n if (!this.config.enabled) return false;\n\n // Respect Cache-Control: no-cache header\n if (headers?.[\"cache-control\"]?.includes(\"no-cache\")) {\n return false;\n }\n\n // Check for explicit cache disable in body\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n if (parsed.cache === false || parsed.no_cache === true) {\n return false;\n }\n } catch {\n // Not JSON, allow caching\n }\n\n return true;\n }\n\n /**\n * Get cached response if available and not expired.\n */\n get(key: string): CachedLLMResponse | undefined {\n const entry = this.cache.get(key);\n if (!entry) {\n this.stats.misses++;\n return undefined;\n }\n\n // Check expiration\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n this.stats.misses++;\n return undefined;\n }\n\n this.stats.hits++;\n return entry;\n }\n\n /**\n * Cache a response with optional custom TTL.\n */\n set(\n key: string,\n response: {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n },\n ttlSeconds?: number,\n ): void {\n // Don't cache if disabled or maxSize is 0\n if (!this.config.enabled || this.config.maxSize <= 0) return;\n\n // Don't cache if item too large\n if (response.body.length > this.config.maxItemSize) {\n console.log(`[ResponseCache] Skipping cache - item too large: ${response.body.length} bytes`);\n return;\n }\n\n // Don't cache error responses\n if (response.status >= 400) {\n return;\n }\n\n // Evict if at capacity\n if (this.cache.size >= this.config.maxSize) {\n this.evict();\n }\n\n const now = Date.now();\n const ttl = ttlSeconds ?? this.config.defaultTTL;\n const expiresAt = now + ttl * 1000;\n\n const entry: CachedLLMResponse = {\n ...response,\n cachedAt: now,\n expiresAt,\n };\n\n this.cache.set(key, entry);\n this.expirationHeap.push({ expiresAt, key });\n }\n\n /**\n * Evict expired and oldest entries to make room.\n */\n private evict(): void {\n const now = Date.now();\n\n // First pass: remove expired entries\n this.expirationHeap.sort((a, b) => a.expiresAt - b.expiresAt);\n\n while (this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap[0];\n\n // Check if entry still exists and matches\n const entry = this.cache.get(oldest.key);\n if (!entry || entry.expiresAt !== oldest.expiresAt) {\n // Stale heap entry, remove it\n this.expirationHeap.shift();\n continue;\n }\n\n if (oldest.expiresAt <= now) {\n // Expired, remove both\n this.cache.delete(oldest.key);\n this.expirationHeap.shift();\n this.stats.evictions++;\n } else {\n // Not expired, stop\n break;\n }\n }\n\n // Second pass: if still at capacity, evict oldest\n while (this.cache.size >= this.config.maxSize && this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap.shift()!;\n if (this.cache.has(oldest.key)) {\n this.cache.delete(oldest.key);\n this.stats.evictions++;\n }\n }\n }\n\n /**\n * Get cache statistics.\n */\n getStats(): {\n size: number;\n maxSize: number;\n hits: number;\n misses: number;\n evictions: number;\n hitRate: string;\n } {\n const total = this.stats.hits + this.stats.misses;\n const hitRate = total > 0 ? ((this.stats.hits / total) * 100).toFixed(1) + \"%\" : \"0%\";\n\n return {\n size: this.cache.size,\n maxSize: this.config.maxSize,\n hits: this.stats.hits,\n misses: this.stats.misses,\n evictions: this.stats.evictions,\n hitRate,\n };\n }\n\n /**\n * Clear all cached entries.\n */\n clear(): void {\n this.cache.clear();\n this.expirationHeap = [];\n }\n\n /**\n * Check if cache is enabled.\n */\n isEnabled(): boolean {\n return this.config.enabled;\n }\n}\n","/**\n * Typed Error Classes for ClawRouter\n *\n * Provides structured errors for balance-related failures with\n * all necessary information for user-friendly error messages.\n */\n\n/**\n * Thrown when wallet has insufficient USDC balance for a request.\n */\nexport class InsufficientFundsError extends Error {\n readonly code = \"INSUFFICIENT_FUNDS\" as const;\n readonly currentBalanceUSD: string;\n readonly requiredUSD: string;\n readonly walletAddress: string;\n\n constructor(opts: { currentBalanceUSD: string; requiredUSD: string; walletAddress: string }) {\n const msg = [\n `Insufficient balance. Current: ${opts.currentBalanceUSD}, Required: ${opts.requiredUSD}`,\n `Options:`,\n ` 1. Fund wallet: ${opts.walletAddress}`,\n ` 2. Use free model: /model free`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"InsufficientFundsError\";\n this.currentBalanceUSD = opts.currentBalanceUSD;\n this.requiredUSD = opts.requiredUSD;\n this.walletAddress = opts.walletAddress;\n }\n}\n\n/**\n * Thrown when wallet has no USDC balance (or effectively zero).\n */\nexport class EmptyWalletError extends Error {\n readonly code = \"EMPTY_WALLET\" as const;\n readonly walletAddress: string;\n\n constructor(walletAddress: string) {\n const msg = [\n `No USDC balance.`,\n `Options:`,\n ` 1. Fund wallet: ${walletAddress}`,\n ` 2. Use free model: /model free`,\n ` 3. Uninstall: bash ~/.openclaw/extensions/clawrouter/scripts/uninstall.sh`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"EmptyWalletError\";\n this.walletAddress = walletAddress;\n }\n}\n\n/**\n * Type guard to check if an error is InsufficientFundsError.\n */\nexport function isInsufficientFundsError(error: unknown): error is InsufficientFundsError {\n return error instanceof Error && (error as InsufficientFundsError).code === \"INSUFFICIENT_FUNDS\";\n}\n\n/**\n * Type guard to check if an error is EmptyWalletError.\n */\nexport function isEmptyWalletError(error: unknown): error is EmptyWalletError {\n return error instanceof Error && (error as EmptyWalletError).code === \"EMPTY_WALLET\";\n}\n\n/**\n * Type guard to check if an error is a balance-related error.\n */\nexport function isBalanceError(error: unknown): error is InsufficientFundsError | EmptyWalletError {\n return isInsufficientFundsError(error) || isEmptyWalletError(error);\n}\n\n/**\n * Thrown when RPC call fails (network error, node down, etc).\n * Distinguishes infrastructure failures from actual empty wallets.\n */\nexport class RpcError extends Error {\n readonly code = \"RPC_ERROR\" as const;\n readonly originalError: unknown;\n\n constructor(message: string, originalError?: unknown) {\n super(`RPC error: ${message}. Check network connectivity.`);\n this.name = \"RpcError\";\n this.originalError = originalError;\n }\n}\n\n/**\n * Type guard to check if an error is RpcError.\n */\nexport function isRpcError(error: unknown): error is RpcError {\n return error instanceof Error && (error as RpcError).code === \"RPC_ERROR\";\n}\n","/**\n * Balance Monitor for ClawRouter\n *\n * Monitors USDC balance on Base network with intelligent caching.\n * Provides pre-request balance checks to prevent failed payments.\n *\n * Caching Strategy:\n * - TTL: 30 seconds (balance is cached to avoid excessive RPC calls)\n * - Optimistic deduction: after successful payment, subtract estimated cost from cache\n * - Invalidation: on payment failure, immediately refresh from RPC\n */\n\nimport { createPublicClient, http, erc20Abi } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { RpcError } from \"./errors.js\";\n\n/** USDC contract address on Base mainnet */\nconst USDC_BASE = \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\" as const;\n\n/** Cache TTL in milliseconds (30 seconds) */\nconst CACHE_TTL_MS = 30_000;\n\n/** Balance thresholds in USDC smallest unit (6 decimals) */\nexport const BALANCE_THRESHOLDS = {\n /** Low balance warning threshold: $1.00 */\n LOW_BALANCE_MICROS: 1_000_000n,\n /** Effectively zero threshold: $0.0001 (covers dust/rounding) */\n ZERO_THRESHOLD: 100n,\n} as const;\n\n/** Balance information returned by checkBalance() */\nexport type BalanceInfo = {\n /** Raw balance in USDC smallest unit (6 decimals) */\n balance: bigint;\n /** Formatted balance as \"$X.XX\" */\n balanceUSD: string;\n /** True if balance < $1.00 */\n isLow: boolean;\n /** True if balance < $0.0001 (effectively zero) */\n isEmpty: boolean;\n /** Wallet address for funding instructions */\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SufficiencyResult = {\n /** True if balance >= estimated cost */\n sufficient: boolean;\n /** Current balance info */\n info: BalanceInfo;\n /** If insufficient, the shortfall as \"$X.XX\" */\n shortfall?: string;\n};\n\n/**\n * Monitors USDC balance on Base network.\n *\n * Usage:\n * const monitor = new BalanceMonitor(\"0x...\");\n * const info = await monitor.checkBalance();\n * if (info.isLow) console.warn(\"Low balance!\");\n */\nexport class BalanceMonitor {\n private readonly client;\n private readonly walletAddress: `0x${string}`;\n\n /** Cached balance (null = not yet fetched) */\n private cachedBalance: bigint | null = null;\n /** Timestamp when cache was last updated */\n private cachedAt = 0;\n\n constructor(walletAddress: string) {\n this.walletAddress = walletAddress as `0x${string}`;\n this.client = createPublicClient({\n chain: base,\n transport: http(undefined, {\n timeout: 10_000, // 10 second timeout to prevent hanging on slow RPC\n }),\n });\n }\n\n /**\n * Check current USDC balance.\n * Uses cache if valid, otherwise fetches from RPC.\n */\n async checkBalance(): Promise {\n const now = Date.now();\n\n // Use cache only when balance is positive and still fresh.\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n if (\n this.cachedBalance !== null &&\n this.cachedBalance > 0n &&\n now - this.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(this.cachedBalance);\n }\n\n // Fetch from RPC\n const balance = await this.fetchBalance();\n if (balance > 0n) {\n this.cachedBalance = balance;\n this.cachedAt = now;\n }\n\n return this.buildInfo(balance);\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n *\n * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals)\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSDC(shortfall),\n };\n }\n\n /**\n * Optimistically deduct estimated cost from cached balance.\n * Call this after a successful payment to keep cache accurate.\n *\n * @param amountMicros - Amount to deduct in USDC smallest unit\n */\n deductEstimated(amountMicros: bigint): void {\n if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {\n this.cachedBalance -= amountMicros;\n }\n }\n\n /**\n * Invalidate cache, forcing next checkBalance() to fetch from RPC.\n * Call this after a payment failure to get accurate balance.\n */\n invalidate(): void {\n this.cachedBalance = null;\n this.cachedAt = 0;\n }\n\n /**\n * Force refresh balance from RPC (ignores cache).\n */\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n /**\n * Format USDC amount (in micros) as \"$X.XX\".\n */\n formatUSDC(amountMicros: bigint): string {\n // USDC has 6 decimals\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n /**\n * Get the wallet address being monitored.\n */\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n /** Fetch balance from RPC */\n private async fetchBalance(): Promise {\n try {\n const balance = await this.client.readContract({\n address: USDC_BASE,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [this.walletAddress],\n });\n return balance;\n } catch (error) {\n // Throw typed error instead of silently returning 0\n // This allows callers to distinguish \"node down\" from \"wallet empty\"\n throw new RpcError(error instanceof Error ? error.message : \"Unknown error\", error);\n }\n }\n\n /** Build BalanceInfo from raw balance */\n private buildInfo(balance: bigint): BalanceInfo {\n return {\n balance,\n balanceUSD: this.formatUSDC(balance),\n isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,\n isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD,\n walletAddress: this.walletAddress,\n };\n }\n}\n","/**\n * BlockRun Auth Methods for OpenClaw\n *\n * Provides wallet-based authentication for the BlockRun provider.\n * Operators configure their wallet private key, which is used to\n * sign x402 micropayments for LLM inference.\n *\n * Three methods:\n * 1. Auto-generate — create a new wallet on first run, save to ~/.openclaw/blockrun/wallet.key\n * 2. Environment variable — read from BLOCKRUN_WALLET_KEY\n * 3. Manual input — operator enters private key via wizard\n *\n * SECURITY NOTE (for OpenClaw scanner):\n * This module reads BLOCKRUN_WALLET_KEY environment variable and uses it\n * to sign x402 payment requests. This is INTENTIONAL and REQUIRED behavior:\n * - The wallet key signs USDC payments on Base L2 for each LLM API call\n * - Without the key, ClawRouter cannot authorize payments to BlockRun\n * - The key is NEVER transmitted over the network, only used locally for signing\n * - This is standard x402 payment flow, not credential harvesting\n *\n * @see https://x402.org - x402 payment protocol specification\n * @see https://blockrun.ai/docs - BlockRun API documentation\n * @openclaw-security env-access=BLOCKRUN_WALLET_KEY purpose=x402-payment-signing\n */\n\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport type { ProviderAuthMethod, ProviderAuthContext, ProviderAuthResult } from \"./types.js\";\nimport {\n generateWalletMnemonic,\n isValidMnemonic,\n deriveSolanaKeyBytes,\n deriveAllKeys,\n getSolanaAddress,\n} from \"./wallet.js\";\n\nconst WALLET_DIR = join(homedir(), \".openclaw\", \"blockrun\");\nconst WALLET_FILE = join(WALLET_DIR, \"wallet.key\");\nconst MNEMONIC_FILE = join(WALLET_DIR, \"mnemonic\");\nconst CHAIN_FILE = join(WALLET_DIR, \"payment-chain\");\n\n// Export for use by wallet command and index.ts\nexport { WALLET_FILE, MNEMONIC_FILE, CHAIN_FILE };\n\n/**\n * Try to load a previously auto-generated wallet key from disk.\n */\nasync function loadSavedWallet(): Promise {\n try {\n const key = (await readTextFile(WALLET_FILE)).trim();\n if (key.startsWith(\"0x\") && key.length === 66) {\n console.log(`[ClawRouter] ✓ Loaded existing wallet from ${WALLET_FILE}`);\n return key;\n }\n // File exists but content is wrong — do NOT silently fall through to generate a new wallet.\n // This would silently replace a funded wallet with an empty one.\n console.error(`[ClawRouter] ✗ CRITICAL: Wallet file exists but has invalid format!`);\n console.error(`[ClawRouter] File: ${WALLET_FILE}`);\n console.error(`[ClawRouter] Expected: 0x followed by 64 hex characters (66 chars total)`);\n console.error(\n `[ClawRouter] To fix: restore your backup key or set BLOCKRUN_WALLET_KEY env var`,\n );\n throw new Error(\n `Wallet file at ${WALLET_FILE} is corrupted or has wrong format. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Restore your backup key or set BLOCKRUN_WALLET_KEY environment variable.`,\n );\n } catch (err) {\n // Re-throw corruption errors (not ENOENT)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n // If it's our own thrown error, re-throw as-is\n if (err instanceof Error && err.message.includes(\"Refusing to auto-generate\")) {\n throw err;\n }\n console.error(\n `[ClawRouter] ✗ Failed to read wallet file: ${err instanceof Error ? err.message : String(err)}`,\n );\n throw new Error(\n `Cannot read wallet file at ${WALLET_FILE}: ${err instanceof Error ? err.message : String(err)}. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Fix file permissions or set BLOCKRUN_WALLET_KEY environment variable.`,\n { cause: err },\n );\n }\n }\n return undefined;\n}\n\n/**\n * Load mnemonic from disk if it exists.\n * Warns on corruption but never throws — callers handle missing mnemonic gracefully.\n */\nasync function loadMnemonic(): Promise {\n try {\n const mnemonic = (await readTextFile(MNEMONIC_FILE)).trim();\n if (mnemonic && isValidMnemonic(mnemonic)) {\n return mnemonic;\n }\n // File exists but content is invalid — warn but continue.\n console.warn(`[ClawRouter] ⚠ Mnemonic file exists but has invalid format — ignoring`);\n return undefined;\n } catch (err) {\n // Only swallow ENOENT (file not found)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n console.warn(`[ClawRouter] ⚠ Cannot read mnemonic file — ignoring`);\n }\n }\n return undefined;\n}\n\n/**\n * Save mnemonic to disk.\n */\nasync function saveMnemonic(mnemonic: string): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Generate a new wallet with BIP-39 mnemonic, save to disk.\n * New users get both EVM and Solana keys derived from the same mnemonic.\n * CRITICAL: Verifies the file was actually written after generation.\n */\nasync function generateAndSaveWallet(): Promise<{\n key: string;\n address: string;\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: if a mnemonic file already exists, a Solana wallet was derived from it.\n // Generating a new wallet would overwrite the mnemonic and lose Solana funds.\n const existingMnemonic = await loadMnemonic();\n if (existingMnemonic) {\n throw new Error(\n `Mnemonic file exists at ${MNEMONIC_FILE} but wallet.key is missing.\\n` +\n `Refusing to generate a new wallet to protect existing funds.\\n\\n` +\n `Restore your EVM private key using one of:\\n` +\n ` Windows: set BLOCKRUN_WALLET_KEY=0x\\n` +\n ` Mac/Linux: export BLOCKRUN_WALLET_KEY=0x\\n\\n` +\n `Then run: npx @blockrun/clawrouter`,\n );\n }\n\n const mnemonic = generateWalletMnemonic();\n const derived = deriveAllKeys(mnemonic);\n\n // Create directory\n await mkdir(WALLET_DIR, { recursive: true });\n\n // Write wallet key file (EVM private key)\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n // Write mnemonic file\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n\n // CRITICAL: Verify the file was actually written\n try {\n const verification = (await readTextFile(WALLET_FILE)).trim();\n if (verification !== derived.evmPrivateKey) {\n throw new Error(\"Wallet file verification failed - content mismatch\");\n }\n console.log(`[ClawRouter] Wallet saved and verified at ${WALLET_FILE}`);\n } catch (err) {\n throw new Error(\n `Failed to verify wallet file after creation: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n // Derive Solana address for display\n let solanaAddress: string | undefined;\n try {\n solanaAddress = await getSolanaAddress(derived.solanaPrivateKeyBytes);\n } catch {\n // Non-fatal — Solana address display is best-effort\n }\n\n // Print prominent backup reminder after generating a new wallet\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] NEW WALLET GENERATED — BACK UP YOUR KEY NOW`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter] Key file : ${WALLET_FILE}`);\n console.log(`[ClawRouter] Mnemonic : ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Both EVM (Base) and Solana wallets are ready.`);\n console.log(`[ClawRouter] To back up, run in OpenClaw:`);\n console.log(`[ClawRouter] /wallet export`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] To restore on another machine:`);\n console.log(`[ClawRouter] export BLOCKRUN_WALLET_KEY=`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n return {\n key: derived.evmPrivateKey,\n address: derived.evmAddress,\n mnemonic,\n solanaPrivateKeyBytes: derived.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Resolve wallet key: load saved → env var → auto-generate.\n * Also loads mnemonic if available for Solana key derivation.\n * Called by index.ts before the auth wizard runs.\n */\nexport type WalletResolution = {\n key: string;\n address: string;\n source: \"saved\" | \"env\" | \"generated\";\n mnemonic?: string;\n solanaPrivateKeyBytes?: Uint8Array;\n};\n\nexport async function resolveOrGenerateWalletKey(): Promise {\n // 1. Previously saved wallet\n const saved = await loadSavedWallet();\n if (saved) {\n const account = privateKeyToAccount(saved as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: saved,\n address: account.address,\n source: \"saved\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: saved, address: account.address, source: \"saved\" };\n }\n\n // 2. Environment variable\n const envKey = process[\"env\"].BLOCKRUN_WALLET_KEY;\n if (typeof envKey === \"string\" && envKey.startsWith(\"0x\") && envKey.length === 66) {\n const account = privateKeyToAccount(envKey as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: envKey,\n address: account.address,\n source: \"env\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: envKey, address: account.address, source: \"env\" };\n }\n\n // 3. Auto-generate with BIP-39 mnemonic (new users get both chains)\n const result = await generateAndSaveWallet();\n return {\n key: result.key,\n address: result.address,\n source: \"generated\",\n mnemonic: result.mnemonic,\n solanaPrivateKeyBytes: result.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Recover wallet.key from existing mnemonic.\n *\n * ONLY works when the mnemonic was originally generated by ClawRouter\n * (i.e., both mnemonic and EVM key were derived from the same seed).\n * If the EVM key was set independently (manually or via env), the derived\n * key will be different — do NOT use this in that case.\n */\nexport async function recoverWalletFromMnemonic(): Promise {\n const mnemonic = await loadMnemonic();\n if (!mnemonic) {\n console.error(`[ClawRouter] No mnemonic found at ${MNEMONIC_FILE}`);\n console.error(`[ClawRouter] Cannot recover — no mnemonic to derive from.`);\n process.exit(1);\n }\n\n // Safety: if wallet.key already exists, refuse to overwrite\n const existing = await loadSavedWallet().catch(() => undefined);\n if (existing) {\n console.error(`[ClawRouter] wallet.key already exists at ${WALLET_FILE}`);\n console.error(`[ClawRouter] Recovery not needed.`);\n process.exit(1);\n }\n\n const derived = deriveAllKeys(mnemonic);\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const solanaAddress = await getSolanaAddress(solanaKeyBytes).catch(() => undefined);\n\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ⚠ WALLET RECOVERY FROM MNEMONIC`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] This only works if your mnemonic was originally`);\n console.log(`[ClawRouter] generated by ClawRouter (not set manually).`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Derived EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Derived Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] If the Solana address above matches your funded`);\n console.log(`[ClawRouter] wallet, recovery is safe to proceed.`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n console.log(`[ClawRouter] ✓ wallet.key restored at ${WALLET_FILE}`);\n console.log(`[ClawRouter] Run: npx @blockrun/clawrouter`);\n console.log(`[ClawRouter]`);\n}\n\n/**\n * Set up Solana wallet for existing EVM-only users.\n * Generates a new mnemonic for Solana key derivation.\n * NEVER touches the existing wallet.key file.\n */\nexport async function setupSolana(): Promise<{\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: mnemonic must not already exist\n const existing = await loadMnemonic();\n if (existing) {\n throw new Error(\"Solana wallet already set up. Mnemonic file exists at \" + MNEMONIC_FILE);\n }\n\n // Safety: wallet.key must exist (can't set up Solana without EVM wallet)\n const savedKey = await loadSavedWallet();\n if (!savedKey) {\n throw new Error(\n \"No EVM wallet found. Run ClawRouter first to generate a wallet before setting up Solana.\",\n );\n }\n\n // Generate new mnemonic for Solana derivation\n const mnemonic = generateWalletMnemonic();\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n\n // Save mnemonic (wallet.key untouched)\n await saveMnemonic(mnemonic);\n\n console.log(`[ClawRouter] Solana wallet set up successfully.`);\n console.log(`[ClawRouter] Mnemonic saved to ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter] Existing EVM wallet unchanged.`);\n\n return { mnemonic, solanaPrivateKeyBytes: solanaKeyBytes };\n}\n\n/**\n * Persist the user's payment chain selection to disk.\n */\nexport async function savePaymentChain(chain: \"base\" | \"solana\"): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(CHAIN_FILE, chain + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Load the persisted payment chain selection from disk.\n * Returns \"base\" if no file exists or the file is invalid.\n */\nexport async function loadPaymentChain(): Promise<\"base\" | \"solana\"> {\n try {\n const content = (await readTextFile(CHAIN_FILE)).trim();\n if (content === \"solana\") return \"solana\";\n return \"base\";\n } catch {\n return \"base\";\n }\n}\n\n/**\n * Resolve payment chain: env var first → persisted file second → default \"base\".\n */\nexport async function resolvePaymentChain(): Promise<\"base\" | \"solana\"> {\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"solana\") return \"solana\";\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"base\") return \"base\";\n return loadPaymentChain();\n}\n\n/**\n * Auth method: operator enters their wallet private key directly.\n */\nexport const walletKeyAuth: ProviderAuthMethod = {\n id: \"wallet-key\",\n label: \"Wallet Private Key\",\n hint: \"Enter your EVM wallet private key (0x...) for x402 payments to BlockRun\",\n kind: \"api_key\",\n run: async (ctx: ProviderAuthContext): Promise => {\n const key = await ctx.prompter.text({\n message: \"Enter your wallet private key (0x...)\",\n validate: (value: string) => {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"0x\")) return \"Key must start with 0x\";\n if (trimmed.length !== 66) return \"Key must be 66 characters (0x + 64 hex)\";\n if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) return \"Key must be valid hex\";\n return undefined;\n },\n });\n\n if (!key || typeof key !== \"string\") {\n throw new Error(\"Wallet key is required\");\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\n \"Wallet key stored securely in OpenClaw credentials.\",\n \"Your wallet signs x402 USDC payments on Base for each LLM call.\",\n \"Fund your wallet with USDC on Base to start using BlockRun models.\",\n ],\n };\n },\n};\n\n/**\n * Auth method: read wallet key from BLOCKRUN_WALLET_KEY environment variable.\n */\nexport const envKeyAuth: ProviderAuthMethod = {\n id: \"env-key\",\n label: \"Environment Variable\",\n hint: \"Use BLOCKRUN_WALLET_KEY environment variable\",\n kind: \"api_key\",\n run: async (): Promise => {\n const key = process[\"env\"].BLOCKRUN_WALLET_KEY;\n\n if (!key) {\n throw new Error(\n \"BLOCKRUN_WALLET_KEY environment variable is not set. \" +\n \"Set it to your EVM wallet private key (0x...).\",\n );\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\"Using wallet key from BLOCKRUN_WALLET_KEY environment variable.\"],\n };\n },\n};\n","/**\n * LLM-Safe Context Compression Types\n *\n * Types for the 7-layer compression system that reduces token usage\n * while preserving semantic meaning for LLM queries.\n */\n\n// Content part for multimodal messages (images, etc.)\nexport interface ContentPart {\n type: \"text\" | \"image_url\";\n text?: string;\n image_url?: {\n url: string;\n detail?: \"low\" | \"high\" | \"auto\";\n };\n}\n\n// Normalized message structure (matches OpenAI format)\n// Note: content can be an array for multimodal messages (images, etc.)\nexport interface NormalizedMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | ContentPart[] | null;\n tool_call_id?: string;\n tool_calls?: ToolCall[];\n name?: string;\n}\n\nexport interface ToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\n// Compression configuration\nexport interface CompressionConfig {\n enabled: boolean;\n preserveRaw: boolean; // Keep original for logging\n\n // Per-layer toggles\n layers: {\n deduplication: boolean;\n whitespace: boolean;\n dictionary: boolean;\n paths: boolean;\n jsonCompact: boolean;\n observation: boolean; // L6: Compress tool results (BIG WIN)\n dynamicCodebook: boolean; // L7: Build codebook from content\n };\n\n // Dictionary settings\n dictionary: {\n maxEntries: number;\n minPhraseLength: number;\n includeCodebookHeader: boolean; // Include codebook in system message\n };\n}\n\n// Compression statistics\nexport interface CompressionStats {\n duplicatesRemoved: number;\n whitespaceSavedChars: number;\n dictionarySubstitutions: number;\n pathsShortened: number;\n jsonCompactedChars: number;\n observationsCompressed: number; // L6: Tool results compressed\n observationCharsSaved: number; // L6: Chars saved from observations\n dynamicSubstitutions: number; // L7: Dynamic codebook substitutions\n dynamicCharsSaved: number; // L7: Chars saved from dynamic codebook\n}\n\n// Result from compression\nexport interface CompressionResult {\n messages: NormalizedMessage[];\n originalMessages: NormalizedMessage[]; // For logging\n\n // Token estimates\n originalChars: number;\n compressedChars: number;\n compressionRatio: number; // 0.85 = 15% reduction\n\n // Per-layer stats\n stats: CompressionStats;\n\n // Codebook used (for decompression in logs)\n codebook: Record;\n pathMap: Record;\n dynamicCodes: Record; // L7: Dynamic codebook\n}\n\n// Log data extension for compression metrics\nexport interface CompressionLogData {\n enabled: boolean;\n ratio: number;\n original_chars: number;\n compressed_chars: number;\n stats: {\n duplicates_removed: number;\n whitespace_saved: number;\n dictionary_subs: number;\n paths_shortened: number;\n json_compacted: number;\n };\n}\n\n// Default configuration - CONSERVATIVE settings for model compatibility\n// Only enable layers that don't require the model to decode anything\nexport const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {\n enabled: true,\n preserveRaw: true,\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // DISABLED: requires model to understand codebook\n paths: false, // DISABLED: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // DISABLED: may lose important context\n dynamicCodebook: false, // DISABLED: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false, // No codebook header needed\n },\n};\n","/**\n * Layer 1: Message Deduplication\n *\n * Removes exact duplicate messages from conversation history.\n * Common in heartbeat patterns and repeated tool calls.\n *\n * Safe for LLM: Identical messages add no new information.\n * Expected savings: 2-5%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport crypto from \"crypto\";\n\nexport interface DeduplicationResult {\n messages: NormalizedMessage[];\n duplicatesRemoved: number;\n originalCount: number;\n}\n\n/**\n * Generate a hash for a message based on its semantic content.\n * Uses role + content + tool_call_id to identify duplicates.\n */\nfunction hashMessage(message: NormalizedMessage): string {\n // Handle content - stringify arrays (multimodal), use string directly, or empty string\n let contentStr = \"\";\n if (typeof message.content === \"string\") {\n contentStr = message.content;\n } else if (Array.isArray(message.content)) {\n contentStr = JSON.stringify(message.content);\n }\n\n const parts = [message.role, contentStr, message.tool_call_id || \"\", message.name || \"\"];\n\n // Include tool_calls if present\n if (message.tool_calls) {\n parts.push(\n JSON.stringify(\n message.tool_calls.map((tc) => ({\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n ),\n );\n }\n\n const content = parts.join(\"|\");\n return crypto.createHash(\"md5\").update(content).digest(\"hex\");\n}\n\n/**\n * Remove exact duplicate messages from the conversation.\n *\n * Strategy:\n * - Keep first occurrence of each unique message\n * - Preserve order for semantic coherence\n * - Never dedupe system messages (they set context)\n * - Allow duplicate user messages (user might repeat intentionally)\n * - CRITICAL: Never dedupe assistant messages with tool_calls that are\n * referenced by subsequent tool messages (breaks Anthropic tool_use/tool_result pairing)\n */\nexport function deduplicateMessages(messages: NormalizedMessage[]): DeduplicationResult {\n const seen = new Set();\n const result: NormalizedMessage[] = [];\n let duplicatesRemoved = 0;\n\n // First pass: collect all tool_call_ids that are referenced by tool messages\n // These tool_calls MUST be preserved to maintain tool_use/tool_result pairing\n const referencedToolCallIds = new Set();\n for (const message of messages) {\n if (message.role === \"tool\" && message.tool_call_id) {\n referencedToolCallIds.add(message.tool_call_id);\n }\n }\n\n for (const message of messages) {\n // Always keep system messages (they set important context)\n if (message.role === \"system\") {\n result.push(message);\n continue;\n }\n\n // Always keep user messages (user might repeat intentionally)\n if (message.role === \"user\") {\n result.push(message);\n continue;\n }\n\n // Always keep tool messages (they are results of tool calls)\n // Removing them would break the tool_use/tool_result pairing\n if (message.role === \"tool\") {\n result.push(message);\n continue;\n }\n\n // For assistant messages with tool_calls, check if any are referenced\n // by subsequent tool messages - if so, we MUST keep this message\n if (message.role === \"assistant\" && message.tool_calls) {\n const hasReferencedToolCall = message.tool_calls.some((tc) =>\n referencedToolCallIds.has(tc.id),\n );\n if (hasReferencedToolCall) {\n // This assistant message has tool_calls that are referenced - keep it\n result.push(message);\n continue;\n }\n }\n\n // For other assistant messages, check for duplicates\n const hash = hashMessage(message);\n\n if (!seen.has(hash)) {\n seen.add(hash);\n result.push(message);\n } else {\n duplicatesRemoved++;\n }\n }\n\n return {\n messages: result,\n duplicatesRemoved,\n originalCount: messages.length,\n };\n}\n","/**\n * Layer 2: Whitespace Normalization\n *\n * Reduces excessive whitespace without changing semantic meaning.\n *\n * Safe for LLM: Tokenizers normalize whitespace anyway.\n * Expected savings: 3-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface WhitespaceResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Normalize whitespace in a string.\n *\n * - Max 2 consecutive newlines\n * - Remove trailing whitespace from lines\n * - Normalize tabs to spaces\n * - Trim start/end\n */\nexport function normalizeWhitespace(content: string): string {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") return content as string;\n\n return (\n content\n // Normalize line endings\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n // Max 2 consecutive newlines (preserve paragraph breaks)\n .replace(/\\n{3,}/g, \"\\n\\n\")\n // Remove trailing whitespace from each line\n .replace(/[ \\t]+$/gm, \"\")\n // Normalize multiple spaces to single (except at line start for indentation)\n .replace(/([^\\n]) {2,}/g, \"$1 \")\n // Reduce excessive indentation (more than 8 spaces → 2 spaces per level)\n .replace(/^[ ]{8,}/gm, (match) => \" \".repeat(Math.ceil(match.length / 4)))\n // Normalize tabs to 2 spaces\n .replace(/\\t/g, \" \")\n // Trim\n .trim()\n );\n}\n\n/**\n * Apply whitespace normalization to all messages.\n */\nexport function normalizeMessagesWhitespace(messages: NormalizedMessage[]): WhitespaceResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const originalLength = message.content.length;\n const normalizedContent = normalizeWhitespace(message.content);\n charsSaved += originalLength - normalizedContent.length;\n\n return {\n ...message,\n content: normalizedContent,\n };\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * Dictionary Codebook\n *\n * Static dictionary of frequently repeated phrases observed in LLM prompts.\n * Built from analysis of BlockRun production logs.\n *\n * Format: Short code ($XX) -> Long phrase\n * The LLM receives a codebook header and decodes in-context.\n */\n\n// Static codebook - common patterns from system prompts\n// Ordered by expected frequency and impact\nexport const STATIC_CODEBOOK: Record = {\n // High-impact: OpenClaw/Agent system prompt patterns (very common)\n $OC01: \"unbrowse_\", // Common prefix in tool names\n $OC02: \"\",\n $OC03: \"\",\n $OC04: \"\",\n $OC05: \"\",\n $OC06: \"\",\n $OC07: \"\",\n $OC08: \"(may need login)\",\n $OC09: \"API skill for OpenClaw\",\n $OC10: \"endpoints\",\n\n // Skill/tool markers\n $SK01: \"\",\n $SK02: \"\",\n $SK03: \"\",\n $SK04: \"\",\n\n // Schema patterns (very common in tool definitions)\n $T01: 'type: \"function\"',\n $T02: '\"type\": \"function\"',\n $T03: '\"type\": \"string\"',\n $T04: '\"type\": \"object\"',\n $T05: '\"type\": \"array\"',\n $T06: '\"type\": \"boolean\"',\n $T07: '\"type\": \"number\"',\n\n // Common descriptions\n $D01: \"description:\",\n $D02: '\"description\":',\n\n // Common instructions\n $I01: \"You are a personal assistant\",\n $I02: \"Tool names are case-sensitive\",\n $I03: \"Call tools exactly as listed\",\n $I04: \"Use when\",\n $I05: \"without asking\",\n\n // Safety phrases\n $S01: \"Do not manipulate or persuade\",\n $S02: \"Prioritize safety and human oversight\",\n $S03: \"unless explicitly requested\",\n\n // JSON patterns\n $J01: '\"required\": [\"',\n $J02: '\"properties\": {',\n $J03: '\"additionalProperties\": false',\n\n // Heartbeat patterns\n $H01: \"HEARTBEAT_OK\",\n $H02: \"Read HEARTBEAT.md if it exists\",\n\n // Role markers\n $R01: '\"role\": \"system\"',\n $R02: '\"role\": \"user\"',\n $R03: '\"role\": \"assistant\"',\n $R04: '\"role\": \"tool\"',\n\n // Common endings/phrases\n $E01: \"would you like to\",\n $E02: \"Let me know if you\",\n $E03: \"internal APIs\",\n $E04: \"session cookies\",\n\n // BlockRun model aliases (common in prompts)\n $M01: \"blockrun/\",\n $M02: \"openai/\",\n $M03: \"anthropic/\",\n $M04: \"google/\",\n $M05: \"xai/\",\n};\n\n/**\n * Get the inverse codebook for decompression.\n */\nexport function getInverseCodebook(): Record {\n const inverse: Record = {};\n for (const [code, phrase] of Object.entries(STATIC_CODEBOOK)) {\n inverse[phrase] = code;\n }\n return inverse;\n}\n\n/**\n * Generate the codebook header for inclusion in system message.\n * LLMs can decode in-context using this header.\n */\nexport function generateCodebookHeader(\n usedCodes: Set,\n pathMap: Record = {},\n): string {\n if (usedCodes.size === 0 && Object.keys(pathMap).length === 0) {\n return \"\";\n }\n\n const parts: string[] = [];\n\n // Add used dictionary codes\n if (usedCodes.size > 0) {\n const codeEntries = Array.from(usedCodes)\n .map((code) => `${code}=${STATIC_CODEBOOK[code]}`)\n .join(\", \");\n parts.push(`[Dict: ${codeEntries}]`);\n }\n\n // Add path map\n if (Object.keys(pathMap).length > 0) {\n const pathEntries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n parts.push(`[Paths: ${pathEntries}]`);\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Decompress a string using the codebook (for logging).\n */\nexport function decompressContent(\n content: string,\n codebook: Record = STATIC_CODEBOOK,\n): string {\n let result = content;\n for (const [code, phrase] of Object.entries(codebook)) {\n result = result.split(code).join(phrase);\n }\n return result;\n}\n","/**\n * Layer 3: Dictionary Encoding\n *\n * Replaces frequently repeated long phrases with short codes.\n * Uses a static codebook of common patterns from production logs.\n *\n * Safe for LLM: Reversible substitution with codebook header.\n * Expected savings: 4-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport { getInverseCodebook } from \"../codebook\";\n\nexport interface DictionaryResult {\n messages: NormalizedMessage[];\n substitutionCount: number;\n usedCodes: Set;\n charsSaved: number;\n}\n\n/**\n * Apply dictionary encoding to a string.\n * Returns the encoded string and stats.\n */\nfunction encodeContent(\n content: string,\n inverseCodebook: Record,\n): { encoded: string; substitutions: number; codes: Set; charsSaved: number } {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") {\n return { encoded: content, substitutions: 0, codes: new Set(), charsSaved: 0 };\n }\n let encoded = content;\n let substitutions = 0;\n let charsSaved = 0;\n const codes = new Set();\n\n // Sort phrases by length (longest first) to avoid partial matches\n const phrases = Object.keys(inverseCodebook).sort((a, b) => b.length - a.length);\n\n for (const phrase of phrases) {\n const code = inverseCodebook[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = encoded.match(regex);\n\n if (matches && matches.length > 0) {\n encoded = encoded.replace(regex, code);\n substitutions += matches.length;\n charsSaved += matches.length * (phrase.length - code.length);\n codes.add(code);\n }\n }\n\n return { encoded, substitutions, codes, charsSaved };\n}\n\n/**\n * Escape special regex characters in a string.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dictionary encoding to all messages.\n */\nexport function encodeMessages(messages: NormalizedMessage[]): DictionaryResult {\n const inverseCodebook = getInverseCodebook();\n let totalSubstitutions = 0;\n let totalCharsSaved = 0;\n const allUsedCodes = new Set();\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const { encoded, substitutions, codes, charsSaved } = encodeContent(\n message.content,\n inverseCodebook,\n );\n\n totalSubstitutions += substitutions;\n totalCharsSaved += charsSaved;\n codes.forEach((code) => allUsedCodes.add(code));\n\n return {\n ...message,\n content: encoded,\n };\n });\n\n return {\n messages: result,\n substitutionCount: totalSubstitutions,\n usedCodes: allUsedCodes,\n charsSaved: totalCharsSaved,\n };\n}\n","/**\n * Layer 4: Path Shortening\n *\n * Detects common filesystem path prefixes and replaces them with short codes.\n * Common in coding assistant contexts with repeated file paths.\n *\n * Safe for LLM: Lossless abbreviation with path map header.\n * Expected savings: 1-3%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface PathShorteningResult {\n messages: NormalizedMessage[];\n pathMap: Record; // $P1 -> /home/user/project/\n charsSaved: number;\n}\n\n// Regex to match filesystem paths\nconst PATH_REGEX = /(?:\\/[\\w.-]+){3,}/g;\n\n/**\n * Extract all paths from messages and find common prefixes.\n */\nfunction extractPaths(messages: NormalizedMessage[]): string[] {\n const paths: string[] = [];\n\n for (const message of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") continue;\n const matches = message.content.match(PATH_REGEX);\n if (matches) {\n paths.push(...matches);\n }\n }\n\n return paths;\n}\n\n/**\n * Group paths by their common prefixes.\n * Returns prefixes that appear at least 3 times.\n */\nfunction findFrequentPrefixes(paths: string[]): string[] {\n const prefixCounts = new Map();\n\n for (const path of paths) {\n const parts = path.split(\"/\").filter(Boolean);\n\n // Try prefixes of different lengths\n for (let i = 2; i < parts.length; i++) {\n const prefix = \"/\" + parts.slice(0, i).join(\"/\") + \"/\";\n prefixCounts.set(prefix, (prefixCounts.get(prefix) || 0) + 1);\n }\n }\n\n // Return prefixes that appear 3+ times, sorted by length (longest first)\n return Array.from(prefixCounts.entries())\n .filter(([, count]) => count >= 3)\n .sort((a, b) => b[0].length - a[0].length)\n .slice(0, 5) // Max 5 path codes\n .map(([prefix]) => prefix);\n}\n\n/**\n * Apply path shortening to all messages.\n */\nexport function shortenPaths(messages: NormalizedMessage[]): PathShorteningResult {\n const allPaths = extractPaths(messages);\n\n if (allPaths.length < 5) {\n // Not enough paths to benefit from shortening\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n const prefixes = findFrequentPrefixes(allPaths);\n\n if (prefixes.length === 0) {\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n // Create path map\n const pathMap: Record = {};\n prefixes.forEach((prefix, i) => {\n pathMap[`$P${i + 1}`] = prefix;\n });\n\n // Replace paths in messages\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n let content = message.content;\n const originalLength = content.length;\n\n // Replace prefixes (longest first to avoid partial replacements)\n for (const [code, prefix] of Object.entries(pathMap)) {\n content = content.split(prefix).join(code + \"/\");\n }\n\n charsSaved += originalLength - content.length;\n\n return {\n ...message,\n content,\n };\n });\n\n return {\n messages: result,\n pathMap,\n charsSaved,\n };\n}\n\n/**\n * Generate the path map header for the codebook.\n */\nexport function generatePathMapHeader(pathMap: Record): string {\n if (Object.keys(pathMap).length === 0) return \"\";\n\n const entries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n\n return `[Paths: ${entries}]`;\n}\n","/**\n * Layer 5: JSON Compaction\n *\n * Minifies JSON in tool_call arguments and tool results.\n * Removes pretty-print whitespace from JSON strings.\n *\n * Safe for LLM: JSON semantics unchanged.\n * Expected savings: 2-4%\n */\n\nimport { NormalizedMessage, ToolCall } from \"../types\";\n\nexport interface JsonCompactResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Compact a JSON string by parsing and re-stringifying without formatting.\n */\nfunction compactJson(jsonString: string): string {\n try {\n const parsed = JSON.parse(jsonString);\n return JSON.stringify(parsed);\n } catch {\n // Not valid JSON, return as-is\n return jsonString;\n }\n}\n\n/**\n * Check if a string looks like JSON (starts with { or [).\n */\nfunction looksLikeJson(str: string): boolean {\n const trimmed = str.trim();\n return (\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) ||\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\"))\n );\n}\n\n/**\n * Compact tool_call arguments in a message.\n */\nfunction compactToolCalls(toolCalls: ToolCall[]): ToolCall[] {\n return toolCalls.map((tc) => ({\n ...tc,\n function: {\n ...tc.function,\n arguments: compactJson(tc.function.arguments),\n },\n }));\n}\n\n/**\n * Apply JSON compaction to all messages.\n *\n * Targets:\n * - tool_call arguments (in assistant messages)\n * - tool message content (often JSON)\n */\nexport function compactMessagesJson(messages: NormalizedMessage[]): JsonCompactResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n const newMessage = { ...message };\n\n // Compact tool_calls arguments\n if (message.tool_calls && message.tool_calls.length > 0) {\n const originalLength = JSON.stringify(message.tool_calls).length;\n newMessage.tool_calls = compactToolCalls(message.tool_calls);\n const newLength = JSON.stringify(newMessage.tool_calls).length;\n charsSaved += originalLength - newLength;\n }\n\n // Compact tool message content if it looks like JSON\n // Only process string content (skip arrays for multimodal messages)\n if (\n message.role === \"tool\" &&\n message.content &&\n typeof message.content === \"string\" &&\n looksLikeJson(message.content)\n ) {\n const originalLength = message.content.length;\n const compacted = compactJson(message.content);\n charsSaved += originalLength - compacted.length;\n newMessage.content = compacted;\n }\n\n return newMessage;\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * L6: Observation Compression (AGGRESSIVE)\n *\n * Inspired by claw-compactor's 97% compression on tool results.\n * Tool call results (especially large ones) are summarized to key info only.\n *\n * This is the biggest compression win - tool outputs can be 10KB+ but\n * only ~200 chars of actual useful information.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface ObservationResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n observationsCompressed: number;\n}\n\n// Max length for tool results before compression kicks in\nconst TOOL_RESULT_THRESHOLD = 500;\n\n// Max length to compress tool results down to\nconst COMPRESSED_RESULT_MAX = 300;\n\n/**\n * Extract key information from tool result.\n * Keeps: errors, key values, status, first/last important lines.\n */\nfunction compressToolResult(content: string): string {\n if (!content || content.length <= TOOL_RESULT_THRESHOLD) {\n return content;\n }\n\n const lines = content\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter(Boolean);\n\n // Priority 1: Error messages (always keep)\n const errorLines = lines.filter(\n (l) => /error|exception|failed|denied|refused|timeout|invalid/i.test(l) && l.length < 200,\n );\n\n // Priority 2: Status/result lines\n const statusLines = lines.filter(\n (l) =>\n /success|complete|created|updated|found|result|status|total|count/i.test(l) && l.length < 150,\n );\n\n // Priority 3: Key JSON fields (extract important values)\n const jsonMatches: string[] = [];\n const jsonPattern = /\"(id|name|status|error|message|count|total|url|path)\":\\s*\"?([^\",}\\n]+)\"?/gi;\n let match;\n while ((match = jsonPattern.exec(content)) !== null) {\n jsonMatches.push(`${match[1]}: ${match[2].slice(0, 50)}`);\n }\n\n // Priority 4: First and last meaningful lines\n const firstLine = lines[0]?.slice(0, 100);\n const lastLine = lines.length > 1 ? lines[lines.length - 1]?.slice(0, 100) : \"\";\n\n // Build compressed observation\n const parts: string[] = [];\n\n if (errorLines.length > 0) {\n parts.push(\"[ERR] \" + errorLines.slice(0, 3).join(\" | \"));\n }\n\n if (statusLines.length > 0) {\n parts.push(statusLines.slice(0, 3).join(\" | \"));\n }\n\n if (jsonMatches.length > 0) {\n parts.push(jsonMatches.slice(0, 5).join(\", \"));\n }\n\n if (parts.length === 0) {\n // Fallback: keep first/last lines with truncation marker\n parts.push(firstLine || \"\");\n if (lines.length > 2) {\n parts.push(`[...${lines.length - 2} lines...]`);\n }\n if (lastLine && lastLine !== firstLine) {\n parts.push(lastLine);\n }\n }\n\n let result = parts.join(\"\\n\");\n\n // Final length cap\n if (result.length > COMPRESSED_RESULT_MAX) {\n result = result.slice(0, COMPRESSED_RESULT_MAX - 20) + \"\\n[...truncated]\";\n }\n\n return result;\n}\n\n/**\n * Compress large repeated content blocks.\n * Detects when same large block appears multiple times.\n */\nfunction deduplicateLargeBlocks(messages: NormalizedMessage[]): {\n messages: NormalizedMessage[];\n charsSaved: number;\n} {\n const blockHashes = new Map(); // hash -> first occurrence index\n let charsSaved = 0;\n\n const result = messages.map((msg, idx) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\" || msg.content.length < 500) {\n return msg;\n }\n\n // Hash first 200 chars as block identifier\n const blockKey = msg.content.slice(0, 200);\n\n if (blockHashes.has(blockKey)) {\n const firstIdx = blockHashes.get(blockKey)!;\n const original = msg.content;\n const compressed = `[See message #${firstIdx + 1} - same content]`;\n charsSaved += original.length - compressed.length;\n return { ...msg, content: compressed };\n }\n\n blockHashes.set(blockKey, idx);\n return msg;\n });\n\n return { messages: result, charsSaved };\n}\n\n/**\n * Compress tool results in messages.\n */\nexport function compressObservations(messages: NormalizedMessage[]): ObservationResult {\n let charsSaved = 0;\n let observationsCompressed = 0;\n\n // First pass: compress individual tool results\n let result = messages.map((msg) => {\n // Only compress tool role messages (these are tool call results)\n // Only process string content (skip arrays for multimodal messages)\n if (msg.role !== \"tool\" || !msg.content || typeof msg.content !== \"string\") {\n return msg;\n }\n\n const original = msg.content;\n if (original.length <= TOOL_RESULT_THRESHOLD) {\n return msg;\n }\n\n const compressed = compressToolResult(original);\n const saved = original.length - compressed.length;\n\n if (saved > 50) {\n charsSaved += saved;\n observationsCompressed++;\n return { ...msg, content: compressed };\n }\n\n return msg;\n });\n\n // Second pass: deduplicate large repeated blocks\n const dedupResult = deduplicateLargeBlocks(result);\n result = dedupResult.messages;\n charsSaved += dedupResult.charsSaved;\n\n return {\n messages: result,\n charsSaved,\n observationsCompressed,\n };\n}\n","/**\n * L7: Dynamic Codebook Builder\n *\n * Inspired by claw-compactor's frequency-based codebook.\n * Builds codebook from actual content being compressed,\n * rather than relying on static patterns.\n *\n * Finds phrases that appear 3+ times and replaces with short codes.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface DynamicCodebookResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n dynamicCodes: Record; // code -> phrase\n substitutions: number;\n}\n\n// Config\nconst MIN_PHRASE_LENGTH = 20;\nconst MAX_PHRASE_LENGTH = 200;\nconst MIN_FREQUENCY = 3;\nconst MAX_ENTRIES = 100;\nconst CODE_PREFIX = \"$D\"; // Dynamic codes: $D01, $D02, etc.\n\n/**\n * Find repeated phrases in content.\n */\nfunction findRepeatedPhrases(allContent: string): Map {\n const phrases = new Map();\n\n // Split by sentence-like boundaries\n const segments = allContent.split(/(?<=[.!?\\n])\\s+/);\n\n for (const segment of segments) {\n const trimmed = segment.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n // Also find repeated lines\n const lines = allContent.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n return phrases;\n}\n\n/**\n * Build dynamic codebook from message content.\n */\nfunction buildDynamicCodebook(messages: NormalizedMessage[]): Record {\n // Combine all content\n let allContent = \"\";\n for (const msg of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (msg.content && typeof msg.content === \"string\") {\n allContent += msg.content + \"\\n\";\n }\n }\n\n // Find repeated phrases\n const phrases = findRepeatedPhrases(allContent);\n\n // Filter by frequency and sort by savings potential\n const candidates: Array<{ phrase: string; count: number; savings: number }> = [];\n for (const [phrase, count] of phrases.entries()) {\n if (count >= MIN_FREQUENCY) {\n // Savings = (phrase length - code length) * occurrences\n const codeLength = 4; // e.g., \"$D01\"\n const savings = (phrase.length - codeLength) * count;\n if (savings > 50) {\n candidates.push({ phrase, count, savings });\n }\n }\n }\n\n // Sort by savings (descending) and take top entries\n candidates.sort((a, b) => b.savings - a.savings);\n const topCandidates = candidates.slice(0, MAX_ENTRIES);\n\n // Build codebook\n const codebook: Record = {};\n topCandidates.forEach((c, i) => {\n const code = `${CODE_PREFIX}${String(i + 1).padStart(2, \"0\")}`;\n codebook[code] = c.phrase;\n });\n\n return codebook;\n}\n\n/**\n * Escape special regex characters.\n */\nfunction escapeRegex(str: string): string {\n // Defensive type check\n if (!str || typeof str !== \"string\") return \"\";\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dynamic codebook to messages.\n */\nexport function applyDynamicCodebook(messages: NormalizedMessage[]): DynamicCodebookResult {\n // Build codebook from content\n const codebook = buildDynamicCodebook(messages);\n\n if (Object.keys(codebook).length === 0) {\n return {\n messages,\n charsSaved: 0,\n dynamicCodes: {},\n substitutions: 0,\n };\n }\n\n // Create inverse map for replacement\n const phraseToCode: Record = {};\n for (const [code, phrase] of Object.entries(codebook)) {\n phraseToCode[phrase] = code;\n }\n\n // Sort phrases by length (longest first) to avoid partial replacements\n const sortedPhrases = Object.keys(phraseToCode).sort((a, b) => b.length - a.length);\n\n let charsSaved = 0;\n let substitutions = 0;\n\n // Apply replacements\n const result = messages.map((msg) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n for (const phrase of sortedPhrases) {\n const code = phraseToCode[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = content.match(regex);\n if (matches) {\n content = content.replace(regex, code);\n charsSaved += (phrase.length - code.length) * matches.length;\n substitutions += matches.length;\n }\n }\n\n return { ...msg, content };\n });\n\n return {\n messages: result,\n charsSaved,\n dynamicCodes: codebook,\n substitutions,\n };\n}\n\n/**\n * Generate header for dynamic codes (to include in system message).\n */\nexport function generateDynamicCodebookHeader(codebook: Record): string {\n if (Object.keys(codebook).length === 0) return \"\";\n\n const entries = Object.entries(codebook)\n .slice(0, 20) // Limit header size\n .map(([code, phrase]) => {\n // Truncate long phrases in header\n const displayPhrase = phrase.length > 40 ? phrase.slice(0, 37) + \"...\" : phrase;\n return `${code}=${displayPhrase}`;\n })\n .join(\", \");\n\n return `[DynDict: ${entries}]`;\n}\n","/**\n * LLM-Safe Context Compression\n *\n * Reduces token usage by 15-40% while preserving semantic meaning.\n * Implements 7 compression layers inspired by claw-compactor.\n *\n * Usage:\n * const result = await compressContext(messages);\n * // result.messages -> compressed version to send to provider\n * // result.originalMessages -> original for logging\n */\n\nimport {\n NormalizedMessage,\n CompressionConfig,\n CompressionResult,\n CompressionStats,\n DEFAULT_COMPRESSION_CONFIG,\n} from \"./types\";\nimport { deduplicateMessages } from \"./layers/deduplication\";\nimport { normalizeMessagesWhitespace } from \"./layers/whitespace\";\nimport { encodeMessages } from \"./layers/dictionary\";\nimport { shortenPaths } from \"./layers/paths\";\nimport { compactMessagesJson } from \"./layers/json-compact\";\nimport { compressObservations } from \"./layers/observation\";\nimport { applyDynamicCodebook, generateDynamicCodebookHeader } from \"./layers/dynamic-codebook\";\nimport { generateCodebookHeader, STATIC_CODEBOOK } from \"./codebook\";\n\nexport * from \"./types\";\nexport { STATIC_CODEBOOK } from \"./codebook\";\n\n/**\n * Calculate total character count for messages.\n */\nfunction calculateTotalChars(messages: NormalizedMessage[]): number {\n return messages.reduce((total, msg) => {\n let chars = 0;\n if (typeof msg.content === \"string\") {\n chars = msg.content.length;\n } else if (Array.isArray(msg.content)) {\n // For multimodal content, stringify to get approximate size\n chars = JSON.stringify(msg.content).length;\n }\n if (msg.tool_calls) {\n chars += JSON.stringify(msg.tool_calls).length;\n }\n return total + chars;\n }, 0);\n}\n\n/**\n * Deep clone messages to preserve originals.\n */\nfunction cloneMessages(messages: NormalizedMessage[]): NormalizedMessage[] {\n return JSON.parse(JSON.stringify(messages));\n}\n\n/**\n * Prepend codebook header to the first USER message (not system).\n *\n * Why not system message?\n * - Google Gemini uses systemInstruction which doesn't support codebook format\n * - The codebook header in user message is still visible to all LLMs\n * - This ensures compatibility across all providers\n */\nfunction prependCodebookHeader(\n messages: NormalizedMessage[],\n usedCodes: Set,\n pathMap: Record,\n): NormalizedMessage[] {\n const header = generateCodebookHeader(usedCodes, pathMap);\n if (!header) return messages;\n\n // Find first user message (not system - Google's systemInstruction doesn't support codebook)\n const userIndex = messages.findIndex((m) => m.role === \"user\");\n\n if (userIndex === -1) {\n // No user message, add codebook as system (fallback)\n return [{ role: \"system\", content: header }, ...messages];\n }\n\n // Prepend to first user message (only if content is a string)\n return messages.map((msg, i) => {\n if (i === userIndex) {\n // Only prepend to string content - skip arrays (multimodal messages)\n if (typeof msg.content === \"string\") {\n return {\n ...msg,\n content: `${header}\\n\\n${msg.content}`,\n };\n }\n // For non-string content, don't modify the message\n // The codebook header would corrupt array content\n }\n return msg;\n });\n}\n\n/**\n * Main compression function.\n *\n * Applies 5 layers in sequence:\n * 1. Deduplication - Remove exact duplicate messages\n * 2. Whitespace - Normalize excessive whitespace\n * 3. Dictionary - Replace common phrases with codes\n * 4. Paths - Shorten repeated file paths\n * 5. JSON - Compact JSON in tool calls\n *\n * Then prepends a codebook header for the LLM to decode in-context.\n */\nexport async function compressContext(\n messages: NormalizedMessage[],\n config: Partial = {},\n): Promise {\n const fullConfig: CompressionConfig = {\n ...DEFAULT_COMPRESSION_CONFIG,\n ...config,\n layers: {\n ...DEFAULT_COMPRESSION_CONFIG.layers,\n ...config.layers,\n },\n dictionary: {\n ...DEFAULT_COMPRESSION_CONFIG.dictionary,\n ...config.dictionary,\n },\n };\n\n // If compression disabled, return as-is\n if (!fullConfig.enabled) {\n const originalChars = calculateTotalChars(messages);\n return {\n messages,\n originalMessages: messages,\n originalChars,\n compressedChars: originalChars,\n compressionRatio: 1,\n stats: {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n },\n codebook: {},\n pathMap: {},\n dynamicCodes: {},\n };\n }\n\n // Preserve originals for logging\n const originalMessages = fullConfig.preserveRaw ? cloneMessages(messages) : messages;\n const originalChars = calculateTotalChars(messages);\n\n // Initialize stats\n const stats: CompressionStats = {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n };\n\n let result = cloneMessages(messages);\n let usedCodes = new Set();\n let pathMap: Record = {};\n let dynamicCodes: Record = {};\n\n // Layer 1: Deduplication\n if (fullConfig.layers.deduplication) {\n const dedupResult = deduplicateMessages(result);\n result = dedupResult.messages;\n stats.duplicatesRemoved = dedupResult.duplicatesRemoved;\n }\n\n // Layer 2: Whitespace normalization\n if (fullConfig.layers.whitespace) {\n const wsResult = normalizeMessagesWhitespace(result);\n result = wsResult.messages;\n stats.whitespaceSavedChars = wsResult.charsSaved;\n }\n\n // Layer 3: Dictionary encoding\n if (fullConfig.layers.dictionary) {\n const dictResult = encodeMessages(result);\n result = dictResult.messages;\n stats.dictionarySubstitutions = dictResult.substitutionCount;\n usedCodes = dictResult.usedCodes;\n }\n\n // Layer 4: Path shortening\n if (fullConfig.layers.paths) {\n const pathResult = shortenPaths(result);\n result = pathResult.messages;\n pathMap = pathResult.pathMap;\n stats.pathsShortened = Object.keys(pathMap).length;\n }\n\n // Layer 5: JSON compaction\n if (fullConfig.layers.jsonCompact) {\n const jsonResult = compactMessagesJson(result);\n result = jsonResult.messages;\n stats.jsonCompactedChars = jsonResult.charsSaved;\n }\n\n // Layer 6: Observation compression (BIG WIN - 97% on tool results)\n if (fullConfig.layers.observation) {\n const obsResult = compressObservations(result);\n result = obsResult.messages;\n stats.observationsCompressed = obsResult.observationsCompressed;\n stats.observationCharsSaved = obsResult.charsSaved;\n }\n\n // Layer 7: Dynamic codebook (learns from actual content)\n if (fullConfig.layers.dynamicCodebook) {\n const dynResult = applyDynamicCodebook(result);\n result = dynResult.messages;\n stats.dynamicSubstitutions = dynResult.substitutions;\n stats.dynamicCharsSaved = dynResult.charsSaved;\n dynamicCodes = dynResult.dynamicCodes;\n }\n\n // Add codebook header if enabled and we have codes to include\n if (\n fullConfig.dictionary.includeCodebookHeader &&\n (usedCodes.size > 0 || Object.keys(pathMap).length > 0 || Object.keys(dynamicCodes).length > 0)\n ) {\n result = prependCodebookHeader(result, usedCodes, pathMap);\n // Also add dynamic codebook header if we have dynamic codes\n if (Object.keys(dynamicCodes).length > 0) {\n const dynHeader = generateDynamicCodebookHeader(dynamicCodes);\n if (dynHeader) {\n const systemIndex = result.findIndex((m) => m.role === \"system\");\n // Only prepend to string content - skip arrays (multimodal messages)\n if (systemIndex >= 0 && typeof result[systemIndex].content === \"string\") {\n result[systemIndex] = {\n ...result[systemIndex],\n content: `${dynHeader}\\n${result[systemIndex].content}`,\n };\n }\n }\n }\n }\n\n // Calculate final stats\n const compressedChars = calculateTotalChars(result);\n const compressionRatio = compressedChars / originalChars;\n\n // Build used codebook for logging\n const usedCodebook: Record = {};\n usedCodes.forEach((code) => {\n usedCodebook[code] = STATIC_CODEBOOK[code];\n });\n\n return {\n messages: result,\n originalMessages,\n originalChars,\n compressedChars,\n compressionRatio,\n stats,\n codebook: usedCodebook,\n pathMap,\n dynamicCodes,\n };\n}\n\n/**\n * Quick check if compression would benefit these messages.\n * Returns true if messages are large enough to warrant compression.\n */\nexport function shouldCompress(messages: NormalizedMessage[]): boolean {\n const chars = calculateTotalChars(messages);\n // Only compress if > 5000 chars (roughly 1000 tokens)\n return chars > 5000;\n}\n","/**\n * Session Persistence Store\n *\n * Tracks model selections per session to prevent model switching mid-task.\n * When a session is active, the router will continue using the same model\n * instead of re-routing each request.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type SessionEntry = {\n model: string;\n tier: string;\n createdAt: number;\n lastUsedAt: number;\n requestCount: number;\n // --- Three-strike escalation ---\n recentHashes: string[]; // Sliding window of last 3 request content fingerprints\n strikes: number; // Consecutive similar request count\n escalated: boolean; // Whether session was already escalated via three-strike\n // --- Cost accumulation for maxCostPerRun ---\n sessionCostMicros: bigint; // Total estimated cost for this session run (USDC 6-decimal)\n};\n\nexport type SessionConfig = {\n /** Enable session persistence (default: false) */\n enabled: boolean;\n /** Session timeout in ms (default: 30 minutes) */\n timeoutMs: number;\n /** Header name for session ID (default: X-Session-ID) */\n headerName: string;\n};\n\nexport const DEFAULT_SESSION_CONFIG: SessionConfig = {\n enabled: true,\n timeoutMs: 30 * 60 * 1000, // 30 minutes\n headerName: \"x-session-id\",\n};\n\n/**\n * Session persistence store for maintaining model selections.\n */\nexport class SessionStore {\n private sessions: Map = new Map();\n private config: SessionConfig;\n private cleanupInterval: ReturnType | null = null;\n\n constructor(config: Partial = {}) {\n this.config = { ...DEFAULT_SESSION_CONFIG, ...config };\n\n // Start cleanup interval (every 5 minutes)\n if (this.config.enabled) {\n this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1000);\n }\n }\n\n /**\n * Get the pinned model for a session, if any.\n */\n getSession(sessionId: string): SessionEntry | undefined {\n if (!this.config.enabled || !sessionId) {\n return undefined;\n }\n\n const entry = this.sessions.get(sessionId);\n if (!entry) {\n return undefined;\n }\n\n // Check if session has expired\n const now = Date.now();\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(sessionId);\n return undefined;\n }\n\n return entry;\n }\n\n /**\n * Pin a model to a session.\n */\n setSession(sessionId: string, model: string, tier: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const existing = this.sessions.get(sessionId);\n const now = Date.now();\n\n if (existing) {\n existing.lastUsedAt = now;\n existing.requestCount++;\n // Update model if different (e.g., fallback)\n if (existing.model !== model) {\n existing.model = model;\n existing.tier = tier;\n }\n } else {\n this.sessions.set(sessionId, {\n model,\n tier,\n createdAt: now,\n lastUsedAt: now,\n requestCount: 1,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n });\n }\n }\n\n /**\n * Touch a session to extend its timeout.\n */\n touchSession(sessionId: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const entry = this.sessions.get(sessionId);\n if (entry) {\n entry.lastUsedAt = Date.now();\n entry.requestCount++;\n }\n }\n\n /**\n * Clear a specific session.\n */\n clearSession(sessionId: string): void {\n this.sessions.delete(sessionId);\n }\n\n /**\n * Clear all sessions.\n */\n clearAll(): void {\n this.sessions.clear();\n }\n\n /**\n * Get session stats for debugging.\n */\n getStats(): { count: number; sessions: Array<{ id: string; model: string; age: number }> } {\n const now = Date.now();\n const sessions = Array.from(this.sessions.entries()).map(([id, entry]) => ({\n id: id.slice(0, 8) + \"...\",\n model: entry.model,\n age: Math.round((now - entry.createdAt) / 1000),\n }));\n return { count: this.sessions.size, sessions };\n }\n\n /**\n * Clean up expired sessions.\n */\n private cleanup(): void {\n const now = Date.now();\n for (const [id, entry] of this.sessions) {\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(id);\n }\n }\n }\n\n /**\n * Record a request content hash and detect repetitive patterns.\n * Returns true if escalation should be triggered (3+ consecutive similar requests).\n */\n recordRequestHash(sessionId: string, hash: string): boolean {\n const entry = this.sessions.get(sessionId);\n if (!entry) return false;\n\n const prev = entry.recentHashes;\n if (prev.length > 0 && prev[prev.length - 1] === hash) {\n entry.strikes++;\n } else {\n entry.strikes = 0;\n }\n\n entry.recentHashes.push(hash);\n if (entry.recentHashes.length > 3) {\n entry.recentHashes.shift();\n }\n\n return entry.strikes >= 2 && !entry.escalated;\n }\n\n /**\n * Escalate session to next tier. Returns the new model/tier or null if already at max.\n */\n escalateSession(\n sessionId: string,\n tierConfigs: Record,\n ): { model: string; tier: string } | null {\n const entry = this.sessions.get(sessionId);\n if (!entry) return null;\n\n const TIER_ORDER = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\"];\n const currentIdx = TIER_ORDER.indexOf(entry.tier);\n if (currentIdx < 0 || currentIdx >= TIER_ORDER.length - 1) return null;\n\n const nextTier = TIER_ORDER[currentIdx + 1];\n const nextConfig = tierConfigs[nextTier];\n if (!nextConfig) return null;\n\n entry.model = nextConfig.primary;\n entry.tier = nextTier;\n entry.strikes = 0;\n entry.escalated = true;\n\n return { model: nextConfig.primary, tier: nextTier };\n }\n\n /**\n * Add cost to a session's running total for maxCostPerRun tracking.\n * Cost is in USDC 6-decimal units (micros).\n * Creates a cost-tracking-only entry if none exists (e.g., explicit model requests\n * that never go through the routing path).\n */\n addSessionCost(sessionId: string, additionalMicros: bigint): void {\n let entry = this.sessions.get(sessionId);\n if (!entry) {\n const now = Date.now();\n entry = {\n model: \"\",\n tier: \"DIRECT\",\n createdAt: now,\n lastUsedAt: now,\n requestCount: 0,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n };\n this.sessions.set(sessionId, entry);\n }\n entry.sessionCostMicros += additionalMicros;\n }\n\n /**\n * Get the total accumulated cost for a session in USD.\n */\n getSessionCostUsd(sessionId: string): number {\n const entry = this.sessions.get(sessionId);\n if (!entry) return 0;\n return Number(entry.sessionCostMicros) / 1_000_000;\n }\n\n /**\n * Stop the cleanup interval.\n */\n close(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n}\n\n/**\n * Generate a session ID from request headers or create a default.\n */\nexport function getSessionId(\n headers: Record,\n headerName: string = DEFAULT_SESSION_CONFIG.headerName,\n): string | undefined {\n const value = headers[headerName] || headers[headerName.toLowerCase()];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n if (Array.isArray(value) && value.length > 0) {\n return value[0];\n }\n return undefined;\n}\n\n/**\n * Derive a stable session ID from message content when no explicit session\n * header is provided. Uses the first user message as the conversation anchor —\n * same opening message = same session ID across all subsequent turns.\n *\n * This prevents model-switching mid-conversation even when OpenClaw doesn't\n * send an x-session-id header (which is the default OpenClaw behaviour).\n */\nexport function deriveSessionId(\n messages: Array<{ role: string; content: unknown }>,\n): string | undefined {\n const firstUser = messages.find((m) => m.role === \"user\");\n if (!firstUser) return undefined;\n\n const content =\n typeof firstUser.content === \"string\" ? firstUser.content : JSON.stringify(firstUser.content);\n\n // 8-char hex prefix of SHA-256 — short enough for logs, collision-resistant\n // enough for session tracking within a single gateway instance.\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 8);\n}\n\n/**\n * Generate a short hash fingerprint from request content.\n * Captures: last user message text + tool call names (if any).\n * Normalizes whitespace to avoid false negatives from minor formatting diffs.\n */\nexport function hashRequestContent(lastUserContent: string, toolCallNames?: string[]): string {\n const normalized = lastUserContent.replace(/\\s+/g, \" \").trim().slice(0, 500);\n const toolSuffix = toolCallNames?.length ? `|tools:${toolCallNames.sort().join(\",\")}` : \"\";\n return createHash(\"sha256\")\n .update(normalized + toolSuffix)\n .digest(\"hex\")\n .slice(0, 12);\n}\n","/**\n * Auto-update checker for ClawRouter.\n * Checks npm registry on startup and notifies user if update available.\n */\n\nimport { VERSION } from \"./version.js\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org/@blockrun/clawrouter/latest\";\nconst CHECK_TIMEOUT_MS = 5_000; // Don't block startup for more than 5s\n\n/**\n * Compare semver versions. Returns:\n * 1 if a > b\n * 0 if a === b\n * -1 if a < b\n */\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split(\".\").map(Number);\n const pb = b.split(\".\").map(Number);\n for (let i = 0; i < 3; i++) {\n if ((pa[i] || 0) > (pb[i] || 0)) return 1;\n if ((pa[i] || 0) < (pb[i] || 0)) return -1;\n }\n return 0;\n}\n\n/**\n * Check npm registry for latest version.\n * Non-blocking, silent on errors.\n */\nexport async function checkForUpdates(): Promise {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);\n\n const res = await fetch(NPM_REGISTRY, {\n signal: controller.signal,\n headers: { Accept: \"application/json\" },\n });\n clearTimeout(timeout);\n\n if (!res.ok) return;\n\n const data = (await res.json()) as { version?: string };\n const latest = data.version;\n\n if (!latest) return;\n\n if (compareSemver(latest, VERSION) > 0) {\n console.log(\"\");\n console.log(`\\x1b[33m⬆️ ClawRouter ${latest} available (you have ${VERSION})\\x1b[0m`);\n console.log(` Run: \\x1b[36mnpx @blockrun/clawrouter@latest\\x1b[0m`);\n console.log(\"\");\n }\n } catch {\n // Silent fail - don't disrupt startup\n }\n}\n","/**\n * Exclude-models persistence module.\n *\n * Manages a user-configurable list of model IDs that the smart router\n * should never select. Stored as a sorted JSON array on disk.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { resolveModelAlias } from \"./models.js\";\n\nconst DEFAULT_FILE_PATH = join(homedir(), \".openclaw\", \"blockrun\", \"exclude-models.json\");\n\n/**\n * Load the exclude list from disk.\n * Returns an empty set if the file does not exist.\n */\nexport function loadExcludeList(filePath: string = DEFAULT_FILE_PATH): Set {\n try {\n const raw = readFileSync(filePath, \"utf-8\");\n const arr: unknown = JSON.parse(raw);\n if (Array.isArray(arr)) {\n return new Set(arr.filter((x): x is string => typeof x === \"string\"));\n }\n return new Set();\n } catch {\n return new Set();\n }\n}\n\n/**\n * Save a set of model IDs to disk as a sorted JSON array.\n */\nfunction saveExcludeList(set: Set, filePath: string): void {\n const sorted = [...set].sort();\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n writeFileSync(filePath, JSON.stringify(sorted, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Add a model to the exclude list.\n * Resolves aliases before persisting.\n * @returns The resolved model ID.\n */\nexport function addExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): string {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n set.add(resolved);\n saveExcludeList(set, filePath);\n return resolved;\n}\n\n/**\n * Remove a model from the exclude list.\n * Resolves aliases before removing.\n * @returns true if the model was present and removed, false otherwise.\n */\nexport function removeExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): boolean {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n const had = set.delete(resolved);\n if (had) {\n saveExcludeList(set, filePath);\n }\n return had;\n}\n\n/**\n * Clear the entire exclude list.\n */\nexport function clearExclusions(filePath: string = DEFAULT_FILE_PATH): void {\n saveExcludeList(new Set(), filePath);\n}\n","/**\n * Configuration Module\n *\n * Reads environment variables at module load time.\n * Separated from network code to avoid security scanner false positives.\n */\n\nconst DEFAULT_PORT = 8402;\n\n/**\n * Proxy port configuration - resolved once at module load.\n * Reads BLOCKRUN_PROXY_PORT env var or defaults to 8402.\n */\nexport const PROXY_PORT = (() => {\n const envPort = process[\"env\"].BLOCKRUN_PROXY_PORT;\n if (envPort) {\n const parsed = parseInt(envPort, 10);\n if (!isNaN(parsed) && parsed > 0 && parsed < 65536) {\n return parsed;\n }\n }\n return DEFAULT_PORT;\n})();\n","/**\n * Session Journal - Memory layer for ClawRouter\n *\n * Maintains a compact record of key actions per session, enabling agents\n * to recall earlier work even when OpenClaw's sessions_history is truncated.\n *\n * How it works:\n * 1. As LLM responses flow through, extracts key actions (\"I created X\", \"I fixed Y\")\n * 2. Stores them in a compact journal per session\n * 3. When a request mentions past work (\"what did you do today?\"), injects the journal\n */\n\nexport interface JournalEntry {\n timestamp: number;\n action: string; // Compact description: \"Created login component\"\n model?: string;\n}\n\nexport interface SessionJournalConfig {\n /** Maximum entries per session (default: 100) */\n maxEntries?: number;\n /** Maximum age of entries in ms (default: 24 hours) */\n maxAgeMs?: number;\n /** Maximum events to extract per response (default: 5) */\n maxEventsPerResponse?: number;\n}\n\nconst DEFAULT_CONFIG: Required = {\n maxEntries: 100,\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxEventsPerResponse: 5,\n};\n\nexport class SessionJournal {\n private journals: Map = new Map();\n private config: Required;\n\n constructor(config?: SessionJournalConfig) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Extract key events from assistant response content.\n * Looks for patterns like \"I created...\", \"I fixed...\", \"Successfully...\"\n */\n extractEvents(content: string): string[] {\n if (!content || typeof content !== \"string\") {\n return [];\n }\n\n const events: string[] = [];\n const seen = new Set();\n\n // Patterns for identifying key actions\n // Note: Patterns allow optional words like \"also\", \"then\", \"have\" between \"I\" and verb\n const patterns = [\n // Creation patterns\n /I (?:also |then |have |)?(?:created|implemented|added|wrote|built|generated|set up|initialized) ([^.!?\\n]{10,150})/gi,\n // Fix patterns\n /I (?:also |then |have |)?(?:fixed|resolved|solved|patched|corrected|addressed|debugged) ([^.!?\\n]{10,150})/gi,\n // Completion patterns\n /I (?:also |then |have |)?(?:completed|finished|done with|wrapped up) ([^.!?\\n]{10,150})/gi,\n // Update patterns\n /I (?:also |then |have |)?(?:updated|modified|changed|refactored|improved|enhanced|optimized) ([^.!?\\n]{10,150})/gi,\n // Success patterns\n /Successfully ([^.!?\\n]{10,150})/gi,\n // Tool usage patterns (when agent uses tools)\n /I (?:also |then |have |)?(?:ran|executed|called|invoked) ([^.!?\\n]{10,100})/gi,\n ];\n\n for (const pattern of patterns) {\n // Reset pattern lastIndex for each iteration\n pattern.lastIndex = 0;\n\n let match;\n while ((match = pattern.exec(content)) !== null) {\n const action = match[0].trim();\n\n // Skip if already seen (dedup)\n const normalized = action.toLowerCase();\n if (seen.has(normalized)) {\n continue;\n }\n\n // Validate length (not too short or too long)\n if (action.length >= 15 && action.length <= 200) {\n events.push(action);\n seen.add(normalized);\n }\n\n // Stop if we have enough events\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n return events;\n }\n\n /**\n * Record events to the session journal.\n */\n record(sessionId: string, events: string[], model?: string): void {\n if (!sessionId || !events.length) {\n return;\n }\n\n const journal = this.journals.get(sessionId) || [];\n const now = Date.now();\n\n for (const action of events) {\n journal.push({\n timestamp: now,\n action,\n model,\n });\n }\n\n // Trim old entries and enforce max count\n const cutoff = now - this.config.maxAgeMs;\n const trimmed = journal.filter((e) => e.timestamp > cutoff).slice(-this.config.maxEntries);\n\n this.journals.set(sessionId, trimmed);\n }\n\n /**\n * Check if the user message indicates a need for historical context.\n */\n needsContext(lastUserMessage: string): boolean {\n if (!lastUserMessage || typeof lastUserMessage !== \"string\") {\n return false;\n }\n\n const lower = lastUserMessage.toLowerCase();\n\n // Trigger phrases that indicate user wants to recall past work\n const triggers = [\n // Direct questions about past work\n \"what did you do\",\n \"what have you done\",\n \"what did we do\",\n \"what have we done\",\n // Temporal references\n \"earlier\",\n \"before\",\n \"previously\",\n \"this session\",\n \"today\",\n \"so far\",\n // Summary requests\n \"remind me\",\n \"summarize\",\n \"summary of\",\n \"recap\",\n // Progress inquiries\n \"your work\",\n \"your progress\",\n \"accomplished\",\n \"achievements\",\n \"completed tasks\",\n ];\n\n return triggers.some((t) => lower.includes(t));\n }\n\n /**\n * Format the journal for injection into system message.\n * Returns null if journal is empty.\n */\n format(sessionId: string): string | null {\n const journal = this.journals.get(sessionId);\n if (!journal?.length) {\n return null;\n }\n\n const lines = journal.map((e) => {\n const time = new Date(e.timestamp).toLocaleTimeString(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n });\n return `- ${time}: ${e.action}`;\n });\n\n return `[Session Memory - Key Actions]\\n${lines.join(\"\\n\")}`;\n }\n\n /**\n * Get the raw journal entries for a session (for debugging/testing).\n */\n getEntries(sessionId: string): JournalEntry[] {\n return this.journals.get(sessionId) || [];\n }\n\n /**\n * Clear journal for a specific session.\n */\n clear(sessionId: string): void {\n this.journals.delete(sessionId);\n }\n\n /**\n * Clear all journals.\n */\n clearAll(): void {\n this.journals.clear();\n }\n\n /**\n * Get stats about the journal.\n */\n getStats(): { sessions: number; totalEntries: number } {\n let totalEntries = 0;\n for (const entries of this.journals.values()) {\n totalEntries += entries.length;\n }\n return {\n sessions: this.journals.size,\n totalEntries,\n };\n }\n}\n","/**\n * @blockrun/clawrouter\n *\n * Smart LLM router for OpenClaw — 55+ models, x402 micropayments, 78% cost savings.\n * Routes each request to the cheapest model that can handle it.\n *\n * Usage:\n * # Install the plugin\n * openclaw plugins install @blockrun/clawrouter\n *\n * # Fund your wallet with USDC on Base (address printed on install)\n *\n * # Use smart routing (auto-picks cheapest model)\n * openclaw models set blockrun/auto\n *\n * # Or use any specific BlockRun model\n * openclaw models set openai/gpt-5.3\n */\n\nimport type {\n OpenClawPluginDefinition,\n OpenClawPluginApi,\n PluginCommandContext,\n OpenClawPluginCommandDefinition,\n} from \"./types.js\";\nimport { blockrunProvider, setActiveProxy } from \"./provider.js\";\nimport { startProxy, getProxyPort } from \"./proxy.js\";\nimport {\n resolveOrGenerateWalletKey,\n setupSolana,\n savePaymentChain,\n resolvePaymentChain,\n WALLET_FILE,\n MNEMONIC_FILE,\n} from \"./auth.js\";\nimport type { RoutingConfig } from \"./router/index.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport {\n loadExcludeList,\n addExclusion,\n removeExclusion,\n clearExclusions,\n} from \"./exclude-models.js\";\n\n/**\n * Wait for proxy health check to pass (quick check, not RPC).\n * Returns true if healthy within timeout, false otherwise.\n */\nasync function waitForProxyHealth(port: number, timeoutMs = 3000): Promise {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n const res = await fetch(`http://127.0.0.1:${port}/health`);\n if (res.ok) return true;\n } catch {\n // Proxy not ready yet\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n return false;\n}\nimport { OPENCLAW_MODELS } from \"./models.js\";\nimport {\n writeFileSync,\n existsSync,\n readdirSync,\n mkdirSync,\n copyFileSync,\n renameSync,\n} from \"node:fs\";\nimport { readTextFileSync } from \"./fs-read.js\";\nimport { homedir } from \"node:os\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { VERSION } from \"./version.js\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { getStats, formatStatsAscii, clearStats } from \"./stats.js\";\nimport { buildPartnerTools, PARTNER_SERVICES } from \"./partners/index.js\";\n\n/**\n * Install ClawRouter skills into OpenClaw's workspace skills directory.\n *\n * OpenClaw agents discover skills by scanning {workspaceDir}/skills/ for SKILL.md\n * files. While the plugin manifest (`openclaw.plugin.json`) exposes skills for\n * OpenClaw's internal registry, agents often try to read skills from the workspace\n * path directly. This copies our bundled skills so they're always resolvable.\n *\n * Workspace path follows OpenClaw's convention:\n * - Default: ~/.openclaw/workspace/skills/\n * - With profile: ~/.openclaw/workspace-{profile}/skills/\n *\n * Only copies if the skill is missing or the content has changed.\n */\nfunction installSkillsToWorkspace(logger: {\n info: (msg: string) => void;\n warn: (msg: string) => void;\n}) {\n try {\n // Resolve the package root: dist/index.js -> package root\n const packageRoot = join(dirname(fileURLToPath(import.meta.url)), \"..\");\n const bundledSkillsDir = join(packageRoot, \"skills\");\n\n if (!existsSync(bundledSkillsDir)) {\n // Skills directory not bundled (dev mode or stripped package)\n return;\n }\n\n // Match OpenClaw's workspace resolution: ~/.openclaw/workspace[-{profile}]/\n const profile = (process[\"env\"].OPENCLAW_PROFILE ?? \"\").trim().toLowerCase();\n const workspaceDirName =\n profile && profile !== \"default\" ? `workspace-${profile}` : \"workspace\";\n const workspaceSkillsDir = join(homedir(), \".openclaw\", workspaceDirName, \"skills\");\n mkdirSync(workspaceSkillsDir, { recursive: true });\n\n // Scan bundled skills: each subdirectory contains a SKILL.md\n // Skip internal-only skills (release is for ClawRouter maintainers, not end users)\n const INTERNAL_SKILLS = new Set([\"release\"]);\n const entries = readdirSync(bundledSkillsDir, { withFileTypes: true });\n let installed = 0;\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n\n const skillName = entry.name;\n if (INTERNAL_SKILLS.has(skillName)) continue;\n const srcSkillFile = join(bundledSkillsDir, skillName, \"SKILL.md\");\n if (!existsSync(srcSkillFile)) continue;\n\n // Use original skill name as folder (matches what agents expect)\n const destDir = join(workspaceSkillsDir, skillName);\n const destSkillFile = join(destDir, \"SKILL.md\");\n\n // Check if update needed: compare content\n let needsUpdate = true;\n if (existsSync(destSkillFile)) {\n try {\n const srcContent = readTextFileSync(srcSkillFile);\n const destContent = readTextFileSync(destSkillFile);\n if (srcContent === destContent) needsUpdate = false;\n } catch {\n // Can't read — overwrite\n }\n }\n\n if (needsUpdate) {\n mkdirSync(destDir, { recursive: true });\n copyFileSync(srcSkillFile, destSkillFile);\n installed++;\n }\n }\n\n if (installed > 0) {\n logger.info(`Installed ${installed} skill(s) to ${workspaceSkillsDir}`);\n }\n } catch (err) {\n logger.warn(`Failed to install skills: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n/**\n * Detect if we're running in shell completion mode.\n * When `openclaw completion --shell zsh` runs, it loads plugins but only needs\n * the completion script output - any stdout logging pollutes the script and\n * causes zsh to interpret colored text like `[plugins]` as glob patterns.\n */\nfunction isCompletionMode(): boolean {\n const args = process.argv;\n // Check for: openclaw completion --shell \n // argv[0] = node/bun, argv[1] = openclaw, argv[2] = completion\n return args.some((arg, i) => arg === \"completion\" && i >= 1 && i <= 3);\n}\n\n/**\n * Detect if we're running in gateway mode.\n * The proxy should ONLY start when the gateway is running.\n * During CLI commands (plugins, models, etc), the proxy keeps the process alive.\n */\nfunction isGatewayMode(): boolean {\n const args = process.argv;\n // Gateway mode is: openclaw gateway start/restart/stop\n return args.includes(\"gateway\");\n}\n\n/**\n * Inject BlockRun models config into OpenClaw config file.\n * This is required because registerProvider() alone doesn't make models available.\n *\n * CRITICAL: This function must be idempotent and handle ALL edge cases:\n * - Config file doesn't exist (create it)\n * - Config file exists but is empty/invalid (reinitialize)\n * - blockrun provider exists but has undefined fields (fix them)\n * - Config exists but uses old port/models (update them)\n *\n * This function is called on EVERY plugin load to ensure config is always correct.\n */\nfunction injectModelsConfig(logger: { info: (msg: string) => void }): void {\n const configDir = join(homedir(), \".openclaw\");\n const configPath = join(configDir, \"openclaw.json\");\n\n let config: Record = {};\n let needsWrite = false;\n\n // Create config directory if it doesn't exist\n if (!existsSync(configDir)) {\n try {\n mkdirSync(configDir, { recursive: true });\n logger.info(\"Created OpenClaw config directory\");\n } catch (err) {\n logger.info(\n `Failed to create config dir: ${err instanceof Error ? err.message : String(err)}`,\n );\n return;\n }\n }\n\n // Load existing config or create new one\n // IMPORTANT: On parse failure, we backup and skip writing to avoid clobbering\n // other plugins' config (e.g. Telegram channels). This prevents a race condition\n // where a partial/corrupt config file causes us to overwrite everything with\n // only our models+agents sections.\n if (existsSync(configPath)) {\n try {\n const content = readTextFileSync(configPath).trim();\n if (content) {\n config = JSON.parse(content);\n } else {\n logger.info(\"OpenClaw config is empty, initializing\");\n needsWrite = true;\n }\n } catch (err) {\n // Config file exists but is corrupt/invalid JSON — likely a partial write\n // from another plugin or a race condition during gateway restart.\n // Backup the corrupt file and SKIP writing to avoid losing other config.\n const backupPath = `${configPath}.backup.${Date.now()}`;\n try {\n copyFileSync(configPath, backupPath);\n logger.info(`Config parse failed, backed up to ${backupPath}`);\n } catch {\n logger.info(\"Config parse failed, could not create backup\");\n }\n logger.info(\n `Skipping config injection (corrupt file): ${err instanceof Error ? err.message : String(err)}`,\n );\n return; // Don't write — we'd lose other plugins' config\n }\n } else {\n logger.info(\"OpenClaw config not found, creating\");\n needsWrite = true;\n }\n\n // Initialize config structure\n if (!config.models) {\n config.models = {};\n needsWrite = true;\n }\n const models = config.models as Record;\n if (!models.providers) {\n models.providers = {};\n needsWrite = true;\n }\n\n const proxyPort = getProxyPort();\n const expectedBaseUrl = `http://127.0.0.1:${proxyPort}/v1`;\n\n const providers = models.providers as Record;\n\n if (!providers.blockrun) {\n // Create new blockrun provider config\n providers.blockrun = {\n baseUrl: expectedBaseUrl,\n api: \"openai-completions\",\n // apiKey is required by pi-coding-agent's ModelRegistry for providers with models.\n // We use a placeholder since the proxy handles real x402 auth internally.\n apiKey: \"x402-proxy-handles-auth\",\n models: OPENCLAW_MODELS,\n };\n logger.info(\"Injected BlockRun provider config\");\n needsWrite = true;\n } else {\n // Validate and fix existing blockrun config\n const blockrun = providers.blockrun as Record;\n let fixed = false;\n\n // Fix: explicitly check for undefined/missing fields\n if (!blockrun.baseUrl || blockrun.baseUrl !== expectedBaseUrl) {\n blockrun.baseUrl = expectedBaseUrl;\n fixed = true;\n }\n // Ensure api field is present\n if (!blockrun.api) {\n blockrun.api = \"openai-completions\";\n fixed = true;\n }\n // Ensure apiKey is present (required by ModelRegistry for /model picker)\n if (!blockrun.apiKey) {\n blockrun.apiKey = \"x402-proxy-handles-auth\";\n fixed = true;\n }\n // Always refresh models list (ensures new models/aliases are available)\n // Check both length AND content - new models may be added without changing count\n const currentModels = blockrun.models as Array<{ id?: string }>;\n const currentModelIds = new Set(\n Array.isArray(currentModels) ? currentModels.map((m) => m?.id).filter(Boolean) : [],\n );\n const expectedModelIds = OPENCLAW_MODELS.map((m) => m.id);\n const needsModelUpdate =\n !currentModels ||\n !Array.isArray(currentModels) ||\n currentModels.length !== OPENCLAW_MODELS.length ||\n expectedModelIds.some((id) => !currentModelIds.has(id));\n\n if (needsModelUpdate) {\n blockrun.models = OPENCLAW_MODELS;\n fixed = true;\n logger.info(`Updated models list (${OPENCLAW_MODELS.length} models)`);\n }\n\n if (fixed) {\n logger.info(\"Fixed incomplete BlockRun provider config\");\n needsWrite = true;\n }\n }\n\n // Set blockrun/auto as default model ONLY on first install (not every load!)\n // This respects user's model selection and prevents hijacking their choice.\n if (!config.agents) {\n config.agents = {};\n needsWrite = true;\n }\n const agents = config.agents as Record;\n if (!agents.defaults) {\n agents.defaults = {};\n needsWrite = true;\n }\n const defaults = agents.defaults as Record;\n if (!defaults.model || typeof defaults.model !== \"object\" || Array.isArray(defaults.model)) {\n // Convert plain string \"blockrun/auto\" → { primary: \"blockrun/auto\" }\n // Also handles number, boolean, array, or any other non-object type\n const prev = typeof defaults.model === \"string\" ? defaults.model : undefined;\n defaults.model = prev ? { primary: prev } : {};\n needsWrite = true;\n }\n const model = defaults.model as Record;\n\n // ONLY set default if no primary model exists (first install)\n // Do NOT override user's selection on subsequent loads\n if (!model.primary) {\n model.primary = \"blockrun/auto\";\n logger.info(\"Set default model to blockrun/auto (first install)\");\n needsWrite = true;\n }\n\n // Populate agents.defaults.models (the allowlist) with top BlockRun models.\n // OpenClaw uses this as a whitelist — only listed models appear in the /model picker.\n // Existing non-blockrun entries are preserved (e.g. from other providers).\n const TOP_MODELS = [\n \"auto\",\n \"free\",\n \"eco\",\n \"premium\",\n \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-haiku-4.5\",\n \"openai/gpt-5.4\",\n \"openai/gpt-5.3\",\n \"openai/gpt-5.3-codex\",\n \"openai/gpt-4o\",\n \"openai/o3\",\n \"google/gemini-3.1-pro\",\n \"google/gemini-3-flash-preview\",\n \"deepseek/deepseek-chat\",\n \"moonshot/kimi-k2.5\",\n \"xai/grok-3\",\n \"minimax/minimax-m2.5\",\n // Free models (free/ prefix so users see \"free\" in picker)\n \"free/gpt-oss-120b\",\n \"free/gpt-oss-20b\",\n \"free/nemotron-ultra-253b\",\n \"free/deepseek-v3.2\",\n \"free/mistral-large-3-675b\",\n \"free/qwen3-coder-480b\",\n \"free/devstral-2-123b\",\n \"free/llama-4-maverick\",\n \"free/nemotron-3-super-120b\",\n \"free/nemotron-super-49b\",\n \"free/glm-4.7\",\n ];\n if (!defaults.models || typeof defaults.models !== \"object\" || Array.isArray(defaults.models)) {\n defaults.models = {};\n needsWrite = true;\n }\n const allowlist = defaults.models as Record;\n const DEPRECATED_BLOCKRUN_MODELS = [\"blockrun/xai/grok-code-fast-1\"];\n let removedDeprecatedCount = 0;\n for (const key of DEPRECATED_BLOCKRUN_MODELS) {\n if (allowlist[key]) {\n delete allowlist[key];\n removedDeprecatedCount++;\n }\n }\n if (removedDeprecatedCount > 0) {\n needsWrite = true;\n logger.info(`Removed ${removedDeprecatedCount} deprecated model entries from allowlist`);\n }\n // Additive-only: add TOP_MODELS entries if missing, never delete user-defined entries.\n // Preserves any blockrun/* IDs the user has manually added outside this curated list.\n let addedCount = 0;\n for (const id of TOP_MODELS) {\n const key = `blockrun/${id}`;\n if (!allowlist[key]) {\n allowlist[key] = {};\n addedCount++;\n }\n }\n if (addedCount > 0) {\n needsWrite = true;\n logger.info(`Added ${addedCount} models to allowlist (${TOP_MODELS.length} total)`);\n }\n\n // Write config file if any changes were made\n // Use atomic write (temp file + rename) to prevent partial writes that could\n // corrupt the config and cause other plugins to lose their settings on next load.\n if (needsWrite) {\n try {\n const tmpPath = `${configPath}.tmp.${process.pid}`;\n writeFileSync(tmpPath, JSON.stringify(config, null, 2));\n renameSync(tmpPath, configPath);\n logger.info(\"Smart routing enabled (blockrun/auto)\");\n } catch (err) {\n logger.info(`Failed to write config: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n}\n\n/**\n * Inject dummy auth profile for BlockRun into agent auth stores.\n * OpenClaw's agent system looks for auth credentials even if provider has auth: [].\n * We inject a placeholder so the lookup succeeds (proxy handles real auth internally).\n */\nfunction injectAuthProfile(logger: { info: (msg: string) => void }): void {\n const agentsDir = join(homedir(), \".openclaw\", \"agents\");\n\n // Create agents directory if it doesn't exist\n if (!existsSync(agentsDir)) {\n try {\n mkdirSync(agentsDir, { recursive: true });\n } catch (err) {\n logger.info(\n `Could not create agents dir: ${err instanceof Error ? err.message : String(err)}`,\n );\n return;\n }\n }\n\n try {\n // Find all agent directories\n let agents = readdirSync(agentsDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name);\n\n // Always ensure \"main\" agent has auth (most common agent)\n if (!agents.includes(\"main\")) {\n agents = [\"main\", ...agents];\n }\n\n for (const agentId of agents) {\n const authDir = join(agentsDir, agentId, \"agent\");\n const authPath = join(authDir, \"auth-profiles.json\");\n\n // Create agent dir if needed\n if (!existsSync(authDir)) {\n try {\n mkdirSync(authDir, { recursive: true });\n } catch {\n continue; // Skip if we can't create the dir\n }\n }\n\n // Load or create auth-profiles.json with correct OpenClaw format\n // Format: { version: 1, profiles: { \"provider:profileId\": { type, provider, key } } }\n let store: { version: number; profiles: Record } = {\n version: 1,\n profiles: {},\n };\n if (existsSync(authPath)) {\n try {\n const existing = JSON.parse(readTextFileSync(authPath));\n // Check if valid OpenClaw format (has version and profiles)\n if (existing.version && existing.profiles) {\n store = existing;\n }\n // Old format without version/profiles is discarded and recreated\n } catch {\n // Invalid JSON, use fresh store\n }\n }\n\n // Check if blockrun auth already exists (OpenClaw format: profiles[\"provider:profileId\"])\n const profileKey = \"blockrun:default\";\n if (store.profiles[profileKey]) {\n continue; // Already configured\n }\n\n // Inject placeholder auth for blockrun (OpenClaw format)\n // The proxy handles real x402 auth internally, this just satisfies OpenClaw's lookup\n store.profiles[profileKey] = {\n type: \"api_key\",\n provider: \"blockrun\",\n key: \"x402-proxy-handles-auth\",\n };\n\n try {\n writeFileSync(authPath, JSON.stringify(store, null, 2));\n logger.info(`Injected BlockRun auth profile for agent: ${agentId}`);\n } catch (err) {\n logger.info(\n `Could not inject auth for ${agentId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n } catch (err) {\n logger.info(`Auth injection failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n// Store active proxy handle for cleanup on gateway_stop\nlet activeProxyHandle: Awaited> | null = null;\n\n/**\n * Start the x402 proxy in the background.\n * Called from register() because OpenClaw's loader only invokes register(),\n * treating activate() as an alias (def.register ?? def.activate).\n */\nasync function startProxyInBackground(api: OpenClawPluginApi): Promise {\n // Resolve wallet key: saved file → env var → auto-generate\n const wallet = await resolveOrGenerateWalletKey();\n\n // Log wallet source\n if (wallet.source === \"generated\") {\n api.logger.warn(`════════════════════════════════════════════════`);\n api.logger.warn(` NEW WALLET GENERATED — BACK UP YOUR KEY NOW!`);\n api.logger.warn(` Address : ${wallet.address}`);\n api.logger.warn(` Run /wallet export to get your private key`);\n api.logger.warn(` Losing this key = losing your USDC funds`);\n api.logger.warn(`════════════════════════════════════════════════`);\n } else if (wallet.source === \"saved\") {\n api.logger.info(`Using saved wallet: ${wallet.address}`);\n } else {\n api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);\n }\n\n // Resolve routing config overrides from plugin config\n const routingConfig = api.pluginConfig?.routing as Partial | undefined;\n\n const maxCostPerRunUsd =\n typeof api.pluginConfig?.maxCostPerRun === \"number\"\n ? (api.pluginConfig.maxCostPerRun as number)\n : undefined;\n\n const maxCostPerRunMode: \"graceful\" | \"strict\" =\n api.pluginConfig?.maxCostPerRunMode === \"strict\" ? \"strict\" : \"graceful\";\n\n if (maxCostPerRunUsd !== undefined) {\n api.logger.info(\n `Cost cap: $${maxCostPerRunUsd.toFixed(2)} per session (mode: ${maxCostPerRunMode})`,\n );\n }\n\n const proxy = await startProxy({\n wallet,\n routingConfig,\n maxCostPerRunUsd,\n maxCostPerRunMode,\n onReady: (port) => {\n api.logger.info(`BlockRun x402 proxy listening on port ${port}`);\n },\n onError: (error) => {\n api.logger.error(`BlockRun proxy error: ${error.message}`);\n },\n onRouted: (decision) => {\n const cost = decision.costEstimate.toFixed(4);\n const saved = (decision.savings * 100).toFixed(0);\n api.logger.info(\n `[${decision.tier}] ${decision.model} $${cost} (saved ${saved}%) | ${decision.reasoning}`,\n );\n },\n onLowBalance: (info) => {\n api.logger.warn(`[!] Low balance: ${info.balanceUSD}. Fund wallet: ${info.walletAddress}`);\n },\n onInsufficientFunds: (info) => {\n api.logger.error(\n `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund wallet: ${info.walletAddress}`,\n );\n },\n });\n\n setActiveProxy(proxy);\n activeProxyHandle = proxy;\n\n const startupExclusions = loadExcludeList();\n if (startupExclusions.size > 0) {\n api.logger.info(\n `Model exclusions active (${startupExclusions.size}): ${[...startupExclusions].join(\", \")}`,\n );\n }\n\n api.logger.info(`ClawRouter ready — smart routing enabled`);\n api.logger.info(`Pricing: Simple ~$0.001 | Code ~$0.01 | Complex ~$0.05 | Free: $0`);\n\n // Non-blocking balance check AFTER proxy is ready (won't hang startup)\n // Uses the proxy's chain-aware balance monitor and matching active-chain address.\n const currentChain = await resolvePaymentChain();\n const displayAddress =\n currentChain === \"solana\" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address;\n const network = currentChain === \"solana\" ? \"Solana\" : \"Base\";\n proxy.balanceMonitor\n .checkBalance()\n .then(async (balance) => {\n if (balance.isEmpty) {\n api.logger.info(`Wallet (${network}): ${displayAddress}`);\n api.logger.info(\n `Balance: $0.00 — send USDC on ${network} to the address above to unlock paid models.`,\n );\n } else if (balance.isLow) {\n api.logger.info(\n `Wallet (${network}): ${displayAddress} | Balance: ${balance.balanceUSD} (low — top up soon)`,\n );\n } else {\n api.logger.info(`Wallet (${network}): ${displayAddress} | Balance: ${balance.balanceUSD}`);\n }\n // On Solana, if USDC is low/empty, check for SOL and suggest swap\n if (currentChain === \"solana\" && (balance.isEmpty || balance.isLow)) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const solLamports: bigint = await (proxy.balanceMonitor as any).checkSolBalance();\n // Only suggest if they have meaningful SOL (> 0.01 SOL = 10M lamports)\n if (solLamports > 10_000_000n) {\n const sol = Number(solLamports) / 1_000_000_000;\n api.logger.info(\n `You have ${sol.toFixed(2)} SOL — swap to USDC: https://jup.ag/swap/SOL-USDC`,\n );\n }\n } catch {\n // SOL check is best-effort, don't block startup\n }\n }\n })\n .catch(() => {\n api.logger.info(`Wallet (${network}): ${displayAddress} | Balance: (checking...)`);\n });\n}\n\n/**\n * /stats command handler for ClawRouter.\n * Shows usage statistics and cost savings.\n */\nasync function createStatsCommand(): Promise {\n return {\n name: \"stats\",\n description: \"Show ClawRouter usage statistics and cost savings\",\n acceptsArgs: true,\n requireAuth: false,\n handler: async (ctx: PluginCommandContext) => {\n const arg = ctx.args?.trim().toLowerCase() || \"7\";\n\n if (arg === \"clear\" || arg === \"reset\") {\n try {\n const { deletedFiles } = await clearStats();\n return {\n text: `Stats cleared — ${deletedFiles} log file(s) deleted. Fresh start!`,\n };\n } catch (err) {\n return {\n text: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n\n const days = parseInt(arg, 10) || 7;\n\n try {\n const stats = await getStats(Math.min(days, 30)); // Cap at 30 days\n const ascii = formatStatsAscii(stats);\n\n return {\n text: [\"```\", ascii, \"```\"].join(\"\\n\"),\n };\n } catch (err) {\n return {\n text: `Failed to load stats: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n },\n };\n}\n\n/**\n * /exclude command handler for ClawRouter.\n * Manages excluded models — /exclude add|remove|clear \n */\nasync function createExcludeCommand(): Promise {\n return {\n name: \"exclude\",\n description: \"Manage excluded models — /exclude add|remove|clear \",\n acceptsArgs: true,\n requireAuth: true,\n handler: async (ctx: PluginCommandContext) => {\n const args = ctx.args?.trim() || \"\";\n const parts = args.split(/\\s+/);\n const subcommand = parts[0]?.toLowerCase() || \"\";\n const modelArg = parts.slice(1).join(\" \").trim();\n\n // /exclude (no args) — show current list\n if (!subcommand) {\n const list = loadExcludeList();\n if (list.size === 0) {\n return {\n text: \"No models excluded.\\n\\nUsage:\\n /exclude add — block a model\\n /exclude remove — unblock\\n /exclude clear — remove all\",\n };\n }\n const models = [...list]\n .sort()\n .map((m) => ` • ${m}`)\n .join(\"\\n\");\n return {\n text: `Excluded models (${list.size}):\\n${models}\\n\\nUse /exclude remove to unblock.`,\n };\n }\n\n // /exclude add \n if (subcommand === \"add\") {\n if (!modelArg) {\n return {\n text: \"Usage: /exclude add \\nExample: /exclude add nvidia/gpt-oss-120b\",\n isError: true,\n };\n }\n const resolved = addExclusion(modelArg);\n const list = loadExcludeList();\n return {\n text: `Excluded: ${resolved}\\n\\nActive exclusions (${list.size}):\\n${[...list]\n .sort()\n .map((m) => ` • ${m}`)\n .join(\"\\n\")}`,\n };\n }\n\n // /exclude remove \n if (subcommand === \"remove\") {\n if (!modelArg) {\n return { text: \"Usage: /exclude remove \", isError: true };\n }\n const removed = removeExclusion(modelArg);\n if (!removed) {\n return { text: `Model \"${modelArg}\" was not in the exclude list.` };\n }\n const list = loadExcludeList();\n return {\n text: `Unblocked: ${modelArg}\\n\\nActive exclusions (${list.size}):\\n${\n list.size > 0\n ? [...list]\n .sort()\n .map((m) => ` • ${m}`)\n .join(\"\\n\")\n : \" (none)\"\n }`,\n };\n }\n\n // /exclude clear\n if (subcommand === \"clear\") {\n clearExclusions();\n return { text: \"All model exclusions cleared.\" };\n }\n\n return {\n text: `Unknown subcommand: ${subcommand}\\n\\nUsage:\\n /exclude — show list\\n /exclude add \\n /exclude remove \\n /exclude clear`,\n isError: true,\n };\n },\n };\n}\n\n/**\n * /wallet command handler for ClawRouter.\n * - /wallet or /wallet status: Show wallet address, balance, usage, and key file location\n * - /wallet export: Show private key for backup (with security warning)\n */\nasync function createWalletCommand(): Promise {\n return {\n name: \"wallet\",\n description: \"Show BlockRun wallet info, usage stats, or export private key\",\n acceptsArgs: true,\n requireAuth: true,\n handler: async (ctx: PluginCommandContext) => {\n const subcommand = ctx.args?.trim().toLowerCase() || \"status\";\n\n // Read wallet key if it exists\n let walletKey: string | undefined;\n let address: string | undefined;\n try {\n if (existsSync(WALLET_FILE)) {\n walletKey = readTextFileSync(WALLET_FILE).trim();\n if (walletKey.startsWith(\"0x\") && walletKey.length === 66) {\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n address = account.address;\n }\n }\n } catch {\n // Wallet file doesn't exist or is invalid\n }\n\n if (!walletKey || !address) {\n return {\n text: `No ClawRouter wallet found.\\n\\nRun \\`openclaw plugins install @blockrun/clawrouter\\` to generate a wallet.`,\n isError: true,\n };\n }\n\n if (subcommand === \"export\") {\n // Export private key + mnemonic for backup\n const lines = [\n \"**ClawRouter Wallet Export**\",\n \"\",\n \"**SECURITY WARNING**: Your private key and mnemonic control your wallet funds.\",\n \"Never share these. Anyone with them can spend your USDC.\",\n \"\",\n \"**EVM (Base):**\",\n ` Address: \\`${address}\\``,\n ` Private Key: \\`${walletKey}\\``,\n ];\n\n // Include mnemonic if it exists (Solana wallet derived from it)\n let hasMnemonic = false;\n try {\n if (existsSync(MNEMONIC_FILE)) {\n const mnemonic = readTextFileSync(MNEMONIC_FILE).trim();\n if (mnemonic) {\n hasMnemonic = true;\n // Derive Solana address for display\n const { deriveSolanaKeyBytes } = await import(\"./wallet.js\");\n const solKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solKeyBytes);\n\n lines.push(\n \"\",\n \"**Solana:**\",\n ` Address: \\`${signer.address}\\``,\n ` (Derived from mnemonic below)`,\n \"\",\n \"**Mnemonic (24 words):**\",\n `\\`${mnemonic}\\``,\n \"\",\n \"CRITICAL: Back up this mnemonic. It is the ONLY way to recover your Solana wallet.\",\n );\n }\n }\n } catch {\n // No mnemonic - EVM-only wallet\n }\n\n lines.push(\n \"\",\n \"**To restore on a new machine:**\",\n \"1. Set the environment variable before running OpenClaw:\",\n ` \\`export BLOCKRUN_WALLET_KEY=${walletKey}\\``,\n \"2. Or save to file:\",\n ` \\`mkdir -p ~/.openclaw/blockrun && echo \"${walletKey}\" > ~/.openclaw/blockrun/wallet.key && chmod 600 ~/.openclaw/blockrun/wallet.key\\``,\n );\n\n if (hasMnemonic) {\n lines.push(\n \"3. Restore the mnemonic for Solana:\",\n ` \\`echo \"\" > ~/.openclaw/blockrun/mnemonic && chmod 600 ~/.openclaw/blockrun/mnemonic\\``,\n );\n }\n\n return { text: lines.join(\"\\n\") };\n }\n\n if (subcommand === \"solana\") {\n // Switch to Solana chain. If mnemonic already exists, just persist the selection.\n // If no mnemonic, set up Solana wallet first.\n try {\n let solanaAddr: string | undefined;\n\n // Check if Solana wallet is already set up (mnemonic exists)\n if (existsSync(MNEMONIC_FILE)) {\n const existingMnemonic = readTextFileSync(MNEMONIC_FILE).trim();\n if (existingMnemonic) {\n // Already set up — just switch chain\n await savePaymentChain(\"solana\");\n const { deriveSolanaKeyBytes } = await import(\"./wallet.js\");\n const solKeyBytes = deriveSolanaKeyBytes(existingMnemonic);\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solKeyBytes);\n solanaAddr = signer.address;\n return {\n text: [\n \"Payment chain set to Solana. Restart the gateway to apply.\",\n \"\",\n `**Solana Address:** \\`${solanaAddr}\\``,\n `**Fund with USDC on Solana:** https://solscan.io/account/${solanaAddr}`,\n ].join(\"\\n\"),\n };\n }\n }\n\n // No mnemonic — first-time Solana setup\n const { solanaPrivateKeyBytes } = await setupSolana();\n await savePaymentChain(\"solana\");\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n return {\n text: [\n \"**Solana Wallet Set Up**\",\n \"\",\n `**Solana Address:** \\`${signer.address}\\``,\n `**Mnemonic File:** \\`${MNEMONIC_FILE}\\``,\n \"\",\n \"Your existing EVM wallet is unchanged.\",\n \"Payment chain set to Solana. Restart the gateway to apply.\",\n \"\",\n `**Fund with USDC on Solana:** https://solscan.io/account/${signer.address}`,\n ].join(\"\\n\"),\n };\n } catch (err) {\n return {\n text: `Failed to set up Solana: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n\n if (subcommand === \"base\") {\n // Switch back to Base (EVM) payment chain\n try {\n await savePaymentChain(\"base\");\n return {\n text: \"Payment chain set to Base (EVM). Restart the gateway to apply.\",\n };\n } catch (err) {\n return {\n text: `Failed to set payment chain: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n\n // Default: show wallet status\n let evmBalanceText: string;\n try {\n const monitor = new BalanceMonitor(address);\n const balance = await monitor.checkBalance();\n evmBalanceText = `Balance: ${balance.balanceUSD}`;\n } catch {\n evmBalanceText = \"Balance: (could not check)\";\n }\n\n // Check for Solana wallet\n let solanaSection = \"\";\n try {\n if (existsSync(MNEMONIC_FILE)) {\n const { deriveSolanaKeyBytes } = await import(\"./wallet.js\");\n const mnemonic = readTextFileSync(MNEMONIC_FILE).trim();\n if (mnemonic) {\n const solKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solKeyBytes);\n const solAddr = signer.address;\n\n let solBalanceText = \"Balance: (checking...)\";\n try {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n const solMonitor = new SolanaBalanceMonitor(solAddr);\n const solBalance = await solMonitor.checkBalance();\n solBalanceText = `Balance: ${solBalance.balanceUSD}`;\n } catch {\n solBalanceText = \"Balance: (could not check)\";\n }\n\n solanaSection = [\n \"\",\n \"**Solana:**\",\n ` Address: \\`${solAddr}\\``,\n ` ${solBalanceText}`,\n ` Fund (USDC only): https://solscan.io/account/${solAddr}`,\n ].join(\"\\n\");\n }\n }\n } catch {\n // No Solana wallet - that's fine\n }\n\n // Show current chain selection\n const currentChain = await resolvePaymentChain();\n\n // Usage summary (last 7 days) — shows all models including openai/, anthropic/, etc.\n let usageSection = \"\";\n try {\n const stats = await getStats(7);\n if (stats.totalRequests > 0) {\n const modelLines = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 8)\n .map(\n ([model, data]) =>\n ` ${model.length > 30 ? model.slice(0, 27) + \"...\" : model} ${data.count} reqs $${data.cost.toFixed(4)}`,\n );\n\n usageSection = [\n \"\",\n `**Usage (${stats.period}):**`,\n ` Total: ${stats.totalRequests} requests, $${stats.totalCost.toFixed(4)} spent`,\n stats.totalSavings > 0\n ? ` Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(0)}% vs Opus baseline)`\n : \"\",\n \"\",\n \"**Top Models:**\",\n ...modelLines,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n }\n } catch {\n // Stats not available — skip\n }\n\n return {\n text: [\n \"**ClawRouter Wallet**\",\n \"\",\n `**Payment Chain:** ${currentChain === \"solana\" ? \"Solana\" : \"Base (EVM)\"}`,\n \"\",\n \"**Base (EVM):**\",\n ` Address: \\`${address}\\``,\n ` ${evmBalanceText}`,\n ` Fund (USDC only): https://basescan.org/address/${address}`,\n solanaSection,\n usageSection,\n \"\",\n `**Key File:** \\`${WALLET_FILE}\\``,\n \"\",\n \"**Commands:**\",\n \"• `/wallet` - Show this status\",\n \"• `/wallet export` - Export private key for backup\",\n \"• `/stats` - Detailed usage breakdown\",\n !solanaSection ? \"• `/wallet solana` - Enable Solana payments\" : \"\",\n solanaSection ? \"• `/wallet base` - Switch to Base (EVM)\" : \"\",\n solanaSection ? \"• `/wallet solana` - Switch to Solana\" : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n };\n },\n };\n}\n\nconst plugin: OpenClawPluginDefinition = {\n id: \"clawrouter\",\n name: \"ClawRouter\",\n description: \"Smart LLM router — 55+ models, x402 micropayments, 78% cost savings\",\n version: VERSION,\n\n register(api: OpenClawPluginApi) {\n // Check if ClawRouter is disabled via environment variable\n // Usage: CLAWROUTER_DISABLED=true openclaw gateway start\n const isDisabled =\n process[\"env\"].CLAWROUTER_DISABLED === \"true\" || process[\"env\"].CLAWROUTER_DISABLED === \"1\";\n if (isDisabled) {\n api.logger.info(\"ClawRouter disabled (CLAWROUTER_DISABLED=true). Using default routing.\");\n return;\n }\n\n // Install skills into OpenClaw workspace so agents can discover them\n // Must run before completion short-circuit so skills are available even on first install\n installSkillsToWorkspace(api.logger);\n\n // Skip heavy initialization in completion mode — only completion script is needed\n // Logging to stdout during completion pollutes the script and causes zsh errors\n if (isCompletionMode()) {\n api.registerProvider(blockrunProvider);\n return;\n }\n\n // Register BlockRun as a provider (sync — available immediately)\n api.registerProvider(blockrunProvider);\n\n // Inject models config into OpenClaw config file\n // This persists the config so models are recognized on restart\n injectModelsConfig(api.logger);\n\n // Inject dummy auth profiles into agent auth stores\n // OpenClaw's agent system looks for auth even if provider has auth: []\n injectAuthProfile(api.logger);\n\n // Also set runtime config for immediate availability\n const runtimePort = getProxyPort();\n if (!api.config.models) {\n api.config.models = { providers: {} };\n }\n if (!api.config.models.providers) {\n api.config.models.providers = {};\n }\n api.config.models.providers.blockrun = {\n baseUrl: `http://127.0.0.1:${runtimePort}/v1`,\n api: \"openai-completions\",\n // apiKey is required by pi-coding-agent's ModelRegistry for providers with models.\n apiKey: \"x402-proxy-handles-auth\",\n models: OPENCLAW_MODELS,\n };\n\n api.logger.info(\"BlockRun provider registered (55+ models via x402)\");\n\n // Register partner API tools (Twitter/X lookup, etc.)\n try {\n const proxyBaseUrl = `http://127.0.0.1:${runtimePort}`;\n const partnerTools = buildPartnerTools(proxyBaseUrl);\n for (const tool of partnerTools) {\n api.registerTool(tool);\n }\n if (partnerTools.length > 0) {\n api.logger.info(\n `Registered ${partnerTools.length} partner tool(s): ${partnerTools.map((t) => t.name).join(\", \")}`,\n );\n }\n\n // Register /partners command\n api.registerCommand({\n name: \"partners\",\n description: \"List available partner APIs and pricing\",\n acceptsArgs: false,\n requireAuth: false,\n handler: async () => {\n if (PARTNER_SERVICES.length === 0) {\n return { text: \"No partner APIs available.\" };\n }\n\n const lines = [\"**Partner APIs** (paid via your ClawRouter wallet)\", \"\"];\n\n for (const svc of PARTNER_SERVICES) {\n lines.push(`**${svc.name}** (${svc.partner})`);\n lines.push(` ${svc.description}`);\n lines.push(` Tool: \\`${`blockrun_${svc.id}`}\\``);\n lines.push(\n ` Pricing: ${svc.pricing.perUnit} per ${svc.pricing.unit} (min ${svc.pricing.minimum}, max ${svc.pricing.maximum})`,\n );\n lines.push(\n ` **How to use:** Ask \"Look up Twitter user @elonmusk\" or \"Get info on these X accounts: @naval, @balajis\"`,\n );\n lines.push(\"\");\n }\n\n return { text: lines.join(\"\\n\") };\n },\n });\n } catch (err) {\n api.logger.warn(\n `Failed to register partner tools: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Register /wallet command — shows wallet info + per-model usage stats\n createWalletCommand()\n .then((walletCommand) => {\n api.registerCommand(walletCommand);\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to register /wallet command: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n\n // Register /stats command for usage statistics\n createStatsCommand()\n .then((statsCommand) => {\n api.registerCommand(statsCommand);\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to register /stats command: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n\n // Register /exclude command for model exclusion management\n createExcludeCommand()\n .then((excludeCommand) => {\n api.registerCommand(excludeCommand);\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to register /exclude command: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n\n // Register a service with stop() for cleanup on gateway shutdown\n // This prevents EADDRINUSE when the gateway restarts\n api.registerService({\n id: \"clawrouter-proxy\",\n start: () => {\n // No-op: proxy is started below in non-blocking mode\n },\n stop: async () => {\n // Close proxy on gateway shutdown to release port 8402\n if (activeProxyHandle) {\n try {\n await activeProxyHandle.close();\n api.logger.info(\"BlockRun proxy closed\");\n } catch (err) {\n api.logger.warn(\n `Failed to close proxy: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n activeProxyHandle = null;\n }\n },\n });\n\n // Skip proxy startup unless we're in gateway mode\n // The proxy keeps the Node.js event loop alive, preventing CLI commands from exiting\n // The proxy will start automatically when the gateway runs\n if (!isGatewayMode()) {\n // Generate wallet on first install (even outside gateway mode)\n // This ensures users can see their wallet address immediately after install\n resolveOrGenerateWalletKey()\n .then(({ address, source }) => {\n if (source === \"generated\") {\n api.logger.warn(`════════════════════════════════════════════════`);\n api.logger.warn(` NEW WALLET GENERATED — BACK UP YOUR KEY NOW!`);\n api.logger.warn(` Address : ${address}`);\n api.logger.warn(` Run /wallet export to get your private key`);\n api.logger.warn(` Losing this key = losing your USDC funds`);\n api.logger.warn(`════════════════════════════════════════════════`);\n } else if (source === \"saved\") {\n api.logger.info(`Using saved wallet: ${address}`);\n } else {\n api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${address}`);\n }\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to initialize wallet: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n api.logger.info(\"Not in gateway mode — proxy will start when gateway runs\");\n return;\n }\n\n // Start x402 proxy in background WITHOUT blocking register()\n // CRITICAL: Do NOT await here - this was blocking model selection UI for 3+ seconds\n // causing Chandler's \"infinite loop\" issue where model selection never finishes\n // Note: startProxyInBackground calls resolveOrGenerateWalletKey internally\n startProxyInBackground(api)\n .then(async () => {\n // Proxy started successfully - verify health\n const port = getProxyPort();\n const healthy = await waitForProxyHealth(port, 5000);\n if (!healthy) {\n api.logger.warn(`Proxy health check timed out, commands may not work immediately`);\n }\n })\n .catch((err) => {\n api.logger.error(\n `Failed to start BlockRun proxy: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n },\n};\n\nexport default plugin;\n\n// Re-export for programmatic use\nexport { startProxy, getProxyPort } from \"./proxy.js\";\nexport type {\n ProxyOptions,\n ProxyHandle,\n WalletConfig,\n PaymentChain,\n LowBalanceInfo,\n InsufficientFundsInfo,\n} from \"./proxy.js\";\nexport type { WalletResolution } from \"./auth.js\";\nexport { blockrunProvider } from \"./provider.js\";\nexport {\n OPENCLAW_MODELS,\n BLOCKRUN_MODELS,\n buildProviderModels,\n MODEL_ALIASES,\n resolveModelAlias,\n isAgenticModel,\n getAgenticModels,\n getModelContextWindow,\n} from \"./models.js\";\nexport {\n route,\n DEFAULT_ROUTING_CONFIG,\n getFallbackChain,\n getFallbackChainFiltered,\n calculateModelCost,\n} from \"./router/index.js\";\nexport type { RoutingDecision, RoutingConfig, Tier } from \"./router/index.js\";\nexport { logUsage } from \"./logger.js\";\nexport type { UsageEntry } from \"./logger.js\";\nexport { RequestDeduplicator } from \"./dedup.js\";\nexport type { CachedResponse } from \"./dedup.js\";\nexport { BalanceMonitor, BALANCE_THRESHOLDS } from \"./balance.js\";\nexport type { BalanceInfo, SufficiencyResult } from \"./balance.js\";\nexport { SolanaBalanceMonitor } from \"./solana-balance.js\";\nexport type { SolanaBalanceInfo } from \"./solana-balance.js\";\nexport {\n SpendControl,\n FileSpendControlStorage,\n InMemorySpendControlStorage,\n formatDuration,\n} from \"./spend-control.js\";\nexport type {\n SpendWindow,\n SpendLimits,\n SpendRecord,\n SpendingStatus,\n CheckResult,\n SpendControlStorage,\n SpendControlOptions,\n} from \"./spend-control.js\";\nexport {\n generateWalletMnemonic,\n isValidMnemonic,\n deriveEvmKey,\n deriveSolanaKeyBytes,\n deriveAllKeys,\n} from \"./wallet.js\";\nexport type { DerivedKeys } from \"./wallet.js\";\nexport { setupSolana, savePaymentChain, loadPaymentChain, resolvePaymentChain } from \"./auth.js\";\nexport {\n InsufficientFundsError,\n EmptyWalletError,\n RpcError,\n isInsufficientFundsError,\n isEmptyWalletError,\n isBalanceError,\n isRpcError,\n} from \"./errors.js\";\nexport { fetchWithRetry, isRetryable, DEFAULT_RETRY_CONFIG } from \"./retry.js\";\nexport type { RetryConfig } from \"./retry.js\";\nexport { getStats, formatStatsAscii, clearStats } from \"./stats.js\";\nexport type { DailyStats, AggregatedStats } from \"./stats.js\";\nexport {\n SessionStore,\n getSessionId,\n hashRequestContent,\n DEFAULT_SESSION_CONFIG,\n} from \"./session.js\";\nexport type { SessionEntry, SessionConfig } from \"./session.js\";\nexport { ResponseCache } from \"./response-cache.js\";\nexport type { CachedLLMResponse, ResponseCacheConfig } from \"./response-cache.js\";\nexport { PARTNER_SERVICES, getPartnerService, buildPartnerTools } from \"./partners/index.js\";\nexport type { PartnerServiceDefinition, PartnerToolDefinition } from \"./partners/index.js\";\n","/**\n * Partner Service Registry\n *\n * Defines available partner APIs that can be called through ClawRouter's proxy.\n * Partners provide specialized data (Twitter/X, etc.) via x402 micropayments.\n * The same wallet used for LLM calls pays for partner API calls — zero extra setup.\n */\n\nexport type PartnerServiceParam = {\n name: string;\n type: \"string\" | \"string[]\" | \"number\";\n description: string;\n required: boolean;\n};\n\nexport type PartnerServiceDefinition = {\n /** Unique service ID used in tool names: blockrun_{id} */\n id: string;\n /** Human-readable name */\n name: string;\n /** Partner providing this service */\n partner: string;\n /** Short description for tool listing */\n description: string;\n /** Proxy path (relative to /v1) */\n proxyPath: string;\n /** HTTP method */\n method: \"GET\" | \"POST\";\n /** Parameters for the tool's JSON Schema */\n params: PartnerServiceParam[];\n /** Pricing info for display */\n pricing: {\n perUnit: string;\n unit: string;\n minimum: string;\n maximum: string;\n };\n /** Example usage for help text */\n example: {\n input: Record;\n description: string;\n };\n};\n\n/**\n * All registered partner services.\n * New partners are added here — the rest of the system picks them up automatically.\n */\nexport const PARTNER_SERVICES: PartnerServiceDefinition[] = [\n {\n id: \"x_users_lookup\",\n name: \"Twitter/X User Lookup\",\n partner: \"AttentionVC\",\n description:\n \"Look up real-time Twitter/X user profiles by username. \" +\n \"Call this ONLY when the user explicitly asks to look up, check, or get information about a specific Twitter/X user's profile (follower count, bio, verification status, etc.). \" +\n \"Do NOT call this for messages that merely contain x.com or twitter.com URLs — only invoke when the user is asking for profile information about a specific account. \" +\n \"Returns: follower count, verification badge, bio, location, join date. \" +\n \"Accepts up to 100 usernames per request (without @ prefix).\",\n proxyPath: \"/x/users/lookup\",\n method: \"POST\",\n params: [\n {\n name: \"usernames\",\n type: \"string[]\",\n description:\n 'Array of Twitter/X usernames to look up (without @ prefix). Example: [\"elonmusk\", \"naval\"]',\n required: true,\n },\n ],\n pricing: {\n perUnit: \"$0.001\",\n unit: \"user\",\n minimum: \"$0.01 (10 users)\",\n maximum: \"$0.10 (100 users)\",\n },\n example: {\n input: { usernames: [\"elonmusk\", \"naval\", \"balaboris\"] },\n description: \"Look up 3 Twitter/X user profiles\",\n },\n },\n];\n\n/**\n * Get a partner service by ID.\n */\nexport function getPartnerService(id: string): PartnerServiceDefinition | undefined {\n return PARTNER_SERVICES.find((s) => s.id === id);\n}\n","/**\n * Partner Tool Builder\n *\n * Converts partner service definitions into OpenClaw tool definitions.\n * Each tool's execute() calls through the local proxy which handles\n * x402 payment transparently using the same wallet.\n */\n\nimport { PARTNER_SERVICES, type PartnerServiceDefinition } from \"./registry.js\";\n\n/** OpenClaw tool definition shape (duck-typed) */\nexport type PartnerToolDefinition = {\n name: string;\n description: string;\n parameters: {\n type: \"object\";\n properties: Record;\n required: string[];\n };\n execute: (toolCallId: string, params: Record) => Promise;\n};\n\n/**\n * Build a single partner tool from a service definition.\n */\nfunction buildTool(service: PartnerServiceDefinition, proxyBaseUrl: string): PartnerToolDefinition {\n // Build JSON Schema properties from service params\n const properties: Record = {};\n const required: string[] = [];\n\n for (const param of service.params) {\n const prop: Record = {\n description: param.description,\n };\n\n if (param.type === \"string[]\") {\n prop.type = \"array\";\n prop.items = { type: \"string\" };\n } else {\n prop.type = param.type;\n }\n\n properties[param.name] = prop;\n if (param.required) {\n required.push(param.name);\n }\n }\n\n return {\n name: `blockrun_${service.id}`,\n description: [\n service.description,\n \"\",\n `Partner: ${service.partner}`,\n `Pricing: ${service.pricing.perUnit} per ${service.pricing.unit} (min: ${service.pricing.minimum}, max: ${service.pricing.maximum})`,\n ].join(\"\\n\"),\n parameters: {\n type: \"object\",\n properties,\n required,\n },\n execute: async (_toolCallId: string, params: Record) => {\n const url = `${proxyBaseUrl}/v1${service.proxyPath}`;\n\n const response = await fetch(url, {\n method: service.method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(params),\n });\n\n if (!response.ok) {\n const errText = await response.text().catch(() => \"\");\n throw new Error(\n `Partner API error (${response.status}): ${errText || response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(data, null, 2),\n },\n ],\n details: data,\n };\n },\n };\n}\n\n/**\n * Build OpenClaw tool definitions for all registered partner services.\n * @param proxyBaseUrl - Local proxy base URL (e.g., \"http://127.0.0.1:8402\")\n */\nexport function buildPartnerTools(proxyBaseUrl: string): PartnerToolDefinition[] {\n return PARTNER_SERVICES.map((service) => buildTool(service, proxyBaseUrl));\n}\n","/**\n * Spend Control - Time-windowed spending limits\n *\n * Absorbed from @blockrun/clawwallet. Chain-agnostic (works for both EVM and Solana).\n *\n * Features:\n * - Per-request limits (e.g., max $0.10 per call)\n * - Hourly limits (e.g., max $3.00 per hour)\n * - Daily limits (e.g., max $20.00 per day)\n * - Session limits (e.g., max $5.00 per session)\n * - Rolling windows (last 1h, last 24h)\n * - Persistent storage (~/.openclaw/blockrun/spending.json)\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { readTextFileSync } from \"./fs-read.js\";\n\nconst WALLET_DIR = path.join(homedir(), \".openclaw\", \"blockrun\");\n\nconst HOUR_MS = 60 * 60 * 1000;\nconst DAY_MS = 24 * HOUR_MS;\n\nexport type SpendWindow = \"perRequest\" | \"hourly\" | \"daily\" | \"session\";\n\nexport interface SpendLimits {\n perRequest?: number;\n hourly?: number;\n daily?: number;\n session?: number;\n}\n\nexport interface SpendRecord {\n timestamp: number;\n amount: number;\n model?: string;\n action?: string;\n}\n\nexport interface SpendingStatus {\n limits: SpendLimits;\n spending: {\n hourly: number;\n daily: number;\n session: number;\n };\n remaining: {\n hourly: number | null;\n daily: number | null;\n session: number | null;\n };\n calls: number;\n}\n\nexport interface CheckResult {\n allowed: boolean;\n blockedBy?: SpendWindow;\n remaining?: number;\n reason?: string;\n resetIn?: number;\n}\n\nexport interface SpendControlStorage {\n load(): { limits: SpendLimits; history: SpendRecord[] } | null;\n save(data: { limits: SpendLimits; history: SpendRecord[] }): void;\n}\n\nexport class FileSpendControlStorage implements SpendControlStorage {\n private readonly spendingFile: string;\n\n constructor() {\n this.spendingFile = path.join(WALLET_DIR, \"spending.json\");\n }\n\n load(): { limits: SpendLimits; history: SpendRecord[] } | null {\n try {\n if (fs.existsSync(this.spendingFile)) {\n const data = JSON.parse(readTextFileSync(this.spendingFile));\n const rawLimits = data.limits ?? {};\n const rawHistory = data.history ?? [];\n\n const limits: SpendLimits = {};\n for (const key of [\"perRequest\", \"hourly\", \"daily\", \"session\"] as const) {\n const val = rawLimits[key];\n if (typeof val === \"number\" && val > 0 && Number.isFinite(val)) {\n limits[key] = val;\n }\n }\n\n const history: SpendRecord[] = [];\n if (Array.isArray(rawHistory)) {\n for (const r of rawHistory) {\n if (\n typeof r?.timestamp === \"number\" &&\n typeof r?.amount === \"number\" &&\n Number.isFinite(r.timestamp) &&\n Number.isFinite(r.amount) &&\n r.amount >= 0\n ) {\n history.push({\n timestamp: r.timestamp,\n amount: r.amount,\n model: typeof r.model === \"string\" ? r.model : undefined,\n action: typeof r.action === \"string\" ? r.action : undefined,\n });\n }\n }\n }\n\n return { limits, history };\n }\n } catch (err) {\n console.error(`[ClawRouter] Failed to load spending data, starting fresh: ${err}`);\n }\n return null;\n }\n\n save(data: { limits: SpendLimits; history: SpendRecord[] }): void {\n try {\n if (!fs.existsSync(WALLET_DIR)) {\n fs.mkdirSync(WALLET_DIR, { recursive: true, mode: 0o700 });\n }\n fs.writeFileSync(this.spendingFile, JSON.stringify(data, null, 2), {\n mode: 0o600,\n });\n } catch (err) {\n console.error(`[ClawRouter] Failed to save spending data: ${err}`);\n }\n }\n}\n\nexport class InMemorySpendControlStorage implements SpendControlStorage {\n private data: { limits: SpendLimits; history: SpendRecord[] } | null = null;\n\n load(): { limits: SpendLimits; history: SpendRecord[] } | null {\n return this.data\n ? {\n limits: { ...this.data.limits },\n history: this.data.history.map((r) => ({ ...r })),\n }\n : null;\n }\n\n save(data: { limits: SpendLimits; history: SpendRecord[] }): void {\n this.data = {\n limits: { ...data.limits },\n history: data.history.map((r) => ({ ...r })),\n };\n }\n}\n\nexport interface SpendControlOptions {\n storage?: SpendControlStorage;\n now?: () => number;\n}\n\nexport class SpendControl {\n private limits: SpendLimits = {};\n private history: SpendRecord[] = [];\n private sessionSpent: number = 0;\n private sessionCalls: number = 0;\n private readonly storage: SpendControlStorage;\n private readonly now: () => number;\n\n constructor(options?: SpendControlOptions) {\n this.storage = options?.storage ?? new FileSpendControlStorage();\n this.now = options?.now ?? (() => Date.now());\n this.load();\n }\n\n setLimit(window: SpendWindow, amount: number): void {\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(\"Limit must be a finite positive number\");\n }\n this.limits[window] = amount;\n this.save();\n }\n\n clearLimit(window: SpendWindow): void {\n delete this.limits[window];\n this.save();\n }\n\n getLimits(): SpendLimits {\n return { ...this.limits };\n }\n\n check(estimatedCost: number): CheckResult {\n const now = this.now();\n\n if (this.limits.perRequest !== undefined) {\n if (estimatedCost > this.limits.perRequest) {\n return {\n allowed: false,\n blockedBy: \"perRequest\",\n remaining: this.limits.perRequest,\n reason: `Per-request limit exceeded: $${estimatedCost.toFixed(4)} > $${this.limits.perRequest.toFixed(2)} max`,\n };\n }\n }\n\n if (this.limits.hourly !== undefined) {\n const hourlySpent = this.getSpendingInWindow(now - HOUR_MS, now);\n const remaining = this.limits.hourly - hourlySpent;\n if (estimatedCost > remaining) {\n const oldestInWindow = this.history.find((r) => r.timestamp >= now - HOUR_MS);\n const resetIn = oldestInWindow\n ? Math.ceil((oldestInWindow.timestamp + HOUR_MS - now) / 1000)\n : 0;\n return {\n allowed: false,\n blockedBy: \"hourly\",\n remaining,\n reason: `Hourly limit exceeded: $${(hourlySpent + estimatedCost).toFixed(2)} > $${this.limits.hourly.toFixed(2)} max`,\n resetIn,\n };\n }\n }\n\n if (this.limits.daily !== undefined) {\n const dailySpent = this.getSpendingInWindow(now - DAY_MS, now);\n const remaining = this.limits.daily - dailySpent;\n if (estimatedCost > remaining) {\n const oldestInWindow = this.history.find((r) => r.timestamp >= now - DAY_MS);\n const resetIn = oldestInWindow\n ? Math.ceil((oldestInWindow.timestamp + DAY_MS - now) / 1000)\n : 0;\n return {\n allowed: false,\n blockedBy: \"daily\",\n remaining,\n reason: `Daily limit exceeded: $${(dailySpent + estimatedCost).toFixed(2)} > $${this.limits.daily.toFixed(2)} max`,\n resetIn,\n };\n }\n }\n\n if (this.limits.session !== undefined) {\n const remaining = this.limits.session - this.sessionSpent;\n if (estimatedCost > remaining) {\n return {\n allowed: false,\n blockedBy: \"session\",\n remaining,\n reason: `Session limit exceeded: $${(this.sessionSpent + estimatedCost).toFixed(2)} > $${this.limits.session.toFixed(2)} max`,\n };\n }\n }\n\n return { allowed: true };\n }\n\n record(amount: number, metadata?: { model?: string; action?: string }): void {\n if (!Number.isFinite(amount) || amount < 0) {\n throw new Error(\"Record amount must be a non-negative finite number\");\n }\n const record: SpendRecord = {\n timestamp: this.now(),\n amount,\n model: metadata?.model,\n action: metadata?.action,\n };\n\n this.history.push(record);\n this.sessionSpent += amount;\n this.sessionCalls += 1;\n\n this.cleanup();\n this.save();\n }\n\n private getSpendingInWindow(from: number, to: number): number {\n return this.history\n .filter((r) => r.timestamp >= from && r.timestamp <= to)\n .reduce((sum, r) => sum + r.amount, 0);\n }\n\n getSpending(window: \"hourly\" | \"daily\" | \"session\"): number {\n const now = this.now();\n switch (window) {\n case \"hourly\":\n return this.getSpendingInWindow(now - HOUR_MS, now);\n case \"daily\":\n return this.getSpendingInWindow(now - DAY_MS, now);\n case \"session\":\n return this.sessionSpent;\n }\n }\n\n getRemaining(window: \"hourly\" | \"daily\" | \"session\"): number | null {\n const limit = this.limits[window];\n if (limit === undefined) return null;\n return Math.max(0, limit - this.getSpending(window));\n }\n\n getStatus(): SpendingStatus {\n const now = this.now();\n const hourlySpent = this.getSpendingInWindow(now - HOUR_MS, now);\n const dailySpent = this.getSpendingInWindow(now - DAY_MS, now);\n\n return {\n limits: { ...this.limits },\n spending: {\n hourly: hourlySpent,\n daily: dailySpent,\n session: this.sessionSpent,\n },\n remaining: {\n hourly: this.limits.hourly !== undefined ? this.limits.hourly - hourlySpent : null,\n daily: this.limits.daily !== undefined ? this.limits.daily - dailySpent : null,\n session: this.limits.session !== undefined ? this.limits.session - this.sessionSpent : null,\n },\n calls: this.sessionCalls,\n };\n }\n\n getHistory(limit?: number): SpendRecord[] {\n const records = [...this.history].reverse();\n return limit ? records.slice(0, limit) : records;\n }\n\n resetSession(): void {\n this.sessionSpent = 0;\n this.sessionCalls = 0;\n }\n\n private cleanup(): void {\n const cutoff = this.now() - DAY_MS;\n this.history = this.history.filter((r) => r.timestamp >= cutoff);\n }\n\n private save(): void {\n this.storage.save({\n limits: { ...this.limits },\n history: [...this.history],\n });\n }\n\n private load(): void {\n const data = this.storage.load();\n if (data) {\n this.limits = data.limits;\n this.history = data.history;\n this.cleanup();\n }\n }\n}\n\nexport function formatDuration(seconds: number): string {\n if (seconds < 60) {\n return `${seconds}s`;\n } else if (seconds < 3600) {\n const mins = Math.ceil(seconds / 60);\n return `${mins} min`;\n } else {\n const hours = Math.floor(seconds / 3600);\n const mins = Math.ceil((seconds % 3600) / 60);\n return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;\n }\n}\n","/**\n * Retry Logic for ClawRouter\n *\n * Provides fetch wrapper with exponential backoff for transient errors.\n * Retries on 429 (rate limit), 502, 503, 504 (server errors).\n */\n\n/** Configuration for retry behavior */\nexport type RetryConfig = {\n /** Maximum number of retries (default: 2) */\n maxRetries: number;\n /** Base delay in ms for exponential backoff (default: 500) */\n baseDelayMs: number;\n /** HTTP status codes that trigger a retry (default: [429, 502, 503, 504]) */\n retryableCodes: number[];\n};\n\n/** Default retry configuration */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 2,\n baseDelayMs: 500,\n retryableCodes: [429, 502, 503, 504],\n};\n\n/** Sleep for a given number of milliseconds */\nfunction sleep(ms: number): Promise {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Wrap a fetch-like function with retry logic and exponential backoff.\n *\n * @param fetchFn - The fetch function to wrap (can be standard fetch or x402 payFetch)\n * @param url - URL to fetch\n * @param init - Fetch init options\n * @param config - Retry configuration (optional, uses defaults)\n * @returns Response from successful fetch or last failed attempt\n *\n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * fetch,\n * \"https://api.example.com/endpoint\",\n * { method: \"POST\", body: JSON.stringify(data) },\n * { maxRetries: 3 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n fetchFn: (url: string, init?: RequestInit) => Promise,\n url: string,\n init?: RequestInit,\n config?: Partial,\n): Promise {\n const cfg: RetryConfig = {\n ...DEFAULT_RETRY_CONFIG,\n ...config,\n };\n\n let lastError: Error | undefined;\n let lastResponse: Response | undefined;\n\n for (let attempt = 0; attempt <= cfg.maxRetries; attempt++) {\n try {\n const response = await fetchFn(url, init);\n\n // Success or non-retryable status — return immediately\n if (!cfg.retryableCodes.includes(response.status)) {\n return response;\n }\n\n // Retryable status — save response and maybe retry\n lastResponse = response;\n\n // Check for Retry-After header (common with 429)\n const retryAfter = response.headers.get(\"retry-after\");\n let delay: number;\n\n if (retryAfter) {\n // Retry-After can be seconds or HTTP-date\n const seconds = parseInt(retryAfter, 10);\n delay = isNaN(seconds) ? cfg.baseDelayMs * Math.pow(2, attempt) : seconds * 1000;\n } else {\n delay = cfg.baseDelayMs * Math.pow(2, attempt);\n }\n\n // Only retry if we have attempts left\n if (attempt < cfg.maxRetries) {\n await sleep(delay);\n }\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n\n // Network errors are retryable\n if (attempt < cfg.maxRetries) {\n const delay = cfg.baseDelayMs * Math.pow(2, attempt);\n await sleep(delay);\n }\n }\n }\n\n // All retries exhausted — return last response or throw last error\n if (lastResponse) {\n return lastResponse;\n }\n\n throw lastError ?? new Error(\"Max retries exceeded\");\n}\n\n/**\n * Check if an error or response indicates a retryable condition.\n */\nexport function isRetryable(\n errorOrResponse: Error | Response,\n config?: Partial,\n): boolean {\n const retryableCodes = config?.retryableCodes ?? DEFAULT_RETRY_CONFIG.retryableCodes;\n\n if (errorOrResponse instanceof Response) {\n return retryableCodes.includes(errorOrResponse.status);\n }\n\n // Network errors are generally retryable\n const message = errorOrResponse.message.toLowerCase();\n return (\n message.includes(\"network\") ||\n message.includes(\"timeout\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"socket hang up\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa;AAAb;;;AAAO,IAAM,UAAU;;;;;ACCvB,IASa;AATb;;;;AASM,IAAO,YAAP,MAAO,mBAAkB,MAAK;MAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,cAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,cAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,cAAM,UAAU;UACd,gBAAgB;UAChB;UACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;UACrD,GAAIA,YAAW,CAAC,4BAA4BA,SAAQ,EAAE,IAAI,CAAA;UAC1D,GAAI,UAAU,CAAC,YAAY,OAAO,EAAE,IAAI,CAAA;UACxC,oBAAoB,OAAO;UAC3B,KAAK,IAAI;AAEX,cAAM,OAAO;AA3Bf,eAAA,eAAA,MAAA,WAAA;;;;;;AACA,eAAA,eAAA,MAAA,YAAA;;;;;;AACA,eAAA,eAAA,MAAA,gBAAA;;;;;;AACA,eAAA,eAAA,MAAA,gBAAA;;;;;;AAES,eAAA,eAAA,MAAA,QAA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G;AAClD,2BAAe;UACnB;MAAA;AAER,YAAM,IAAI,YAAY,MAAyB,YAAmD;IACtG;EACJ,OAAO;AACH,UAAM,UACF,OAAO,0BAA0B,YACjC,0BAA0B,QAC1B,aAAa,yBACb,OAAO,sBAAsB,YAAY,WACnC,sBAAsB,UACtB;AACV,UAAM,IAAI,YAAY,wCAAwC,EAAE,OAAO,uBAAuB,QAAA,CAAS;EAC3G;AACA,wBAAsB,KAAK,8BAA8B;AACzD,SAAO;AACX;AAEA,SAAS,mBAAmB,OAA2C;AACnE,SACI,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,aAAa,UACZ,OAAO,MAAM,SAAS,YAAY,OAAO,MAAM,SAAS,aACzD,OAAO,MAAM,YAAY;AAEjC;AC5HO,SAAS,sBAAsB,OAAyB;AAC3D,QAAM,kBAAqC;IACvC;IACA;EAAA;AAEJ,MAAI,cAAc,KAAK,KAAK,CAAC,CAAC,MAAM,SAAS,gBAAgB,SAAS,MAAM,QAAQ,MAAM,GAAG;AACzF,WAAO,MAAM;EACjB;AACA,SAAO;AACX;IVnBa,qCACA,6BACA,uCACA,oDACA,6CACA,qCACA,uCACA,uCACA,sCACA,wCAKA,qCACA,wCACA,wCACA,0CACA,yCACA,oEACA,8DACA,kEACA,mEACA,sEACA,qEACA,yEACA,oCACA,wEACA,wEACA,qEACA,kDACA,mDACA,kFACA,qDACA,0DACA,iFACA,yEACA,uDAIA,8CACA,qDACA,yDACA,qDACA,wCACA,qDACA,2DACA,uDACA,uDACA,8DACA,mDACA,oDAIA,2CACA,wDACA,kDACA,kDACA,6DAIA,6DACA,mDACA,8DACA,4DACA,8DACA,0DACA,4DACA,gEAIA,4DAIA,kDACA,qDACA,mDACA,0DACA,uDAIA,sDACA,kDACA,gDAKA,0CACA,gDACA,mDACA,2DACA,uDACA,yDACA,qDACA,uDACA,6DACA,8DACA,wDACA,yDACA,sDACA,iEACA,iEACA,0DACA,yDACA,0DACA,sDACA,sDACA,0DACA,4DACA,yDACA,wDACA,6DACA,gEACA,yCACA,gDACA,2DACA,4DACA,qEACA,yDACA,6CACA,kDACA,yDACA,2DACA,gDACA,kDACA,gEACA,uDACA,oEACA,6DACA,4DACA,4CACA,sDACA,iDACA,0DACA,wDACA,sDACA,qDACA,gDACA,yEACA,wDACA,wEACA,8EAIA,4DACA,gDACA,+CACA,yDACA,uDACA,mDACA,6DACA,2DACA,2DACA,wEACA,0DACA,sDAIA,yDACA,8EACA,+EACA,wEACA,yDACA,qEACA,8DACA,yDACA,yDACA,2DACA,wEACA,oDACA,2DACA,wEACA,oDACA,4DACA,4DACA,gEAIA,6DACA,kEACA,wDACA,oDACA,wDACA,sFACA,wFACA,sFACA,kEACA,+CACA,4CACA,8CACA,wDACA,2EACA,8FACA,8DACA,gEACA,wDACA,6DACA,6EACA,+CACA,yDACA,oEAKA,0CACA,iDACA,uDACA,oDACA,4DACA,6DACA,0DACA,oDACA,sDAEA,sDACA,4DACA,wDACA,oDACA,gEACA,mDACA,sDACA,6DACA,oEACA,sDACA,2DACA,sEACA,wEACA,yDACA,iEACA,qEACA,oEACA,qEACA,8DACA,mEACA,wEACA,wDACA,8DACA,yEACA,0EACA,wDACA,2EACA,yDAIA,kEACA,kEACA,yDACA,qEACA,gFACA,kFACA,8DACA,8DACA,qEACA,8EAIA,sDACA,2CACA,6CACA,gDACA,mEACA,2DACA,yDACA,+CACA,uDACA,2DACA,4CACA,2CACA,+CACA,qDACA,2CACA,qDACA,gEACA,kDACA,wCACA,oEACA,+DACA,yDACA,wEACA,qEAIA,qCACA,oDACA,yCACA,oDAIA,kEACA,kEACA,yEACA,4DACA,4DAMA,wEACA,kHACA,kFACA,8DACA,yEACA,kEACA,kEEnEA,qBC1QP,aACA,MCsFO,aGhGP,qBCaAA;;;;ARUC,IAAM,sCAAsC;AAC5C,IAAM,8BAA8B;AACpC,IAAM,wCAAwC;AAC9C,IAAM,qDAAqD;AAC3D,IAAM,8CAA8C;AACpD,IAAM,sCAAsC;AAC5C,IAAM,wC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AkB,EAAE,GAAG,SAAS,YAAY,QAAQ,WAAW,QAAQ,kBAAkB,WAAW,EAAA;QACpG,uBAAuB,QAAQ,WAAW,QAAQ,kBAAkB,aAAa;MAAA,CACpF;IACL;IACA;EAAA,CACH;AACL;AAEO,SAAS,gCACZ,QACyB;AACzB,SAAO,yCAA+C,MAAM;AAChE;AAEO,SAAS,yCAAyC,QAAiB;AACtE,SAAO;IACH;EAAA;AAER;AAUA,SAASA,6BAEP;AACE,MAAI,CAACC,mBAAkB;AACnB,IAAAA,oBAAmB;MACf,sBAAsB,0BAA0B,IAAI,CAAA,MAAK,CAAC,SAAS,GAAG,CAAC,CAAC;MACxE,oBAAoB;QAChB;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ,CAAC,SAAS,SAAS,gBAAgB,kBAAkB,QAAQ,WAAW,kBAAkB,YAAY;QACtG;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ;UACI;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QAAA;QAEJ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,8BAAoB;AAAA,QACtB;AAAA,MACF;AAAA,IACF,CAAC;AAKD,QAAI,CAAC,cAAc,GAAG;AAGpB,iCAA2B,EACxB,KAAK,CAAC,EAAE,SAAAA,UAAS,OAAO,MAAM;AAC7B,YAAI,WAAW,aAAa;AAC1B,cAAI,OAAO,KAAK,kSAAkD;AAClE,cAAI,OAAO,KAAK,qDAAgD;AAChE,cAAI,OAAO,KAAK,eAAeA,QAAO,EAAE;AACxC,cAAI,OAAO,KAAK,8CAA8C;AAC9D,cAAI,OAAO,KAAK,4CAA4C;AAC5D,cAAI,OAAO,KAAK,kSAAkD;AAAA,QACpE,WAAW,WAAW,SAAS;AAC7B,cAAI,OAAO,KAAK,uBAAuBA,QAAO,EAAE;AAAA,QAClD,OAAO;AACL,cAAI,OAAO,KAAK,0CAA0CA,QAAO,EAAE;AAAA,QACrE;AAAA,MACF,CAAC,EACA,MAAM,CAAC,QAAQ;AACd,YAAI,OAAO;AAAA,UACT,gCAAgC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,QAClF;AAAA,MACF,CAAC;AACH,UAAI,OAAO,KAAK,+DAA0D;AAC1E;AAAA,IACF;AAMA,2BAAuB,GAAG,EACvB,KAAK,YAAY;AAEhB,YAAM,OAAO,aAAa;AAC1B,YAAM,UAAU,MAAM,mBAAmB,MAAM,GAAI;AACnD,UAAI,CAAC,SAAS;AACZ,YAAI,OAAO,KAAK,iEAAiE;AAAA,MACnF;AAAA,IACF,CAAC,EACA,MAAM,CAAC,QAAQ;AACd,UAAI,OAAO;AAAA,QACT,mCAAmC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MACrF;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAEA,IAAOK,iBAAQ;","names":["docsPath","signature","signature","signature","signature","signature","abi","signature","signature","signature","length","formatAbiItem","init_formatAbiItem","version","init_version","BaseError","init_version","docsPath","version","init_formatAbiItem","BaseError","docsPath","size","signature","formatAbiItem","BaseError","size","size","BaseError","size","size","size","index","BaseError","encoder","l","s","crypto","toBytes","pad","crypto","init_utils","s","init_utils","l","toBytes","signature","BaseError","BaseError","address","size","hash","address","address","cacheKey","concatBytes","bytesRegex","integerRegex","init_regex","size","integerRegex","length","BaseError","index","init_regex","abi","index","abi","docsPath","formatAbiItem","init_formatAbiItem","abi","signature","BaseError","init_cursor","size","data","length","consumed","value","size","init_cursor","abi","signature","formatAbiItem","init_formatAbiItem","value","address","BaseError","BaseError","docsPath","chain","hash","index","init_utils","address","init_formatAbiItem","init_utils","BaseError","docsPath","chain","abi","formatAbiItem","signature","init_utils","BaseError","BaseError","docsPath","address","isLE","_32n","l","init_utils","toBytes","buffer","finished","init_utils","D","init_utils","hash","toBytes","pad","finished","isBytes","abytes","num","hexToNumber","_0n","bytesToHex","hexes","hexToBytes","e","concatBytes","pad","utf8ToBytes","_1n","gen","init_utils","_0n","modulo","_1n","gcd","_2n","P","num","bitLen","isLE","init_utils","_1n","s","P","_0n","base","wbits","init_utils","num","size","bytesToHex","Fn","toBytes","concatBytes","fromBytes","_3n","_4n","_1n","isBytes","Point","P","endo","_0n","a","modN","s","from","l","hexToBytes","utils","hash","randomBytes","e","sign","signature","isHex","o","_2n","tv5","c1","c2","init_utils","hash","create","init_utils","abytes","concatBytes","utf8ToBytes","hash","e","createHasher","Point","num","P","init_utils","P","_3n","_2n","concatBytes","_1n","_0n","e","signature","s","init_utils","createHasher","encode","BaseError","init_cursor","address","hash","BaseError","BaseError","e","formatted","address","init_stateOverride","address","sha256","sha256","init_sha256","version","sha256","init_sha256","version","init_blob","BaseError","size","hash","version","size","init_blob","init_cursor","abi","docsPath","isBytes","abytes","abool","numberToHexUnpadded","num","hexToNumber","_0n","bytesToHex","hasHexBuiltin","hexes","asciiToBase16","asciis","hexToBytes","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","e","concatBytes","pad","inRange","isPosBig","aInRange","bitLen","_1n","createHmacDrbg","u8n","u8fr","gen","validateObject","validatorFns","memoized","bitMask","init_utils","version","init_version","version","init_errors","init_version","walk","BaseError","init_errors","docsPath","version","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","charCodeToBase16","charCodeMap","pad","SizeExceedsPaddingSizeError","trim","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","pad","SizeExceedsPaddingSizeError","trim","stringify","value","size","assertSize","index","charCodeToBase16","BaseError","encoder","padRight","pad","slice","assertStartOffset","assertEndOffset","toBigInt","InvalidBytesBooleanError","toNumber","trim","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","stringify","assert","concat","from","assertSize","hexes","size","IntegerOutOfRangeError","fromString","encoder","pad","slice","assertStartOffset","assertEndOffset","trimLeft","trim","validate","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","BaseError","stringify","toRpc","init_contract","BaseError","chain","abi","docsPath","chain","docsPath","cause","wait","args","split","init_utils","BaseError","abi","signature","formatAbiItem","init_formatAbiItem","abi","docsPath","formatAbiItem","signature","init_formatAbiItem","abi","docsPath","ccipRequest","init_ccip","BaseError","toRpc","base","data","offchainLookup","offchainLookupSignature","wait","args","size","init_contract","init_stateOverride","address","hash","version","BaseError","init_blob","address","signature","blobs","commitments","proofs","v","s","signature","BaseError","integerRegex","base","bytesRegex","struct","init_typedData","init_regex","init_typedData","s","signature","isBytes","anumber","wrap","encode","decode","l","from","padding","num","checksum","hash","init_utils","wordlist","e","init_esm","init_utils","hash","s","signature","address","signature","signature","address","hash","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","bytesToHex","hasHexBuiltin","hexes","asciiToBase16","asciis","hexToBytes","concatBytes","pad","createHasher","randomBytes","init_utils","Chi","Maj","HashMD","SHA256_IV","init_md","init_utils","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","SHA256_K","SHA256_W","sha256","init_sha2","init_md","init_utils","HashMD","D","rotr","Chi","Maj","clean","SHA256_IV","createHasher","abool","isPosBig","anumber","numberToHexUnpadded","num","hexToNumber","_0n","bytesToNumberBE","bytesToHex","bytesToNumberLE","abytes","numberToBytesBE","hexToBytes","numberToBytesLE","inRange","aInRange","bitLen","_1n","createHmacDrbg","u8n","concatBytes","gen","validateObject","memoized","bitMask","init_utils","mod","_0n","pow2","modulo","invert","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","P","Field","tonelliShanks","_7n","e2","e3","_3n","FpLegendre","FpSqrt","validateField","FIELD_FIELDS","validateObject","FpPow","num","FpInvertBatch","nLength","anumber","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","abytes","bytesToNumberLE","bytesToNumberBE","numberToBytesLE","numberToBytesBE","init_modular","init_utils","FpInvertBatch","validateW","calcWOpts","bitMask","calcOffsets","_1n","getW","P","pointWindowSizes","_0n","Point","isLE","validateField","Field","Fn","pointPrecomputes","wNAF","init_curve","init_utils","init_modular","base","hmac","init_hmac","init_utils","hash","ahash","abytes","pad","clean","aexists","finished","divNearest","_0n","bitMask","bitLen","_1n","abool","weierstrass","Fn","validateObject","pointToBytes","concatBytes","abytes","_3n","_4n","Point","memoized","P","hexToBytes","endo","bytesToHex","wNAF","randomBytes","getMinHashLength","num","l","mapHashToField","isBytes","s","utils","hash","ahash","hmac","_2n","size","r","DER","bytesToNumberBE","aInRange","extraEntropy","e","sign","createHmacDrbg","signature","recoverPublicKey","DERErr","init_weierstrass","init_hmac","init_utils","init_curve","init_modular","numberToHexUnpadded","sqrtMod","P","_3n","pow2","_2n","Fpk1","secp256k1","init_secp256k1","init_sha2","init_modular","init_weierstrass","Field","weierstrass","sha256","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","concatBytes","pad","createHasher","oidNist","init_utils","_HMAC","hmac","init_hmac","init_utils","hash","ahash","abytes","pad","clean","aexists","finished","Chi","Maj","HashMD","SHA256_IV","SHA512_IV","init_md","init_utils","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","init_md","init_utils","HashMD","clean","createHasher","fromBig","U32_MASK64","_32n","split","l","add","shrSH","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add3L","add3H","add4L","add4H","add5L","add5H","init_u64","s","SHA256_K","SHA256_W","SHA2_32B","_SHA256","K512","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","sha256","sha512","init_sha2","init_md","init_u64","init_utils","HashMD","D","rotr","Chi","Maj","clean","SHA256_IV","split","rotrSH","shrSH","rotrSL","shrSL","rotrBH","rotrBL","add4L","add4H","add5L","add5H","add","add3L","add3H","SHA512_IV","createHasher","oidNist","isBytes","isArrayOf","afn","astr","anumber","aArr","astrArr","anumArr","chain","wrap","encode","decode","alphabet","l","join","from","convertRadix","radix","num","checksum","init_base","sha256","Point","init_secp256k1","init_hmac","init_sha2","init_utils","init_base","secp256k1","sha256","createView","concatBytes","abytes","hmac","sha512","version","path","index","hash","signature","sha512","e","isSolanaError","index","ORDERED_ERROR_NAMES","padBytes","slice","index","encoder","decoder","SolanaError","size","buffer","alphabet","base","charCodeToBase16","TextDecoder","TextEncoder","createEncoder","SolanaError","SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE","hexBytes","createDecoder","combineCodec","buffer","decoder","address","index","SolanaError","SolanaError","isAddress","base58Encoder","mod","pow2","SolanaError","address","e","encode","decode","Endian","combineCodec","createEncoder","createDecoder","size","newOffset","createEncoder","createDecoder","slice","combineCodec","getBase16Decoder","SolanaError","index","getEncodedSize","isFixedSize","getU8Encoder","transformEncoder","getU8Decoder","transformDecoder","l","encoder","decoder","containsBytes","init_index_node","AccountRole","isAddress","SolanaError","combineCodec","assertValidBaseString","alphabet","SolanaError","partitionLeadingZeroes","getBigIntFromBaseX","base","getBaseXFromBigInt","getU8Encoder","getU8Decoder","getStructEncoder","getStructDecoder","getArrayEncoder","getShortU16Encoder","getArrayDecoder","getShortU16Decoder","createEncoder","createDecoder","version","combineCodec","transformEncoder","getBase58Encoder","getAddressEncoder","getAddressDecoder","getBase58Decoder","transformDecoder","address","TYPE","index","AccountRole","getAddressComparator","isWritableRole","isSignerRole","l","getBaseXEncoder","getBaseXDecoder","SolanaError","signature","randomBytes","privateKey","signature","getBytesEncoder","SolanaError","address","index","SYSTEM_PROGRAM_ADDRESS","isAdvanceNonceAccountInstructionData","isAddress","signatureBytes","signTransaction","SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT","index","appendTransactionMessageInstruction","SolanaError","signature","context","traverse","traverseSequential","traverseParallel","traverseSingle","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND","candidate","message","appendTransactionMessageInstructions","getAbortablePromise","getTransactionMessageSize","TRANSACTION_SIZE_LIMIT","isSolanaError","SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND","isAddress","version","SolanaError","transformEncoder","getAddressDecoder","getSignaturesToEncode","signature","getSignaturesEncoder","getU8Encoder","getStructEncoder","getBytesEncoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO","address","transformDecoder","getStructDecoder","getArrayDecoder","getBytesDecoder","getU8Decoder","combineCodec","index","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO","getArrayEncoder","getAddressEncoder","getUtf8Encoder","fixDecoderSize","getTupleDecoder","getUtf8Decoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY","getTupleEncoder","getHiddenPrefixDecoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED","encoder","SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE","signatureBytes","OffchainMessageContentFormat","plugin","unwrapBigIntValueObject","wrapBigIntValueObject","traverse","pipe","SolanaError","stringify","path","e","normalizeHeaders","AbortController","args","setMaxListeners","init_index_node","createExplicitAbortToken","e","EXPLICIT_ABORT_TOKEN","AbortController","EventTarget","args","setMaxListeners","e","SolanaError","AbortController","args","setMaxListeners","getAllowedNumericKeypaths","memoizedKeypaths","concat","buffer","toArrayBuffer","e","num","data","e","concat","toArrayBuffer","Receiver","num","Sender","http","randomBytes","createHash","URL","Receiver","Sender","WebSocket","address","e","key","WebSocket","createWebSocketStream","err","open","protocol","http","createHash","WebSocket","WebSocketServer","index","version","WebSocket","s","EventTarget","index_node_default","args","setMaxListeners","WebSocketImpl","createSolanaJsonRpcIntegerOverflowError","path","e","index","pipe","transformChannelInboundMessages","transformChannelOutboundMessages","cache","AbortController","args","setMaxListeners","SolanaError","address","isAddress","offchainMessageEnvelope","SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING","signature","transaction","o","TextEncoder","e","base58Decoder","SolanaError","signature","safeRace","getTimeoutPromise","AbortController","args","setMaxListeners","lamports","l","createRecentSignatureConfirmationPromiseFactory","signature","e","commitmentComparator","sha512","index","createKeyPairSignerFromPrivateKeyBytes","init_esm","CACHE_TTL_MS","init_index_node","fixDecoderSize","getBytesDecoder","getStructDecoder","getU64Decoder","getU16Decoder","getOptionDecoder","getAddressDecoder","getU32Decoder","getBooleanDecoder","address","isTransactionSigner","kitIsTransactionSigner","getAddressEncoder","transformEncoder","getStructEncoder","getU8Encoder","getU64Encoder","AccountRole","ASSOCIATED_TOKEN_ERROR__INVALID_OWNER","associatedTokenErrorMessages","AccountState","init_index_node","transformEncoder","getStructEncoder","getU8Encoder","getU32Encoder","appendTransactionMessageInstruction","init_src","init_index_node","x402Version","tx","NETWORKS","init_src","init_index_node","x402Version","tx","NETWORKS","homedir","join","mkdir","writeFile","readFileSync","BaseError","init_formatAbiItem","abi","formatAbiItem","signature","address","abi","abi","address","docsPath","BaseError","err","hash","signature","secp256k1","s","yParityOrV","recoveryBit","hash","signature","signature","BaseError","docsPath","chain","docsPath","cause","init_stateOverride","BaseError","BaseError","formatAuthorizationList","chain","chain","base","docsPath","cause","chain","format","base","chain","prepareTransactionRequest","getChainId","chainId","from","gas","nonce","type","e","error","getBlock","block","BaseError","abi","address","init_formatAbiItem","docsPath","abi","signature","formatAbiItem","abi","isEqual","index","value","input","address","event","abi","address","abi","address","abi","address","listeners","cleanup","poll","cacheKey","cache","abi","address","transport","eventName","args","shouldRetry","size","chain","base","key","BaseError","e","hash","hash","chain","address","BaseError","res","chain","address","chain","chain","address","event","address","address","address","BaseError","address","address","version","e","address","signature","promiseCache","uid","BaseError","chain","base","body","response","assert","from","validate","LruMap","size","LruMap","keccak256","assert","from","validate","fromHex","fromBytes","assert","x","slice","prefix","toHex","assert","concat","BaseError","stringify","size","from","addressRegex","assert","InvalidAddressError","checksum","address","hash","keccak256","from","toHex","validate","address","assert","InvalidAddressError","BaseError","bytesRegex","integerRegex","maxInt8","maxInt16","maxInt24","maxInt32","maxInt40","maxInt48","maxInt56","maxInt64","maxInt72","maxInt80","maxInt88","maxInt96","maxInt104","maxInt112","maxInt120","maxInt128","maxInt136","maxInt144","maxInt152","maxInt160","maxInt168","maxInt176","maxInt184","maxInt192","maxInt200","maxInt208","maxInt216","maxInt224","maxInt232","maxInt240","maxInt248","maxInt256","minInt8","minInt16","minInt24","minInt32","minInt40","minInt48","minInt56","minInt64","minInt72","minInt80","minInt88","minInt96","minInt104","minInt112","minInt120","minInt128","minInt136","minInt144","minInt152","minInt160","minInt168","minInt176","minInt184","minInt192","minInt200","minInt208","minInt216","minInt224","minInt232","minInt240","minInt248","minInt256","maxUint8","maxUint16","maxUint24","maxUint32","maxUint40","maxUint48","maxUint56","maxUint64","maxUint72","maxUint80","maxUint88","maxUint96","maxUint104","maxUint112","maxUint120","maxUint128","maxUint136","maxUint144","maxUint152","maxUint160","maxUint168","maxUint176","maxUint184","maxUint192","maxUint200","maxUint208","maxUint216","maxUint224","maxUint232","maxUint240","maxUint248","maxUint256","decodeParameter","checksumAddress","getArrayComponents","decodeArray","decodeTuple","decodeAddress","decodeBool","decodeBytes","decodeNumber","decodeString","sizeOfLength","sizeOfOffset","checksum","wrap","address","slice","toNumber","length","hasDynamicChild","consumed","value","size","toBigInt","encodeArray","encodeTuple","encodeAddress","integerRegex","encodeNumber","encodeBytes","encodeString","concat","assert","InvalidArrayError","BytesSizeMismatchError","BaseError","IntegerOutOfRangeError","fromString","index","staticCursor","RecursiveReadLimitExceededError","PositionOutOfBoundsError","NegativeOffsetError","size","BaseError","checksumAddress","size","data","decodeParameter","encode","concat","encodePacked","address","assert","fromString","integerRegex","bytesRegex","BytesSizeMismatchError","from","BaseError","size","BytesSizeMismatchError","InvalidArrayError","from","getEncodable","fromHex","from","getEncodable","getEncodableList","getEncodableBytes","getSizeOfLength","encode","BaseError","init_utils","init_utils","_0n","_1n","_2n","_3n","_4n","_5n","_8n","mod","pow2","modulo","_0n","invert","mod","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","tonelliShanks","P","Field","FpLegendre","FpSqrt","_3n","FIELD_FIELDS","validateField","validateObject","FpPow","num","_0n","_1n","FpInvertBatch","FpLegendre","_1n","_2n","nLength","Field","bitLen","isLE","_0n","bitMask","_1n","num","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","num","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","init_utils","_0n","_1n","constTimeNegate","validateW","calcWOpts","bitMask","calcOffsets","validateMSMPoints","validateMSMScalars","s","pointPrecomputes","pointWindowSizes","getW","P","wNAF","base","pippenger","bitLen","wbits","validateBasic","validateField","validateObject","nLength","init_utils","validateSigVerOpts","abool","validatePointOpts","validateBasic","validateObject","DERErr","DER","numberToHexUnpadded","num","_0n","bytesToNumberBE","ensureBytes","numToSizedHex","size","bytesToHex","numberToBytesBE","_1n","_2n","_3n","_4n","weierstrassPoints","Fn","Field","toBytes","concatBytes","fromBytes","inRange","isBytes","mod","aInRange","Point","memoized","FpInvertBatch","P","pippenger","endo","a","wNAF","validateOpts","weierstrass","modN","invert","s","from","l","hexToBytes","utils","getMinHashLength","mapHashToField","bitMask","hash","randomBytes","e","sign","createHmacDrbg","signature","isHex","getHash","hash","createCurve","create","weierstrass","secp256k1P","secp256k1N","_0n","_1n","_2n","divNearest","sqrtMod","P","_3n","pow2","Fpk1","Field","secp256k1","createCurve","mod","assert","signature","maxUint256","fromBytes","fromHex","InvalidSerializedSizeError","slice","s","yParity","extract","from","fromRpc","signature","fromRpc","yParity","signature","s","trimLeft","InvalidSerializedSizeError","BaseError","signature","size","from","stringify","from","fromRpc","address","signature","extract","hash","keccak256","concat","fromHex","toTuple","toTuple","address","signature","extract","recoverAddress","recoverPublicKey","signature","s","secp256k1","from","from","assert","slice","signature","recoverAddress","encode","size","concat","validate","BaseError","address","address","hash","index","hash","hash","contracts","abi","address","result","BaseError","init_stateOverride","block","toRpc","call","abi","result","error","e","normalizeSignature","signature","BaseError","isArgOfType","validate","index","getAmbiguousTypes","from","abi","validate","abiItem","slice","index","isArgOfType","getAmbiguousTypes","signature","normalizeSignature","keccak256","fromString","BaseError","encode","abi","options","fromAbi","concat","from","fromAbi","abi","item","encodeData","abi","args","fromAbi","abiFunction","getSelector","encode","concat","from","fromAbi","abi","getSelector","BaseError","encode","from","encodeData","call","address","InvalidWrappedSignatureError","assert","from","magicBytes","unwrap","validate","wrap","magicBytes","assert","slice","InvalidWrappedSignatureError","from","unwrap","signature","wrap","concat","encode","validate","BaseError","address","chain","hash","signature","address","signature","hash","address","signature","hash","transport","hash","from","block","transport","address","transport","event","args","hash","address","address","signature","hash","uid","BaseError","chain","wait","body","serializeTransaction","signature","from","decoder","x402Version","cache","cacheKey","payload","response","randomBytes","x402Version","signature","version","x402Version","signature","version","getAddress","getAddress","signature","from","encodeFunctionData","x402Version","readContract","signTransaction","getTransactionCount","estimateFeesPerGas","confidence","supportsToolCalling","supportsVision","decision","join","size","join","homedir","join","require","LOG_DIR","join","homedir","e","DEFAULT_TTL_MS","createHash","canonicalize","TIMESTAMP_PATTERN","InsufficientFundsError","RpcError","RpcError","mkdir","join","homedir","mkdir","chain","mkdir","crypto","hashMessage","hash","path","path","l","escapeRegex","originalChars","createHash","hash","join","dirname","homedir","join","homedir","dirname","DEFAULT_CONFIG","e","join","homedir","sanitized","size","readFileSync","buffer","account","baseUrl","createKeyPairSignerFromPrivateKeyBytes","balanceMonitor","SolanaBalanceMonitor","registerExactSvmScheme","chain","responseCache","s","mkdir","port","writeFile","normalizedModel","cacheKey","index","writeFileSync","existsSync","mkdirSync","homedir","join","dirname","fileURLToPath","s","homedir","WALLET_DIR","homedir","from","join","dirname","fileURLToPath","existsSync","homedir","mkdirSync","writeFileSync","address","deriveSolanaKeyBytes","createKeyPairSignerFromPrivateKeyBytes","signer","SolanaBalanceMonitor","index_default"]} \ No newline at end of file +{"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/abitype/src/human-readable/parseAbiItem.ts","../node_modules/abitype/src/human-readable/parseAbiParameters.ts","../node_modules/abitype/src/exports/index.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/version.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/errors/data.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/@noble/hashes/src/_u64.ts","../node_modules/@noble/hashes/src/cryptoNode.ts","../node_modules/@noble/hashes/src/utils.ts","../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/toEventSelector.ts","../node_modules/viem/errors/address.ts","../node_modules/viem/utils/lru.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/address/isAddress.ts","../node_modules/viem/utils/data/concat.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/regex.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/utils/hash/toFunctionSelector.ts","../node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/viem/constants/solidity.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/utils/encoding/fromBytes.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/abi/formatAbiItemWithArgs.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/errors/request.ts","../node_modules/viem/errors/rpc.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/hashes/src/sha2.ts","../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","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/utils/authorization/hashAuthorization.ts","../node_modules/viem/errors/node.ts","../node_modules/viem/utils/errors/getNodeError.ts","../node_modules/viem/utils/formatters/extract.ts","../node_modules/viem/utils/formatters/formatter.ts","../node_modules/viem/utils/formatters/transactionRequest.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/getTransactionCount.ts","../node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/@noble/hashes/src/sha256.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/utils/transaction/getTransactionType.ts","../node_modules/viem/utils/address/isAddressEqual.ts","../node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/ox/core/version.ts","../node_modules/ox/core/internal/errors.ts","../node_modules/ox/core/Errors.ts","../node_modules/ox/core/internal/bytes.ts","../node_modules/ox/core/internal/hex.ts","../node_modules/ox/core/Json.ts","../node_modules/ox/core/Bytes.ts","../node_modules/ox/core/Hex.ts","../node_modules/ox/core/Withdrawal.ts","../node_modules/ox/core/BlockOverrides.ts","../node_modules/viem/constants/abis.ts","../node_modules/viem/constants/contract.ts","../node_modules/viem/constants/contracts.ts","../node_modules/viem/errors/chain.ts","../node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/viem/utils/errors/getCallError.ts","../node_modules/viem/utils/promise/withResolvers.ts","../node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/viem/errors/ccip.ts","../node_modules/viem/utils/abi/decodeFunctionData.ts","../node_modules/viem/utils/abi/encodeErrorResult.ts","../node_modules/viem/utils/abi/encodeFunctionResult.ts","../node_modules/viem/utils/ens/localBatchGatewayRequest.ts","../node_modules/viem/utils/ccip.ts","../node_modules/viem/actions/public/call.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/utils/authorization/serializeAuthorizationList.ts","../node_modules/viem/constants/strings.ts","../node_modules/viem/utils/signature/toPrefixedMessage.ts","../node_modules/viem/utils/signature/hashMessage.ts","../node_modules/viem/errors/typedData.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/utils/signature/hashTypedData.ts","../node_modules/viem/utils/signature/serializeSignature.ts","../node_modules/@scure/base/index.ts","../node_modules/@noble/hashes/src/pbkdf2.ts","../node_modules/@scure/bip39/esm/index.js","../node_modules/viem/accounts/toAccount.ts","../node_modules/viem/accounts/utils/sign.ts","../node_modules/viem/accounts/utils/signAuthorization.ts","../node_modules/viem/accounts/utils/signMessage.ts","../node_modules/viem/accounts/utils/signTransaction.ts","../node_modules/viem/accounts/utils/signTypedData.ts","../node_modules/viem/accounts/privateKeyToAccount.ts","../node_modules/@scure/bip39/esm/wordlists/english.js","../node_modules/viem/accounts/index.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@noble/curves/src/utils.ts","../node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/@noble/curves/src/secp256k1.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_md.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/legacy.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts","../node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha2.ts","../node_modules/@scure/bip32/node_modules/@scure/base/index.ts","../node_modules/@scure/bip32/index.ts","../node_modules/@noble/hashes/src/sha512.ts","../node_modules/@solana/errors/src/codes.ts","../node_modules/@solana/errors/src/context.ts","../node_modules/@solana/errors/src/messages.ts","../node_modules/@solana/errors/src/message-formatter.ts","../node_modules/@solana/errors/src/error.ts","../node_modules/@solana/errors/src/stack-trace.ts","../node_modules/@solana/errors/src/rpc-enum-errors.ts","../node_modules/@solana/errors/src/instruction-error.ts","../node_modules/@solana/errors/src/transaction-error.ts","../node_modules/@solana/errors/src/json-rpc-error.ts","../node_modules/@solana/errors/src/simulation-errors.ts","../node_modules/@solana/codecs-core/src/bytes.ts","../node_modules/@solana/codecs-core/src/codec.ts","../node_modules/@solana/codecs-core/src/combine-codec.ts","../node_modules/@solana/codecs-core/src/add-codec-sentinel.ts","../node_modules/@solana/codecs-core/src/assertions.ts","../node_modules/@solana/codecs-core/src/add-codec-size-prefix.ts","../node_modules/@solana/codecs-core/src/array-buffers.ts","../node_modules/@solana/codecs-core/src/decoder-entire-byte-array.ts","../node_modules/@solana/codecs-core/src/fix-codec-size.ts","../node_modules/@solana/codecs-core/src/offset-codec.ts","../node_modules/@solana/codecs-core/src/resize-codec.ts","../node_modules/@solana/codecs-core/src/pad-codec.ts","../node_modules/@solana/codecs-core/src/reverse-codec.ts","../node_modules/@solana/codecs-core/src/transform-codec.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base10.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/codecs-strings/src/baseX-reslice.ts","../node_modules/@solana/codecs-strings/src/base64.ts","../node_modules/@solana/codecs-strings/src/null-characters.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/codecs-strings/src/utf8.ts","../node_modules/@solana/accounts/src/account.ts","../node_modules/@solana/accounts/src/decode-account.ts","../node_modules/@solana/accounts/src/parse-account.ts","../node_modules/@solana/accounts/src/fetch-account.ts","../node_modules/@solana/accounts/src/maybe-account.ts","../node_modules/@solana/assertions/src/crypto.ts","../node_modules/@solana/assertions/src/subtle-crypto.ts","../node_modules/@solana/addresses/src/address.ts","../node_modules/@solana/addresses/src/vendor/noble/ed25519.ts","../node_modules/@solana/addresses/src/curve-internal.ts","../node_modules/@solana/addresses/src/curve.ts","../node_modules/@solana/addresses/src/program-derived-address.ts","../node_modules/@solana/addresses/src/public-key.ts","../node_modules/@solana/codecs-numbers/src/assertions.ts","../node_modules/@solana/codecs-numbers/src/common.ts","../node_modules/@solana/codecs-numbers/src/utils.ts","../node_modules/@solana/codecs-numbers/src/f32.ts","../node_modules/@solana/codecs-numbers/src/f64.ts","../node_modules/@solana/codecs-numbers/src/i128.ts","../node_modules/@solana/codecs-numbers/src/i16.ts","../node_modules/@solana/codecs-numbers/src/i32.ts","../node_modules/@solana/codecs-numbers/src/i64.ts","../node_modules/@solana/codecs-numbers/src/i8.ts","../node_modules/@solana/codecs-numbers/src/short-u16.ts","../node_modules/@solana/codecs-numbers/src/u128.ts","../node_modules/@solana/codecs-numbers/src/u16.ts","../node_modules/@solana/codecs-numbers/src/u32.ts","../node_modules/@solana/codecs-numbers/src/u64.ts","../node_modules/@solana/codecs-numbers/src/u8.ts","../node_modules/@solana/codecs-data-structures/src/assertions.ts","../node_modules/@solana/codecs-data-structures/src/utils.ts","../node_modules/@solana/codecs-data-structures/src/array.ts","../node_modules/@solana/codecs-data-structures/src/bit-array.ts","../node_modules/@solana/codecs-data-structures/src/boolean.ts","../node_modules/@solana/codecs-data-structures/src/bytes.ts","../node_modules/@solana/codecs-strings/src/base16.ts","../node_modules/@solana/codecs-data-structures/src/constant.ts","../node_modules/@solana/codecs-data-structures/src/tuple.ts","../node_modules/@solana/codecs-data-structures/src/union.ts","../node_modules/@solana/codecs-data-structures/src/discriminated-union.ts","../node_modules/@solana/codecs-data-structures/src/enum-helpers.ts","../node_modules/@solana/codecs-data-structures/src/enum.ts","../node_modules/@solana/codecs-data-structures/src/hidden-prefix.ts","../node_modules/@solana/codecs-data-structures/src/hidden-suffix.ts","../node_modules/@solana/codecs-data-structures/src/literal-union.ts","../node_modules/@solana/codecs-data-structures/src/map.ts","../node_modules/@solana/codecs-data-structures/src/unit.ts","../node_modules/@solana/codecs-data-structures/src/nullable.ts","../node_modules/@solana/codecs-data-structures/src/set.ts","../node_modules/@solana/codecs-data-structures/src/struct.ts","../node_modules/@solana/options/src/option.ts","../node_modules/@solana/options/src/unwrap-option.ts","../node_modules/@solana/options/src/option-codec.ts","../node_modules/@solana/options/src/unwrap-option-recursively.ts","../node_modules/@solana/codecs/dist/index.node.mjs","../node_modules/@solana/functional/src/pipe.ts","../node_modules/@solana/instructions/src/instruction.ts","../node_modules/@solana/instructions/src/roles.ts","../node_modules/@solana/rpc-types/src/blockhash.ts","../node_modules/@solana/rpc-types/src/cluster-url.ts","../node_modules/@solana/rpc-types/src/commitment.ts","../node_modules/@solana/rpc-types/src/lamports.ts","../node_modules/@solana/rpc-types/src/stringified-bigint.ts","../node_modules/@solana/rpc-types/src/stringified-number.ts","../node_modules/@solana/rpc-types/src/unix-timestamp.ts","../node_modules/@solana/transaction-messages/src/blockhash.ts","../node_modules/@solana/codecs-strings/src/assertions.ts","../node_modules/@solana/codecs-strings/src/baseX.ts","../node_modules/@solana/codecs-strings/src/base58.ts","../node_modules/@solana/transaction-messages/src/codecs/address-table-lookup.ts","../node_modules/@solana/transaction-messages/src/codecs/header.ts","../node_modules/@solana/transaction-messages/src/codecs/instruction.ts","../node_modules/@solana/transaction-messages/src/transaction-message.ts","../node_modules/@solana/transaction-messages/src/codecs/transaction-version.ts","../node_modules/@solana/transaction-messages/src/codecs/message.ts","../node_modules/@solana/transaction-messages/src/compile/accounts.ts","../node_modules/@solana/transaction-messages/src/compile/address-table-lookups.ts","../node_modules/@solana/transaction-messages/src/compile/header.ts","../node_modules/@solana/transaction-messages/src/compile/instructions.ts","../node_modules/@solana/transaction-messages/src/compile/lifetime-token.ts","../node_modules/@solana/transaction-messages/src/compile/static-accounts.ts","../node_modules/@solana/transaction-messages/src/compile/message.ts","../node_modules/@solana/transaction-messages/src/compress-transaction-message.ts","../node_modules/@solana/transaction-messages/src/create-transaction-message.ts","../node_modules/@solana/transaction-messages/src/durable-nonce-instruction.ts","../node_modules/@solana/transaction-messages/src/durable-nonce.ts","../node_modules/@solana/transaction-messages/src/fee-payer.ts","../node_modules/@solana/transaction-messages/src/instructions.ts","../node_modules/@solana/transaction-messages/src/decompile-message.ts","../node_modules/@solana/keys/src/algorithm.ts","../node_modules/@solana/keys/src/private-key.ts","../node_modules/@solana/keys/src/public-key.ts","../node_modules/@solana/keys/src/signatures.ts","../node_modules/@solana/keys/src/key-pair.ts","../node_modules/@solana/transactions/src/codecs/signatures-encoder.ts","../node_modules/@solana/transactions/src/codecs/transaction-codec.ts","../node_modules/@solana/transactions/src/lifetime.ts","../node_modules/@solana/transactions/src/compile-transaction.ts","../node_modules/@solana/transactions/src/signatures.ts","../node_modules/@solana/transactions/src/wire-transaction.ts","../node_modules/@solana/transactions/src/transaction-size.ts","../node_modules/@solana/transactions/src/sendable-transaction.ts","../node_modules/@solana/transactions/src/transaction-message-size.ts","../node_modules/@solana/promises/src/race.ts","../node_modules/@solana/promises/src/abortable.ts","../node_modules/@solana/instruction-plans/src/instruction-plan.ts","../node_modules/@solana/instruction-plans/src/append-instruction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-result.ts","../node_modules/@solana/instruction-plans/src/transaction-plan-executor.ts","../node_modules/@solana/instruction-plans/src/transaction-planner.ts","../node_modules/@solana/offchain-messages/src/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/application-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/signing-domain.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-common.ts","../node_modules/@solana/offchain-messages/src/codecs/signatures.ts","../node_modules/@solana/offchain-messages/src/codecs/envelope.ts","../node_modules/@solana/offchain-messages/src/content.ts","../node_modules/@solana/offchain-messages/src/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/content.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v0.ts","../node_modules/@solana/offchain-messages/src/codecs/preamble-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message-v1.ts","../node_modules/@solana/offchain-messages/src/codecs/message.ts","../node_modules/@solana/offchain-messages/src/envelope-common.ts","../node_modules/@solana/offchain-messages/src/envelope-v0.ts","../node_modules/@solana/offchain-messages/src/envelope-v1.ts","../node_modules/@solana/offchain-messages/src/envelope.ts","../node_modules/@solana/offchain-messages/src/signatures.ts","../node_modules/@solana/plugin-core/src/client.ts","../node_modules/@solana/programs/src/program-error.ts","../node_modules/@solana/rpc-spec-types/src/parse-json-with-bigints.ts","../node_modules/@solana/rpc-spec-types/src/rpc-message.ts","../node_modules/@solana/rpc-spec-types/src/stringify-json-with-bigints.ts","../node_modules/@solana/rpc-spec/src/rpc.ts","../node_modules/@solana/rpc-spec/src/rpc-api.ts","../node_modules/@solana/rpc-spec/src/rpc-transport.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast-internal.ts","../node_modules/@solana/rpc-transformers/src/tree-traversal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-bigint-downcast.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-default-commitment.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow-internal.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-integer-overflow.ts","../node_modules/@solana/rpc-transformers/src/request-transformer-options-object-position-config.ts","../node_modules/@solana/rpc-transformers/src/request-transformer.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast-internal.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-bigint-upcast.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-result.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-allowed-numeric-values.ts","../node_modules/@solana/rpc-transformers/src/response-transformer-throw-solana-error.ts","../node_modules/@solana/rpc-transformers/src/response-transformer.ts","../node_modules/@solana/rpc-api/src/index.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-headers.ts","../node_modules/@solana/rpc-transport-http/src/http-transport.ts","../node_modules/@solana/rpc-transport-http/src/is-solana-request.ts","../node_modules/@solana/rpc-transport-http/src/http-transport-for-solana-rpc.ts","../node_modules/@solana/fast-stable-stringify/src/index.ts","../node_modules/@solana/rpc/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc/src/rpc-request-coalescer.ts","../node_modules/@solana/rpc/src/rpc-request-deduplication.ts","../node_modules/@solana/rpc/src/rpc-transport.ts","../node_modules/@solana/rpc/src/rpc.ts","../node_modules/@solana/rpc-parsed-types/dist/index.node.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/subscribable/src/async-iterable.ts","../node_modules/@solana/subscribable/src/data-publisher.ts","../node_modules/@solana/subscribable/src/demultiplex.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-api.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-channel.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-spec/src/rpc-subscriptions-pubsub-plan.ts","../node_modules/@solana/rpc-subscriptions-api/src/index.ts","../node_modules/ws/lib/constants.js","../node_modules/ws/lib/buffer-util.js","../node_modules/ws/lib/limiter.js","../node_modules/ws/lib/permessage-deflate.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/stream.js","../node_modules/ws/lib/subprotocol.js","../node_modules/ws/lib/websocket-server.js","../node_modules/ws/wrapper.mjs","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/ws-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions-channel-websocket/src/websocket-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-integer-overflow-error.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-default-config.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-autopinger.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool-internal.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel-pool.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-json-bigint.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-channel.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-coalescer.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions-transport.ts","../node_modules/@solana/rpc-subscriptions/src/rpc-subscriptions.ts","../node_modules/@solana/signers/src/deduplicate-signers.ts","../node_modules/@solana/signers/src/transaction-modifying-signer.ts","../node_modules/@solana/signers/src/transaction-partial-signer.ts","../node_modules/@solana/signers/src/transaction-sending-signer.ts","../node_modules/@solana/signers/src/transaction-signer.ts","../node_modules/@solana/signers/src/account-signer-meta.ts","../node_modules/@solana/signers/src/add-signers.ts","../node_modules/@solana/signers/src/fee-payer-signer.ts","../node_modules/@solana/signers/src/message-partial-signer.ts","../node_modules/@solana/signers/src/keypair-signer.ts","../node_modules/@solana/signers/src/message-modifying-signer.ts","../node_modules/@solana/signers/src/message-signer.ts","../node_modules/@solana/signers/src/noop-signer.ts","../node_modules/@solana/signers/src/offchain-message-signer.ts","../node_modules/@solana/signers/src/sign-offchain-message.ts","../node_modules/@solana/signers/src/transaction-with-single-sending-signer.ts","../node_modules/@solana/signers/src/sign-transaction.ts","../node_modules/@solana/text-encoding-impl/src/index.node.ts","../node_modules/@solana/signers/src/signable-message.ts","../node_modules/@solana/event-target-impl/src/index.node.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-blockheight.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-nonce.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-recent-signature.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-timeout.ts","../node_modules/@solana/transaction-confirmation/src/confirmation-strategy-racer.ts","../node_modules/@solana/transaction-confirmation/src/waiters.ts","../node_modules/@solana/kit/src/airdrop-internal.ts","../node_modules/@solana/kit/src/airdrop.ts","../node_modules/@solana/kit/src/fetch-lookup-tables.ts","../node_modules/@solana/kit/src/decompile-transaction-message-fetching-lookup-tables.ts","../node_modules/@solana/kit/src/get-minimum-balance-for-rent-exemption.ts","../node_modules/@solana/kit/src/send-transaction-internal.ts","../node_modules/@solana/kit/src/send-and-confirm-durable-nonce-transaction.ts","../node_modules/@solana/kit/src/send-and-confirm-transaction.ts","../node_modules/@solana/kit/src/send-transaction-without-confirming.ts","../src/wallet.ts","../src/solana-balance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/programs/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/errors/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/programs/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/errors/system.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/node_modules/.pnpm/@solana-program+system@0.9.0_@solana+kit@5.0.0_fastestsmallesttextencoderdecoder@1.0.22_typescript@5.5.3_ws@8.17.0_/node_modules/@solana-program/system/src/generated/instructions/createAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/createMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/mintToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token/src/transferToATA.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/accountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/authorityType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/decryptableBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/encryptedBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extension.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/extensionType.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/tokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/types/transferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/mint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/multisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/accounts/token.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/programs/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/errors/token2022.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/shared/index.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/applyConfidentialPendingBalance.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approve.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/approveConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burn.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/burnChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/closeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialDeposit.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialTransferWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/confidentialWithdraw.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/configureConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/pdas/associatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createAssociatedTokenIdempotent.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/createNativeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/disableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emitTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/emptyConfidentialTransferAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableCpiGuard.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableHarvestToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableMemoTransfers.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/enableNonConfidentialCredits.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/freezeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/getAccountDataSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/harvestWithheldTokensToMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeAccount3.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeImmutableOwner.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMint2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMintCloseAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeMultisig2.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeNonTransferableMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePausableConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializePermanentDelegate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeScaledUiAmountMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroup.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenGroupMember.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTokenMetadata.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferFeeConfig.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/initializeTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintTo.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/mintToChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/pause.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/reallocate.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/recoverNestedAssociatedToken.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/removeTokenMetadataKey.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/resume.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/revoke.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/setTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/syncNative.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/thawAccount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transfer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferChecked.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/transferCheckedWithFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/uiAmountToAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateConfidentialTransferMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateDefaultAccountState.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupMemberPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateGroupPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMetadataPointer.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateMultiplierScaledUiMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateRateInterestBearingMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupMaxSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenGroupUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataField.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTokenMetadataUpdateAuthority.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/updateTransferHook.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawExcessLamports.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccounts.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromAccountsForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMint.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/generated/instructions/withdrawWithheldTokensFromMintForConfidentialTransferFee.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/amountToUiAmount.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getInitializeInstructionsForExtensions.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getTokenSize.ts","../node_modules/@x402/svm/node_modules/@solana-program/token-2022/src/getMintSize.ts","../node_modules/@x402/svm/src/constants.ts","../node_modules/@x402/svm/src/utils.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/programs/computeBudget.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestHeapFrame.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/requestUnits.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setComputeUnitPrice.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/generated/instructions/setLoadedAccountsDataSizeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/constants.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/internal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateAndSetComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimitInternal.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/estimateComputeLimit.ts","../node_modules/@x402/svm/node_modules/@solana-program/compute-budget/src/setComputePrice.ts","../node_modules/@x402/svm/src/exact/client/scheme.ts","../node_modules/@x402/svm/src/v1/index.ts","../node_modules/@x402/svm/src/exact/v1/client/scheme.ts","../node_modules/@x402/svm/src/exact/client/register.ts","../src/models.ts","../src/provider.ts","../src/proxy.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/utils/abi/encodeEventTopics.ts","../node_modules/viem/errors/log.ts","../node_modules/viem/actions/public/createContractEventFilter.ts","../node_modules/viem/utils/filters/createFilterRequestScope.ts","../node_modules/viem/actions/public/estimateContractGas.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/viem/utils/authorization/recoverAuthorizationAddress.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/fillTransaction.ts","../node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/public/getContractEvents.ts","../node_modules/viem/utils/abi/parseEventLogs.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/actions/public/getLogs.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/viem/actions/public/watchContractEvent.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/getFilterChanges.ts","../node_modules/viem/actions/public/uninstallFilter.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/viem/actions/ens/getEnsResolver.ts","../node_modules/viem/clients/decorators/public.ts","../node_modules/viem/actions/public/createAccessList.ts","../node_modules/viem/actions/public/createBlockFilter.ts","../node_modules/viem/actions/public/createEventFilter.ts","../node_modules/viem/actions/public/createPendingTransactionFilter.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/getBlobBaseFee.ts","../node_modules/viem/actions/public/getBlockTransactionCount.ts","../node_modules/viem/actions/public/getCode.ts","../node_modules/viem/actions/public/getDelegation.ts","../node_modules/viem/errors/eip712.ts","../node_modules/viem/actions/public/getEip712Domain.ts","../node_modules/viem/actions/public/getFeeHistory.ts","../node_modules/viem/utils/formatters/feeHistory.ts","../node_modules/viem/actions/public/getFilterLogs.ts","../node_modules/viem/actions/public/getProof.ts","../node_modules/viem/utils/authorization/verifyAuthorization.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/utils/promise/withDedupe.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/utils/index.ts","../node_modules/viem/utils/rpc/http.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/utils/rpc/id.ts","../node_modules/ox/erc8010/SignatureErc8010.ts","../node_modules/ox/core/AbiParameters.ts","../node_modules/ox/core/Address.ts","../node_modules/ox/core/internal/lru.ts","../node_modules/ox/core/Caches.ts","../node_modules/ox/core/Hash.ts","../node_modules/ox/core/PublicKey.ts","../node_modules/ox/core/internal/abiParameters.ts","../node_modules/ox/core/Solidity.ts","../node_modules/ox/core/internal/cursor.ts","../node_modules/ox/core/Authorization.ts","../node_modules/ox/core/Rlp.ts","../node_modules/ox/node_modules/@noble/curves/src/secp256k1.ts","../node_modules/ox/node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/ox/node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/ox/core/Signature.ts","../node_modules/ox/core/Secp256k1.ts","../node_modules/viem/utils/formatters/proof.ts","../node_modules/viem/actions/public/getStorageAt.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/actions/public/getTransactionConfirmations.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/viem/actions/public/simulateBlocks.ts","../node_modules/ox/core/AbiItem.ts","../node_modules/ox/core/internal/abiItem.ts","../node_modules/ox/core/AbiConstructor.ts","../node_modules/ox/core/AbiFunction.ts","../node_modules/viem/actions/public/simulateCalls.ts","../node_modules/viem/constants/address.ts","../node_modules/ox/erc6492/SignatureErc6492.ts","../node_modules/viem/actions/public/verifyHash.ts","../node_modules/viem/actions/public/verifyMessage.ts","../node_modules/viem/actions/public/verifyTypedData.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/actions/public/watchBlocks.ts","../node_modules/viem/actions/public/watchEvent.ts","../node_modules/viem/actions/public/watchPendingTransactions.ts","../node_modules/viem/actions/siwe/verifySiweMessage.ts","../node_modules/viem/utils/siwe/parseSiweMessage.ts","../node_modules/viem/utils/siwe/validateSiweMessage.ts","../node_modules/viem/actions/wallet/sendRawTransactionSync.ts","../node_modules/viem/clients/createPublicClient.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/index.ts","../node_modules/viem/op-stack/contracts.ts","../node_modules/viem/op-stack/formatters.ts","../node_modules/viem/op-stack/serializers.ts","../node_modules/viem/op-stack/chainConfig.ts","../node_modules/viem/chains/definitions/base.ts","../node_modules/@x402/core/src/index.ts","../node_modules/@x402/core/src/utils/index.ts","../node_modules/@x402/core/src/http/x402HTTPResourceServer.ts","../node_modules/@x402/core/src/http/httpFacilitatorClient.ts","../node_modules/@x402/core/src/http/x402HTTPClient.ts","../node_modules/@x402/core/src/http/index.ts","../node_modules/@x402/core/src/client/x402Client.ts","../src/payment-preauth.ts","../node_modules/@x402/evm/src/exact/extensions.ts","../node_modules/@x402/evm/src/exact/v1/client/scheme.ts","../node_modules/@x402/evm/src/constants.ts","../node_modules/@x402/evm/src/utils.ts","../node_modules/@x402/evm/src/exact/v1/facilitator/scheme.ts","../node_modules/@x402/evm/src/exact/facilitator/errors.ts","../node_modules/@x402/evm/src/exact/facilitator/eip3009-utils.ts","../node_modules/@x402/evm/src/multicall.ts","../node_modules/@x402/evm/src/v1/index.ts","../node_modules/@x402/evm/src/exact/client/scheme.ts","../node_modules/@x402/evm/src/exact/client/eip3009.ts","../node_modules/@x402/evm/src/exact/client/permit2.ts","../node_modules/@x402/evm/src/exact/client/eip2612.ts","../node_modules/@x402/evm/src/exact/client/erc20approval.ts","../node_modules/@x402/evm/src/exact/client/rpc.ts","../node_modules/@x402/evm/src/exact/client/register.ts","../node_modules/@x402/evm/src/signer.ts","../src/router/rules.ts","../src/router/selector.ts","../src/router/strategy.ts","../src/router/config.ts","../src/router/index.ts","../src/logger.ts","../src/stats.ts","../src/fs-read.ts","../src/version.ts","../src/dedup.ts","../src/response-cache.ts","../src/errors.ts","../src/payment-asset.ts","../src/balance.ts","../src/auth.ts","../src/compression/types.ts","../src/compression/layers/deduplication.ts","../src/compression/layers/whitespace.ts","../src/compression/codebook.ts","../src/compression/layers/dictionary.ts","../src/compression/layers/paths.ts","../src/compression/layers/json-compact.ts","../src/compression/layers/observation.ts","../src/compression/layers/dynamic-codebook.ts","../src/compression/index.ts","../src/session.ts","../src/updater.ts","../src/exclude-models.ts","../src/config.ts","../src/journal.ts","../src/index.ts","../src/partners/registry.ts","../src/partners/tools.ts","../src/spend-control.ts","../src/retry.ts"],"sourcesContent":["export const version = '1.2.3'\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}\nexport function execFallbackSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(fallbackSignatureRegex, 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} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @param structs Struct definitions to include in cache key\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}${structKey}`\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 execFallbackSignature,\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 return parseFunctionSignature(signature, structs)\n\n if (isEventSignature(signature))\n return parseEventSignature(signature, structs)\n\n if (isErrorSignature(signature))\n return parseErrorSignature(signature, structs)\n\n if (isConstructorSignature(signature))\n return parseConstructorSignature(signature, structs)\n\n if (isFallbackSignature(signature)) return parseFallbackSignature(signature)\n\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nexport function parseFunctionSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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\nexport function parseEventSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'event', inputs: abiParameters }\n}\n\nexport function parseErrorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return { name: match.name, type: 'error', inputs: abiParameters }\n}\n\nexport function parseConstructorSignature(\n signature: string,\n structs: StructLookup = {},\n) {\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 return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n}\n\nexport function parseFallbackSignature(signature: string) {\n const match = execFallbackSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'fallback' })\n\n return {\n type: 'fallback',\n stateMutability: match.stateMutability ?? 'nonpayable',\n }\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\\spayable)?)(?(?:\\[\\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 if (match.type === 'address payable') {\n type = 'address'\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 structs\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 { Abi } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiItemError } from './errors/abiItem.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signature, 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 item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * type Result = ParseAbiItem<'function balanceOf(address owner) view returns (uint256)'>\n * // ^? type Result = { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * type Result = ParseAbiItem<\n * // ^? type Result = { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * ['function foo(Baz bar) view returns (string)', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n> =\n | (signature extends string\n ? string extends signature\n ? Abi[number]\n : signature extends Signature // Validate signature\n ? ParseSignature\n : never\n : never)\n | (signature extends readonly string[]\n ? string[] extends signature\n ? Abi[number] // Return generic Abi item since type was no inferrable\n : signature extends Signatures // Validate signature\n ? ParseStructs extends infer structs\n ? {\n [key in keyof signature]: ParseSignature<\n signature[key] extends string ? signature[key] : never,\n structs\n >\n } extends infer mapped extends readonly unknown[]\n ? // Filter out `never` since those are structs\n Filter[0] extends infer result\n ? result extends undefined // convert `undefined` to `never` (e.g. `ParseAbiItem<['struct Foo { string name; }']>`)\n ? never\n : result\n : never\n : never\n : never\n : never\n : never)\n\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint256)')\n * // ^? const abiItem: { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * const abiItem = parseAbiItem([\n * // ^? const abiItem: { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * 'function foo(Baz bar) view returns (string)',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiItem<\n signature extends string | readonly string[] | readonly unknown[],\n>(\n signature: Narrow &\n (\n | (signature extends string\n ? string extends signature\n ? unknown\n : Signature\n : never)\n | (signature extends readonly string[]\n ? signature extends readonly [] // empty array\n ? Error<'At least one signature required.'>\n : string[] extends signature\n ? unknown\n : Signatures\n : never)\n ),\n): ParseAbiItem {\n let abiItem: ParseAbiItem | undefined\n if (typeof signature === 'string')\n abiItem = parseSignature(signature) as ParseAbiItem\n else {\n const structs = parseStructs(signature as readonly string[])\n const length = signature.length as number\n for (let i = 0; i < length; i++) {\n const signature_ = (signature as readonly string[])[i]!\n if (isStructSignature(signature_)) continue\n abiItem = parseSignature(signature_, structs) as ParseAbiItem\n break\n }\n }\n\n if (!abiItem) throw new InvalidAbiItemError({ signature })\n return abiItem as ParseAbiItem\n}\n","import type { AbiParameter } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiParametersError } from './errors/abiParameter.js'\nimport { isStructSignature, modifiers } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { splitParameters } from './runtime/utils.js'\nimport { parseAbiParameter as parseAbiParameter_ } from './runtime/utils.js'\nimport type { IsStructSignature, Modifier } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { SplitParameters } from './types/utils.js'\nimport type { ParseAbiParameters as ParseAbiParameters_ } from './types/utils.js'\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * type Result = ParseAbiParameters('address from, address to, uint256 amount')\n * // ^? type Result: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * type Result = ParseAbiParameters<\n * // ^? type Result: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * ['Baz bar', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n> =\n | (params extends string\n ? params extends ''\n ? never\n : string extends params\n ? readonly AbiParameter[]\n : ParseAbiParameters_, { modifier: Modifier }>\n : never)\n | (params extends readonly string[]\n ? string[] extends params\n ? AbiParameter // Return generic AbiParameter item since type was no inferrable\n : ParseStructs extends infer structs\n ? {\n [key in keyof params]: params[key] extends string\n ? IsStructSignature extends true\n ? never\n : ParseAbiParameters_<\n SplitParameters,\n { modifier: Modifier; structs: structs }\n >\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends readonly [...infer content]\n ? content['length'] extends 0\n ? never\n : DeepFlatten\n : never\n : never\n : never\n : never)\n\n/**\n * Flatten all members of {@link T}\n *\n * @param T - List of items to flatten\n * @param Acc - The accumulator used while recursing\n * @returns The flattened array\n *\n * @example\n * type Result = DeepFlatten<[['a', 'b'], [['c']]]>\n * // ^? type Result = ['a', 'b', 'c']\n */\ntype DeepFlatten<\n T extends readonly unknown[],\n Acc extends readonly unknown[] = readonly [],\n> = T extends readonly [infer head, ...infer tail]\n ? tail extends undefined\n ? never\n : head extends readonly unknown[]\n ? DeepFlatten]>\n : DeepFlatten\n : Acc\n\n/**\n * Parses human-readable ABI parameters into {@link AbiParameter}s\n *\n * @param params - Human-readable ABI parameters\n * @returns Parsed {@link AbiParameter}s\n *\n * @example\n * const abiParameters = parseAbiParameters('address from, address to, uint256 amount')\n * // ^? const abiParameters: [{ type: \"address\"; name: \"from\"; }, { type: \"address\";...\n *\n * @example\n * const abiParameters = parseAbiParameters([\n * // ^? const abiParameters: [{ type: \"tuple\"; components: [{ type: \"string\"; name:...\n * 'Baz bar',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiParameters<\n params extends string | readonly string[] | readonly unknown[],\n>(\n params: Narrow &\n (\n | (params extends string\n ? params extends ''\n ? Error<'Empty string is not allowed.'>\n : unknown\n : never)\n | (params extends readonly string[]\n ? params extends readonly [] // empty array\n ? Error<'At least one parameter required.'>\n : string[] extends params\n ? unknown\n : unknown // TODO: Validate param string\n : never)\n ),\n): ParseAbiParameters {\n const abiParameters: AbiParameter[] = []\n if (typeof params === 'string') {\n const parameters = splitParameters(params)\n const length = parameters.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(parseAbiParameter_(parameters[i]!, { modifiers }))\n }\n } else {\n const structs = parseStructs(params as readonly string[])\n const length = params.length as number\n for (let i = 0; i < length; i++) {\n const signature = (params as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n const parameters = splitParameters(signature)\n const length = parameters.length\n for (let k = 0; k < length; k++) {\n abiParameters.push(\n parseAbiParameter_(parameters[k]!, { modifiers, structs }),\n )\n }\n }\n }\n\n if (abiParameters.length === 0)\n throw new InvalidAbiParametersError({ params })\n\n return abiParameters as ParseAbiParameters\n}\n","export type {\n Abi,\n AbiConstructor,\n AbiError,\n AbiEvent,\n AbiEventParameter,\n AbiFallback,\n AbiFunction,\n AbiInternalType,\n AbiItemType,\n AbiParameter,\n AbiParameterKind,\n AbiReceive,\n AbiStateMutability,\n AbiType,\n Address,\n SolidityAddress,\n SolidityArray,\n SolidityArrayWithoutTuple,\n SolidityArrayWithTuple,\n SolidityBool,\n SolidityBytes,\n SolidityFixedArrayRange,\n SolidityFixedArraySizeLookup,\n SolidityFunction,\n SolidityInt,\n SolidityString,\n SolidityTuple,\n TypedData,\n TypedDataDomain,\n TypedDataParameter,\n TypedDataType,\n} from '../abi.js'\n\n// biome-ignore lint/performance/noBarrelFile: \nexport { BaseError } from '../errors.js'\n\nexport type { Narrow } from '../narrow.js'\nexport { narrow } from '../narrow.js'\n\nexport type {\n Register,\n DefaultRegister,\n ResolvedRegister,\n} from '../register.js'\n\nexport type {\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n AbiTypeToPrimitiveType,\n ExtractAbiError,\n ExtractAbiErrorNames,\n ExtractAbiErrors,\n ExtractAbiEvent,\n ExtractAbiEventNames,\n ExtractAbiEvents,\n ExtractAbiFunction,\n ExtractAbiFunctionNames,\n ExtractAbiFunctions,\n IsAbi,\n IsTypedData,\n TypedDataToPrimitiveTypes,\n} from '../utils.js'\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Human-Readable\n\nexport {\n formatAbi,\n type FormatAbi,\n} from '../human-readable/formatAbi.js'\n\nexport {\n formatAbiItem,\n type FormatAbiItem,\n} from '../human-readable/formatAbiItem.js'\n\nexport {\n formatAbiParameter,\n type FormatAbiParameter,\n} from '../human-readable/formatAbiParameter.js'\n\nexport {\n formatAbiParameters,\n type FormatAbiParameters,\n} from '../human-readable/formatAbiParameters.js'\n\nexport { parseAbi, type ParseAbi } from '../human-readable/parseAbi.js'\n\nexport {\n parseAbiItem,\n type ParseAbiItem,\n} from '../human-readable/parseAbiItem.js'\n\nexport {\n parseAbiParameter,\n type ParseAbiParameter,\n} from '../human-readable/parseAbiParameter.js'\n\nexport {\n parseAbiParameters,\n type ParseAbiParameters,\n} from '../human-readable/parseAbiParameters.js'\n\nexport {\n UnknownTypeError,\n InvalidAbiItemError,\n UnknownSolidityTypeError,\n} from '../human-readable/errors/abiItem.js'\n\nexport {\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n SolidityProtectedKeywordError,\n InvalidParameterError,\n InvalidAbiParametersError,\n InvalidAbiParameterError,\n} from '../human-readable/errors/abiParameter.js'\n\nexport {\n InvalidStructSignatureError,\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../human-readable/errors/signature.js'\n\nexport { InvalidParenthesisError } from '../human-readable/errors/splitParameters.js'\n\nexport { CircularReferenceError } from '../human-readable/errors/struct.js'\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","export const version = '2.46.3'\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 { 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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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://4byte.sourcify.dev/?q=${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 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 IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\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 =\n | HexToBigIntErrorType\n | IntegerOutOfRangeErrorType\n | 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 const value = hexToBigInt(hex, opts)\n const number = Number(value)\n if (!Number.isSafeInteger(number))\n throw new IntegerOutOfRangeError({\n max: `${Number.MAX_SAFE_INTEGER}`,\n min: `${Number.MIN_SAFE_INTEGER}`,\n signed: opts.signed,\n size: opts.size,\n value: `${value}n`,\n })\n return number\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","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * Internal webcrypto alias.\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 * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\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","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\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';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\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\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\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\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 abstract clone(): T;\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\n/** Hash function */\nexport type CHash = ReturnType;\n/** Hash function with output */\nexport type CHashO = ReturnType;\n/** XOF with output */\nexport type CHashXO = ReturnType;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher>(\n hashCons: () => Hash\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash;\n} {\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 createOptHasher, T extends Object>(\n hashCons: (opts?: T) => Hash\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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 createXOFer, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\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 Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\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 IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\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/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\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 clean(B);\n}\n\n/** Keccak sponge function. */\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\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\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(): void {\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): 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(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\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 createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__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 { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.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 { 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 { 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'\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 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 { 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","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","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 AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\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 boolToHex,\n type NumberToHexErrorType,\n numberToHex,\n type StringToHexErrorType,\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, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\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 { 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 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\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 (\n argType === 'object' &&\n isArgOfType(\n Object.values(arg as unknown[] | Record)[\n index\n ],\n component as AbiParameter,\n )\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","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","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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.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 { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.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 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 { 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 = NegativeOffsetErrorType | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetErrorType | 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 ?? bytes,\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 assertSize,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\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 {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.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 AbiParameterKind,\n true\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 never\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, 10), 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', 10)\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 { AbiParameter } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\nimport { stringify } from '../stringify.js'\n\nexport type FormatAbiItemWithArgsErrorType = ErrorType\n\nexport function formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName = true,\n includeName = false,\n}: {\n abiItem: AbiItem\n args: readonly unknown[]\n includeFunctionName?: boolean | undefined\n includeName?: boolean | undefined\n}) {\n if (!('name' in abiItem)) return\n if (!('inputs' in abiItem)) return\n if (!abiItem.inputs) return\n return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n .map(\n (input: AbiParameter, i: number) =>\n `${includeName && input.name ? `${input.name}: ` : ''}${\n typeof args[i] === 'object' ? stringify(args[i]) : args[i]\n }`,\n )\n .join(', ')})`\n}\n","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 {\n TransactionReceipt,\n TransactionType,\n} 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 TransactionReceiptRevertedErrorType =\n TransactionReceiptRevertedError & {\n name: 'TransactionReceiptRevertedError'\n }\nexport class TransactionReceiptRevertedError extends BaseError {\n receipt: TransactionReceipt\n\n constructor({ receipt }: { receipt: TransactionReceipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n })\n\n this.receipt = receipt\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 raw?: Hex | 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\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://4byte.sourcify.dev/?q=${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.raw = data\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 { 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 url: string\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 this.url = url\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n url: string\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 this.url = url\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n url: string | undefined\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 this.url = url\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n url: string\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 this.url = url\n }\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n | -1\n | -32700 // Parse error\n | -32600 // Invalid request\n | -32601 // Method not found\n | -32602 // Invalid params\n | -32603 // Internal error\n | -32000 // Invalid input\n | -32001 // Resource not found\n | -32002 // Resource unavailable\n | -32003 // Transaction rejected\n | -32004 // Method not supported\n | -32005 // Limit exceeded\n | -32006 // JSON-RPC version not supported\n | -32042 // Method not found\n\ntype RpcErrorOptions = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : (code ?? unknownErrorCode)\n ) as code_\n }\n}\n\nexport type ProviderRpcErrorCode =\n | 4001 // User Rejected Request\n | 4100 // Unauthorized\n | 4200 // Unsupported Method\n | 4900 // Disconnected\n | 4901 // Chain Disconnected\n | 4902 // Chain Not Recognized\n | 5700 // Unsupported non-optional capability\n | 5710 // Unsupported chain id\n | 5720 // Duplicate ID\n | 5730 // Unknown bundle id\n | 5740 // Bundle too large\n | 5750 // Atomic-ready wallet rejected upgrade\n | 5760 // Atomicity not supported\n | 7000 // WalletConnect Session Settlement Failed\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n T = undefined,\n> extends RpcError {\n data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions & {\n data?: T | undefined\n }\n >,\n ) {\n super(cause, options)\n\n this.data = options.data\n }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n code: -32700\n name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage:\n 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n })\n }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n code: -32600\n name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n code: -32601\n name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n code: -32602\n name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n code: -32603\n name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n code: -32000\n name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n code: -32001\n name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n override name = 'ResourceNotFoundRpcError'\n static code = -32001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n })\n }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n code: -32002\n name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n })\n }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n code: -32003\n name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n code: -32004\n name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not supported.`,\n })\n }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n code: -32005\n name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n })\n }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n JsonRpcVersionUnsupportedError & {\n code: -32006\n name: 'JsonRpcVersionUnsupportedError'\n }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n })\n }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n code: 4001\n name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n code: 4100\n name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage:\n 'The requested method and/or account has not been authorized by the user.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n UnsupportedProviderMethodError & {\n code: 4200\n name: 'UnsupportedProviderMethodError'\n }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n code: 4900\n name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n })\n }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n code: 4901\n name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n code: 4902\n name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported non-optional capability\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedNonOptionalCapabilityErrorType =\n UnsupportedNonOptionalCapabilityError & {\n code: 5700\n name: 'UnsupportedNonOptionalCapabilityError'\n }\nexport class UnsupportedNonOptionalCapabilityError extends ProviderRpcError {\n static code = 5700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedNonOptionalCapabilityError.code,\n name: 'UnsupportedNonOptionalCapabilityError',\n shortMessage:\n 'This Wallet does not support a capability that was not marked as optional.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported chain id\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedChainIdErrorType = UnsupportedChainIdError & {\n code: 5710\n name: 'UnsupportedChainIdError'\n}\nexport class UnsupportedChainIdError extends ProviderRpcError {\n static code = 5710 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedChainIdError.code,\n name: 'UnsupportedChainIdError',\n shortMessage: 'This Wallet does not support the requested chain ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Duplicate ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type DuplicateIdErrorType = DuplicateIdError & {\n code: 5720\n name: 'DuplicateIdError'\n}\nexport class DuplicateIdError extends ProviderRpcError {\n static code = 5720 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: DuplicateIdError.code,\n name: 'DuplicateIdError',\n shortMessage: 'There is already a bundle submitted with this ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unknown bundle ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnknownBundleIdErrorType = UnknownBundleIdError & {\n code: 5730\n name: 'UnknownBundleIdError'\n}\nexport class UnknownBundleIdError extends ProviderRpcError {\n static code = 5730 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnknownBundleIdError.code,\n name: 'UnknownBundleIdError',\n shortMessage: 'This bundle id is unknown / has not been submitted',\n })\n }\n}\n\n/**\n * Subclass for an \"Bundle too large\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type BundleTooLargeErrorType = BundleTooLargeError & {\n code: 5740\n name: 'BundleTooLargeError'\n}\nexport class BundleTooLargeError extends ProviderRpcError {\n static code = 5740 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: BundleTooLargeError.code,\n name: 'BundleTooLargeError',\n shortMessage: 'The call bundle is too large for the Wallet to process.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomic-ready wallet rejected upgrade\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicReadyWalletRejectedUpgradeErrorType =\n AtomicReadyWalletRejectedUpgradeError & {\n code: 5750\n name: 'AtomicReadyWalletRejectedUpgradeError'\n }\nexport class AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {\n static code = 5750 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicReadyWalletRejectedUpgradeError.code,\n name: 'AtomicReadyWalletRejectedUpgradeError',\n shortMessage:\n 'The Wallet can support atomicity after an upgrade, but the user rejected the upgrade.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomicity not supported\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicityNotSupportedErrorType = AtomicityNotSupportedError & {\n code: 5760\n name: 'AtomicityNotSupportedError'\n}\nexport class AtomicityNotSupportedError extends ProviderRpcError {\n static code = 5760 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicityNotSupportedError.code,\n name: 'AtomicityNotSupportedError',\n shortMessage:\n 'The wallet does not support atomic execution but the request requires it.',\n })\n }\n}\n\n/**\n * Subclass for a \"Session Settlement Failed\" WalletConnect error.\n *\n * WalletConnect https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n */\nexport type WalletConnectSessionSettlementErrorType =\n WalletConnectSessionSettlementError & {\n code: 7000\n name: 'WalletConnectSessionSettlementError'\n }\nexport class WalletConnectSessionSettlementError extends ProviderRpcError {\n static code = 7000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: WalletConnectSessionSettlementError.code,\n name: 'WalletConnectSessionSettlementError',\n shortMessage: 'WalletConnect session settlement failed.',\n })\n }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\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","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): 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/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\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 protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\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 clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\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(): Uint8Array {\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 clone(): HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC;\n} = (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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * hash-to-curve from RFC 9380.\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\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.ts';\nimport { FpInvertBatch, type IField, mod } from './modular.ts';\nimport type { CHash } from './utils.ts';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.ts';\n\nexport type UnicodeOrBytes = string | Uint8Array;\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 */\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/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\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/**\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 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\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 * [RFC 9380 5.2](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 type XY = (x: T, y: T) => { x: T; y: T };\nexport type XYRatio = [T[], T[], T[], T[]]; // xn/xd, yn/yd\nexport function isogenyMap>(field: F, map: XYRatio): XY {\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 [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\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 };\nexport type HTFMethod = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint;\nexport type MapMethod = (scalars: bigint[]) => H2CPoint;\nexport type Hasher = {\n hashToCurve: HTFMethod;\n encodeToCurve: HTFMethod;\n mapToCurve: MapMethod;\n defaults: Opts & { encodeDST?: UnicodeOrBytes };\n};\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n defaults: Opts & { encodeDST?: UnicodeOrBytes }\n): Hasher {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n function map(num: bigint[]) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial: H2CPoint) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n\n return {\n defaults,\n\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): H2CPoint {\n const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options } as Opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\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): H2CPoint {\n const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options } as Opts);\n return clear(map(u[0]));\n },\n\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]): H2CPoint {\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n };\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\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 { AuthorizationRequest } from '../../types/authorization.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type NumberToHexErrorType, numberToHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters =\n AuthorizationRequest & {\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, nonce, to } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n address,\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 { 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|gas required exceeds allowance/\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 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 { 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 { Prettify } from '../../types/utils.js'\n\nexport type DefineFormatterErrorType = ErrorType\n\nexport function defineFormatter(\n type: type,\n format: (args: parameters, action?: string | undefined) => returnType,\n) {\n return <\n parametersOverride,\n returnTypeOverride,\n exclude extends (keyof parameters | keyof parametersOverride)[] = [],\n >({\n exclude,\n format: overrides,\n }: {\n exclude?: exclude | undefined\n format: (\n args: parametersOverride,\n action?: string | undefined,\n ) => returnTypeOverride\n }) => {\n return {\n exclude,\n format: (args: parametersOverride, action?: string | undefined) => {\n const formatted = format(args as any, action)\n if (exclude) {\n for (const key of exclude) {\n delete (formatted as any)[key]\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n } as Prettify & {\n [_key in exclude[number]]: never\n }\n },\n type,\n }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { AuthorizationList } from '../../types/authorization.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type {\n RpcAuthorizationList,\n RpcTransactionRequest,\n} 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 & { account?: Account | undefined },\n _?: string | undefined,\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 (request.account) rpcRequest.from = request.account.address\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.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : 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","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 type { FeeConflictErrorType } 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 { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = 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\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 } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n /** The account address. */\n address: Address\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [\n address,\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : blockTag,\n ],\n },\n {\n dedupe: Boolean(blockNumber),\n },\n )\n return hexToNumber(count)\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","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\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 {\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 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, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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);\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// Used in weierstrass, der\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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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): boolean {\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\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 = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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","/** @internal */\nexport const version = '0.1.1'\n","import { version } from '../version.js'\n\n/** @internal */\nexport function getUrl(url: string) {\n return url\n}\n\n/** @internal */\nexport function getVersion() {\n return version\n}\n\n/** @internal */\nexport function prettyPrint(args: unknown) {\n if (!args) return ''\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","import { getVersion } from './internal/errors.js'\n\nexport type GlobalErrorType = Error & {\n name: name\n}\n\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError<\n cause extends Error | undefined = undefined,\n> extends Error {\n details: string\n docs?: string | undefined\n docsOrigin?: string | undefined\n docsPath?: string | undefined\n shortMessage: string\n showVersion?: boolean | undefined\n version?: string | undefined\n\n override cause: cause\n override name = 'BaseError'\n\n static defaultStaticOptions = {\n docsOrigin: 'https://oxlib.sh',\n showVersion: false,\n version: `ox@${getVersion()}`,\n } satisfies BaseError.GlobalOptions\n\n static setStaticOptions(options: BaseError.GlobalOptions) {\n BaseError.prototype.docsOrigin = options.docsOrigin\n BaseError.prototype.showVersion = options.showVersion\n BaseError.prototype.version = options.version\n }\n\n static {\n BaseError.setStaticOptions(BaseError.defaultStaticOptions)\n }\n\n constructor(shortMessage: string, options: BaseError.Options = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details) return options.cause.details\n if (options.cause.shortMessage) return options.cause.shortMessage\n }\n if (\n options.cause &&\n 'details' in options.cause &&\n typeof options.cause.details === 'string'\n )\n return options.cause.details\n if (options.cause?.message) return options.cause.message\n return options.details!\n })()\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath\n return options.docsPath\n })()\n\n const docsBaseUrl = options.docsOrigin ?? BaseError.prototype.docsOrigin\n const docs = `${docsBaseUrl}${docsPath ?? ''}`\n const showVersion = Boolean(\n options.version ?? BaseError.prototype.showVersion,\n )\n const version = options.version ?? BaseError.prototype.version\n\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath || showVersion\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n showVersion ? `Version: ${version}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n')\n\n super(message, options.cause ? { cause: options.cause } : undefined)\n\n this.cause = options.cause as any\n this.details = details\n this.docs = docs\n this.docsOrigin = docsBaseUrl\n this.docsPath = docsPath\n this.shortMessage = shortMessage\n this.showVersion = showVersion\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\nexport declare namespace BaseError {\n type Options = {\n /** Cause of the error. */\n cause?: cause | undefined\n /** Details of the error. */\n details?: string | undefined\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Path of the docs. */\n docsPath?: string | undefined\n /** Meta messages to add to the error. */\n metaMessages?: (string | undefined)[] | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n\n type GlobalOptions = {\n /** Origin of the docs. */\n docsOrigin?: string | undefined\n /** Whether to show the version of the library in the error message. */\n showVersion?: boolean | undefined\n /** Version of the library to attribute the error to. */\n version?: string | undefined\n }\n}\n\n/** @internal */\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import * as Bytes from '../Bytes.js'\nimport type * as Errors from '../Errors.js'\n\n/** @internal */\nexport function assertSize(bytes: Bytes.Bytes, size_: number): void {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Bytes.size.ErrorType\n | Bytes.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n export type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start\n ) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n })\n }\n}\n\n/** @internal */\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\n/** @internal */\nexport function 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\n/** @internal */\nexport function pad(bytes: Bytes.Bytes, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n if (size === 0) return bytes\n if (bytes.length > size)\n throw new Bytes.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\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Bytes.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Bytes.Bytes,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value\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 return data as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\n\n/** @internal */\nexport function assertSize(hex: Hex.Hex, size_: number): void {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Hex.size.ErrorType\n | Hex.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(value: Hex.Hex, start?: number | undefined) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Hex.Hex,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start\n ) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n })\n }\n}\n\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function pad(hex_: Hex.Hex, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n\n if (size === 0) return hex_\n\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}` as Hex.Hex\n}\n\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n type ErrorType = Hex.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Hex.Hex,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value.replace('0x', '')\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 (data === '0') return '0x'\n if (dir === 'right' && data.length % 2 === 1) return `0x${data}0`\n return `0x${data}` as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Hex.Hex\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from './Errors.js'\n\nconst bigIntSuffix = '#__bigint'\n\n/**\n * Serializes a value to a canonical JSON string as defined by\n * [RFC 8785 (JSON Canonicalization Scheme)](https://www.rfc-editor.org/rfc/rfc8785).\n *\n * - Object keys are sorted recursively by UTF-16 code unit comparison.\n * - Primitives are serialized per ECMAScript rules (no trailing zeros on numbers, etc.).\n * - No whitespace is inserted.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ b: 2, a: 1 })\n * // @log: '{\"a\":1,\"b\":2}'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.canonicalize({ z: [3, { y: 1, x: 2 }], a: 'hello' })\n * // @log: '{\"a\":\"hello\",\"z\":[3,{\"x\":2,\"y\":1}]}'\n * ```\n *\n * @param value - The value to canonicalize.\n * @returns The canonical JSON string.\n */\nexport function canonicalize(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'string')\n return JSON.stringify(value)\n if (typeof value === 'number') {\n if (!Number.isFinite(value))\n throw new TypeError('Cannot canonicalize non-finite number')\n return Object.is(value, -0) ? '0' : JSON.stringify(value)\n }\n if (typeof value === 'bigint')\n throw new TypeError('Cannot canonicalize bigint')\n if (Array.isArray(value))\n return `[${value.map((item) => canonicalize(item)).join(',')}]`\n if (typeof value === 'object') {\n const entries = Object.keys(value as Record)\n .sort()\n .reduce((acc, key) => {\n const v = (value as Record)[key]\n if (v !== undefined)\n acc.push(`${JSON.stringify(key)}:${canonicalize(v)}`)\n return acc\n }, [])\n return `{${entries.join(',')}}`\n }\n return undefined as never\n}\n\nexport declare namespace canonicalize {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(\n string: string,\n reviver?: ((this: any, key: string, value: any) => any) | undefined,\n) {\n return JSON.parse(string, (key, value_) => {\n const value = value_\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length))\n return typeof reviver === 'function' ? reviver(key, value) : value\n })\n}\n\nexport declare namespace parse {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(\n value: any,\n replacer?: ((this: any, key: string, value: any) => any) | null | undefined,\n space?: string | number | undefined,\n) {\n return JSON.stringify(\n value,\n (key, value) => {\n if (typeof replacer === 'function') return replacer(key, value)\n if (typeof value === 'bigint') return value.toString() + bigIntSuffix\n return value\n },\n space,\n )\n}\n\nexport declare namespace stringify {\n type ErrorType = Errors.GlobalErrorType\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/bytes.js'\nimport * as internal_hex from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst decoder = /*#__PURE__*/ new TextDecoder()\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/** Root type for a Bytes array. */\nexport type Bytes = Uint8Array\n\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value: unknown): asserts value is Bytes {\n if (value instanceof Uint8Array) return\n if (!value) throw new InvalidBytesTypeError(value)\n if (typeof value !== 'object') throw new InvalidBytesTypeError(value)\n if (!('BYTES_PER_ELEMENT' in value)) throw new InvalidBytesTypeError(value)\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value)\n}\n\nexport declare namespace assert {\n type ErrorType = InvalidBytesTypeError | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values: readonly Bytes[]): Bytes {\n let length = 0\n for (const arr of values) {\n length += arr.length\n }\n const result = new Uint8Array(length)\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i]\n result.set(arr!, index)\n index += arr!.length\n }\n return result\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value: Hex.Hex | Bytes | readonly number[]): Bytes {\n if (value instanceof Uint8Array) return value\n if (typeof value === 'string') return fromHex(value)\n return fromArray(value)\n}\n\nexport declare namespace from {\n type ErrorType =\n | fromHex.ErrorType\n | fromArray.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value: readonly number[] | Uint8Array): Bytes {\n return value instanceof Uint8Array ? value : new Uint8Array(value)\n}\n\nexport declare namespace fromArray {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value: boolean, options: fromBoolean.Options = {}) {\n const { size } = options\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padLeft(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {\n const { size } = options\n\n let hex = value\n if (size) {\n internal_hex.assertSize(value, size)\n hex = Hex.padRight(value, 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 = internal.charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`,\n )\n }\n bytes[index] = (nibbleLeft << 4) | nibbleRight\n }\n return bytes\n}\n\nexport declare namespace fromHex {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_hex.assertSize.ErrorType\n | Hex.padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(\n value: bigint | number,\n options?: fromNumber.Options | undefined,\n) {\n const hex = Hex.fromNumber(value, options)\n return fromHex(hex)\n}\n\nexport declare namespace fromNumber {\n export type Options = Hex.fromNumber.Options\n\n export type ErrorType =\n | Hex.fromNumber.ErrorType\n | fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: 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 * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Bytes {\n const { size } = options\n\n const bytes = encoder.encode(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padRight(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromString {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA: Bytes, bytesB: Bytes) {\n return equalBytes(bytesA, bytesB)\n}\n\nexport declare namespace isEqual {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(\n value: Bytes,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(\n value: Bytes,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length: number): Bytes {\n return crypto.getRandomValues(new Uint8Array(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value: Bytes): number {\n return value.length\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(\n value: Bytes,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Bytes {\n const { strict } = options\n internal.assertStartOffset(value, start)\n const value_ = value.slice(start, end)\n if (strict) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n export type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes: Bytes, options: toBigInt.Options = {}): bigint {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toBigInt(hex, options)\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(\n bytes: Bytes,\n options: toBoolean.Options = {},\n): boolean {\n const { size } = options\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimLeft(bytes_)\n }\n if (bytes_.length > 1 || bytes_[0]! > 1)\n throw new InvalidBytesBooleanError(bytes_)\n return Boolean(bytes_[0])\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes, options: toHex.Options = {}): Hex.Hex {\n return Hex.fromBytes(value, options)\n}\n\nexport declare namespace toHex {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes: Bytes, options: toNumber.Options = {}): number {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toNumber(hex, options)\n}\n\nexport declare namespace toNumber {\n type Options = {\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\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes: Bytes, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimRight(bytes_)\n }\n return decoder.decode(bytes_)\n}\n\nexport declare namespace toString {\n export type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n export type ErrorType =\n | internal.assertSize.ErrorType\n | trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n export type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value: unknown): value is Bytes {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesBooleanError'\n\n constructor(bytes: Bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n })\n }\n}\n\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`,\n {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Bytes.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as internal_bytes from './internal/bytes.js'\nimport * as internal from './internal/hex.js'\nimport * as Json from './Json.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\n/** Root type for a Hex string. */\nexport type Hex = `0x${string}`\n\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(\n value: unknown,\n options: assert.Options = {},\n): asserts value is Hex {\n const { strict = false } = options\n if (!value) throw new InvalidHexTypeError(value)\n if (typeof value !== 'string') throw new InvalidHexTypeError(value)\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value)) throw new InvalidHexValueError(value)\n }\n if (!value.startsWith('0x')) throw new InvalidHexValueError(value)\n}\n\nexport declare namespace assert {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | InvalidHexTypeError\n | InvalidHexValueError\n | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values: readonly Hex[]): Hex {\n return `0x${(values as Hex[]).reduce((acc, x) => acc + x.replace('0x', ''), '')}`\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value: Hex | Bytes.Bytes | readonly number[]): Hex {\n if (value instanceof Uint8Array) return fromBytes(value)\n if (Array.isArray(value)) return fromBytes(new Uint8Array(value))\n return value as never\n}\n\nexport declare namespace from {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(\n value: boolean,\n options: fromBoolean.Options = {},\n): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padLeft(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(\n value: Bytes.Bytes,\n options: fromBytes.Options = {},\n): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) string += hexes[value[i]!]\n const hex = `0x${string}` as const\n\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padRight(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBytes {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(\n value: number | bigint,\n options: fromNumber.Options = {},\n): Hex {\n const { signed, size } = options\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 stringValue = (\n signed && value_ < 0 ? BigInt.asUintN(size * 8, BigInt(value_)) : value_\n ).toString(16)\n\n const hex = `0x${stringValue}` as Hex\n if (size) return padLeft(hex, size) as Hex\n return hex\n}\n\nexport declare namespace fromNumber {\n type Options =\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\n type ErrorType =\n | IntegerOutOfRangeError\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Hex {\n return fromBytes(encoder.encode(value), options)\n}\n\nexport declare namespace fromString {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA: Hex, hexB: Hex) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB))\n}\n\nexport declare namespace isEqual {\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(\n value: Hex,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(\n value: Hex,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length: number): Hex {\n return fromBytes(Bytes.random(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(\n value: Hex,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Hex {\n const { strict } = options\n internal.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) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value: Hex): number {\n return Math.ceil((value.length - 2) / 2)\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value: Hex): trimLeft.ReturnType {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value: Hex): trimRight.ReturnType {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {\n const { signed } = options\n\n if (options.size) internal.assertSize(hex, options.size)\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n\n const max_signed = max_unsigned >> 1n\n\n if (value <= max_signed) return value\n return value - max_unsigned - 1n\n}\n\nexport declare namespace toBigInt {\n type Options = {\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\n type ErrorType = internal.assertSize.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex: Hex, options: toBoolean.Options = {}): boolean {\n if (options.size) internal.assertSize(hex, options.size)\n const hex_ = trimLeft(hex)\n if (hex_ === '0x') return false\n if (hex_ === '0x1') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | InvalidHexBooleanError\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex: Hex, options: toBytes.Options = {}): Bytes.Bytes {\n return Bytes.fromHex(hex, options)\n}\n\nexport declare namespace toBytes {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex: Hex, options: toNumber.Options = {}): number {\n const { signed, size } = options\n if (!signed && !size) return Number(hex)\n return Number(toBigInt(hex, options))\n}\n\nexport declare namespace toNumber {\n type Options = toBigInt.Options\n\n type ErrorType = toBigInt.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex: Hex, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes = Bytes.fromHex(hex)\n if (size) {\n internal_bytes.assertSize(bytes, size)\n bytes = Bytes.trimRight(bytes)\n }\n return new TextDecoder().decode(bytes)\n}\n\nexport declare namespace toString {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_bytes.assertSize.ErrorType\n | Bytes.fromHex.ErrorType\n | Bytes.trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(\n value: unknown,\n options: validate.Options = {},\n): value is Hex {\n const { strict = false } = options\n try {\n assert(value, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n override readonly name = 'Hex.IntegerOutOfRangeError'\n\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` : ''\n }${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`,\n )\n }\n}\n\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexBooleanError'\n\n constructor(hex: Hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`,\n {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexValueError'\n\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidLengthError'\n\n constructor(value: Hex) {\n super(\n `Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`,\n {\n metaMessages: ['It must be an even length.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Hex.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Hex.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Hex.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/** A Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Withdrawal = {\n address: Hex.Hex\n amount: bigintType\n index: numberType\n validatorIndex: numberType\n}\n\n/** An RPC Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Rpc = Withdrawal\n\n/**\n * Converts a {@link ox#Withdrawal.Rpc} to an {@link ox#Withdrawal.Withdrawal}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.fromRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: '0x620323',\n * index: '0x0',\n * validatorIndex: '0x1',\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: 6423331n,\n * // @log: index: 0,\n * // @log: validatorIndex: 1\n * // @log: }\n * ```\n *\n * @param withdrawal - The RPC withdrawal to convert.\n * @returns An instantiated {@link ox#Withdrawal.Withdrawal}.\n */\nexport function fromRpc(withdrawal: Rpc): Withdrawal {\n return {\n ...withdrawal,\n amount: BigInt(withdrawal.amount),\n index: Number(withdrawal.index),\n validatorIndex: Number(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace fromRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Withdrawal.Withdrawal} to an {@link ox#Withdrawal.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.toRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: 6423331n,\n * index: 0,\n * validatorIndex: 1,\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: '0x620323',\n * // @log: index: '0x0',\n * // @log: validatorIndex: '0x1',\n * // @log: }\n * ```\n *\n * @param withdrawal - The Withdrawal to convert.\n * @returns An RPC Withdrawal.\n */\nexport function toRpc(withdrawal: Withdrawal): Rpc {\n return {\n address: withdrawal.address,\n amount: Hex.fromNumber(withdrawal.amount),\n index: Hex.fromNumber(withdrawal.index),\n validatorIndex: Hex.fromNumber(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace toRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Address from './Address.js'\nimport * as Hex from './Hex.js'\nimport * as Withdrawal from './Withdrawal.js'\n\n/**\n * Block overrides.\n */\nexport type BlockOverrides = {\n /** Base fee per gas. */\n baseFeePerGas?: bigintType | undefined\n /** Blob base fee. */\n blobBaseFee?: bigintType | undefined\n /** Fee recipient (also known as coinbase). */\n feeRecipient?: Address.Address | undefined\n /** Gas limit. */\n gasLimit?: bigintType | undefined\n /** Block number. */\n number?: bigintType | undefined\n /** The previous value of randomness beacon. */\n prevRandao?: bigintType | undefined\n /** Block timestamp. */\n time?: bigintType | undefined\n /** Withdrawals made by validators. */\n withdrawals?: Withdrawal.Withdrawal[] | undefined\n}\n\n/**\n * RPC block overrides.\n */\nexport type Rpc = BlockOverrides\n\n/**\n * Converts an {@link ox#BlockOverrides.Rpc} to an {@link ox#BlockOverrides.BlockOverrides}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.fromRpc({\n * baseFeePerGas: '0x1',\n * blobBaseFee: '0x2',\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: '0x4',\n * number: '0x5',\n * prevRandao: '0x6',\n * time: '0x1234567890',\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: '0x1',\n * index: '0x0',\n * validatorIndex: '0x1',\n * },\n * ],\n * })\n * ```\n *\n * @param rpcBlockOverrides - The RPC block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.BlockOverrides}.\n */\nexport function fromRpc(rpcBlockOverrides: Rpc): BlockOverrides {\n return {\n ...(rpcBlockOverrides.baseFeePerGas && {\n baseFeePerGas: BigInt(rpcBlockOverrides.baseFeePerGas),\n }),\n ...(rpcBlockOverrides.blobBaseFee && {\n blobBaseFee: BigInt(rpcBlockOverrides.blobBaseFee),\n }),\n ...(rpcBlockOverrides.feeRecipient && {\n feeRecipient: rpcBlockOverrides.feeRecipient,\n }),\n ...(rpcBlockOverrides.gasLimit && {\n gasLimit: BigInt(rpcBlockOverrides.gasLimit),\n }),\n ...(rpcBlockOverrides.number && {\n number: BigInt(rpcBlockOverrides.number),\n }),\n ...(rpcBlockOverrides.prevRandao && {\n prevRandao: BigInt(rpcBlockOverrides.prevRandao),\n }),\n ...(rpcBlockOverrides.time && {\n time: BigInt(rpcBlockOverrides.time),\n }),\n ...(rpcBlockOverrides.withdrawals && {\n withdrawals: rpcBlockOverrides.withdrawals.map(Withdrawal.fromRpc),\n }),\n }\n}\n\n/**\n * Converts an {@link ox#BlockOverrides.BlockOverrides} to an {@link ox#BlockOverrides.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.toRpc({\n * baseFeePerGas: 1n,\n * blobBaseFee: 2n,\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: 4n,\n * number: 5n,\n * prevRandao: 6n,\n * time: 78187493520n,\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: 1n,\n * index: 0,\n * validatorIndex: 1,\n * },\n * ],\n * })\n * ```\n *\n * @param blockOverrides - The block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.Rpc}.\n */\nexport function toRpc(blockOverrides: BlockOverrides): Rpc {\n return {\n ...(typeof blockOverrides.baseFeePerGas === 'bigint' && {\n baseFeePerGas: Hex.fromNumber(blockOverrides.baseFeePerGas),\n }),\n ...(typeof blockOverrides.blobBaseFee === 'bigint' && {\n blobBaseFee: Hex.fromNumber(blockOverrides.blobBaseFee),\n }),\n ...(typeof blockOverrides.feeRecipient === 'string' && {\n feeRecipient: blockOverrides.feeRecipient,\n }),\n ...(typeof blockOverrides.gasLimit === 'bigint' && {\n gasLimit: Hex.fromNumber(blockOverrides.gasLimit),\n }),\n ...(typeof blockOverrides.number === 'bigint' && {\n number: Hex.fromNumber(blockOverrides.number),\n }),\n ...(typeof blockOverrides.prevRandao === 'bigint' && {\n prevRandao: Hex.fromNumber(blockOverrides.prevRandao),\n }),\n ...(typeof blockOverrides.time === 'bigint' && {\n time: Hex.fromNumber(blockOverrides.time),\n }),\n ...(blockOverrides.withdrawals && {\n withdrawals: blockOverrides.withdrawals.map(Withdrawal.toRpc),\n }),\n }\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 {\n inputs: [\n {\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n\nexport const batchGatewayAbi = [\n {\n name: 'query',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n type: 'tuple[]',\n name: 'queries',\n components: [\n {\n type: 'address',\n name: 'sender',\n },\n {\n type: 'string[]',\n name: 'urls',\n },\n {\n type: 'bytes',\n name: 'data',\n },\n ],\n },\n ],\n outputs: [\n {\n type: 'bool[]',\n name: 'failures',\n },\n {\n type: 'bytes[]',\n name: 'responses',\n },\n ],\n },\n {\n name: 'HttpError',\n type: 'error',\n inputs: [\n {\n type: 'uint16',\n name: 'status',\n },\n {\n type: 'string',\n name: 'message',\n },\n ],\n },\n] as const\n\nconst universalResolverErrors = [\n {\n inputs: [\n {\n name: 'dns',\n type: 'bytes',\n },\n ],\n name: 'DNSDecodingFailed',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'ens',\n type: 'string',\n },\n ],\n name: 'DNSEncodingFailed',\n type: 'error',\n },\n {\n inputs: [],\n name: 'EmptyAddress',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'HttpError',\n type: 'error',\n },\n {\n inputs: [],\n name: 'InvalidBatchGatewayResponse',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'errorData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n {\n name: 'resolver',\n type: 'address',\n },\n ],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n ],\n name: 'ResolverNotFound',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'primary',\n type: 'string',\n },\n {\n name: 'primaryAddress',\n type: 'bytes',\n },\n ],\n name: 'ReverseAddressMismatch',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'selector',\n type: 'bytes4',\n },\n ],\n name: 'UnsupportedResolverProfile',\n type: 'error',\n },\n] as const\n\nexport const universalResolverResolveAbi = [\n ...universalResolverErrors,\n {\n name: 'resolveWithGateways',\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: 'reverseWithGateways',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'uint256', name: 'coinType' },\n { type: 'string[]', name: 'gateways' },\n ],\n outputs: [\n { type: 'string', name: 'resolvedName' },\n { type: 'address', name: 'resolver' },\n { type: 'address', name: 'reverseResolver' },\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 erc1271Abi = [\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 erc6492SignatureValidatorAbi = [\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-1155 Multi Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-1155) */\nexport const erc1155Abi = [\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'needed',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InsufficientBalance',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'approver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidApprover',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: 'idsLength',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'valuesLength',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InvalidArrayLength',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidOperator',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidReceiver',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidSender',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'ERC1155MissingApprovalForAll',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n ],\n name: 'TransferBatch',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'TransferSingle',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'string',\n name: 'value',\n type: 'string',\n },\n {\n indexed: true,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'URI',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address[]',\n name: 'accounts',\n type: 'address[]',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n ],\n name: 'balanceOfBatch',\n outputs: [\n {\n internalType: 'uint256[]',\n name: '',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'isApprovedForAll',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'interfaceId',\n type: 'bytes4',\n },\n ],\n name: 'supportsInterface',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'uri',\n outputs: [\n {\n internalType: 'string',\n name: '',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\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: 'tokenId',\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 erc6492SignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\nexport const multicall3Bytecode =\n '0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033'\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 { 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 {\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 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","/** @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 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 { Abi, AbiStateMutability } from 'abitype'\n\nimport { AbiFunctionSignatureNotFoundError } from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type SliceErrorType, 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 DecodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = {\n abi: abi\n data: Hex\n}\n\nexport type DecodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allFunctionNames extends\n ContractFunctionName = ContractFunctionName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [functionName in allFunctionNames]: {\n args: ContractFunctionArgs\n functionName: functionName\n }\n }[allFunctionNames]\n >\n : {\n args: readonly unknown[] | undefined\n functionName: string\n }\n\nexport type DecodeFunctionDataErrorType =\n | AbiFunctionSignatureNotFoundError\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | SliceErrorType\n | ErrorType\n\nexport function decodeFunctionData(\n parameters: DecodeFunctionDataParameters,\n) {\n const { abi, data } = parameters as DecodeFunctionDataParameters\n const signature = slice(data, 0, 4)\n const description = abi.find(\n (x) =>\n x.type === 'function' &&\n signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!description)\n throw new AbiFunctionSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeFunctionData',\n })\n return {\n functionName: (description as { name: string }).name,\n args: ('inputs' in description &&\n description.inputs &&\n description.inputs.length > 0\n ? decodeAbiParameters(description.inputs, slice(data, 4))\n : undefined) as readonly unknown[] | undefined,\n } as DecodeFunctionDataReturnType\n}\n","import type { Abi, ExtractAbiErrors } from 'abitype'\n\nimport {\n AbiErrorInputsNotFoundError,\n AbiErrorNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\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 { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeErrorResult'\n\nexport type EncodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n errorName extends ContractErrorName | undefined = ContractErrorName,\n ///\n hasErrors = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiErrors] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractErrorArgs<\n abi,\n errorName extends ContractErrorName\n ? errorName\n : ContractErrorName\n >,\n allErrorNames = ContractErrorName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { errorName?: errorName | allErrorNames | undefined }\n : { errorName: errorName | allErrorNames }\n : { errorName?: errorName | allErrorNames | undefined }\n> &\n (hasErrors extends true ? unknown : never)\n\nexport type EncodeErrorResultReturnType = Hex\n\nexport type EncodeErrorResultErrorType =\n | GetAbiItemErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | EncodeAbiParametersErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function encodeErrorResult<\n const abi extends Abi | readonly unknown[],\n errorName extends ContractErrorName | undefined = undefined,\n>(\n parameters: EncodeErrorResultParameters,\n): EncodeErrorResultReturnType {\n const { abi, errorName, args } = parameters as EncodeErrorResultParameters\n\n let abiItem = abi[0]\n if (errorName) {\n const item = getAbiItem({ abi, args, name: errorName })\n if (!item) throw new AbiErrorNotFoundError(errorName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'error')\n throw new AbiErrorNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toFunctionSelector(definition)\n\n let data: Hex = '0x'\n if (args && args.length > 0) {\n if (!abiItem.inputs)\n throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath })\n data = encodeAbiParameters(abiItem.inputs, args)\n }\n return concatHex([signature, data])\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n AbiFunctionOutputsNotFoundError,\n InvalidArrayError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionName,\n ContractFunctionReturnType,\n} from '../../types/contract.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 GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionResult'\n\nexport type EncodeFunctionResultParameters<\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 allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n result?:\n | ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n never // allow all args. required for overloads to work.\n >\n | undefined\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 (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionResultReturnType = Hex\n\nexport type EncodeFunctionResultErrorType =\n | AbiFunctionOutputsNotFoundError\n | AbiFunctionNotFoundError\n | EncodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function encodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionResultParameters,\n): EncodeFunctionResultReturnType {\n const { abi, functionName, result } =\n parameters as EncodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, 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\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath })\n\n const values = (() => {\n if (abiItem.outputs.length === 0) return []\n if (abiItem.outputs.length === 1) return [result]\n if (Array.isArray(result)) return result\n throw new InvalidArrayError(result)\n })()\n\n return encodeAbiParameters(abiItem.outputs, values)\n}\n","import { batchGatewayAbi } from '../../constants/abis.js'\nimport { solidityError } from '../../constants/solidity.js'\nimport type { Hex } from '../../types/misc.js'\nimport { decodeFunctionData } from '../abi/decodeFunctionData.js'\nimport { encodeErrorResult } from '../abi/encodeErrorResult.js'\nimport { encodeFunctionResult } from '../abi/encodeFunctionResult.js'\nimport type {\n CcipRequestErrorType,\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../ccip.js'\n\nexport const localBatchGatewayUrl = 'x-batch-gateway:true'\n\nexport async function localBatchGatewayRequest(parameters: {\n data: Hex\n ccipRequest: (\n parameters: CcipRequestParameters,\n ) => Promise\n}): Promise {\n const { data, ccipRequest } = parameters\n\n const {\n args: [queries],\n } = decodeFunctionData({ abi: batchGatewayAbi, data })\n\n const failures: boolean[] = []\n const responses: Hex[] = []\n await Promise.all(\n queries.map(async (query, i) => {\n try {\n responses[i] = query.urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({ data: query.data, ccipRequest })\n : await ccipRequest(query)\n failures[i] = false\n } catch (err) {\n failures[i] = true\n responses[i] = encodeError(err as CcipRequestErrorType)\n }\n }),\n )\n\n return encodeFunctionResult({\n abi: batchGatewayAbi,\n functionName: 'query',\n result: [failures, responses],\n })\n}\n\nfunction encodeError(error: CcipRequestErrorType): Hex {\n if (error.name === 'HttpRequestError' && error.status)\n return encodeErrorResult({\n abi: batchGatewayAbi,\n errorName: 'HttpError',\n args: [error.status, error.shortMessage],\n })\n return encodeErrorResult({\n abi: [solidityError],\n errorName: 'Error',\n args: ['shortMessage' in error ? error.shortMessage : error.message],\n })\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Client } from '../clients/createClient.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 { ErrorType } from '../errors/utils.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.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 {\n localBatchGatewayRequest,\n localBatchGatewayUrl,\n} from './ens/localBatchGatewayRequest.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 = urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({\n data: callData,\n ccipRequest: ccipRequest_,\n })\n : 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.toLowerCase()).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","import { type Address, parseAbi } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\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 multicall3Bytecode,\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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } 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 /** Block overrides for the call. */\n blockOverrides?: BlockOverrides.BlockOverrides | 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 authorizationList,\n batch = Boolean(client.batch?.multicall),\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n accessList,\n blobs,\n blockOverrides,\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 =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcBlockOverrides = blockOverrides\n ? BlockOverrides.toRpc(blockOverrides)\n : undefined\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 {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\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,\n 'call',\n ) as TransactionRequest\n\n if (\n batch &&\n shouldPerformMulticall({ request }) &&\n !rpcStateOverride &&\n !rpcBlockOverrides\n ) {\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 params = (() => {\n const base = [\n request as ExactPartial,\n block,\n ] as const\n if (rpcStateOverride && rpcBlockOverrides)\n return [...base, rpcStateOverride, rpcBlockOverrides] as const\n if (rpcStateOverride) return [...base, rpcStateOverride] as const\n if (rpcBlockOverrides) return [...base, {}, rpcBlockOverrides] as const\n return base\n })()\n\n const response = await client.request({\n method: 'eth_call',\n params,\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 {\n batchSize = 1024,\n deployless = false,\n wait = 0,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n data,\n to,\n } = args\n\n const multicallAddress = (() => {\n if (deployless) return null\n if (args.multicallAddress) return args.multicallAddress\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new ClientChainNotConfiguredError()\n })()\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? 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 ...(multicallAddress === null\n ? {\n data: toDeploylessCallViaBytecodeData({\n code: multicall3Bytecode,\n data: calldata,\n }),\n }\n : { to: multicallAddress, data: calldata }),\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: { code: Hex; data: Hex }) {\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 { 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 { chainId } = authorization\n const address = authorization.address\n if (!isAddress(address)) throw new InvalidAddressError({ address })\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 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 { MaybePromise, OneOf } from '../../types/utils.js'\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../authorization/serializeAuthorizationList.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 {\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\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> = (\n transaction: OneOf,\n signature?: Signature | undefined,\n) => MaybePromise<\n SerializedTransactionReturnType<\n OneOf,\n _transactionType\n >\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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 | NumberToHexErrorType\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 ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(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 numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(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 ? numberToHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return numberToHex(1)\n\n return v === 27n ? '0x' : numberToHex(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 {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../../types/authorization.js'\nimport { toHex } from '../encoding/toHex.js'\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.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 { chainId, nonce, ...signature } = authorization\n const contractAddress = authorization.address\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","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 bytesToHex,\n type StringToHexErrorType,\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 { 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_, 10) / 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_, 10))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_, 10),\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}: {\n domain?: TypedDataDomain | undefined\n}): 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 typeof domain?.chainId === 'bigint') && {\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: domain as never,\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 } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from '../../types/typedData.js'\nimport type { UnionOmit } from '../../types/utils.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 getTypesForEIP712Domain,\n type ValidateTypedDataErrorType,\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 const typedData extends TypedData | Record = TypedData,\n>({\n domain,\n types,\n}: UnionOmit, 'primaryType'>) {\n return hashStruct({\n data: domain as Record,\n primaryType: 'EIP712Domain',\n types: types as Record,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>({\n data,\n primaryType,\n types,\n}: MessageDefinition) {\n const encoded = encodeData({\n data: data as Record,\n primaryType,\n types: types as Record,\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') return [{ type: 'bytes32' }, keccak256(value)]\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 { 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","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\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\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: Hash,\n PRFSalt: Hash,\n DK: Uint8Array,\n prfW: Hash,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/**\n * Audited & minimal JS implementation of\n * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).\n * @module\n * @example\n```js\nimport * as bip39 from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nconst mn = bip39.generateMnemonic(wordlist);\nconsole.log(mn);\nconst ent = bip39.mnemonicToEntropy(mn, wordlist)\nbip39.entropyToMnemonic(ent, wordlist);\nbip39.validateMnemonic(mn, wordlist);\nawait bip39.mnemonicToSeed(mn, 'password');\nbip39.mnemonicToSeedSync(mn, 'password');\n\n// Wordlists\nimport { wordlist as czech } from '@scure/bip39/wordlists/czech';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { wordlist as french } from '@scure/bip39/wordlists/french';\nimport { wordlist as italian } from '@scure/bip39/wordlists/italian';\nimport { wordlist as japanese } from '@scure/bip39/wordlists/japanese';\nimport { wordlist as korean } from '@scure/bip39/wordlists/korean';\nimport { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';\nimport { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';\nimport { wordlist as spanish } from '@scure/bip39/wordlists/spanish';\nimport { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';\n```\n */\n/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n abytes(ent, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\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 type { ErrorType } from '../errors/utils.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.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 signAuthorization: source.signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\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 { type IsHexErrorType, isHex } from '../../utils/data/isHex.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 { 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 =\n | HexToBytesErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | 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 {\n lowS: true,\n extraEntropy: isHex(extraEntropy, { strict: false })\n ? hexToBytes(extraEntropy)\n : extraEntropy,\n },\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 type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../utils/authorization/hashAuthorization.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 AuthorizationRequest & {\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 signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const { chainId, nonce, privateKey, to = 'object' } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n address,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\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 { 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(await serializer(signableTransaction)),\n privateKey,\n })\n return (await serializer(\n transaction,\n signature,\n )) as SignTransactionReturnType\n}\n","import type { TypedData } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\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'\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 [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):\n * `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(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'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.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 { 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 signAuthorization(authorization) {\n return 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","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport { HDKey } from '@scure/bip32'\nexport type { Address } from 'abitype'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from '../utils/nonceManager.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from '../utils/signature/serializeSignature.js'\nexport {\n type GenerateMnemonicErrorType,\n generateMnemonic,\n} from './generateMnemonic.js'\nexport {\n type GeneratePrivateKeyErrorType,\n generatePrivateKey,\n} from './generatePrivateKey.js'\nexport {\n type HDKeyToAccountErrorType,\n type HDKeyToAccountOptions,\n hdKeyToAccount,\n} from './hdKeyToAccount.js'\nexport {\n type MnemonicToAccountErrorType,\n type MnemonicToAccountOptions,\n mnemonicToAccount,\n} from './mnemonicToAccount.js'\nexport {\n type PrivateKeyToAccountErrorType,\n type PrivateKeyToAccountOptions,\n privateKeyToAccount,\n} from './privateKeyToAccount.js'\nexport { type ToAccountErrorType, toAccount } from './toAccount.js'\nexport type {\n Account,\n AccountSource,\n CustomSource,\n HDAccount,\n HDOptions,\n JsonRpcAccount,\n LocalAccount,\n PrivateKeyAccount,\n} from './types.js'\nexport {\n type ParseAccountErrorType,\n parseAccount,\n} from './utils/parseAccount.js'\nexport {\n type PrivateKeyToAddressErrorType,\n privateKeyToAddress,\n} from './utils/privateKeyToAddress.js'\nexport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nexport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n setSignEntropy,\n sign,\n} from './utils/sign.js'\nexport {\n type SignAuthorizationErrorType,\n type SignAuthorizationParameters,\n type SignAuthorizationReturnType,\n signAuthorization,\n} from './utils/signAuthorization.js'\nexport {\n type SignMessageErrorType,\n type SignMessageParameters,\n type SignMessageReturnType,\n signMessage,\n} from './utils/signMessage.js'\nexport {\n type SignTransactionErrorType,\n type SignTransactionParameters,\n type SignTransactionReturnType,\n signTransaction,\n} from './utils/signTransaction.js'\nexport {\n type SignTypedDataErrorType,\n type SignTypedDataParameters,\n type SignTypedDataReturnType,\n signTypedData,\n} from './utils/signTypedData.js'\nexport {\n czech,\n english,\n french,\n italian,\n japanese,\n korean,\n portuguese,\n simplifiedChinese,\n spanish,\n traditionalChinese,\n} from './wordlists.js'\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(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// 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 return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\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(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\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): boolean {\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): void {\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 * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\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): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\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, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\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 = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, 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++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\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\nexport function validateObject(\n object: Record,\n fields: Record = {},\n optFields: Record = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\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(\n fn: (arg: T, ...args: O) => R\n): (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\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _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 */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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\nfunction assertIsSquare(Fp: IField, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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 assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): (Fp: IField, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return (Fp: IField, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // 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): boolean =>\n (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 isLE: boolean;\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 isValidNot0: (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 invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): 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): IField {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security 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're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 * 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.Point.Fn.ORDER)\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 abytes(key);\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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons

> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns Fp type from Point (P_F

== P.F) */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns Fp type from PointCons (PC_F == PC.P.F) */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P == PC.P) */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper = (i: T[]) => T[];\n\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport function normalizeZ

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\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\n/** Internal wNAF opts for specific W and scalarBits */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = 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 point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\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 * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\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 const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\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 acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, 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 createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 than 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 secret keys / bigints)\n */\nexport function pippenger

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\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 const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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 P;\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

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\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 const fieldN = c.Fn;\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 = bitMask(windowSize);\n const tables = points.map((p: P) => {\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[]): P => {\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\nexport type ValidCurveParams = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: IField, isLE?: boolean): IField {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField;\n }\n}\nexport type FpFn = { Fp: IField; Fn: IField };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: Partial> = {},\n FpFnLE?: boolean\n): FpFn & { CURVE: ValidCurveParams } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abool,\n abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n memoized,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * https://paulmillr.com/posts/deterministic-signatures/\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates sigs with increased security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): Required {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n CURVE(): WeierstrassOpts;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\nexport type WeierstrassExtraOpts = Partial<{\n Fp: IField;\n Fn: IField;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n fromBytes: (bytes: Uint8Array) => AffinePoint;\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: (key: Uint8Array, message: Uint8Array) => Uint8Array;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed?: boolean\n ) => Uint8Array;\n Point: WeierstrassPointCons;\n utils: {\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Uint8Array, secretKey: Uint8Array, opts?: ECDSASignOpts) => Uint8Array;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(data);\n },\n },\n toSig(bytes: Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\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\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\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 { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: 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 x = Fp.mul(X, iz);\n const y = 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, y };\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 (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) 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 if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) 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 function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\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 WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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 // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\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 *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\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) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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(): boolean {\n return this.equals(Point.ZERO);\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 } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n hasHighS(): boolean;\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n}\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASignatureFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\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, 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, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, 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, 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, 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: IField, Fn: IField) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: Uint8Array) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey: Uint8Array, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(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: Uint8Array): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item)) return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey) return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed = true\n ): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor(): void {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: Uint8Array,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\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 toBytes(format: ECDSASignatureFormat = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\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 ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\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 *\n * Warning: we cannot assume here that message 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 */\n function prepSig(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\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 function k2sig(kBytes: Uint8Array): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\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 = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts = {}): Uint8Array {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n }) satisfies Signer;\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\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 = secp256k1_CURVE.p;\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(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\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\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(asciiToBytes(tag));\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.toBytes(true).slice(1);\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: Uint8Array) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { 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 const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\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 Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Uint8Array): Uint8Array {\n return schnorrGetExtPubKey(secretKey).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: Uint8Array,\n secretKey: Uint8Array,\n auxRand: Uint8Array = randomBytes(32)\n): Uint8Array {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(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 // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\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(Fn.toBytes(Fn.create(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: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\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 (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!Fn.isValidNot0(s)) return false;\n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\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 }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\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 ))();\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\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/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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 * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(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/**\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.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\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\ntype EmptyObj = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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\n/** Hash constructor */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash = Hash, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: HashInfo = {}\n): CHash {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC> implements Hash<_HMAC> {\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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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 clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\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(): Uint8Array {\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 clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\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: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC(hash, key);\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> implements 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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\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 clean(this.buffer.subarray(pos));\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl } from './utils.ts';\n\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\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 }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1: CHash = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\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 this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5: CHash = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B> extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * const hdkey1 = HDKey.fromMasterSeed(seed);\n * const hdkey2 = HDKey.fromExtendedKey(base58key);\n * const hdkey3 = HDKey.fromJSON({ xpriv: string });\n *\n * // props\n * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];\n * console.log(hdkey2.privateKey, hdkey2.publicKey);\n * console.log(hdkey3.derive(\"m/0/2147483647'/1\"));\n * const sig = hdkey3.sign(hash);\n * hdkey3.verify(hash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.Point;\nconst { Fn } = Point;\nconst base58check = createBase58check(sha256);\n\nconst MASTER_SECRET = Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n\n/** Network-specific versioning. */\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened offset from Bitcoin, default */\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number): Uint8Array => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array;\n}\n\n/**\n * HDKey from BIP32\n * @example\n```js\nconst hdkey1 = HDKey.fromMasterSeed(seed);\nconst hdkey2 = HDKey.fromExtendedKey(base58key);\nconst hdkey3 = HDKey.fromJSON({ xpriv: string });\n```\n */\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this._privateKey || null;\n }\n get publicKey(): Uint8Array | null {\n return this._publicKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n\n static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n\n static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n readonly versions: Versions;\n readonly depth: number = 0;\n readonly index: number = 0;\n readonly chainCode: Uint8Array | null = null;\n readonly parentFingerprint: number = 0;\n private _privateKey?: Uint8Array;\n private _publicKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key');\n this._privateKey = opt.privateKey;\n this._publicKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n\n derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n deriveChild(index: number): HDKey {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = I.slice(0, 32);\n const chainCode = I.slice(32);\n if (!secp.utils.isValidSecretKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n const ctweak = Fn.fromBytes(childTweak);\n try {\n // Private parent key -> private child key\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n } else {\n const added = Point.fromBytes(this._publicKey).add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n sign(hash: Uint8Array): Uint8Array {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n\n verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n\n wipePrivateData(): this {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA384 as SHA384n,\n sha384 as sha384n,\n sha512_224 as sha512_224n,\n SHA512_224 as SHA512_224n,\n sha512_256 as sha512_256n,\n SHA512_256 as SHA512_256n,\n SHA512 as SHA512n,\n sha512 as sha512n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512: typeof SHA512n = SHA512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512: typeof sha512n = sha512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA384: typeof SHA384n = SHA384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha384: typeof sha384n = sha384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_224: typeof SHA512_224n = SHA512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_224: typeof sha512_224n = sha512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_256: typeof SHA512_256n = SHA512_256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_256: typeof sha512_256n = sha512_256n;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @module\n * @privateRemarks\n * WARNING:\n * - Don't remove error codes\n * - Don't change or reorder error codes.\n *\n * Good naming conventions:\n * - Prefixing common errors — e.g. under the same package — can be a good way to namespace them. E.g. All codec-related errors start with `SOLANA_ERROR__CODECS__`.\n * - Use consistent names — e.g. choose `PDA` or `PROGRAM_DERIVED_ADDRESS` and stick with it. Ensure your names are consistent with existing error codes. The decision might have been made for you.\n * - Recommended prefixes and suffixes:\n * - `MALFORMED_`: Some input was not constructed properly. E.g. `MALFORMED_BASE58_ENCODED_ADDRESS`.\n * - `INVALID_`: Some input is invalid (other than because it was MALFORMED). E.g. `INVALID_NUMBER_OF_BYTES`.\n * - `EXPECTED_`: Some input was different than expected, no need to specify the \"GOT\" part unless necessary. E.g. `EXPECTED_DECODED_ACCOUNT`.\n * - `_CANNOT_`: Some operation cannot be performed or some input cannot be used due to some condition. E.g. `CANNOT_DECODE_EMPTY_BYTE_ARRAY` or `PDA_CANNOT_END_WITH_PDA_MARKER`.\n * - `_MUST_BE_`: Some condition must be true. E.g. `NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE`.\n * - `_FAILED_TO_`: Tried to perform some operation and failed. E.g. `FAILED_TO_DECODE_ACCOUNT`.\n * - `_NOT_FOUND`: Some operation lead to not finding something. E.g. `ACCOUNT_NOT_FOUND`.\n * - `_OUT_OF_RANGE`: Some value is out of range. E.g. `ENUM_DISCRIMINATOR_OUT_OF_RANGE`.\n * - `_EXCEEDED`: Some limit was exceeded. E.g. `PDA_MAX_SEED_LENGTH_EXCEEDED`.\n * - `_MISMATCH`: Some elements do not match. E.g. `ENCODER_DECODER_FIXED_SIZE_MISMATCH`.\n * - `_MISSING`: Some required input is missing. E.g. `TRANSACTION_FEE_PAYER_MISSING`.\n * - `_UNIMPLEMENTED`: Some required component is not available in the environment. E.g. `SUBTLE_CRYPTO_VERIFY_FUNCTION_UNIMPLEMENTED`.\n */\nexport const SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;\nexport const SOLANA_ERROR__INVALID_NONCE = 2;\nexport const SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;\nexport const SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;\nexport const SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;\nexport const SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;\nexport const SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;\nexport const SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;\nexport const SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;\nexport const SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;\n\n// JSON-RPC-related errors.\n// Reserve error codes in the range [-32768, -32000]\n// Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs\nexport const SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;\nexport const SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;\nexport const SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;\nexport const SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;\nexport const SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;\nexport const SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;\n\n// Addresses-related errors.\n// Reserve error codes in the range [2800000-2800999].\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 2800000;\nexport const SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;\nexport const SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;\nexport const SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;\nexport const SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;\nexport const SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;\nexport const SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;\nexport const SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;\nexport const SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;\n\n// Account-related errors.\n// Reserve error codes in the range [3230000-3230999].\nexport const SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 3230000;\nexport const SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;\nexport const SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;\nexport const SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;\n\n// Subtle-Crypto-related errors.\n// Reserve error codes in the range [3610000-3610999].\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 3610000;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;\nexport const SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;\n\n// Crypto-related errors.\n// Reserve error codes in the range [3611000-3611050].\nexport const SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611000;\n\n// Key-related errors.\n// Reserve error codes in the range [3704000-3704999].\nexport const SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704000;\nexport const SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;\nexport const SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;\nexport const SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;\nexport const SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;\n\n// Instruction-related errors.\n// Reserve error codes in the range [4128000-4128999].\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128000;\nexport const SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;\nexport const SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;\n\n// Instruction errors.\n// Reserve error codes starting with [4615000-4615999] for the Rust enum `InstructionError`.\n// Error names here are dictated by the RPC (see ./instruction-error.ts).\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615000;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;\nexport const SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;\n\n// Signer-related errors.\n// Reserve error codes in the range [5508000-5508999].\nexport const SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508000;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;\nexport const SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;\nexport const SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;\nexport const SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;\n\n// Offchain-message-related errors.\n// Reserve error codes in the range [5607000-5607999].\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED = 5607000;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE = 5607001;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE = 5607002;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH = 5607003;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH = 5607004;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO = 5607005;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED = 5607006;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH = 5607007;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH = 5607008;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY = 5607009;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO = 5607010;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING = 5607011;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH = 5607012;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE = 5607013;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION = 5607014;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED = 5607015;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE = 5607016;\nexport const SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE = 5607017;\n\n// Transaction-related errors.\n// Reserve error codes in the range [5663000-5663999].\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663000;\nexport const SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;\nexport const SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;\nexport const SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;\nexport const SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;\nexport const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;\nexport const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;\nexport const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;\nexport const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;\nexport const SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;\nexport const SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;\nexport const SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;\nexport const SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;\n\n// Transaction errors.\n// Reserve error codes starting with [7050000-7050999] for the Rust enum `TransactionError`.\n// Error names here are dictated by the RPC (see ./transaction-error.ts).\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 7050000;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;\n// `InstructionError` intentionally omitted.\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;\nexport const SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;\n\n// Instruction plan related errors.\n// Reserve error codes in the range [7618000-7618999].\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618000;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED = 7618004;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND = 7618005;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN = 7618006;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN = 7618007;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT = 7618008;\nexport const SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT = 7618009;\n\n// Codec-related errors.\n// Reserve error codes in the range [8078000-8078999].\nexport const SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078000;\nexport const SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;\nexport const SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;\nexport const SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;\nexport const SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;\nexport const SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;\nexport const SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;\nexport const SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;\nexport const SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;\nexport const SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;\nexport const SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;\nexport const SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;\nexport const SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;\nexport const SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;\nexport const SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;\nexport const SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;\nexport const SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;\nexport const SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;\nexport const SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;\nexport const SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;\nexport const SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;\nexport const SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;\n\n// RPC-related errors.\n// Reserve error codes in the range [8100000-8100999].\nexport const SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 8100000;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;\nexport const SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;\nexport const SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;\n\n// RPC-Subscriptions-related errors.\n// Reserve error codes in the range [8190000-8190999].\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 8190000;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;\nexport const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;\n\n// Invariant violation errors.\n// Reserve error codes in the range [9900000-9900999].\n// These errors should only be thrown when there is a bug with the\n// library itself and should, in theory, never reach the end user.\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 9900000;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;\nexport const SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;\n\n/**\n * A union of every Solana error code\n *\n * @privateRemarks\n * You might be wondering why this is not a TypeScript enum or const enum.\n *\n * One of the goals of this library is to enable people to use some or none of it without having to\n * bundle all of it.\n *\n * If we made the set of error codes an enum then anyone who imported it (even if to only use a\n * single error code) would be forced to bundle every code and its label.\n *\n * Const enums appear to solve this problem by letting the compiler inline only the codes that are\n * actually used. Unfortunately exporting ambient (const) enums from a library like `@solana/errors`\n * is not safe, for a variety of reasons covered here: https://stackoverflow.com/a/28818850\n */\nexport type SolanaErrorCode =\n | typeof SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED\n | typeof SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT\n | typeof SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND\n | typeof SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS\n | typeof SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE\n | typeof SOLANA_ERROR__ADDRESSES__MALFORMED_PDA\n | typeof SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE\n | typeof SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER\n | typeof SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED\n | typeof SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS\n | typeof SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH\n | typeof SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY\n | typeof SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH\n | typeof SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE\n | typeof SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH\n | typeof SOLANA_ERROR__CODECS__INVALID_CONSTANT\n | typeof SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT\n | typeof SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS\n | typeof SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE\n | typeof SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES\n | typeof SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE\n | typeof SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS\n | typeof SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA\n | typeof SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN\n | typeof SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT\n | typeof SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH\n | typeof SOLANA_ERROR__INVALID_NONCE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING\n | typeof SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE\n | typeof SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_PARAMS\n | typeof SOLANA_ERROR__JSON_RPC__INVALID_REQUEST\n | typeof SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND\n | typeof SOLANA_ERROR__JSON_RPC__PARSE_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SCAN_ERROR\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION\n | typeof SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH\n | typeof SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY\n | typeof SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE\n | typeof SOLANA_ERROR__MALFORMED_BIGINT_STRING\n | typeof SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR\n | typeof SOLANA_ERROR__MALFORMED_NUMBER_STRING\n | typeof SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION\n | typeof SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD\n | typeof SOLANA_ERROR__RPC__INTEGER_OVERFLOW\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR\n | typeof SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID\n | typeof SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER\n | typeof SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS\n | typeof SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING\n | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED\n | typeof SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES\n | typeof SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE\n | typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES\n | typeof SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE\n | typeof SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH\n | typeof SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE\n | typeof SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED\n | typeof SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT\n | typeof SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT;\n\n/**\n * Errors of this type are understood to have an optional {@link SolanaError} nested inside as\n * `cause`.\n */\nexport type SolanaErrorCodeWithCause = typeof SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE;\n\n/**\n * Errors of this type have a deprecated `cause` property. Consumers should use the error's\n * `context` instead to access relevant error information.\n */\nexport type SolanaErrorCodeWithDeprecatedCause =\n typeof SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN;\n","/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors/#adding-a-new-error\n *\n * @privateRemarks\n * WARNING:\n * - Don't change or remove members of an error's context.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SolanaErrorCode,\n} from './codes';\nimport { RpcSimulateTransactionResult } from './json-rpc-error';\n\ntype BasicInstructionErrorContext = { [P in T]: { index: number } };\n\ntype DefaultUnspecifiedErrorContextToUndefined = {\n [P in SolanaErrorCode]: P extends keyof T ? T[P] : undefined;\n};\n\ntype ReadonlyContextValue = {\n [P in keyof T]: Readonly;\n};\n\ntype TypedArrayMutableProperties = 'copyWithin' | 'fill' | 'reverse' | 'set' | 'sort';\ninterface ReadonlyUint8Array extends Omit {\n readonly [n: number]: number;\n}\n\n/** A amount of bytes. */\ntype Bytes = number;\n\n/**\n * A map of every {@link SolanaError} code to the type of its `context` property.\n */\nexport type SolanaErrorContext = ReadonlyContextValue<\n DefaultUnspecifiedErrorContextToUndefined<\n BasicInstructionErrorContext<\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID\n | typeof SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR\n > & {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: {\n address: string;\n };\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: {\n putativeAddress: string;\n };\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: {\n actual: number;\n maxSeeds: number;\n };\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: {\n actual: number;\n index: number;\n maxSeedLength: number;\n };\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: {\n bump: number;\n };\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: {\n currentBlockHeight: bigint;\n lastValidBlockHeight: bigint;\n };\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: {\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: {\n stringValues: readonly string[];\n };\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: {\n encodedBytes: ReadonlyUint8Array;\n hexEncodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: {\n decoderFixedSize: number;\n encoderFixedSize: number;\n };\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: {\n decoderMaxSize: number | undefined;\n encoderMaxSize: number | undefined;\n };\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n formattedValidDiscriminators: string;\n validDiscriminators: readonly number[];\n };\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: {\n expectedLength: number;\n numExcessBytes: number;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n };\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: {\n codecDescription: string;\n expectedSize: number;\n hexZeroValue: string;\n zeroValue: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: {\n bytesLength: number;\n codecDescription: string;\n expected: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: {\n constant: ReadonlyUint8Array;\n data: ReadonlyUint8Array;\n hexConstant: string;\n hexData: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: {\n formattedNumericalValues: string;\n numericalValues: readonly number[];\n stringValues: readonly string[];\n variant: number | string | symbol;\n };\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: {\n value: bigint | boolean | number | string | null | undefined;\n variants: readonly (bigint | boolean | number | string | null | undefined)[];\n };\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: {\n actual: bigint | number;\n codecDescription: string;\n expected: bigint | number;\n };\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: {\n alphabet: string;\n base: number;\n value: string;\n };\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: {\n discriminator: bigint | number;\n maxRange: number;\n minRange: number;\n };\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: {\n codecDescription: string;\n max: bigint | number;\n min: bigint | number;\n value: bigint | number;\n };\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: {\n bytesLength: number;\n codecDescription: string;\n offset: number;\n };\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: {\n decodedBytes: ReadonlyUint8Array;\n hexDecodedBytes: string;\n hexSentinel: string;\n sentinel: ReadonlyUint8Array;\n };\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: {\n maxRange: number;\n minRange: number;\n variant: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: {\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: {\n code: number;\n index: number;\n };\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: {\n errorName: string;\n index: number;\n instructionErrorContext?: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: {\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: {\n numBytesRequired: number;\n numFreeBytes: number;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n instructionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]: {\n actualKind: string;\n expectedKind: string;\n transactionPlan: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]: {\n actualKind: string;\n expectedKind: string;\n transactionPlanResult: unknown;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: {\n data?: ReadonlyUint8Array;\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: {\n accountAddresses?: readonly string[];\n programAddress: string;\n };\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: {\n actualProgramAddress: string;\n expectedProgramAddress: string;\n };\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__INVALID_NONCE]: {\n actualNonceValue: string;\n expectedNonceValue: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: {\n cacheKey: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: {\n channelName: string;\n supportedChannelNames: readonly string[];\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: {\n kind: string;\n };\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: {\n unexpectedValue: unknown;\n };\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: {\n currentBlockHeight: bigint;\n rewardsCompleteBlockHeight: bigint;\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: {\n contextSlot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: {\n numSlotsBehind?: number;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: Omit<\n RpcSimulateTransactionResult,\n 'err'\n >;\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: {\n slot: bigint;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: {\n __serverMessage: string;\n };\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: {\n byteLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: {\n error: unknown;\n message: string;\n };\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: {\n value: string;\n };\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: {\n nonceAccountAddress: string;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]: {\n missingRequiredSigners: readonly string[];\n unexpectedSigners: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]: {\n actualLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]: {\n actualBytes: number;\n maxBytes: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]: {\n actualMessageFormat: number;\n expectedMessageFormat: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]: {\n actualLength: number;\n specifiedLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signatoryAddresses: readonly string[];\n signaturesLength: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]: {\n signatoriesWithInvalidSignatures: readonly string[];\n signatoriesWithMissingSignatures: readonly string[];\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]: {\n actualVersion: number;\n expectedVersion: number;\n };\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: {\n notificationName: string;\n };\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: {\n errorEvent: Event;\n };\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: {\n method: string;\n params: readonly unknown[];\n };\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: {\n argumentLabel: string;\n keyPath: readonly (number | string | symbol)[];\n methodName: string;\n optionalPathLabel: string;\n path?: string;\n value: bigint;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: {\n headers: Headers;\n message: string;\n statusCode: number;\n };\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: {\n headers: readonly string[];\n };\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: {\n address: string;\n };\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: {\n key: CryptoKey;\n };\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: {\n value: bigint;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: {\n accountIndex: number;\n };\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: {\n errorName: string;\n transactionErrorContext?: unknown;\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: {\n expectedAddresses: readonly string[];\n unexpectedAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: {\n transactionSize: Bytes;\n transactionSizeLimit: Bytes;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: {\n lookupTableAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: {\n highestKnownIndex: number;\n highestRequestedIndex: number;\n lookupTableAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: {\n index: number;\n };\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: {\n unitsConsumed: number;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: {\n programAddress: string;\n };\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: {\n numRequiredSignatures: number;\n signaturesLength: number;\n signerAddresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: {\n nonce: string;\n };\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: {\n addresses: readonly string[];\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: {\n unsupportedVersion: number;\n };\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: {\n actualVersion: number;\n };\n }\n >\n>;\n\nexport function decodeEncodedContext(encodedContext: string): object {\n const decodedUrlString = __NODEJS__ ? Buffer.from(encodedContext, 'base64').toString('utf8') : atob(encodedContext);\n return Object.fromEntries(new URLSearchParams(decodedUrlString).entries());\n}\n\nfunction encodeValue(value: unknown): string {\n if (Array.isArray(value)) {\n const commaSeparatedValues = value.map(encodeValue).join('%2C%20' /* \", \" */);\n return '%5B' /* \"[\" */ + commaSeparatedValues + /* \"]\" */ '%5D';\n } else if (typeof value === 'bigint') {\n return `${value}n`;\n } else {\n return encodeURIComponent(\n String(\n value != null && Object.getPrototypeOf(value) === null\n ? // Plain objects with no prototype don't have a `toString` method.\n // Convert them before stringifying them.\n { ...(value as object) }\n : value,\n ),\n );\n }\n}\n\nfunction encodeObjectContextEntry([key, value]: [string, unknown]): `${typeof key}=${string}` {\n return `${key}=${encodeValue(value)}`;\n}\n\nexport function encodeContextObject(context: object): string {\n const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join('&');\n return __NODEJS__ ? Buffer.from(searchParamsString, 'utf8').toString('base64') : btoa(searchParamsString);\n}\n","/* eslint-disable sort-keys-fix/sort-keys-fix */\n/**\n * To add a new error, follow the instructions at\n * https://github.com/anza-xyz/kit/tree/main/packages/errors#adding-a-new-error\n *\n * WARNING:\n * - Don't change the meaning of an error message.\n */\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,\n SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__INVALID_CONSTANT,\n SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,\n SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,\n SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,\n SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,\n SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,\n SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,\n SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,\n SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,\n SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,\n SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,\n SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,\n SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,\n SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,\n SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,\n SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SOLANA_ERROR__INVALID_NONCE,\n SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,\n SOLANA_ERROR__MALFORMED_BIGINT_STRING,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SOLANA_ERROR__MALFORMED_NUMBER_STRING,\n SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,\n SOLANA_ERROR__RPC__INTEGER_OVERFLOW,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,\n SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,\n SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,\n SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,\n SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,\n SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,\n SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,\n SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,\n SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,\n SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,\n SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,\n SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,\n SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,\n SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,\n SolanaErrorCode,\n} from './codes';\n\n/**\n * A map of every {@link SolanaError} code to the error message shown to developers in development\n * mode.\n */\nexport const SolanaErrorMessages: Readonly<{\n // This type makes this data structure exhaustive with respect to `SolanaErrorCode`.\n // TypeScript will fail to build this project if add an error code without a message.\n [P in SolanaErrorCode]: string;\n}> = {\n [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: 'Account not found at address: $address',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]:\n 'Not all accounts were decoded. Encoded accounts found at addresses: $addresses.',\n [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: 'Expected decoded account at address: $address',\n [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: 'Failed to decode account data at address: $address',\n [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: 'Accounts not found at addresses: $addresses',\n [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]:\n 'Unable to find a viable program address bump seed.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: '$putativeAddress is not a base58-encoded address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]:\n 'Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: 'The `CryptoKey` must be an `Ed25519` public key.',\n [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]:\n '$putativeOffCurveAddress is not a base58-encoded off-curve address.',\n [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: 'Invalid seeds; point must fall off the Ed25519 curve.',\n [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]:\n 'Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].',\n [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]:\n 'A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.',\n [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]:\n 'The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.',\n [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]:\n 'Expected program derived address bump to be in the range [0, 255], got: $bump.',\n [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: 'Program address cannot end with PDA marker.',\n [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]:\n 'The network has progressed past the last block for which this transaction could have been committed.',\n [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]:\n 'Codec [$codecDescription] cannot decode empty byte arrays.',\n [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]:\n 'Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.',\n [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]:\n 'Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]:\n 'Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].',\n [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]:\n 'Encoder and decoder must either both be fixed-size or variable-size.',\n [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.',\n [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: 'Expected a fixed-size codec, got a variable-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected a positive byte length, got $bytesLength.',\n [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: 'Expected a variable-size codec, got a fixed-size one.',\n [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]:\n 'Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].',\n [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]:\n 'Codec [$codecDescription] expected $expected bytes, got $bytesLength.',\n [SOLANA_ERROR__CODECS__INVALID_CONSTANT]:\n 'Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].',\n [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]:\n 'Invalid discriminated union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]:\n 'Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.',\n [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]:\n 'Invalid literal union variant. Expected one of [$variants], got $value.',\n [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]:\n 'Expected [$codecDescription] to have $expected items, got $actual.',\n [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: 'Invalid value $value for base $base with alphabet $alphabet.',\n [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]:\n 'Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.',\n [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.',\n [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]:\n 'Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.',\n [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]:\n 'Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].',\n [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]:\n 'Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.',\n [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]:\n 'This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?',\n [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: 'No random values implementation could be found.',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: 'instruction requires an uninitialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]:\n 'instruction tries to borrow reference for an account which is already borrowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'instruction left account with an outstanding borrowed reference',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]:\n \"program other than the account's owner changed the size of the account data\",\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: 'account data too small for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: 'instruction expected an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]:\n 'An account does not have enough lamports to be rent-exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: 'Program arithmetic overflowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: 'Failed to serialize or deserialize account data: $encodedData',\n [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]:\n 'Builtin programs must consume compute units',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: 'Cross-program invocation call depth too deep',\n [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: 'Computational budget exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: 'custom program error: #$code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: 'instruction contains duplicate accounts',\n [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]:\n 'instruction modifications of multiply-passed account differ',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: 'executable accounts must be rent exempt',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: 'instruction changed executable accounts data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]:\n 'instruction changed the balance of an executable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: 'instruction changed executable bit of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]:\n 'instruction modified data of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]:\n 'instruction spent from the balance of an account it does not own',\n [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: 'generic instruction error',\n [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: 'Provided owner is not allowed',\n [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: 'Account is immutable',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: 'Incorrect authority provided',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: 'incorrect program id for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: 'insufficient funds for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: 'invalid account data for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: 'Invalid account owner',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: 'invalid program argument',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: 'program returned invalid error code',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: 'invalid instruction data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: 'Failed to reallocate account data',\n [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: 'Provided seeds do not result in a valid address',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]:\n 'Accounts data allocations exceeded the maximum allowed per transaction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: 'Max accounts exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: 'Max instruction trace length exceeded',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]:\n 'Length of the seed is too long for address generation',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: 'An account required by the instruction is missing',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: 'missing required signature for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]:\n 'instruction illegally modified the program id of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: 'insufficient account keys for instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]:\n 'Cross-program invocation with unauthorized signer or writable account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]:\n 'Failed to create program execution environment',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: 'Program failed to compile',\n [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: 'Program failed to complete',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: 'instruction modified data of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]:\n 'instruction changed the balance of a read-only account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]:\n 'Cross-program invocation reentrancy not allowed for this instruction',\n [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: 'instruction modified rent epoch of an account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]:\n 'sum of account balances before and after instruction do not match',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: 'instruction requires an initialized account',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: '',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: 'Unsupported program id',\n [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: 'Unsupported sysvar',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: 'Invalid instruction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: 'The provided instruction plan is empty.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]:\n 'No failed transaction plan result was found in the provided transaction plan result.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]:\n 'This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved — e.g. by targetting RPCs that support transaction bundles.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]:\n 'The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]:\n 'The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).',\n [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: 'Invalid transaction plan kind: $kind.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]:\n 'No more instructions to pack; the message packer has completed the instruction plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]:\n 'Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]:\n 'Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]:\n 'Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.',\n [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]:\n 'Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: 'The instruction does not have any accounts.',\n [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: 'The instruction does not have any data.',\n [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]:\n 'Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.',\n [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]:\n 'Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__INVALID_NONCE]:\n 'The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`',\n [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]:\n 'Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It ' +\n 'should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]:\n 'Invariant violation: This data publisher does not publish to the channel named ' +\n '`$channelName`. Supported channels include $supportedChannelNames.',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]:\n 'Invariant violation: WebSocket message iterator state is corrupt; iterated without first ' +\n 'resolving existing message promise. It should be impossible to hit this error; please ' +\n 'file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]:\n 'Invariant violation: WebSocket message iterator is missing state storage. It should be ' +\n 'impossible to hit this error; please file an issue at https://sola.na/web3invariant',\n [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]:\n 'Invariant violation: Switch statement non-exhaustive. Received unexpected value ' +\n '`$unexpectedValue`. It should be impossible to hit this error; please file an issue at ' +\n 'https://sola.na/web3invariant',\n [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: 'JSON-RPC error: Internal JSON-RPC error ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: 'JSON-RPC error: Invalid method parameter(s) ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]:\n 'JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]:\n 'JSON-RPC error: The method does not exist / is not available ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]:\n 'JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)',\n [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]:\n 'Epoch rewards period still active at slot $slot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]:\n 'Failed to query long-term storage; please try again',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: 'Minimum context slot has not been reached',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: 'Node is unhealthy; behind by $numSlotsBehind slots',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: 'No snapshot',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: 'Transaction simulation failed',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]:\n \"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage\",\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]:\n 'Transaction history is not available from this node',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: '$__serverMessage',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: 'Transaction signature length mismatch',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]:\n 'Transaction signature verification failure',\n [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: '$__serverMessage',\n [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: 'Key pair bytes must be of length 64, got $byteLength.',\n [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]:\n 'Expected private key bytes with length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]:\n 'Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.',\n [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]:\n 'The provided private key does not match the provided public key.',\n [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.',\n [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: 'Lamports value must be in the range [0, 2e64-1]',\n [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: '`$value` cannot be parsed as a `BigInt`',\n [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: '$message',\n [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: '`$value` cannot be parsed as a `Number`',\n [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: 'No nonce account could be found at address `$nonceAccountAddress`',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]:\n 'Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]:\n 'Attempted to sign an offchain message with an address that is not a signer for it',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]:\n 'Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]:\n 'The signer addresses in this offchain message envelope do not match the list of ' +\n 'required signers in the message preamble. These unexpected signers were present in the ' +\n 'envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope ' +\n '`[$missingSigners]`.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]:\n 'The message body provided has a byte-length of $actualBytes. The maximum allowable ' +\n 'byte-length is $maxBytes',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]:\n 'Expected message format $expectedMessageFormat, got $actualMessageFormat',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]:\n 'The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]: 'Offchain message content must be non-empty',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]:\n 'Offchain message must specify the address of at least one required signer',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]:\n 'Offchain message envelope must reserve space for at least one signature',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]:\n 'The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]:\n 'The signatories of this offchain message must be listed in lexicographical order',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]:\n 'An address must be listed no more than once among the signatories of an offchain message',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]:\n 'Offchain message is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]:\n 'Offchain message signature verification failed. Signature mismatch for required ' +\n 'signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories ' +\n '[$signatoriesWithMissingSignatures]',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]:\n 'The message body provided contains characters whose codes fall outside the allowed ' +\n 'range. In order to ensure clear-signing compatiblity with hardware wallets, the message ' +\n 'may only contain line feeds and characters in the range [\\\\x20-\\\\x7e].',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]:\n 'Expected offchain message version $expectedVersion. Got $actualVersion.',\n [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding offchain messages with version ' +\n '$unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]:\n \"The notification name must end in 'Notifications' and the API must supply a \" +\n \"subscription plan creator function for the notification '$notificationName'.\",\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]:\n 'WebSocket was closed before payload could be added to the send buffer',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: 'WebSocket connection closed',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: 'WebSocket failed to connect',\n [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]:\n 'Failed to obtain a subscription id from the server',\n [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: 'Could not find an API plan for RPC method: `$method`',\n [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]:\n 'The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was ' +\n '`$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds ' +\n '`Number.MAX_SAFE_INTEGER`.',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: 'HTTP error ($statusCode): $message',\n [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]:\n 'HTTP header(s) forbidden: $headers. Learn more at ' +\n 'https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.',\n [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]:\n 'Multiple distinct signers were identified for address `$address`. Please ensure that ' +\n 'you are using the same signer instance for each address.',\n [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]:\n 'The provided value does not implement the `KeyPairSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]:\n 'The provided value does not implement the `MessageModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]:\n 'The provided value does not implement the `MessagePartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]:\n 'The provided value does not implement any of the `MessageSigner` interfaces',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]:\n 'The provided value does not implement the `TransactionModifyingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]:\n 'The provided value does not implement the `TransactionPartialSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]:\n 'The provided value does not implement the `TransactionSendingSigner` interface',\n [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]:\n 'The provided value does not implement any of the `TransactionSigner` interfaces',\n [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]:\n 'More than one `TransactionSendingSigner` was identified.',\n [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]:\n 'No `TransactionSendingSigner` was identified. Please provide a valid ' +\n '`TransactionWithSingleSendingSigner` transaction.',\n [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]:\n 'Wallet account signers do not support signing multiple messages/transactions in a single operation',\n [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: 'Cannot export a non-extractable key.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: 'No digest implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]:\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]:\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall ' +\n '@solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]:\n 'No signature verification implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: 'No key generation implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: 'No signing implementation could be found.',\n [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: 'No key export implementation could be found.',\n [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]:\n 'Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]:\n 'Transaction processing left an account with an outstanding borrowed reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: 'Account in use',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: 'Account loaded twice',\n [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]:\n 'Attempt to debit an account but found no record of a prior credit.',\n [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]:\n \"Transaction loads an address table account that doesn't exist\",\n [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: 'This transaction has already been processed',\n [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: 'Blockhash not found',\n [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: 'Loader call chain is too deep',\n [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]:\n 'Transactions are currently disabled due to cluster maintenance',\n [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]:\n 'Transaction contains a duplicate instruction ($index) that is not allowed',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: 'Insufficient funds for fee',\n [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]:\n 'Transaction results in an account ($accountIndex) with insufficient funds for rent',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: 'This account may not be used to pay transaction fees',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: 'Transaction contains an invalid account reference',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]:\n 'Transaction loads an address table account with invalid data',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]:\n 'Transaction address table lookup uses an invalid index',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]:\n 'Transaction loads an address table account with an invalid owner',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]:\n 'LoadedAccountsDataSizeLimit set for transaction must be greater than 0.',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]:\n 'This program may not be used for executing instructions',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]:\n 'Transaction leaves an account with a lower balance than rent-exempt minimum',\n [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]:\n 'Transaction loads a writable account that cannot be written',\n [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]:\n 'Transaction exceeded max loaded accounts data size cap',\n [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]:\n 'Transaction requires a fee but has no signature present',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: 'Attempt to load a program that does not exist',\n [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]:\n 'Execution of the program referenced by account at index $accountIndex is temporarily restricted.',\n [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: 'ResanitizationNeeded',\n [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: 'Transaction failed to sanitize accounts offsets correctly',\n [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: 'Transaction did not pass signature verification',\n [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: 'Transaction locked too many accounts',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]:\n 'Sum of account balances before and after transaction do not match',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: 'The transaction failed with the error `$errorName`',\n [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: 'Transaction version is unsupported',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]:\n 'Transaction would exceed account data limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]:\n 'Transaction would exceed total account data limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]:\n 'Transaction would exceed max account limit within the block',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]:\n 'Transaction would exceed max Block Cost Limit',\n [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: 'Transaction would exceed max Vote Cost Limit',\n [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]:\n 'Attempted to sign a transaction with an address that is not a signer for it',\n [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: 'Transaction is missing an address at index: $index.',\n [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]:\n 'Transaction has no expected signers therefore it cannot be encoded',\n [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]:\n 'Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: 'Transaction does not have a blockhash lifetime',\n [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: 'Transaction is not a durable nonce transaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]:\n 'Contents of these address lookup tables unknown: $lookupTableAddresses',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]:\n 'Lookup of address at index $highestRequestedIndex failed for lookup table ' +\n '`$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table ' +\n 'may have been extended since its contents were retrieved',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: 'No fee payer set in CompiledTransaction',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]:\n 'Could not find program address at index $index',\n [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Failed to estimate the compute unit consumption for this transaction message. This is ' +\n 'likely because simulating the transaction failed. Inspect the `cause` property of this ' +\n 'error to learn more',\n [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]:\n 'Transaction failed when it was simulated in order to estimate the compute unit consumption. ' +\n 'The compute unit estimate provided is for a transaction that failed when simulated and may not ' +\n 'be representative of the compute units this transaction would consume if successful. Inspect the ' +\n '`cause` property of this error to learn more',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: 'Transaction is missing a fee payer.',\n [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]:\n \"Could not determine this transaction's signature. Make sure that the transaction has \" +\n 'been signed by its fee payer.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]:\n 'Transaction first instruction is not advance nonce account instruction.',\n [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]:\n 'Transaction with no instructions cannot be durable nonce transaction.',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]:\n 'This transaction includes an address (`$programAddress`) which is both ' +\n 'invoked and set as the fee payer. Program addresses may not pay fees',\n [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]:\n 'This transaction includes an address (`$programAddress`) which is both invoked and ' +\n 'marked writable. Program addresses may not be writable',\n [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]:\n 'The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.',\n [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: 'Transaction is missing signatures for addresses: $addresses.',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]:\n 'Transaction version must be in the range [0, 127]. `$actualVersion` given',\n [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]:\n 'This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.',\n [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]:\n 'The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction.',\n};\n","import { SolanaErrorCode } from './codes';\nimport { encodeContextObject } from './context';\nimport { SolanaErrorMessages } from './messages';\n\nconst enum StateType {\n EscapeSequence,\n Text,\n Variable,\n}\ntype State = Readonly<{\n [START_INDEX]: number;\n [TYPE]: StateType;\n}>;\nconst START_INDEX = 'i';\nconst TYPE = 't';\n\nexport function getHumanReadableErrorMessage(\n code: TErrorCode,\n context: object = {},\n): string {\n const messageFormatString = SolanaErrorMessages[code];\n if (messageFormatString.length === 0) {\n return '';\n }\n let state: State;\n function commitStateUpTo(endIndex?: number) {\n if (state[TYPE] === StateType.Variable) {\n const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);\n\n fragments.push(\n variableName in context\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${context[variableName as keyof typeof context]}`\n : `$${variableName}`,\n );\n } else if (state[TYPE] === StateType.Text) {\n fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));\n }\n }\n const fragments: string[] = [];\n messageFormatString.split('').forEach((char, ii) => {\n if (ii === 0) {\n state = {\n [START_INDEX]: 0,\n [TYPE]:\n messageFormatString[0] === '\\\\'\n ? StateType.EscapeSequence\n : messageFormatString[0] === '$'\n ? StateType.Variable\n : StateType.Text,\n };\n return;\n }\n let nextState;\n switch (state[TYPE]) {\n case StateType.EscapeSequence:\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n break;\n case StateType.Text:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n }\n break;\n case StateType.Variable:\n if (char === '\\\\') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.EscapeSequence };\n } else if (char === '$') {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Variable };\n } else if (!char.match(/\\w/)) {\n nextState = { [START_INDEX]: ii, [TYPE]: StateType.Text };\n }\n break;\n }\n if (nextState) {\n if (state !== nextState) {\n commitStateUpTo(ii);\n }\n state = nextState;\n }\n });\n commitStateUpTo();\n return fragments.join('');\n}\n\nexport function getErrorMessage(\n code: TErrorCode,\n context: Record = {},\n): string {\n if (process.env.NODE_ENV !== \"production\") {\n return getHumanReadableErrorMessage(code, context);\n } else {\n let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \\`npx @solana/errors decode -- ${code}`;\n if (Object.keys(context).length) {\n /**\n * DANGER: Be sure that the shell command is escaped in such a way that makes it\n * impossible for someone to craft malicious context values that would result in\n * an exploit against anyone who bindly copy/pastes it into their terminal.\n */\n decodingAdviceMessage += ` '${encodeContextObject(context)}'`;\n }\n return `${decodingAdviceMessage}\\``;\n }\n}\n","import { SolanaErrorCode, SolanaErrorCodeWithCause, SolanaErrorCodeWithDeprecatedCause } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { getErrorMessage } from './message-formatter';\n\n/**\n * A variant of {@link SolanaError} where the `cause` property is deprecated.\n *\n * This type is returned by {@link isSolanaError} when checking for error codes in\n * {@link SolanaErrorCodeWithDeprecatedCause}. Accessing `cause` on these errors will show\n * a deprecation warning in IDEs that support JSDoc `@deprecated` tags.\n */\nexport interface SolanaErrorWithDeprecatedCause<\n TErrorCode extends SolanaErrorCodeWithDeprecatedCause = SolanaErrorCodeWithDeprecatedCause,\n> extends Omit, 'cause'> {\n /**\n * @deprecated The `cause` property is deprecated for this error code.\n * Use the error's `context` property instead to access relevant error information.\n */\n readonly cause?: unknown;\n}\n\n/**\n * A type guard that returns `true` if the input is a {@link SolanaError}, optionally with a\n * particular error code.\n *\n * When the `code` argument is supplied and the input is a {@link SolanaError}, TypeScript will\n * refine the error's {@link SolanaError#context | `context`} property to the type associated with\n * that error code. You can use that context to render useful error messages, or to make\n * context-aware decisions that help your application to recover from the error.\n *\n * @example\n * ```ts\n * import {\n * SOLANA_ERROR__TRANSACTION__MISSING_SIGNATURE,\n * SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n * isSolanaError,\n * } from '@solana/errors';\n * import { assertIsFullySignedTransaction, getSignatureFromTransaction } from '@solana/transactions';\n *\n * try {\n * const transactionSignature = getSignatureFromTransaction(tx);\n * assertIsFullySignedTransaction(tx);\n * /* ... *\\/\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * displayError(\n * \"We can't send this transaction without signatures for these addresses:\\n- %s\",\n * // The type of the `context` object is now refined to contain `addresses`.\n * e.context.addresses.join('\\n- '),\n * );\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING)) {\n * if (!tx.feePayer) {\n * displayError('Choose a fee payer for this transaction before sending it');\n * } else {\n * displayError('The fee payer still needs to sign for this transaction');\n * }\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function isSolanaError(\n e: unknown,\n code: TErrorCode,\n): e is SolanaErrorWithDeprecatedCause;\nexport function isSolanaError(\n e: unknown,\n code?: TErrorCode,\n): e is SolanaError;\nexport function isSolanaError(\n e: unknown,\n /**\n * When supplied, this function will require that the input is a {@link SolanaError} _and_ that\n * its error code is exactly this value.\n */\n code?: TErrorCode,\n): e is SolanaError {\n const isSolanaError = e instanceof Error && e.name === 'SolanaError';\n if (isSolanaError) {\n if (code !== undefined) {\n return (e as SolanaError).context.__code === code;\n }\n return true;\n }\n return false;\n}\n\ntype SolanaErrorCodedContext = {\n [P in SolanaErrorCode]: Readonly<{\n __code: P;\n }> &\n (SolanaErrorContext[P] extends undefined ? object : SolanaErrorContext[P]);\n};\n\n/**\n * Encapsulates an error's stacktrace, a Solana-specific numeric code that indicates what went\n * wrong, and optional context if the type of error indicated by the code supports it.\n */\nexport class SolanaError extends Error {\n /**\n * Indicates the root cause of this {@link SolanaError}, if any.\n *\n * For example, a transaction error might have an instruction error as its root cause. In this\n * case, you will be able to access the instruction error on the transaction error as `cause`.\n */\n readonly cause?: TErrorCode extends SolanaErrorCodeWithCause ? SolanaError : unknown = this.cause;\n /**\n * Contains context that can assist in understanding or recovering from a {@link SolanaError}.\n */\n readonly context: SolanaErrorCodedContext[TErrorCode];\n constructor(\n ...[code, contextAndErrorOptions]: SolanaErrorContext[TErrorCode] extends undefined\n ? [code: TErrorCode, errorOptions?: ErrorOptions | undefined]\n : [code: TErrorCode, contextAndErrorOptions: SolanaErrorContext[TErrorCode] & (ErrorOptions | undefined)]\n ) {\n let context: SolanaErrorContext[TErrorCode] | undefined;\n let errorOptions: ErrorOptions | undefined;\n if (contextAndErrorOptions) {\n Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {\n // If the `ErrorOptions` type ever changes, update this code.\n if (name === 'cause') {\n errorOptions = { cause: descriptor.value };\n } else {\n if (context === undefined) {\n context = {\n __code: code,\n } as unknown as SolanaErrorContext[TErrorCode];\n }\n Object.defineProperty(context, name, descriptor);\n }\n });\n }\n const message = getErrorMessage(code, context);\n super(message, errorOptions);\n this.context = Object.freeze(\n context === undefined\n ? {\n __code: code,\n }\n : context,\n ) as SolanaErrorCodedContext[TErrorCode];\n // This is necessary so that `isSolanaError()` can identify a `SolanaError` without having\n // to import the class for use in an `instanceof` check.\n this.name = 'SolanaError';\n }\n}\n","export function safeCaptureStackTrace(...args: Parameters): void {\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(...args);\n }\n}\n","import { SolanaErrorCode } from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\n\ntype Config = Readonly<{\n /**\n * Oh, hello. You might wonder what in tarnation is going on here. Allow us to explain.\n *\n * One of the goals of `@solana/errors` is to allow errors that are not interesting to your\n * application to shake out of your app bundle in production. This means that we must never\n * export large hardcoded maps of error codes/messages.\n *\n * Unfortunately, where instruction and transaction errors from the RPC are concerned, we have\n * no choice but to keep a map between the RPC `rpcEnumError` enum name and its corresponding\n * `SolanaError` code. In the interest of implementing that map in as few bytes of source code\n * as possible, we do the following:\n *\n * 1. Reserve a block of sequential error codes for the enum in question\n * 2. Hardcode the list of enum names in that same order\n * 3. Match the enum error name from the RPC with its index in that list, and reconstruct the\n * `SolanaError` code by adding the `errorCodeBaseOffset` to that index\n */\n errorCodeBaseOffset: number;\n getErrorContext: (\n errorCode: SolanaErrorCode,\n rpcErrorName: string,\n rpcErrorContext?: unknown,\n ) => SolanaErrorContext[SolanaErrorCode];\n orderedErrorNames: string[];\n rpcEnumError: string | { [key: string]: unknown };\n}>;\n\nexport function getSolanaErrorFromRpcError(\n { errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }: Config,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructorOpt: Function,\n): SolanaError {\n let rpcErrorName;\n let rpcErrorContext;\n if (typeof rpcEnumError === 'string') {\n rpcErrorName = rpcEnumError;\n } else {\n rpcErrorName = Object.keys(rpcEnumError)[0];\n rpcErrorContext = rpcEnumError[rpcErrorName];\n }\n const codeOffset = orderedErrorNames.indexOf(rpcErrorName);\n const errorCode = (errorCodeBaseOffset + codeOffset) as SolanaErrorCode;\n const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);\n const err = new SolanaError(errorCode, errorContext);\n safeCaptureStackTrace(err, constructorOpt);\n return err;\n}\n","import { SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN } from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/solana-sdk/blob/master/instruction-error/src/lib.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'GenericError',\n 'InvalidArgument',\n 'InvalidInstructionData',\n 'InvalidAccountData',\n 'AccountDataTooSmall',\n 'InsufficientFunds',\n 'IncorrectProgramId',\n 'MissingRequiredSignature',\n 'AccountAlreadyInitialized',\n 'UninitializedAccount',\n 'UnbalancedInstruction',\n 'ModifiedProgramId',\n 'ExternalAccountLamportSpend',\n 'ExternalAccountDataModified',\n 'ReadonlyLamportChange',\n 'ReadonlyDataModified',\n 'DuplicateAccountIndex',\n 'ExecutableModified',\n 'RentEpochModified',\n 'NotEnoughAccountKeys',\n 'AccountDataSizeChanged',\n 'AccountNotExecutable',\n 'AccountBorrowFailed',\n 'AccountBorrowOutstanding',\n 'DuplicateAccountOutOfSync',\n 'Custom',\n 'InvalidError',\n 'ExecutableDataModified',\n 'ExecutableLamportChange',\n 'ExecutableAccountNotRentExempt',\n 'UnsupportedProgramId',\n 'CallDepth',\n 'MissingAccount',\n 'ReentrancyNotAllowed',\n 'MaxSeedLengthExceeded',\n 'InvalidSeeds',\n 'InvalidRealloc',\n 'ComputationalBudgetExceeded',\n 'PrivilegeEscalation',\n 'ProgramEnvironmentSetupFailure',\n 'ProgramFailedToComplete',\n 'ProgramFailedToCompile',\n 'Immutable',\n 'IncorrectAuthority',\n 'BorshIoError',\n 'AccountNotRentExempt',\n 'InvalidAccountOwner',\n 'ArithmeticOverflow',\n 'UnsupportedSysvar',\n 'IllegalOwner',\n 'MaxAccountsDataAllocationsExceeded',\n 'MaxAccountsExceeded',\n 'MaxInstructionTraceLengthExceeded',\n 'BuiltinProgramsMustConsumeComputeUnits',\n];\n\nexport function getSolanaErrorFromInstructionError(\n /**\n * The index of the instruction inside the transaction.\n */\n index: bigint | number,\n instructionError: string | { [key: string]: unknown },\n): SolanaError {\n const numberIndex = Number(index);\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 4615001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n index: numberIndex,\n ...(rpcErrorContext !== undefined ? { instructionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {\n return {\n code: Number(rpcErrorContext as bigint | number),\n index: numberIndex,\n };\n }\n return { index: numberIndex };\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: instructionError,\n },\n getSolanaErrorFromInstructionError,\n );\n}\n","import {\n SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,\n SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,\n SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,\n SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,\n} from './codes';\nimport { SolanaError } from './error';\nimport { getSolanaErrorFromInstructionError } from './instruction-error';\nimport { getSolanaErrorFromRpcError } from './rpc-enum-errors';\n\n/**\n * How to add an error when an entry is added to the RPC `TransactionError` enum:\n *\n * 1. Follow the instructions in `./codes.ts` to add a corresponding Solana error code\n * 2. Add the `TransactionError` enum name in the same order as it appears in `./codes.ts`\n * 3. Add the new error name/code mapping to `./__tests__/transaction-error-test.ts`\n */\nconst ORDERED_ERROR_NAMES = [\n // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs\n // If this list ever gets too large, consider implementing a compression strategy like this:\n // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47\n 'AccountInUse',\n 'AccountLoadedTwice',\n 'AccountNotFound',\n 'ProgramAccountNotFound',\n 'InsufficientFundsForFee',\n 'InvalidAccountForFee',\n 'AlreadyProcessed',\n 'BlockhashNotFound',\n // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`\n 'CallChainTooDeep',\n 'MissingSignatureForFee',\n 'InvalidAccountIndex',\n 'SignatureFailure',\n 'InvalidProgramForExecution',\n 'SanitizeFailure',\n 'ClusterMaintenance',\n 'AccountBorrowOutstanding',\n 'WouldExceedMaxBlockCostLimit',\n 'UnsupportedVersion',\n 'InvalidWritableAccount',\n 'WouldExceedMaxAccountCostLimit',\n 'WouldExceedAccountDataBlockLimit',\n 'TooManyAccountLocks',\n 'AddressLookupTableNotFound',\n 'InvalidAddressLookupTableOwner',\n 'InvalidAddressLookupTableData',\n 'InvalidAddressLookupTableIndex',\n 'InvalidRentPayingAccount',\n 'WouldExceedMaxVoteCostLimit',\n 'WouldExceedAccountDataTotalLimit',\n 'DuplicateInstruction',\n 'InsufficientFundsForRent',\n 'MaxLoadedAccountsDataSizeExceeded',\n 'InvalidLoadedAccountsDataSizeLimit',\n 'ResanitizationNeeded',\n 'ProgramExecutionTemporarilyRestricted',\n 'UnbalancedTransaction',\n];\n\nexport function getSolanaErrorFromTransactionError(transactionError: string | { [key: string]: unknown }): SolanaError {\n if (typeof transactionError === 'object' && 'InstructionError' in transactionError) {\n return getSolanaErrorFromInstructionError(\n ...(transactionError.InstructionError as Parameters),\n );\n }\n return getSolanaErrorFromRpcError(\n {\n errorCodeBaseOffset: 7050001,\n getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {\n if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {\n return {\n errorName: rpcErrorName,\n ...(rpcErrorContext !== undefined ? { transactionErrorContext: rpcErrorContext } : null),\n };\n } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {\n return {\n index: Number(rpcErrorContext as bigint | number),\n };\n } else if (\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT ||\n errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED\n ) {\n return {\n accountIndex: Number((rpcErrorContext as { account_index: bigint | number }).account_index),\n };\n }\n },\n orderedErrorNames: ORDERED_ERROR_NAMES,\n rpcEnumError: transactionError,\n },\n getSolanaErrorFromTransactionError,\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,\n SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,\n SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,\n SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,\n SOLANA_ERROR__JSON_RPC__PARSE_ERROR,\n SOLANA_ERROR__JSON_RPC__SCAN_ERROR,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,\n SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,\n SolanaErrorCode,\n} from './codes';\nimport { SolanaErrorContext } from './context';\nimport { SolanaError } from './error';\nimport { safeCaptureStackTrace } from './stack-trace';\nimport { getSolanaErrorFromTransactionError } from './transaction-error';\n\ninterface RpcErrorResponse {\n code: bigint | number;\n data?: unknown;\n message: string;\n}\n\ntype TransactionError = string | { [key: string]: unknown };\n\n/**\n * Keep in sync with https://github.com/anza-xyz/agave/blob/master/rpc-client-types/src/response.rs\n * @hidden\n */\nexport interface RpcSimulateTransactionResult {\n accounts:\n | ({\n data:\n | string // LegacyBinary\n | {\n // Json\n parsed: unknown;\n program: string;\n space: bigint;\n }\n // Binary\n | [encodedBytes: string, encoding: 'base58' | 'base64' | 'base64+zstd' | 'binary' | 'jsonParsed'];\n executable: boolean;\n lamports: bigint;\n owner: string;\n rentEpoch: bigint;\n space?: bigint;\n } | null)[]\n | null;\n err: TransactionError | null;\n // Enabled by `enable_cpi_recording`\n innerInstructions?:\n | {\n index: number;\n instructions: (\n | {\n // Compiled\n accounts: number[];\n data: string;\n programIdIndex: number;\n stackHeight?: number;\n }\n | {\n // Parsed\n parsed: unknown;\n program: string;\n programId: string;\n stackHeight?: number;\n }\n | {\n // PartiallyDecoded\n accounts: string[];\n data: string;\n programId: string;\n stackHeight?: number;\n }\n )[];\n }[]\n | null;\n loadedAccountsDataSize: number | null;\n logs: string[] | null;\n replacementBlockhash: string | null;\n returnData: {\n data: [string, 'base64'];\n programId: string;\n } | null;\n unitsConsumed: bigint | null;\n}\n\nexport function getSolanaErrorFromJsonRpcError(putativeErrorResponse: unknown): SolanaError {\n let out: SolanaError;\n if (isRpcErrorResponse(putativeErrorResponse)) {\n const { code: rawCode, data, message } = putativeErrorResponse;\n const code = Number(rawCode);\n if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {\n const { err, ...preflightErrorContext } = data as RpcSimulateTransactionResult;\n const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;\n out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {\n ...preflightErrorContext,\n ...causeObject,\n });\n } else {\n let errorContext;\n switch (code) {\n case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:\n case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:\n case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:\n case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:\n case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:\n case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:\n case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:\n // The server supplies no structured data, but rather a pre-formatted message. Put\n // the server message in `context` so as not to completely lose the data. The long\n // term fix for this is to add data to the server responses and modify the\n // messages in `@solana/errors` to be actual format strings.\n errorContext = { __serverMessage: message };\n break;\n default:\n if (typeof data === 'object' && !Array.isArray(data)) {\n errorContext = data;\n }\n }\n out = new SolanaError(code as SolanaErrorCode, errorContext as SolanaErrorContext[SolanaErrorCode]);\n }\n } else {\n const message =\n typeof putativeErrorResponse === 'object' &&\n putativeErrorResponse !== null &&\n 'message' in putativeErrorResponse &&\n typeof putativeErrorResponse.message === 'string'\n ? putativeErrorResponse.message\n : 'Malformed JSON-RPC error with no message attribute';\n out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });\n }\n safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);\n return out;\n}\n\nfunction isRpcErrorResponse(value: unknown): value is RpcErrorResponse {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'code' in value &&\n 'message' in value &&\n (typeof value.code === 'number' || typeof value.code === 'bigint') &&\n typeof value.message === 'string'\n );\n}\n","import {\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaErrorCode,\n} from './codes';\nimport { isSolanaError } from './error';\n\n/**\n * Extracts the underlying cause from a simulation-related error.\n *\n * When a transaction simulation fails, the error is often wrapped in a\n * simulation-specific {@link SolanaError}. This function unwraps such errors\n * by returning the `cause` property, giving you access to the actual error\n * that triggered the simulation failure.\n *\n * If the provided error is not a simulation-related error, it is returned unchanged.\n *\n * The following error codes are considered simulation errors:\n * - {@link SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE}\n * - {@link SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT}\n *\n * @param error - The error to unwrap.\n * @return The underlying cause if the error is a simulation error, otherwise the original error.\n *\n * @example\n * Unwrapping a preflight failure to access the root cause.\n * ```ts\n * import { unwrapSimulationError } from '@solana/errors';\n *\n * try {\n * await sendTransaction(signedTransaction);\n * } catch (e) {\n * const cause = unwrapSimulationError(e);\n * console.log('Send transaction failed due to:', cause);\n * }\n * ```\n */\nexport function unwrapSimulationError(error: unknown): unknown {\n const simulationCodes: SolanaErrorCode[] = [\n SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n ];\n if (isSolanaError(error) && !!error.cause && simulationCodes.includes(error.context.__code)) {\n return error.cause;\n }\n return error;\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n *\n * @param byteArrays - The array of byte arrays to concatenate.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02]);\n * const bytes2 = new Uint8Array([]);\n * const bytes3 = new Uint8Array([0x03, 0x04]);\n * const bytes = mergeBytes([bytes1, bytes2, bytes3]);\n * // ^ [0x01, 0x02, 0x03, 0x04]\n * ```\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n *\n * @param bytes - The byte array to pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const paddedBytes = padBytes(bytes, 2);\n * // bytes === paddedBytes\n * ```\n */\nexport function padBytes(bytes: Uint8Array, length: number): Uint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array;\nexport function padBytes(bytes: ReadonlyUint8Array, length: number): ReadonlyUint8Array {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n}\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n *\n * @param bytes - The byte array to truncate or pad.\n * @param length - The desired length of the byte array.\n *\n * @example\n * Truncates the byte array to the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // ^ [0x01, 0x02]\n * ```\n *\n * @example\n * Adds zeroes to the end of the byte array to reach the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 4);\n * // ^ [0x01, 0x02, 0x00, 0x00]\n * ```\n *\n * @example\n * Returns the original byte array if it is already at the desired length.\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02]);\n * const fixedBytes = fixBytes(bytes, 2);\n * // bytes === fixedBytes\n * ```\n */\nexport const fixBytes = (bytes: ReadonlyUint8Array | Uint8Array, length: number): ReadonlyUint8Array | Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n\n/**\n * Returns true if and only if the provided `data` byte array contains\n * the provided `bytes` byte array at the specified `offset`.\n *\n * @param data - The byte sequence to search for.\n * @param bytes - The byte array in which to search for `data`.\n * @param offset - The position in `bytes` where the search begins.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const data = new Uint8Array([0x02, 0x03]);\n * containsBytes(bytes, data, 1); // true\n * containsBytes(bytes, data, 2); // false\n * ```\n */\nexport function containsBytes(\n data: ReadonlyUint8Array | Uint8Array,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset: number,\n): boolean {\n const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);\n return bytesEqual(slice, bytes);\n}\n\n/**\n * Returns true if and only if the provided `bytes1` and `bytes2` byte arrays are equal.\n *\n * @param bytes1 - The first byte array to compare.\n * @param bytes2 - The second byte array to compare.\n *\n * @example\n * ```ts\n * const bytes1 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * const bytes2 = new Uint8Array([0x01, 0x02, 0x03, 0x04]);\n * bytesEqual(bytes1, bytes2); // true\n * ```\n */\nexport function bytesEqual(bytes1: ReadonlyUint8Array | Uint8Array, bytes2: ReadonlyUint8Array | Uint8Array): boolean {\n return bytes1.length === bytes2.length && bytes1.every((value, index) => value === bytes2[index]);\n}\n","import {\n SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,\n SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * This is a common interface for {@link FixedSizeEncoder} and {@link VariableSizeEncoder}.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n */\ntype BaseEncoder = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => ReadonlyUint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a fixed-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const encoder: FixedSizeEncoder;\n * const bytes = encoder.encode(42);\n * const size = encoder.fixedSize; // 4\n * ```\n *\n * @see {@link Encoder}\n * @see {@link VariableSizeEncoder}\n */\nexport type FixedSizeEncoder = BaseEncoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a variable-size {@link ReadonlyUint8Array}.\n *\n * See {@link Encoder} to learn more about creating and composing encoders.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * ```ts\n * const encoder: VariableSizeEncoder;\n * const bytes = encoder.encode('hello');\n * const size = encoder.getSizeFromValue('hello');\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n */\nexport type VariableSizeEncoder = BaseEncoder & {\n /** Returns the size of the encoded value in bytes for a given input. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value of type {@link TFrom} into a {@link ReadonlyUint8Array}.\n *\n * An `Encoder` can be either:\n * - A {@link FixedSizeEncoder}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeEncoder}, where encoded values can vary in size.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @example\n * Encoding a value into a new byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = encoder.encode('hello');\n * ```\n *\n * @example\n * Writing the encoded value into an existing byte array.\n * ```ts\n * const encoder: Encoder;\n * const bytes = new Uint8Array(100);\n * const nextOffset = encoder.write('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Encoders` manually using the {@link createEncoder} function but it is more common\n * to compose multiple `Encoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Encoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructEncoder, addEncoderSizePrefix, getUtf8Encoder, getU32Encoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonEncoder = (): Encoder =>\n * getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * ```\n *\n * Note that composed `Encoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Encoder()` is\n * a fixed-size encoder, while `addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())`\n * is a variable-size encoder. This makes the final `Person` encoder a variable-size encoder.\n *\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link createEncoder}\n */\nexport type Encoder = FixedSizeEncoder | VariableSizeEncoder;\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * This is a common interface for {@link FixedSizeDecoder} and {@link VariableSizeDecoder}.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n */\ntype BaseDecoder = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: ReadonlyUint8Array | Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: ReadonlyUint8Array | Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\n/**\n * An object that can decode a fixed-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const decoder: FixedSizeDecoder;\n * const value = decoder.decode(bytes);\n * const size = decoder.fixedSize; // 4\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type FixedSizeDecoder = BaseDecoder & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\n/**\n * An object that can decode a variable-size byte array into a value of type {@link TTo}.\n *\n * See {@link Decoder} to learn more about creating and composing decoders.\n *\n * @interface\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const decoder: VariableSizeDecoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @see {@link Decoder}\n * @see {@link VariableSizeDecoder}\n */\nexport type VariableSizeDecoder = BaseDecoder & {\n /** The maximum possible size of an encoded value in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a byte array into a value of type {@link TTo}.\n *\n * An `Decoder` can be either:\n * - A {@link FixedSizeDecoder}, where all byte arrays have the same fixed size.\n * - A {@link VariableSizeDecoder}, where byte arrays can vary in size.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * Getting the decoded value from a byte array.\n * ```ts\n * const decoder: Decoder;\n * const value = decoder.decode(bytes);\n * ```\n *\n * @example\n * Reading the decoded value from a byte array at a specific offset\n * and getting the offset of the next byte to read.\n * ```ts\n * const decoder: Decoder;\n * const [value, nextOffset] = decoder.read('hello', bytes, 20);\n * ```\n *\n * @remarks\n * You may create `Decoders` manually using the {@link createDecoder} function but it is more common\n * to compose multiple `Decoders` together using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create an `Decoder` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructDecoder, addDecoderSizePrefix, getUtf8Decoder, getU32Decoder } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonDecoder = (): Decoder =>\n * getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * ```\n *\n * Note that composed `Decoder` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Decoder()` is\n * a fixed-size decoder, while `addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())`\n * is a variable-size decoder. This makes the final `Person` decoder a variable-size decoder.\n *\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link createDecoder}\n */\nexport type Decoder = FixedSizeDecoder | VariableSizeDecoder;\n\n/**\n * An object that can encode and decode a value to and from a fixed-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const codec: FixedSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.fixedSize; // 8\n * ```\n *\n * @see {@link Codec}\n * @see {@link VariableSizeCodec}\n */\nexport type FixedSizeCodec = FixedSizeDecoder<\n TTo,\n TSize\n> &\n FixedSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a variable-size byte array.\n *\n * See {@link Codec} to learn more about creating and composing codecs.\n *\n * @interface\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec: VariableSizeCodec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * const size = codec.getSizeFromValue(42);\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n */\nexport type VariableSizeCodec = VariableSizeDecoder & VariableSizeEncoder;\n\n/**\n * An object that can encode and decode a value to and from a byte array.\n *\n * A `Codec` can be either:\n * - A {@link FixedSizeCodec}, where all encoded values have the same fixed size.\n * - A {@link VariableSizeCodec}, where encoded values can vary in size.\n *\n * @example\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode('hello');\n * const value = codec.decode(bytes); // 'hello'\n * ```\n *\n * @remarks\n * For convenience, codecs can encode looser types than they decode.\n * That is, type {@link TFrom} can be a superset of type {@link TTo}.\n * For instance, a `Codec` can encode both\n * `bigint` and `number` values, but will always decode to a `bigint`.\n *\n * ```ts\n * const codec: Codec;\n * const bytes = codec.encode(42);\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * It is worth noting that codecs are the union of encoders and decoders.\n * This means that a `Codec` can be combined from an `Encoder`\n * and a `Decoder` using the {@link combineCodec} function. This is particularly\n * useful for library authors who want to expose all three types of objects to their users.\n *\n * ```ts\n * const encoder: Encoder;\n * const decoder: Decoder;\n * const codec: Codec = combineCodec(encoder, decoder);\n * ```\n *\n * Aside from combining encoders and decoders, codecs can also be created from scratch using\n * the {@link createCodec} function but it is more common to compose multiple codecs together\n * using the various helpers of the `@solana/codecs` package.\n *\n * For instance, here's how you might create a `Codec` for a `Person` object type that contains\n * a `name` string and an `age` number:\n *\n * ```ts\n * import { getStructCodec, addCodecSizePrefix, getUtf8Codec, getU32Codec } from '@solana/codecs';\n *\n * type Person = { name: string; age: number };\n * const getPersonCodec = (): Codec =>\n * getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * ```\n *\n * Note that composed `Codec` types are clever enough to understand whether\n * they are fixed-size or variable-size. In the example above, `getU32Codec()` is\n * a fixed-size codec, while `addCodecSizePrefix(getUtf8Codec(), getU32Codec())`\n * is a variable-size codec. This makes the final `Person` codec a variable-size codec.\n *\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link combineCodec}\n * @see {@link createCodec}\n */\nexport type Codec = FixedSizeCodec | VariableSizeCodec;\n\n/**\n * Gets the encoded size of a given value in bytes using the provided encoder.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @param value - The value to be encoded.\n * @param encoder - The encoder used to determine the encoded size.\n * @returns The size of the encoded value in bytes.\n *\n * @example\n * ```ts\n * const fixedSizeEncoder = { fixedSize: 4 };\n * getEncodedSize(123, fixedSizeEncoder); // Returns 4.\n *\n * const variableSizeEncoder = { getSizeFromValue: (value: string) => value.length };\n * getEncodedSize(\"hello\", variableSizeEncoder); // Returns 5.\n * ```\n *\n * @see {@link Encoder}\n */\nexport function getEncodedSize(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/**\n * Creates an `Encoder` by filling in the missing `encode` function using the provided `write` function and\n * either the `fixedSize` property (for {@link FixedSizeEncoder | FixedSizeEncoders}) or\n * the `getSizeFromValue` function (for {@link VariableSizeEncoder | VariableSizeEncoders}).\n *\n * Instead of manually implementing `encode`, this utility leverages the existing `write` function\n * and the size helpers to generate a complete encoder. The provided `encode` method will allocate\n * a new `Uint8Array` of the correct size and use `write` to populate it.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size encoders).\n *\n * @param encoder - An encoder object that implements `write`, but not `encode`.\n * - If the encoder has a `fixedSize` property, it is treated as a {@link FixedSizeEncoder}.\n * - Otherwise, it is treated as a {@link VariableSizeEncoder}.\n *\n * @returns A fully functional `Encoder` with both `write` and `encode` methods.\n *\n * @example\n * Creating a custom fixed-size encoder.\n * ```ts\n * const encoder = createEncoder({\n * fixedSize: 4,\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n * ```\n *\n * @example\n * Creating a custom variable-size encoder:\n * ```ts\n * const encoder = createEncoder({\n * getSizeFromValue: (value: string) => value.length,\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = encoder.encode(\"hello\");\n * // 0x68656c6c6f\n * ```\n *\n * @remarks\n * Note that, while `createEncoder` is useful for defining more complex encoders, it is more common to compose\n * encoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createEncoder`.\n *\n * ```ts\n * // Fixed-size encoder for unsigned 32-bit integers.\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42);\n * // 0x2a000000\n *\n * // Variable-size encoder for 32-bytes prefixed UTF-8 strings.\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const bytes = encoder.encode(\"hello\");\n * // 0x0500000068656c6c6f\n *\n * // Variable-size encoder for custom objects.\n * type Person = { name: string; age: number };\n * const encoder: Encoder = getStructEncoder([\n * ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n * ['age', getU32Encoder()],\n * ]);\n * const bytes = encoder.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * ```\n *\n * @see {@link Encoder}\n * @see {@link FixedSizeEncoder}\n * @see {@link VariableSizeEncoder}\n * @see {@link getStructEncoder}\n * @see {@link getU32Encoder}\n * @see {@link getUtf8Encoder}\n * @see {@link addEncoderSizePrefix}\n */\nexport function createEncoder(\n encoder: Omit, 'encode'>,\n): FixedSizeEncoder;\nexport function createEncoder(encoder: Omit, 'encode'>): VariableSizeEncoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder;\nexport function createEncoder(\n encoder: Omit, 'encode'> | Omit, 'encode'>,\n): Encoder {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Creates a `Decoder` by filling in the missing `decode` function using the provided `read` function.\n *\n * Instead of manually implementing `decode`, this utility leverages the existing `read` function\n * and the size properties to generate a complete decoder. The provided `decode` method will read\n * from a `Uint8Array` at the given offset and return the decoded value.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeDecoder} will be created, otherwise\n * a {@link VariableSizeDecoder} will be created.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size decoders).\n *\n * @param decoder - A decoder object that implements `read`, but not `decode`.\n * - If the decoder has a `fixedSize` property, it is treated as a {@link FixedSizeDecoder}.\n * - Otherwise, it is treated as a {@link VariableSizeDecoder}.\n *\n * @returns A fully functional `Decoder` with both `read` and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size decoder.\n * ```ts\n * const decoder = createDecoder({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size decoder:\n * ```ts\n * const decoder = createDecoder({\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * });\n *\n * const value = decoder.decode(new Uint8Array([104, 101, 108, 108, 111]));\n * // \"hello\"\n * ```\n *\n * @remarks\n * Note that, while `createDecoder` is useful for defining more complex decoders, it is more common to compose\n * decoders together using the various helpers and primitives of the `@solana/codecs` package.\n *\n * Here are some alternative examples using codec primitives instead of `createDecoder`.\n *\n * ```ts\n * // Fixed-size decoder for unsigned 32-bit integers.\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([42, 0, 0, 0]));\n * // 42\n *\n * // Variable-size decoder for 32-bytes prefixed UTF-8 strings.\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const value = decoder.decode(new Uint8Array([5, 0, 0, 0, 104, 101, 108, 108, 111]));\n * // \"hello\"\n *\n * // Variable-size decoder for custom objects.\n * type Person = { name: string; age: number };\n * const decoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n * const value = decoder.decode(new Uint8Array([3, 0, 0, 0, 66, 111, 98, 42, 0, 0, 0]));\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Decoder}\n * @see {@link FixedSizeDecoder}\n * @see {@link VariableSizeDecoder}\n * @see {@link getStructDecoder}\n * @see {@link getU32Decoder}\n * @see {@link getUtf8Decoder}\n * @see {@link addDecoderSizePrefix}\n */\nexport function createDecoder(\n decoder: Omit, 'decode'>,\n): FixedSizeDecoder;\nexport function createDecoder(decoder: Omit, 'decode'>): VariableSizeDecoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder;\nexport function createDecoder(\n decoder: Omit, 'decode'> | Omit, 'decode'>,\n): Decoder {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/**\n * Creates a `Codec` by filling in the missing `encode` and `decode` functions using the provided `write` and `read` functions.\n *\n * This utility combines the behavior of {@link createEncoder} and {@link createDecoder} to produce a fully functional `Codec`.\n * The `encode` method is derived from the `write` function, while the `decode` method is derived from the `read` function.\n *\n * If the `fixedSize` property is provided, a {@link FixedSizeCodec} will be created, otherwise\n * a {@link VariableSizeCodec} will be created.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param codec - A codec object that implements `write` and `read`, but not `encode` or `decode`.\n * - If the codec has a `fixedSize` property, it is treated as a {@link FixedSizeCodec}.\n * - Otherwise, it is treated as a {@link VariableSizeCodec}.\n *\n * @returns A fully functional `Codec` with `write`, `read`, `encode`, and `decode` methods.\n *\n * @example\n * Creating a custom fixed-size codec.\n * ```ts\n * const codec = createCodec({\n * fixedSize: 4,\n * read: (bytes, offset) => {\n * const value = bytes[offset];\n * return [value, offset + 4];\n * },\n * write: (value: number, bytes, offset) => {\n * bytes.set(new Uint8Array([value]), offset);\n * return offset + 4;\n * },\n * });\n *\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n * ```\n *\n * @example\n * Creating a custom variable-size codec:\n * ```ts\n * const codec = createCodec({\n * getSizeFromValue: (value: string) => value.length,\n * read: (bytes, offset) => {\n * const decodedValue = new TextDecoder().decode(bytes.subarray(offset));\n * return [decodedValue, bytes.length];\n * },\n * write: (value: string, bytes, offset) => {\n * const encodedValue = new TextEncoder().encode(value);\n * bytes.set(encodedValue, offset);\n * return offset + encodedValue.length;\n * },\n * });\n *\n * const bytes = codec.encode(\"hello\");\n * // 0x68656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n * ```\n *\n * @remarks\n * This function effectively combines the behavior of {@link createEncoder} and {@link createDecoder}.\n * If you only need to encode or decode (but not both), consider using those functions instead.\n *\n * Here are some alternative examples using codec primitives instead of `createCodec`.\n *\n * ```ts\n * // Fixed-size codec for unsigned 32-bit integers.\n * const codec = getU32Codec();\n * const bytes = codec.encode(42);\n * // 0x2a000000\n * const value = codec.decode(bytes);\n * // 42\n *\n * // Variable-size codec for 32-bytes prefixed UTF-8 strings.\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const bytes = codec.encode(\"hello\");\n * // 0x0500000068656c6c6f\n * const value = codec.decode(bytes);\n * // \"hello\"\n *\n * // Variable-size codec for custom objects.\n * type Person = { name: string; age: number };\n * const codec: Codec = getStructCodec([\n * ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n * ['age', getU32Codec()],\n * ]);\n * const bytes = codec.encode({ name: \"Bob\", age: 42 });\n * // 0x03000000426f622a000000\n * const value = codec.decode(bytes);\n * // { name: \"Bob\", age: 42 }\n * ```\n *\n * @see {@link Codec}\n * @see {@link FixedSizeCodec}\n * @see {@link VariableSizeCodec}\n * @see {@link createEncoder}\n * @see {@link createDecoder}\n * @see {@link getStructCodec}\n * @see {@link getU32Codec}\n * @see {@link getUtf8Codec}\n * @see {@link addCodecSizePrefix}\n */\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): FixedSizeCodec;\nexport function createCodec(\n codec: Omit, 'decode' | 'encode'>,\n): VariableSizeCodec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec;\nexport function createCodec(\n codec:\n | Omit, 'decode' | 'encode'>\n | Omit, 'decode' | 'encode'>,\n): Codec {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is fixed-size.\n *\n * A fixed-size object is identified by the presence of a `fixedSize` property.\n * If this property exists, the object is considered a {@link FixedSizeCodec},\n * {@link FixedSizeEncoder}, or {@link FixedSizeDecoder}.\n * Otherwise, it is assumed to be a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is fixed-size, `false` otherwise.\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isFixedSize(encoder); // true\n * ```\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isFixedSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is commonly used to distinguish between fixed-size and variable-size objects at runtime.\n * If you need to enforce this distinction with type assertions, consider using {@link assertIsFixedSize}.\n *\n * @see {@link assertIsFixedSize}\n */\nexport function isFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): encoder is FixedSizeEncoder;\nexport function isFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): decoder is FixedSizeDecoder;\nexport function isFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): codec is FixedSizeCodec;\nexport function isFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is fixed-size.\n *\n * If the object is not fixed-size (i.e., it lacks a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not fixed-size.\n *\n * @example\n * Asserting a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsFixedSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsFixedSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isFixedSize}.\n * If you only need to check whether an object is fixed-size without throwing an error, use {@link isFixedSize} instead.\n *\n * @see {@link isFixedSize}\n */\nexport function assertIsFixedSize(\n encoder: FixedSizeEncoder | VariableSizeEncoder,\n): asserts encoder is FixedSizeEncoder;\nexport function assertIsFixedSize(\n decoder: FixedSizeDecoder | VariableSizeDecoder,\n): asserts decoder is FixedSizeDecoder;\nexport function assertIsFixedSize(\n codec: FixedSizeCodec | VariableSizeCodec,\n): asserts codec is FixedSizeCodec;\nexport function assertIsFixedSize(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);\n }\n}\n\n/**\n * Determines whether the given codec, encoder, or decoder is variable-size.\n *\n * A variable-size object is identified by the absence of a `fixedSize` property.\n * If this property is missing, the object is considered a {@link VariableSizeCodec},\n * {@link VariableSizeEncoder}, or {@link VariableSizeDecoder}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @returns `true` if the object is variable-size, `false` otherwise.\n *\n * @example\n * Checking a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * isVariableSize(encoder); // true\n * ```\n *\n * @example\n * Checking a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * isVariableSize(encoder); // false\n * ```\n *\n * @remarks\n * This function is the inverse of {@link isFixedSize}.\n *\n * @see {@link isFixedSize}\n * @see {@link assertIsVariableSize}\n */\nexport function isVariableSize(encoder: Encoder): encoder is VariableSizeEncoder;\nexport function isVariableSize(decoder: Decoder): decoder is VariableSizeDecoder;\nexport function isVariableSize(\n codec: Codec,\n): codec is VariableSizeCodec;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\n/**\n * Asserts that the given codec, encoder, or decoder is variable-size.\n *\n * If the object is not variable-size (i.e., it has a `fixedSize` property),\n * this function throws a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n * @throws {SolanaError} If the object is not variable-size.\n *\n * @example\n * Asserting a variable-size encoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * assertIsVariableSize(encoder); // Passes\n * ```\n *\n * @example\n * Attempting to assert a fixed-size encoder.\n * ```ts\n * const encoder = getU32Encoder();\n * assertIsVariableSize(encoder); // Throws SolanaError\n * ```\n *\n * @remarks\n * This function is the assertion-based counterpart of {@link isVariableSize}.\n * If you only need to check whether an object is variable-size without throwing an error, use {@link isVariableSize} instead.\n *\n * Also note that this function is the inverse of {@link assertIsFixedSize}.\n *\n * @see {@link isVariableSize}\n * @see {@link assertIsFixedSize}\n */\nexport function assertIsVariableSize(encoder: Encoder): asserts encoder is VariableSizeEncoder;\nexport function assertIsVariableSize(decoder: Decoder): asserts decoder is VariableSizeDecoder;\nexport function assertIsVariableSize(\n codec: Codec,\n): asserts codec is VariableSizeCodec;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);\n }\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,\n SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an `Encoder` and a `Decoder` into a `Codec`.\n *\n * That is, given a `Encoder` and a `Decoder`, this function returns a `Codec`.\n *\n * This allows for modular composition by keeping encoding and decoding logic separate\n * while still offering a convenient way to bundle them into a single `Codec`.\n * This is particularly useful for library maintainers who want to expose `Encoders`,\n * `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic.\n *\n * The provided `Encoder` and `Decoder` must be compatible in terms of:\n * - **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value.\n * - **Variable Size:** If either has a `maxSize` attribute, it must match the other.\n *\n * If these conditions are not met, a {@link SolanaError} will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).\n *\n * @param encoder - The `Encoder` to combine.\n * @param decoder - The `Decoder` to combine.\n * @returns A `Codec` that provides both `encode` and `decode` methods.\n *\n * @throws {SolanaError}\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH`\n * Thrown if the encoder and decoder have mismatched size types (fixed vs. variable).\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH`\n * Thrown if both are fixed-size but have different `fixedSize` values.\n * - `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH`\n * Thrown if the `maxSize` attributes do not match.\n *\n * @example\n * Creating a fixed-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = getU32Encoder();\n * const decoder = getU32Decoder();\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(42); // 0x2a000000\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Creating a variable-size `Codec` from an encoder and a decoder.\n * ```ts\n * const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n * const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());\n * const codec = combineCodec(encoder, decoder);\n *\n * const bytes = codec.encode(\"hello\"); // 0x0500000068656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec.\n * This allows users to import only what they need, improving tree-shaking efficiency.\n *\n * ```ts\n * type MyType = \\/* ... *\\/;\n * const getMyTypeEncoder = (): Encoder => { \\/* ... *\\/ };\n * const getMyTypeDecoder = (): Decoder => { \\/* ... *\\/ };\n * const getMyTypeCodec = (): Codec =>\n * combineCodec(getMyTypeEncoder(), getMyTypeDecoder());\n * ```\n *\n * @see {@link Codec}\n * @see {@link Encoder}\n * @see {@link Decoder}\n */\nexport function combineCodec(\n encoder: FixedSizeEncoder,\n decoder: FixedSizeDecoder,\n): FixedSizeCodec;\nexport function combineCodec(\n encoder: VariableSizeEncoder,\n decoder: VariableSizeDecoder,\n): VariableSizeCodec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec;\nexport function combineCodec(\n encoder: Encoder,\n decoder: Decoder,\n): Codec {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {\n decoderFixedSize: decoder.fixedSize,\n encoderFixedSize: encoder.fixedSize,\n });\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {\n decoderMaxSize: decoder.maxSize,\n encoderMaxSize: encoder.maxSize,\n });\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import {\n SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,\n SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,\n SolanaError,\n} from '@solana/errors';\n\nimport { containsBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Creates an encoder that writes a `Uint8Array` sentinel after the encoded value.\n * This is useful to delimit the encoded value when being read by a decoder.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addEncoderSentinel(\n encoder: FixedSizeEncoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeEncoder;\nexport function addEncoderSentinel(\n encoder: Encoder,\n sentinel: ReadonlyUint8Array,\n): VariableSizeEncoder;\nexport function addEncoderSentinel(encoder: Encoder, sentinel: ReadonlyUint8Array): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds\n // and to avoid writing the sentinel as part of the encoded value.\n const encoderBytes = encoder.encode(value);\n if (findSentinelIndex(encoderBytes, sentinel) >= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {\n encodedBytes: encoderBytes,\n hexEncodedBytes: hexBytes(encoderBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n bytes.set(encoderBytes, offset);\n offset += encoderBytes.length;\n bytes.set(sentinel, offset);\n offset += sentinel.length;\n return offset;\n }) as Encoder['write'];\n\n if (isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });\n }\n\n return createEncoder({\n ...encoder,\n ...(encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {}),\n getSizeFromValue: value => encoder.getSizeFromValue(value) + sentinel.length,\n write,\n });\n}\n\n/**\n * Creates a decoder that continues reading until\n * a given `Uint8Array` sentinel is found.\n *\n * See {@link addCodecSentinel} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSentinel}\n */\nexport function addDecoderSentinel(\n decoder: FixedSizeDecoder,\n sentinel: ReadonlyUint8Array,\n): FixedSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): VariableSizeDecoder;\nexport function addDecoderSentinel(decoder: Decoder, sentinel: ReadonlyUint8Array): Decoder {\n const read = ((bytes, offset) => {\n const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);\n const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);\n if (sentinelIndex === -1) {\n throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {\n decodedBytes: candidateBytes,\n hexDecodedBytes: hexBytes(candidateBytes),\n hexSentinel: hexBytes(sentinel),\n sentinel,\n });\n }\n const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds\n // and ensure that the sentinel is not part of the decoded value.\n return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];\n }) as Decoder['read'];\n\n if (isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });\n }\n\n return createDecoder({\n ...decoder,\n ...(decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {}),\n read,\n });\n}\n\n/**\n * Creates a Codec that writes a given `Uint8Array` sentinel after the encoded\n * value and, when decoding, continues reading until the sentinel is found.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * ```ts\n * const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255]));\n * codec.encode('hello');\n * // 0x68656c6c6fffff\n * // | └-- Our sentinel.\n * // └-- Our encoded string.\n * ```\n *\n * @remarks\n * Note that the sentinel _must not_ be present in the encoded data and\n * _must_ be present in the decoded data for this to work.\n * If this is not the case, dedicated errors will be thrown.\n *\n * ```ts\n * const sentinel = new Uint8Array([108, 108]); // 'll'\n * const codec = addCodecSentinel(getUtf8Codec(), sentinel);\n *\n * codec.encode('hello'); // Throws: sentinel is in encoded data.\n * codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data.\n * ```\n *\n * Separate {@link addEncoderSentinel} and {@link addDecoderSentinel} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello');\n * const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSentinel}\n * @see {@link addDecoderSentinel}\n */\nexport function addCodecSentinel(\n codec: FixedSizeCodec,\n sentinel: ReadonlyUint8Array,\n): FixedSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): VariableSizeCodec;\nexport function addCodecSentinel(\n codec: Codec,\n sentinel: ReadonlyUint8Array,\n): Codec {\n return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));\n}\n\nfunction findSentinelIndex(bytes: ReadonlyUint8Array, sentinel: ReadonlyUint8Array) {\n return bytes.findIndex((byte, index, arr) => {\n if (sentinel.length === 1) return byte === sentinel[0];\n return containsBytes(arr, sentinel, index);\n });\n}\n\nfunction hexBytes(bytes: ReadonlyUint8Array): string {\n return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n","import {\n SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,\n SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Asserts that a given byte array is not empty (after the optional provided offset).\n *\n * Returns void if the byte array is not empty but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n * If provided, the byte array is considered empty if it has no bytes after the offset.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK\n * assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws\n * ```\n */\nexport function assertByteArrayIsNotEmptyForCodec(\n codecDescription: string,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n if (bytes.length - offset <= 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {\n codecDescription,\n });\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode\n * (after the optional provided offset).\n *\n * Returns void if the byte array has at least the expected number\n * of bytes but throws a {@link SolanaError} otherwise.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param expected - The minimum number of bytes expected in the byte array.\n * @param bytes - The byte array to check.\n * @param offset - The offset from which to start checking the byte array.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK\n * assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws\n * ```\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: ReadonlyUint8Array | Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {\n bytesLength,\n codecDescription,\n expected,\n });\n }\n}\n\n/**\n * Asserts that a given offset is within the byte array bounds.\n * This range is between 0 and the byte array length and is inclusive.\n * An offset equals to the byte array length is considered a valid offset\n * as it allows the post-offset of codecs to signal the end of the byte array.\n *\n * @param codecDescription - A description of the codec used by the assertion error.\n * @param offset - The offset to check.\n * @param bytesLength - The length of the byte array from which the offset should be within bounds.\n *\n * @example\n * ```ts\n * const bytes = new Uint8Array([0x01, 0x02, 0x03]);\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK\n * assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws\n * ```\n */\nexport function assertByteArrayOffsetIsNotOutOfRange(codecDescription: string, offset: number, bytesLength: number) {\n if (offset < 0 || offset > bytesLength) {\n throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {\n bytesLength,\n codecDescription,\n offset,\n });\n }\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\ntype NumberEncoder = Encoder | Encoder;\ntype FixedSizeNumberEncoder =\n | FixedSizeEncoder\n | FixedSizeEncoder;\ntype NumberDecoder = Decoder | Decoder;\ntype FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\ntype NumberCodec = Codec | Codec;\ntype FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Stores the size of the `encoder` in bytes as a prefix using the `prefix` encoder.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addEncoderSizePrefix(\n encoder: FixedSizeEncoder,\n prefix: FixedSizeNumberEncoder,\n): FixedSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): VariableSizeEncoder;\nexport function addEncoderSizePrefix(encoder: Encoder, prefix: NumberEncoder): Encoder {\n const write = ((value, bytes, offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function to contain the content of the encoder within its own bounds.\n const encoderBytes = encoder.encode(value);\n offset = prefix.write(encoderBytes.length, bytes, offset);\n bytes.set(encoderBytes, offset);\n return offset + encoderBytes.length;\n }) as Encoder['write'];\n\n if (isFixedSize(prefix) && isFixedSize(encoder)) {\n return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : (encoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;\n\n return createEncoder({\n ...encoder,\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: value => {\n const encoderSize = getEncodedSize(value, encoder);\n return getEncodedSize(encoderSize, prefix) + encoderSize;\n },\n write,\n });\n}\n\n/**\n * Bounds the size of the nested `decoder` by reading its encoded `prefix`.\n *\n * See {@link addCodecSizePrefix} for more information.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @see {@link addCodecSizePrefix}\n */\nexport function addDecoderSizePrefix(\n decoder: FixedSizeDecoder,\n prefix: FixedSizeNumberDecoder,\n): FixedSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): VariableSizeDecoder;\nexport function addDecoderSizePrefix(decoder: Decoder, prefix: NumberDecoder): Decoder {\n const read = ((bytes, offset) => {\n const [bigintSize, decoderOffset] = prefix.read(bytes, offset);\n const size = Number(bigintSize);\n offset = decoderOffset;\n // Slice the byte array to the contained size if necessary.\n if (offset > 0 || bytes.length > size) {\n bytes = bytes.slice(offset, offset + size);\n }\n assertByteArrayHasEnoughBytesForCodec('addDecoderSizePrefix', size, bytes);\n // Here we exceptionally use the `decode` function instead of the `read`\n // function to contain the content of the decoder within its own bounds.\n return [decoder.decode(bytes), offset + size];\n }) as Decoder['read'];\n\n if (isFixedSize(prefix) && isFixedSize(decoder)) {\n return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });\n }\n\n const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : (prefix.maxSize ?? null);\n const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : (decoder.maxSize ?? null);\n const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;\n return createDecoder({ ...decoder, ...(maxSize !== null ? { maxSize } : {}), read });\n}\n\n/**\n * Stores the byte size of any given codec as an encoded number prefix.\n *\n * This sets a limit on variable-size codecs and tells us when to stop decoding.\n * When encoding, the size of the encoded data is stored before the encoded data itself.\n * When decoding, the size is read first to know how many bytes to read next.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @example\n * For example, say we want to bound a variable-size base-58 string using a `u32` size prefix.\n * Here’s how you can use the `addCodecSizePrefix` function to achieve that.\n *\n * ```ts\n * const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());\n *\n * getU32Base58Codec().encode('hello world');\n * // 0x0b00000068656c6c6f20776f726c64\n * // | └-- Our encoded base-58 string.\n * // └-- Our encoded u32 size prefix.\n * ```\n *\n * @remarks\n * Separate {@link addEncoderSizePrefix} and {@link addDecoderSizePrefix} functions are also available.\n *\n * ```ts\n * const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');\n * const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link addEncoderSizePrefix}\n * @see {@link addDecoderSizePrefix}\n */\nexport function addCodecSizePrefix(\n codec: FixedSizeCodec,\n prefix: FixedSizeNumberCodec,\n): FixedSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): VariableSizeCodec;\nexport function addCodecSizePrefix(\n codec: Codec,\n prefix: NumberCodec,\n): Codec {\n return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));\n}\n","import { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Converts a `Uint8Array` to an `ArrayBuffer`. If the underlying buffer is a `SharedArrayBuffer`,\n * it will be copied to a non-shared buffer, for safety.\n *\n * @remarks\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nexport function toArrayBuffer(bytes: ReadonlyUint8Array | Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n let buffer: ArrayBuffer;\n if (typeof SharedArrayBuffer === 'undefined') {\n buffer = bytes.buffer as ArrayBuffer;\n } else if (bytes.buffer instanceof SharedArrayBuffer) {\n buffer = new ArrayBuffer(bytes.length);\n new Uint8Array(buffer).set(new Uint8Array(bytes));\n } else {\n buffer = bytes.buffer;\n }\n return (bytesOffset === 0 || bytesOffset === -bytes.byteLength) && bytesLength === bytes.byteLength\n ? buffer\n : buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, SolanaError } from '@solana/errors';\n\nimport { createDecoder, Decoder } from './codec';\n\n/**\n * Create a {@link Decoder} that asserts that the bytes provided to `decode` or `read` are fully consumed by the inner decoder\n * @param decoder A decoder to wrap\n * @returns A new decoder that will throw if provided with a byte array that it does not fully consume\n *\n * @typeParam T - The type of the decoder\n *\n * @remarks\n * Note that this compares the offset after encoding to the length of the input byte array\n *\n * The `offset` parameter to `decode` and `read` is still considered, and will affect the new offset that is compared to the byte array length\n *\n * The error that is thrown by the returned decoder is a {@link SolanaError} with the code `SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY`\n *\n * @example\n * Create a decoder that decodes a `u32` (4 bytes) and ensures the entire byte array is consumed\n * ```ts\n * const decoder = createDecoderThatUsesExactByteArray(getU32Decoder());\n * decoder.decode(new Uint8Array([0, 0, 0, 0])); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0])); // throws\n *\n * // with an offset\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0]), 1); // 0\n * decoder.decode(new Uint8Array([0, 0, 0, 0, 0, 0]), 1); // throws\n * ```\n */\nexport function createDecoderThatConsumesEntireByteArray(decoder: Decoder): Decoder {\n return createDecoder({\n ...decoder,\n read(bytes, offset) {\n const [value, newOffset] = decoder.read(bytes, offset);\n if (bytes.length > newOffset) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, {\n expectedLength: newOffset,\n numExcessBytes: bytes.length - newOffset,\n });\n }\n return [value, newOffset];\n },\n });\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * The resulting encoder ensures that encoded values always have the specified number of bytes.\n * If the original encoded value is larger than `fixedBytes`, it is truncated.\n * If it is smaller, it is padded with trailing zeroes.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @returns A `FixedSizeEncoder` that ensures a consistent output size.\n *\n * @example\n * ```ts\n * const encoder = fixEncoderSize(getUtf8Encoder(), 4);\n * encoder.encode(\"Hello\"); // 0x48656c6c (truncated)\n * encoder.encode(\"Hi\"); // 0x48690000 (padded)\n * encoder.encode(\"Hiya\"); // 0x48697961 (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixEncoderSize(\n encoder: Encoder,\n fixedBytes: TSize,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * The resulting decoder always reads exactly `fixedBytes` bytes from the input.\n * If the nested decoder is also fixed-size, the bytes are truncated or padded as needed.\n *\n * For more details, see {@link fixCodecSize}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @returns A `FixedSizeDecoder` that ensures a consistent input size.\n *\n * @example\n * ```ts\n * const decoder = fixDecoderSize(getUtf8Decoder(), 4);\n * decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // \"Hell\" (truncated)\n * decoder.decode(new Uint8Array([72, 105, 0, 0])); // \"Hi\" (zeroes ignored)\n * decoder.decode(new Uint8Array([72, 105, 121, 97])); // \"Hiya\" (same length)\n * ```\n *\n * @remarks\n * If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.\n *\n * @see {@link fixCodecSize}\n * @see {@link fixEncoderSize}\n */\nexport function fixDecoderSize(\n decoder: Decoder,\n fixedBytes: TSize,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes, offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodecSize', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes.\n * When encoding:\n * - If the encoded value is larger than `fixedBytes`, it is truncated.\n * - If it is smaller, it is padded with trailing zeroes.\n * - If it is exactly `fixedBytes`, it remains unchanged.\n *\n * When decoding:\n * - Exactly `fixedBytes` bytes are read from the input.\n * - If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @returns A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size.\n *\n * @example\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 4);\n *\n * const bytes1 = codec.encode(\"Hello\"); // 0x48656c6c (truncated)\n * const value1 = codec.decode(bytes1); // \"Hell\"\n *\n * const bytes2 = codec.encode(\"Hi\"); // 0x48690000 (padded)\n * const value2 = codec.decode(bytes2); // \"Hi\"\n *\n * const bytes3 = codec.encode(\"Hiya\"); // 0x48697961 (same length)\n * const value3 = codec.decode(bytes3); // \"Hiya\"\n * ```\n *\n * @remarks\n * If you only need to enforce a fixed size for encoding, use {@link fixEncoderSize}.\n * If you only need to enforce a fixed size for decoding, use {@link fixDecoderSize}.\n *\n * ```ts\n * const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode(\"Hiya\");\n * const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);\n * ```\n *\n * @see {@link fixEncoderSize}\n * @see {@link fixDecoderSize}\n */\nexport function fixCodecSize(\n codec: Codec,\n fixedBytes: TSize,\n): FixedSizeCodec {\n return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));\n}\n","import { assertByteArrayOffsetIsNotOutOfRange } from './assertions';\nimport { Codec, createDecoder, createEncoder, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Configuration object for modifying the offset of an encoder, decoder, or codec.\n *\n * This type defines optional functions for adjusting the **pre-offset** (before encoding/decoding)\n * and the **post-offset** (after encoding/decoding). These functions allow precise control\n * over where data is written or read within a byte array.\n *\n * @property preOffset - A function that modifies the offset before encoding or decoding.\n * @property postOffset - A function that modifies the offset after encoding or decoding.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * };\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const config: OffsetConfig = {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * };\n * ```\n *\n * @example\n * Using both pre-offset and post-offset together.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * postOffset: ({ postOffset }) => postOffset + 4,\n * };\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n * @see {@link offsetCodec}\n */\ntype OffsetConfig = {\n postOffset?: PostOffsetFunction;\n preOffset?: PreOffsetFunction;\n};\n\n/**\n * Scope provided to the `preOffset` and `postOffset` functions,\n * containing contextual information about the current encoding or decoding process.\n *\n * The pre-offset function modifies where encoding or decoding begins,\n * while the post-offset function modifies where the next operation continues.\n *\n * @property bytes - The entire byte array being encoded or decoded.\n * @property preOffset - The original offset before encoding or decoding starts.\n * @property wrapBytes - A helper function that wraps offsets around the byte array length.\n *\n * @example\n * Using `wrapBytes` to wrap a negative offset to the end of the byte array.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves to last 4 bytes\n * };\n * ```\n *\n * @example\n * Adjusting the offset dynamically based on the byte array size.\n * ```ts\n * const config: OffsetConfig = {\n * preOffset: ({ bytes }) => bytes.length > 10 ? 4 : 2,\n * };\n * ```\n *\n * @see {@link PreOffsetFunction}\n * @see {@link PostOffsetFunction}\n */\ntype PreOffsetFunctionScope = {\n /** The entire byte array. */\n bytes: ReadonlyUint8Array | Uint8Array;\n /** The original offset prior to encode or decode. */\n preOffset: Offset;\n /** Wraps the offset to the byte array length. */\n wrapBytes: (offset: Offset) => Offset;\n};\n\n/**\n * A function that modifies the pre-offset before encoding or decoding.\n *\n * This function is used to adjust the starting position before writing\n * or reading data in a byte array.\n *\n * @param scope - The current encoding or decoding context.\n * @returns The new offset at which encoding or decoding should start.\n *\n * @example\n * Skipping the first 2 bytes before writing or reading.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ preOffset }) => preOffset + 2;\n * ```\n *\n * @example\n * Wrapping the offset to ensure it stays within bounds.\n * ```ts\n * const preOffset: PreOffsetFunction = ({ wrapBytes, preOffset }) => wrapBytes(preOffset + 10);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PreOffsetFunction = (scope: PreOffsetFunctionScope) => Offset;\n\n/**\n * A function that modifies the post-offset after encoding or decoding.\n *\n * This function adjusts where the next encoder or decoder should start\n * after the current operation has completed.\n *\n * @param scope - The current encoding or decoding context, including the modified pre-offset\n * and the original post-offset.\n * @returns The new offset at which the next operation should begin.\n *\n * @example\n * Moving the post-offset forward by 4 bytes.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset }) => postOffset + 4;\n * ```\n *\n * @example\n * Wrapping the post-offset within the byte array length.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ wrapBytes, postOffset }) => wrapBytes(postOffset);\n * ```\n *\n * @example\n * Ensuring a minimum spacing of 8 bytes between values.\n * ```ts\n * const postOffset: PostOffsetFunction = ({ postOffset, newPreOffset }) =>\n * Math.max(postOffset, newPreOffset + 8);\n * ```\n *\n * @see {@link OffsetConfig}\n * @see {@link PreOffsetFunctionScope}\n */\ntype PostOffsetFunction = (\n scope: PreOffsetFunctionScope & {\n /** The modified offset used to encode or decode. */\n newPreOffset: Offset;\n /** The original offset returned by the encoder or decoder. */\n postOffset: Offset;\n },\n) => Offset;\n\n/**\n * Moves the offset of a given encoder before and/or after encoding.\n *\n * This function allows an encoder to write its encoded value at a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before encoding) and post-offset adjustments (after encoding).\n *\n * The pre-offset function determines where encoding should start, while the\n * post-offset function adjusts where the next encoder should continue writing.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new encoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Actually written at offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * const nextOffset = encoder.write(42, bytes, 0); // Next encoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to ensure an offset wraps around the byte array length.\n * ```ts\n * const encoder = offsetEncoder(getU32Encoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array(10);\n * encoder.write(42, bytes, 0); // Writes at bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetDecoder}\n */\nexport function offsetEncoder(encoder: TEncoder, config: OffsetConfig): TEncoder {\n return createEncoder({\n ...encoder,\n write: (value, bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPreOffset, bytes.length);\n const postOffset = encoder.write(value, bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetEncoder', newPostOffset, bytes.length);\n return newPostOffset;\n },\n }) as TEncoder;\n}\n\n/**\n * Moves the offset of a given decoder before and/or after decoding.\n *\n * This function allows a decoder to read its input from a different offset\n * than the one originally provided. It supports both pre-offset adjustments\n * (before decoding) and post-offset adjustments (after decoding).\n *\n * The pre-offset function determines where decoding should start, while the\n * post-offset function adjusts where the next decoder should continue reading.\n *\n * For more details, see {@link offsetCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new decoder with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array([0, 0, 42, 0]); // Value starts at offset 2\n * decoder.read(bytes, 0); // Actually reads from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array([42, 0, 0, 0]);\n * const [value, nextOffset] = decoder.read(bytes, 0); // Next decoder starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to read from the last 4 bytes of an array.\n * ```ts\n * const decoder = offsetDecoder(getU32Decoder(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array\n * });\n * const bytes = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 42]); // Value stored at the last 4 bytes\n * decoder.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you need both encoding and decoding offsets to be adjusted, use {@link offsetCodec}.\n *\n * @see {@link offsetCodec}\n * @see {@link offsetEncoder}\n */\nexport function offsetDecoder(decoder: TDecoder, config: OffsetConfig): TDecoder {\n return createDecoder({\n ...decoder,\n read: (bytes, preOffset) => {\n const wrapBytes = (offset: Offset) => modulo(offset, bytes.length);\n const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPreOffset, bytes.length);\n const [value, postOffset] = decoder.read(bytes, newPreOffset);\n const newPostOffset = config.postOffset\n ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes })\n : postOffset;\n assertByteArrayOffsetIsNotOutOfRange('offsetDecoder', newPostOffset, bytes.length);\n return [value, newPostOffset];\n },\n }) as TDecoder;\n}\n\n/**\n * Moves the offset of a given codec before and/or after encoding and decoding.\n *\n * This function allows a codec to encode and decode values at custom offsets\n * within a byte array. It modifies both the **pre-offset** (where encoding/decoding starts)\n * and the **post-offset** (where the next operation should continue).\n *\n * This is particularly useful when working with structured binary formats\n * that require skipping reserved bytes, inserting padding, or aligning fields at\n * specific locations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to adjust.\n * @param config - An object specifying how the offset should be modified.\n * @returns A new codec with adjusted offsets.\n *\n * @example\n * Moving the pre-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ preOffset }) => preOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Actually written at offset 2\n * codec.read(bytes, 0); // Actually read from offset 2\n * ```\n *\n * @example\n * Moving the post-offset forward by 2 bytes when encoding and decoding.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * postOffset: ({ postOffset }) => postOffset + 2,\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0);\n * // Next encoding starts at offset 6 instead of 4\n * codec.read(bytes, 0);\n * // Next decoding starts at offset 6 instead of 4\n * ```\n *\n * @example\n * Using `wrapBytes` to loop around negative offsets.\n * ```ts\n * const codec = offsetCodec(getU32Codec(), {\n * preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes\n * });\n * const bytes = new Uint8Array(10);\n * codec.write(42, bytes, 0); // Writes at bytes.length - 4\n * codec.read(bytes, 0); // Reads from bytes.length - 4\n * ```\n *\n * @remarks\n * If you only need to adjust offsets for encoding, use {@link offsetEncoder}.\n * If you only need to adjust offsets for decoding, use {@link offsetDecoder}.\n *\n * ```ts\n * const bytes = new Uint8Array(10);\n * offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).write(42, bytes, 0);\n * const [value] = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).read(bytes, 0);\n * ```\n *\n * @see {@link offsetEncoder}\n * @see {@link offsetDecoder}\n */\nexport function offsetCodec(codec: TCodec, config: OffsetConfig): TCodec {\n return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config)) as TCodec;\n}\n\n/** A modulo function that handles negative dividends and zero divisors. */\nfunction modulo(dividend: number, divisor: number) {\n if (divisor === 0) return 0;\n return ((dividend % divisor) + divisor) % divisor;\n}\n","import { SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Updates the size of a given encoder.\n *\n * This function modifies the size of an encoder using a provided transformation function.\n * For fixed-size encoders, it updates the `fixedSize` property, and for variable-size\n * encoders, it adjusts the size calculation based on the encoded value.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The original fixed size of the encoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param encoder - The encoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new encoder with the updated size.\n *\n * @example\n * Increasing the size of a `u16` encoder by 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU16Encoder(), size => size + 2);\n * encoder.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * ```\n *\n * @example\n * Shrinking a `u32` encoder to only use 2 bytes.\n * ```ts\n * const encoder = resizeEncoder(getU32Encoder(), () => 2);\n * encoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeDecoder}\n */\nexport function resizeEncoder(\n encoder: FixedSizeEncoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder;\nexport function resizeEncoder(\n encoder: TEncoder,\n resize: (size: number) => number,\n): TEncoder {\n if (isFixedSize(encoder)) {\n const fixedSize = resize(encoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return createEncoder({ ...encoder, fixedSize }) as TEncoder;\n }\n return createEncoder({\n ...encoder,\n getSizeFromValue: value => {\n const newSize = resize(encoder.getSizeFromValue(value));\n if (newSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: newSize,\n codecDescription: 'resizeEncoder',\n });\n }\n return newSize;\n },\n }) as TEncoder;\n}\n\n/**\n * Updates the size of a given decoder.\n *\n * This function modifies the size of a decoder using a provided transformation function.\n * For fixed-size decoders, it updates the `fixedSize` property to reflect the new size.\n * Variable-size decoders remain unchanged, as their size is determined dynamically.\n *\n * If the new size is negative, an error will be thrown.\n *\n * For more details, see {@link resizeCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the decoded value.\n * @typeParam TNewSize - The new fixed size after resizing.\n *\n * @param decoder - The decoder whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new decoder with the updated size.\n *\n * @example\n * Expanding a `u16` decoder to read 4 bytes instead of 2.\n * ```ts\n * const decoder = resizeDecoder(getU16Decoder(), size => size + 2);\n * decoder.fixedSize; // 4\n * ```\n *\n * @example\n * Shrinking a `u32` decoder to only read 2 bytes.\n * ```ts\n * const decoder = resizeDecoder(getU32Decoder(), () => 2);\n * decoder.fixedSize; // 2\n * ```\n *\n * @see {@link resizeCodec}\n * @see {@link resizeEncoder}\n */\nexport function resizeDecoder(\n decoder: FixedSizeDecoder,\n resize: (size: TSize) => TNewSize,\n): FixedSizeDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder;\nexport function resizeDecoder(\n decoder: TDecoder,\n resize: (size: number) => number,\n): TDecoder {\n if (isFixedSize(decoder)) {\n const fixedSize = resize(decoder.fixedSize);\n if (fixedSize < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {\n bytesLength: fixedSize,\n codecDescription: 'resizeDecoder',\n });\n }\n return createDecoder({ ...decoder, fixedSize }) as TDecoder;\n }\n return decoder;\n}\n\n/**\n * Updates the size of a given codec.\n *\n * This function modifies the size of both the codec using a provided\n * transformation function. It is useful for adjusting the allocated byte size for\n * encoding and decoding without altering the underlying data structure.\n *\n * If the new size is negative, an error will be thrown.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The original fixed size of the encoded/decoded value (for fixed-size codecs).\n * @typeParam TNewSize - The new fixed size after resizing (for fixed-size codecs).\n *\n * @param codec - The codec whose size will be updated.\n * @param resize - A function that takes the current size and returns the new size.\n * @returns A new codec with the updated size.\n *\n * @example\n * Expanding a `u16` codec from 2 to 4 bytes.\n * ```ts\n * const codec = resizeCodec(getU16Codec(), size => size + 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (reads original two bytes)\n * ```\n *\n * @example\n * Shrinking a `u32` codec to only use 2 bytes.\n * ```ts\n * const codec = resizeCodec(getU32Codec(), () => 2);\n * codec.fixedSize; // 2\n * ```\n *\n * @remarks\n * If you only need to resize an encoder, use {@link resizeEncoder}.\n * If you only need to resize a decoder, use {@link resizeDecoder}.\n *\n * ```ts\n * const bytes = resizeEncoder(getU32Encoder(), (size) => size + 2).encode(0xffff);\n * const value = resizeDecoder(getU32Decoder(), (size) => size + 2).decode(bytes);\n * ```\n *\n * @see {@link resizeEncoder}\n * @see {@link resizeDecoder}\n */\nexport function resizeCodec(\n codec: FixedSizeCodec,\n resize: (size: TSize) => TNewSize,\n): FixedSizeCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec;\nexport function resizeCodec(codec: TCodec, resize: (size: number) => number): TCodec {\n return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize)) as TCodec;\n}\n","import { Codec, Decoder, Encoder, Offset } from './codec';\nimport { combineCodec } from './combine-codec';\nimport { offsetDecoder, offsetEncoder } from './offset-codec';\nimport { resizeDecoder, resizeEncoder } from './resize-codec';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyEncoder = Encoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyDecoder = Decoder;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyCodec = Codec;\n\n/**\n * Adds left padding to the given encoder, shifting the encoded value forward\n * by `offset` bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add before encoding.\n * @returns A new encoder with left padding applied.\n *\n * @example\n * ```ts\n * const encoder = padLeftEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given encoder, extending the encoded value by `offset`\n * bytes whilst increasing the size of the encoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n *\n * @param encoder - The encoder to pad.\n * @param offset - The number of padding bytes to add after encoding.\n * @returns A new encoder with right padding applied.\n *\n * @example\n * ```ts\n * const encoder = padRightEncoder(getU16Encoder(), 2);\n * const bytes = encoder.encode(0xffff); // 0xffff0000 (two extra bytes added at the end)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightDecoder}\n */\nexport function padRightEncoder(encoder: TEncoder, offset: Offset): TEncoder {\n return offsetEncoder(\n resizeEncoder(encoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given decoder, shifting the decoding position forward\n * by `offset` bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padLeftCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip before decoding.\n * @returns A new decoder with left padding applied.\n *\n * @example\n * ```ts\n * const decoder = padLeftDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0, 0, 0x12, 0x34])); // 0xffff (reads from offset 2)\n * ```\n *\n * @see {@link padLeftCodec}\n * @see {@link padLeftEncoder}\n */\nexport function padLeftDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { preOffset: ({ preOffset }) => preOffset + offset },\n );\n}\n\n/**\n * Adds right padding to the given decoder, extending the post-offset by `offset`\n * bytes whilst increasing the size of the decoder accordingly.\n *\n * For more details, see {@link padRightCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n *\n * @param decoder - The decoder to pad.\n * @param offset - The number of padding bytes to skip after decoding.\n * @returns A new decoder with right padding applied.\n *\n * @example\n * ```ts\n * const decoder = padRightDecoder(getU16Decoder(), 2);\n * const value = decoder.decode(new Uint8Array([0x12, 0x34, 0, 0])); // 0xffff (ignores trailing bytes)\n * ```\n *\n * @see {@link padRightCodec}\n * @see {@link padRightEncoder}\n */\nexport function padRightDecoder(decoder: TDecoder, offset: Offset): TDecoder {\n return offsetDecoder(\n resizeDecoder(decoder, size => size + offset),\n { postOffset: ({ postOffset }) => postOffset + offset },\n );\n}\n\n/**\n * Adds left padding to the given codec, shifting the encoding and decoding positions\n * forward by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * This ensures that values are read and written at a later position in the byte array,\n * while the padding bytes remain unused.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add before encoding and decoding.\n * @returns A new codec with left padding applied.\n *\n * @example\n * ```ts\n * const codec = padLeftCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0x0000ffff (0xffff written at offset 2)\n * const value = codec.decode(bytes); // 0xffff (reads from offset 2)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padLeftEncoder}.\n * If you only need to apply padding for decoding, use {@link padLeftDecoder}.\n *\n * ```ts\n * const bytes = padLeftEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padLeftDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padLeftEncoder}\n * @see {@link padLeftDecoder}\n */\nexport function padLeftCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset)) as TCodec;\n}\n\n/**\n * Adds right padding to the given codec, extending the encoded and decoded value\n * by `offset` bytes whilst increasing the size of the codec accordingly.\n *\n * The extra bytes remain unused, ensuring that the next operation starts further\n * along the byte array.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n *\n * @param codec - The codec to pad.\n * @param offset - The number of padding bytes to add after encoding and decoding.\n * @returns A new codec with right padding applied.\n *\n * @example\n * ```ts\n * const codec = padRightCodec(getU16Codec(), 2);\n * const bytes = codec.encode(0xffff); // 0xffff0000 (two extra bytes added)\n * const value = codec.decode(bytes); // 0xffff (ignores padding bytes)\n * ```\n *\n * @remarks\n * If you only need to apply padding for encoding, use {@link padRightEncoder}.\n * If you only need to apply padding for decoding, use {@link padRightDecoder}.\n *\n * ```ts\n * const bytes = padRightEncoder(getU16Encoder(), 2).encode(0xffff);\n * const value = padRightDecoder(getU16Decoder(), 2).decode(bytes);\n * ```\n *\n * @see {@link padRightEncoder}\n * @see {@link padRightDecoder}\n */\nexport function padRightCodec(codec: TCodec, offset: Offset): TCodec {\n return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset)) as TCodec;\n}\n","import {\n assertIsFixedSize,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\nfunction copySourceToTargetInReverse(\n source: ReadonlyUint8Array,\n target_WILL_MUTATE: Uint8Array,\n sourceOffset: number,\n sourceLength: number,\n targetOffset: number = 0,\n) {\n while (sourceOffset < --sourceLength) {\n const leftValue = source[sourceOffset];\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];\n target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;\n sourceOffset++;\n }\n if (sourceOffset === sourceLength) {\n target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];\n }\n}\n\n/**\n * Reverses the bytes of a fixed-size encoder.\n *\n * Given a `FixedSizeEncoder`, this function returns a new `FixedSizeEncoder` that\n * reverses the bytes within the fixed-size byte array when encoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TSize - The fixed size of the encoded value in bytes.\n *\n * @param encoder - The fixed-size encoder to reverse.\n * @returns A new encoder that writes bytes in reverse order.\n *\n * @example\n * Encoding a `u16` value in reverse order.\n * ```ts\n * const encoder = reverseEncoder(getU16Encoder({ endian: Endian.Big }));\n * const bytes = encoder.encode(0x1234); // 0x3412 (bytes are flipped)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseDecoder}\n */\nexport function reverseEncoder(\n encoder: FixedSizeEncoder,\n): FixedSizeEncoder {\n assertIsFixedSize(encoder);\n return createEncoder({\n ...encoder,\n write: (value: TFrom, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n copySourceToTargetInReverse(\n bytes /* source */,\n bytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + encoder.fixedSize /* sourceLength */,\n );\n return newOffset;\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size decoder.\n *\n * Given a `FixedSizeDecoder`, this function returns a new `FixedSizeDecoder` that\n * reverses the bytes within the fixed-size byte array before decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * For more details, see {@link reverseCodec}.\n *\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the decoded value in bytes.\n *\n * @param decoder - The fixed-size decoder to reverse.\n * @returns A new decoder that reads bytes in reverse order.\n *\n * @example\n * Decoding a reversed `u16` value.\n * ```ts\n * const decoder = reverseDecoder(getU16Decoder({ endian: Endian.Big }));\n * const value = decoder.decode(new Uint8Array([0x34, 0x12])); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @see {@link reverseCodec}\n * @see {@link reverseEncoder}\n */\nexport function reverseDecoder(\n decoder: FixedSizeDecoder,\n): FixedSizeDecoder {\n assertIsFixedSize(decoder);\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reversedBytes = bytes.slice();\n copySourceToTargetInReverse(\n bytes /* source */,\n reversedBytes /* target_WILL_MUTATE */,\n offset /* sourceOffset */,\n offset + decoder.fixedSize /* sourceLength */,\n );\n return decoder.read(reversedBytes, offset);\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size codec.\n *\n * Given a `FixedSizeCodec`, this function returns a new `FixedSizeCodec` that\n * reverses the bytes within the fixed-size byte array during encoding and decoding.\n *\n * This can be useful to modify endianness or for other byte-order transformations.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value.\n * @typeParam TSize - The fixed size of the encoded/decoded value in bytes.\n *\n * @param codec - The fixed-size codec to reverse.\n * @returns A new codec that encodes and decodes bytes in reverse order.\n *\n * @example\n * Reversing a `u16` codec.\n * ```ts\n * const codec = reverseCodec(getU16Codec({ endian: Endian.Big }));\n * const bytes = codec.encode(0x1234); // 0x3412 (bytes are flipped)\n * const value = codec.decode(bytes); // 0x1234 (bytes are flipped back)\n * ```\n *\n * @remarks\n * If you only need to reverse an encoder, use {@link reverseEncoder}.\n * If you only need to reverse a decoder, use {@link reverseDecoder}.\n *\n * ```ts\n * const bytes = reverseEncoder(getU16Encoder()).encode(0x1234);\n * const value = reverseDecoder(getU16Decoder()).decode(bytes);\n * ```\n *\n * @see {@link reverseEncoder}\n * @see {@link reverseDecoder}\n */\nexport function reverseCodec(\n codec: FixedSizeCodec,\n): FixedSizeCodec {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\nimport { ReadonlyUint8Array } from './readonly-uint8array';\n\n/**\n * Transforms an encoder by mapping its input values.\n *\n * This function takes an existing `Encoder` and returns an `Encoder`, allowing values of type `B`\n * to be converted into values of type `A` before encoding. The transformation is applied via the `unmap` function.\n *\n * This is useful for handling type conversions, applying default values, or structuring data before encoding.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldFrom - The original type expected by the encoder.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n *\n * @param encoder - The encoder to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @returns A new encoder that accepts `TNewFrom` values and transforms them before encoding.\n *\n * @example\n * Encoding a string by counting its characters and storing the length as a `u32`.\n * ```ts\n * const encoder = transformEncoder(getU32Encoder(), (value: string) => value.length);\n * encoder.encode(\"hello\"); // 0x05000000 (stores length 5)\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformDecoder}\n */\nexport function transformEncoder(\n encoder: FixedSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder;\nexport function transformEncoder(\n encoder: VariableSizeEncoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder;\nexport function transformEncoder(\n encoder: Encoder,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Transforms a decoder by mapping its output values.\n *\n * This function takes an existing `Decoder` and returns a `Decoder`, allowing values of type `A`\n * to be converted into values of type `B` after decoding. The transformation is applied via the `map` function.\n *\n * This is useful for post-processing, type conversions, or enriching decoded data.\n *\n * For more details, see {@link transformCodec}.\n *\n * @typeParam TOldTo - The original type returned by the decoder.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param decoder - The decoder to transform.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding.\n * @returns A new decoder that decodes into `TNewTo`.\n *\n * @example\n * Decoding a stored `u32` length into a string of `'x'` characters.\n * ```ts\n * const decoder = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length));\n * decoder.decode(new Uint8Array([0x05, 0x00, 0x00, 0x00])); // \"xxxxx\"\n * ```\n *\n * @see {@link transformCodec}\n * @see {@link transformEncoder}\n */\nexport function transformDecoder(\n decoder: FixedSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder;\nexport function transformDecoder(\n decoder: VariableSizeDecoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder;\nexport function transformDecoder(\n decoder: Decoder,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Decoder {\n return createDecoder({\n ...decoder,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Transforms a codec by mapping its input and output values.\n *\n * This function takes an existing `Codec` and returns a `Codec`, allowing:\n * - Values of type `C` to be transformed into `A` before encoding.\n * - Values of type `B` to be transformed into `D` after decoding.\n *\n * This is useful for adapting codecs to work with different representations, handling default values, or\n * converting between primitive and structured types.\n *\n * @typeParam TOldFrom - The original type expected by the codec.\n * @typeParam TNewFrom - The new type that will be transformed before encoding.\n * @typeParam TOldTo - The original type returned by the codec.\n * @typeParam TNewTo - The new type that will be transformed after decoding.\n *\n * @param codec - The codec to transform.\n * @param unmap - A function that converts values of `TNewFrom` into `TOldFrom` before encoding.\n * @param map - A function that converts values of `TOldTo` into `TNewTo` after decoding (optional).\n * @returns A new codec that encodes `TNewFrom` and decodes into `TNewTo`.\n *\n * @example\n * Mapping a `u32` codec to encode string lengths and decode them into `'x'` characters.\n * ```ts\n * const codec = transformCodec(\n * getU32Codec(),\n * (value: string) => value.length, // Encode string length\n * (length) => 'x'.repeat(length) // Decode length into a string of 'x's\n * );\n *\n * const bytes = codec.encode(\"hello\"); // 0x05000000 (stores length 5)\n * const value = codec.decode(bytes); // \"xxxxx\"\n * ```\n *\n * @remarks\n * If only input transformation is needed, use {@link transformEncoder}.\n * If only output transformation is needed, use {@link transformDecoder}.\n *\n * ```ts\n * const bytes = transformEncoder(getU32Encoder(), (value: string) => value.length).encode(\"hello\");\n * const value = transformDecoder(getU32Decoder(), (length) => 'x'.repeat(length)).decode(bytes);\n * ```\n *\n * @see {@link transformEncoder}\n * @see {@link transformDecoder}\n */\nexport function transformCodec(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec;\nexport function transformCodec<\n TOldFrom,\n TNewFrom,\n TOldTo extends TOldFrom,\n TNewTo extends TNewFrom,\n TSize extends number,\n>(\n codec: FixedSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec;\nexport function transformCodec(\n codec: VariableSizeCodec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec;\nexport function transformCodec(\n codec: Codec,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo,\n): Codec {\n return createCodec({\n ...transformEncoder(codec, unmap),\n read: map ? transformDecoder(codec, map).read : (codec.read as unknown as Decoder['read']),\n });\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '0123456789';\n\n/**\n * Returns an encoder for base-10 strings.\n *\n * This encoder serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-10 strings.\n *\n * @example\n * Encoding a base-10 string.\n * ```ts\n * const encoder = getBase10Encoder();\n * const bytes = encoder.encode('1024'); // 0x0400\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-10 strings.\n *\n * This decoder deserializes base-10 encoded strings from a byte array.\n *\n * For more details, see {@link getBase10Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-10 strings.\n *\n * @example\n * Decoding a base-10 string.\n * ```ts\n * const decoder = getBase10Decoder();\n * const value = decoder.decode(new Uint8Array([0x04, 0x00])); // \"1024\"\n * ```\n *\n * @see {@link getBase10Codec}\n */\nexport const getBase10Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-10 strings.\n *\n * This codec serializes strings using a base-10 encoding scheme.\n * The output consists of bytes representing the numerical values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-10 strings.\n *\n * @example\n * Encoding and decoding a base-10 string.\n * ```ts\n * const codec = getBase10Codec();\n * const bytes = codec.encode('1024'); // 0x0400\n * const value = codec.decode(bytes); // \"1024\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-10 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase10Codec(), 5);\n * ```\n *\n * If you need a size-prefixed base-10 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase10Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase10Encoder} and {@link getBase10Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase10Encoder().encode('1024');\n * const value = getBase10Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase10Encoder}\n * @see {@link getBase10Decoder}\n */\nexport const getBase10Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings using bit re-slicing.\n *\n * This encoder serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to an alphabet, and encoding the result into a byte array.\n * This approach is commonly used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeEncoder` for encoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding a base-X string using bit re-slicing.\n * ```ts\n * const encoder = getBaseXResliceEncoder('elho', 2);\n * const bytes = encoder.encode('hellolol'); // 0x4aee\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceEncoder = (alphabet: string, bits: number): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.floor((value.length * bits) / 8),\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n const charIndices = [...value].map(c => alphabet.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-X encoded strings using bit re-slicing.\n *\n * This decoder deserializes base-X encoded strings by re-slicing the bits of a byte array into\n * custom-sized chunks and mapping them to a specified alphabet.\n * This is typically used for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * For more details, see {@link getBaseXResliceCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeDecoder` for decoding base-X strings using bit re-slicing.\n *\n * @example\n * Decoding a base-X string using bit re-slicing.\n * ```ts\n * const decoder = getBaseXResliceDecoder('elho', 2);\n * const value = decoder.decode(new Uint8Array([0x4a, 0xee])); // \"hellolol\"\n * ```\n *\n * @see {@link getBaseXResliceCodec}\n */\nexport const getBaseXResliceDecoder = (alphabet: string, bits: number): VariableSizeDecoder =>\n createDecoder({\n read(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map(i => alphabet[i]).join(''), rawBytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-X strings using bit re-slicing.\n *\n * This codec serializes strings by dividing the input into custom-sized bit chunks,\n * mapping them to a given alphabet, and encoding the result into bytes.\n * It is particularly suited for encoding schemes where the alphabet's length is a power of 2,\n * such as base-16 or base-64.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @param bits - The number of bits per encoded chunk, typically `log2(alphabet.length)`.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings using bit re-slicing.\n *\n * @example\n * Encoding and decoding a base-X string using bit re-slicing.\n * ```ts\n * const codec = getBaseXResliceCodec('elho', 2);\n * const bytes = codec.encode('hellolol'); // 0x4aee\n * const value = codec.decode(bytes); // \"hellolol\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXResliceCodec('elho', 2), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXResliceCodec('elho', 2), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXResliceEncoder} and {@link getBaseXResliceDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXResliceEncoder('elho', 2).encode('hellolol');\n * const value = getBaseXResliceDecoder('elho', 2).decode(bytes);\n * ```\n *\n * @see {@link getBaseXResliceEncoder}\n * @see {@link getBaseXResliceDecoder}\n */\nexport const getBaseXResliceCodec = (alphabet: string, bits: number): VariableSizeCodec =>\n combineCodec(getBaseXResliceEncoder(alphabet, bits), getBaseXResliceDecoder(alphabet, bits));\n\n/** Helper function to reslice the bits inside bytes. */\nfunction reslice(input: number[], inputBits: number, outputBits: number, useRemainder: boolean): number[] {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = (accumulator << inputBits) | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push((accumulator >> bitsInAccumulator) & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push((accumulator << (outputBits - bitsInAccumulator)) & mask);\n }\n return output;\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n toArrayBuffer,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Returns an encoder for base-64 strings.\n *\n * This encoder serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-64 strings.\n *\n * @example\n * Encoding a base-64 string.\n * ```ts\n * const encoder = getBase64Encoder();\n * const bytes = encoder.encode('hello+world'); // 0x85e965a3ec28ae57\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Encoder = (): VariableSizeEncoder => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: 64,\n value,\n });\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return transformEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/**\n * Returns a decoder for base-64 strings.\n *\n * This decoder deserializes base-64 encoded strings from a byte array.\n *\n * For more details, see {@link getBase64Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-64 strings.\n *\n * @example\n * Decoding a base-64 string.\n * ```ts\n * const decoder = getBase64Decoder();\n * const value = decoder.decode(new Uint8Array([0x85, 0xe9, 0x65, 0xa3, 0xec, 0x28, 0xae, 0x57])); // \"hello+world\"\n * ```\n *\n * @see {@link getBase64Codec}\n */\nexport const getBase64Decoder = (): VariableSizeDecoder => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(toArrayBuffer(bytes), offset).toString('base64'), bytes.length],\n });\n }\n\n return transformDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/**\n * Returns a codec for encoding and decoding base-64 strings.\n *\n * This codec serializes strings using a base-64 encoding scheme,\n * commonly used for data encoding in URLs, cryptographic keys, and binary-to-text encoding.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-64 strings.\n *\n * @example\n * Encoding and decoding a base-64 string.\n * ```ts\n * const codec = getBase64Codec();\n * const bytes = codec.encode('hello+world'); // 0x85e965a3ec28ae57\n * const value = codec.decode(bytes); // \"hello+world\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-64 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase64Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-64 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase64Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase64Encoder} and {@link getBase64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase64Encoder().encode('hello+world');\n * const value = getBase64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase64Encoder}\n * @see {@link getBase64Decoder}\n */\nexport const getBase64Codec = (): VariableSizeCodec => combineCodec(getBase64Encoder(), getBase64Decoder());\n","/**\n * Removes all null characters (`\\u0000`) from a string.\n *\n * This function cleans a string by stripping out any null characters,\n * which are often used as padding in fixed-size string encodings.\n *\n * @param value - The string to process.\n * @returns The input string with all null characters removed.\n *\n * @example\n * Removing null characters from a string.\n * ```ts\n * removeNullCharacters('hello\\u0000\\u0000'); // \"hello\"\n * ```\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters (`\\u0000`) at the end to reach a fixed length.\n *\n * If the input string is shorter than the specified length, it is padded with null characters\n * until it reaches the desired size. If it is already long enough, it remains unchanged.\n *\n * @param value - The string to pad.\n * @param chars - The total length of the resulting string, including padding.\n * @returns The input string padded with null characters up to the specified length.\n *\n * @example\n * Padding a string with null characters.\n * ```ts\n * padNullCharacters('hello', 8); // \"hello\\u0000\\u0000\\u0000\"\n * ```\n */\nexport const padNullCharacters = (value: string, chars: number) => value.padEnd(chars, '\\u0000');\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { TextDecoder, TextEncoder } from '@solana/text-encoding-impl';\n\nimport { removeNullCharacters } from './null-characters';\n\n/**\n * Returns an encoder for UTF-8 strings.\n *\n * This encoder serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding UTF-8 strings.\n *\n * @example\n * Encoding a UTF-8 string.\n * ```ts\n * const encoder = getUtf8Encoder();\n * const bytes = encoder.encode('hello'); // 0x68656c6c6f\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Encoder = (): VariableSizeEncoder => {\n let textEncoder: TextEncoder;\n return createEncoder({\n getSizeFromValue: value => (textEncoder ||= new TextEncoder()).encode(value).length,\n write: (value: string, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new TextEncoder()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for UTF-8 strings.\n *\n * This decoder deserializes UTF-8 encoded strings from a byte array.\n * It reads all available bytes starting from the given offset.\n *\n * For more details, see {@link getUtf8Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding UTF-8 strings.\n *\n * @example\n * Decoding a UTF-8 string.\n * ```ts\n * const decoder = getUtf8Decoder();\n * const value = decoder.decode(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // \"hello\"\n * ```\n *\n * @see {@link getUtf8Codec}\n */\nexport const getUtf8Decoder = (): VariableSizeDecoder => {\n let textDecoder: TextDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new TextDecoder()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding UTF-8 strings.\n *\n * This codec serializes strings using UTF-8 encoding.\n * The encoded output contains as many bytes as needed to represent the string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding UTF-8 strings.\n *\n * @example\n * Encoding and decoding a UTF-8 string.\n * ```ts\n * const codec = getUtf8Codec();\n * const bytes = codec.encode('hello'); // 0x68656c6c6f\n * const value = codec.decode(bytes); // \"hello\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size UTF-8 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getUtf8Codec(), 5);\n * ```\n *\n * If you need a size-prefixed UTF-8 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getUtf8Encoder} and {@link getUtf8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getUtf8Encoder().encode('hello');\n * const value = getUtf8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getUtf8Encoder}\n * @see {@link getUtf8Decoder}\n */\nexport const getUtf8Codec = (): VariableSizeCodec => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n","import type { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport type { Lamports } from '@solana/rpc-types';\n\n/**\n * The number of bytes required to store the {@link BaseAccount} information without its data.\n *\n * @example\n * ```ts\n * const myTotalAccountSize = myAccountDataSize + BASE_ACCOUNT_SIZE;\n * ```\n */\nexport const BASE_ACCOUNT_SIZE = 128;\n\n/**\n * Defines the attributes common to all Solana accounts. Namely, it contains everything stored\n * on-chain except the account data itself.\n *\n * @interface\n *\n * @example\n * ```ts\n * const BaseAccount: BaseAccount = {\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type BaseAccount = {\n readonly executable: boolean;\n readonly lamports: Lamports;\n readonly programAddress: Address;\n readonly space: bigint;\n};\n\n/**\n * Contains all the information relevant to a Solana account. It includes the account's address and\n * data, as well as the properties of {@link BaseAccount}.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Encoded\n * const myEncodedAccount: Account = {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n *\n * // Decoded\n * type MyAccountData = { name: string; age: number };\n * const myDecodedAccount: Account = {\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * };\n * ```\n */\nexport type Account = BaseAccount & {\n readonly address: Address;\n readonly data: TData;\n};\n\n/**\n * Represents an encoded account and is equivalent to an {@link Account} with `Uint8Array` account\n * data.\n *\n * @interface\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * {\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * executable: false,\n * lamports: lamports(1_000_000_000n),\n * programAddress: address('1111..1111'),\n * space: 42n,\n * } satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport type EncodedAccount = Account;\n","import type { Decoder, ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,\n SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,\n SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,\n SolanaError,\n} from '@solana/errors';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/**\n * Transforms an {@link EncodedAccount} into an {@link Account} (or a {@link MaybeEncodedAccount}\n * into a {@link MaybeAccount}) by decoding the account data using the provided {@link Decoder}\n * instance.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: EncodedAccount<'1234..5678'>;\n * const myDecoder: Decoder = getStructDecoder([\n * ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n * ['age', getU32Decoder()],\n * ]);\n *\n * const myDecodedAccount = decodeAccount(myAccount, myDecoder);\n * myDecodedAccount satisfies Account;\n * ```\n */\nexport function decodeAccount(\n encodedAccount: EncodedAccount,\n decoder: Decoder,\n): Account;\nexport function decodeAccount(\n encodedAccount: MaybeEncodedAccount,\n decoder: Decoder,\n): MaybeAccount;\nexport function decodeAccount(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n decoder: Decoder,\n): Account | MaybeAccount {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, {\n address: encodedAccount.address,\n });\n }\n}\n\nfunction accountExists(account: Account | MaybeAccount): account is Account {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/**\n * Asserts that an account stores decoded data, ie. not a `Uint8Array`.\n *\n * Note that it does not check the shape of the data matches the decoded type, only that it is not a\n * `Uint8Array`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The type of this account's data.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccount: Account;\n * assertAccountDecoded(myAccount);\n *\n * // now the account data can be used as MyAccountData\n * account.data satisfies MyAccountData;\n * ```\n *\n * This is particularly useful for narrowing the result of fetching a JSON parsed account.\n *\n * ```ts\n * const account: MaybeAccount = await fetchJsonParsedAccount(\n * rpc,\n * '1234..5678' as Address,\n * );\n *\n * assertAccountDecoded(account);\n * // now we have a MaybeAccount\n * account satisfies MaybeAccount;\n * ```\n */\nexport function assertAccountDecoded(\n account: Account,\n): asserts account is Account;\nexport function assertAccountDecoded(\n account: MaybeAccount,\n): asserts account is MaybeAccount;\nexport function assertAccountDecoded(\n account: Account | MaybeAccount,\n): asserts account is Account | MaybeAccount {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, {\n address: account.address,\n });\n }\n}\n\n/**\n * Asserts that all input accounts store decoded data, ie. not a `Uint8Array`.\n *\n * As with {@link assertAccountDecoded} it does not check the shape of the data matches the decoded\n * type, only that it is not a `Uint8Array`.\n *\n * @example\n * ```ts\n * type MyAccountData = { name: string; age: number };\n *\n * const myAccounts: Account[];\n * assertAccountsDecoded(myAccounts);\n *\n * // now the account data can be used as MyAccountData\n * for (const a of account) {\n * account.data satisfies MyAccountData;\n * }\n * ```\n */\nexport function assertAccountsDecoded(\n accounts: Account[],\n): asserts accounts is Account[];\nexport function assertAccountsDecoded(\n accounts: MaybeAccount[],\n): asserts accounts is MaybeAccount[];\nexport function assertAccountsDecoded(\n accounts: (Account | MaybeAccount)[],\n): asserts accounts is (Account | MaybeAccount)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, {\n addresses: encodedAddresses,\n });\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n} from '@solana/rpc-types';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type { JsonParsedDataResponse } from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/**\n * Parses a base64-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase64RpcAccount(\n address: Address,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/**\n * Parses a base58-encoded account provided by the RPC client into an {@link EncodedAccount} type or\n * a {@link MaybeEncodedAccount} type if the raw data can be set to `null`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send();\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount);\n * ```\n */\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount;\nexport function parseBase58RpcAccount(\n address: Address,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount | MaybeEncodedAccount {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse };\ntype ParsedAccountMeta = { program: string; type?: string };\ntype JsonParsedAccountData = TData & { parsedAccountMeta?: ParsedAccountMeta };\n\n/**\n * Parses an arbitrary `jsonParsed` account provided by the RPC client into an {@link Account} type\n * or a {@link MaybeAccount} type if the raw data can be set to `null`.\n *\n * The expected data type should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * const myAccount: Account = parseJsonRpcAccount(myJsonRpcAccount);\n * ```\n */\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount,\n): Account, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount, TAddress>;\nexport function parseJsonRpcAccount(\n address: Address,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account, TAddress> | MaybeAccount, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = (rpcAccount.data.parsed.info || {}) as TData;\n\n if (rpcAccount.data.program || rpcAccount.data.parsed.type) {\n (data as JsonParsedAccountData).parsedAccountMeta = {\n program: rpcAccount.data.program,\n type: rpcAccount.data.parsed.type,\n };\n }\n\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n space: rpcAccount.space,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Rpc } from '@solana/rpc-spec';\nimport type { Commitment, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/**\n * Optional configuration for fetching a singular account.\n *\n * @interface\n */\nexport type FetchAccountConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the account as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches a {@link MaybeEncodedAccount} from the provided RPC client and address.\n *\n * It uses the {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} RPC method under the hood\n * with base64 encoding and an additional configuration object can be provided to customize the\n * behavior of the RPC call.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * const myAddress = address('1234..5678');\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress);\n *\n * // With custom configuration.\n * const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/**\n * Fetches a {@link MaybeAccount} from the provided RPC client and address by using\n * {@link GetAccountInfoApi.getAccountInfo | getAccountInfo} under the hood with the `jsonParsed`\n * encoding.\n *\n * It may also return a {@link MaybeEncodedAccount} if the RPC client does not know how to parse the\n * account at the requested address. In any case, the expected data type should be explicitly\n * provided as the first type parameter.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The expected type of this account's data.\n *\n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress);\n * myAccount satisfies MaybeAccount | MaybeEncodedAccount;\n *\n * // With custom configuration.\n * const myAccount = await fetchJsonParsedAccount(rpc, myAddress, {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchJsonParsedAccount(\n rpc: Rpc,\n address: Address,\n config: FetchAccountConfig = {},\n): Promise<\n | MaybeAccount\n | MaybeEncodedAccount\n> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(address, account as Parameters[1])\n : parseBase64RpcAccount(address, account as Parameters[1]);\n}\n\n/**\n * Optional configuration for fetching multiple accounts.\n *\n * @interface\n */\nexport type FetchAccountsConfig = {\n abortSignal?: AbortSignal;\n /**\n * Fetch the details of the accounts as of the highest slot that has reached this level of\n * commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\n/**\n * Fetches an array of {@link MaybeEncodedAccount | MaybeEncodedAccounts} from the provided RPC\n * client and an array of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with base64 encodings and an additional configuration object can be provided to\n * customize the behavior of the RPC call.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n *\n * @example\n * ```ts\n * const myAddressA = address('1234..5678');\n * const myAddressB = address('8765..4321');\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeEncodedAccount<'1234..5678'>;\n * myAccountB satisfies MaybeEncodedAccount<'8765..4321'>;\n *\n * // With custom configuration.\n * const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], {\n * abortSignal: myAbortController.signal,\n * commitment: 'confirmed',\n * });\n * ```\n */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount;\n };\n}\n\n/**\n * Fetches an array of {@link MaybeAccount | MaybeAccounts} from a provided RPC client and an array\n * of addresses.\n *\n * It uses the {@link GetMultipleAccountsApi#getMultipleAccounts | getMultipleAccounts} RPC method\n * under the hood with the `jsonParsed` encoding. It may also return a\n * {@link MaybeEncodedAccount} instead of the expected {@link MaybeAccount} if the RPC client does\n * not know how to parse some of the requested accounts. In any case, the array of expected data\n * types should be explicitly provided as the first type parameter.\n *\n * @typeParam TAddresses - Supply an array of string literals to define accounts having particular\n * addresses.\n * @typeParam TData - The expected types of these accounts' data.\n \n * @example\n * ```ts\n * type TokenData = { mint: Address; owner: Address };\n * type MintData = { supply: bigint };\n * const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]);\n * myAccountA satisfies MaybeAccount | MaybeEncodedAccount;\n * myAccountB satisfies MaybeAccount | MaybeEncodedAccount;\n * ```\n */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address } = {\n [P in keyof TAddresses]: Address;\n },\n>(rpc: Rpc, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters[1]);\n }) as {\n [P in keyof TAddresses]:\n | MaybeAccount<\n TData[P & keyof TData] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P]\n >\n | MaybeEncodedAccount;\n } & {\n [P in keyof TData]:\n | MaybeAccount<\n TData[P] & { parsedAccountMeta?: { program: string; type?: string } },\n TAddresses[P & keyof TAddresses]\n >\n | MaybeEncodedAccount;\n };\n}\n","import { Address } from '@solana/addresses';\nimport {\n SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,\n SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\n\nimport { Account } from './account';\n\n/**\n * Represents an account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type with an additional `exists`\n * attribute set to `true`. When it does not exist, it is represented by an object containing only\n * the address of the account and an `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * // Account exists\n * const myExistingAccount: MaybeAccount = {\n * exists: true,\n * address: address('1234..5678'),\n * data: { name: 'Alice', age: 30 },\n * // ...\n * };\n *\n * // Account does not exist\n * const myMissingAccount: MaybeAccount = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeAccount =\n | { readonly address: Address; readonly exists: false }\n | (Account & { readonly exists: true });\n\n/**\n * Represents an encoded account that may or may not exist on-chain.\n *\n * When the account exists, it is represented as an {@link Account} type having its `TData` type\n * parameter set to `Uint8Array` with an additional `exists` attribute set to `true`. When it does\n * not exist, it is represented by an object containing only the address of the account and an\n * `exists` attribute set to `false`.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n *\n * @example\n * ```ts\n * // Encoded account exists\n * const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = {\n * exists: true,\n * address: address('1234..5678'),\n * data: new Uint8Array([1, 2, 3]),\n * // ...\n * };\n *\n * // Encoded account does not exist\n * const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = {\n * exists: false,\n * address: address('8765..4321'),\n * };\n * ```\n */\nexport type MaybeEncodedAccount = MaybeAccount;\n\n/**\n * Given a {@link MaybeAccount}, asserts that the account exists and allows it to be used as an\n * {@link Account} type going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccount: MaybeEncodedAccount<'1234..5678'>;\n * assertAccountExists(myAccount);\n *\n * // Now we can use myAccount as an `EncodedAccount`\n * myAccount satisfies EncodedAccount<'1234..5678'>;\n * ```\n */\nexport function assertAccountExists(\n account: MaybeAccount,\n): asserts account is Account & { exists: true } {\n if (!account.exists) {\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, { address: account.address });\n }\n}\n\n/**\n * Given an array of {@link MaybeAccount | MaybeAccounts}, asserts that all the accounts exist and\n * allows them to be used as an array of {@link Account | Accounts} going forward.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TData - The nature of this account's data. It can be represented as either a\n * `Uint8Array` – meaning the account is encoded – or a custom data type – meaning\n * the account is decoded.\n *\n * @example\n * ```ts\n * const myAccounts: MaybeEncodedAccount

[];\n * assertAccountsExist(myAccounts);\n *\n * // Now we can use them as an array of `EncodedAccounts`\n * for (const a of myAccounts) {\n * a satisfies EncodedAccount
;\n * }\n * ```\n */\nexport function assertAccountsExist(\n accounts: MaybeAccount[],\n): asserts accounts is (Account & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, { addresses: missingAddresses });\n }\n}\n","import { SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SolanaError } from '@solana/errors';\n\n/**\n * Throws an exception unless {@link Crypto#getRandomValues | `crypto.getRandomValues()`} is\n * available in the current JavaScript environment.\n */\nexport function assertPRNGIsAvailable() {\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.getRandomValues !== 'function') {\n throw new SolanaError(SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,\n SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,\n SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,\n SolanaError,\n} from '@solana/errors';\n\nfunction assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT);\n }\n}\n\nlet cachedEd25519Decision: PromiseLike | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .then(() => {\n resolve((cachedEd25519Decision = true));\n })\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#digest | `crypto.subtle.digest()`} is available in\n * the current JavaScript environment.\n */\nexport function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#generateKey | `crypto.subtle.generateKey()`} is\n * available in the current JavaScript environment and has support for the Ed25519 curve.\n */\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED);\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#exportKey | `crypto.subtle.exportKey()`} is\n * available in the current JavaScript environment.\n */\nexport function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);\n }\n}\n\n/**\n * Throws an exception unless {@link SubtleCrypto#sign | `crypto.subtle.sign()`} is available in the\n * current JavaScript environment.\n */\nexport function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);\n }\n}\n/**\n * Throws an exception unless {@link SubtleCrypto#verify | `crypto.subtle.verify()`} is available in\n * the current JavaScript environment.\n */\nexport function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);\n }\n}\n","import {\n combineCodec,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * Represents a string that validates as a Solana address. Functions that require well-formed\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an arbitrary string as a base58-encoded address, use the\n * {@link address}, {@link assertIsAddress}, or {@link isAddress} functions in this package.\n */\nexport type Address = Brand, 'Address'>;\n\nlet memoizedBase58Encoder: Encoder | undefined;\nlet memoizedBase58Decoder: Decoder | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Address} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAddress } from '@solana/addresses';\n *\n * if (isAddress(ownerAddress)) {\n * // At this point, `ownerAddress` has been refined to a\n * // `Address` that can be used with the RPC.\n * const { value: lamports } = await rpc.getBalance(ownerAddress).send();\n * setBalanceLamports(lamports);\n * } else {\n * setError(`${ownerAddress} is not an address`);\n * }\n * ```\n */\nexport function isAddress(putativeAddress: string): putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n try {\n return base58Encoder.encode(putativeAddress).byteLength === 32;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an address or public\n * key, from an untrusted network API or user input. Use this function to assert that such an\n * arbitrary string is a base58-encoded address.\n *\n * @example\n * ```ts\n * import { assertIsAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // At this point, `address` is an `Address` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out not to be a base58-encoded address\n * }\n * }\n * ```\n */\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * Combines _asserting_ that a string is an address with _coercing_ it to the {@link Address} type.\n * It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good address as a string, it's more efficient to typecast it rather\n * than to use the {@link address} helper, because the helper unconditionally performs validation on\n * its input.\n * >\n * > ```ts\n * > import { Address } from '@solana/addresses';\n * >\n * > const MEMO_PROGRAM_ADDRESS =\n * > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;\n * > ```\n */\nexport function address(putativeAddress: TAddress): Address {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded address to a byte array.\n *\n * @example\n * ```ts\n * import { getAddressEncoder } from '@solana/addresses';\n *\n * const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;\n * const addressEncoder = getAddressEncoder();\n * const addressBytes = addressEncoder.encode(address);\n * // Uint8Array(32) [\n * // 150, 183, 190, 48, 171, 8, 39, 156,\n * // 122, 213, 172, 108, 193, 95, 26, 158,\n * // 149, 243, 115, 254, 20, 200, 36, 30,\n * // 248, 179, 178, 232, 220, 89, 53, 127\n * // ]\n * ```\n */\nexport function getAddressEncoder(): FixedSizeEncoder {\n return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), putativeAddress =>\n address(putativeAddress),\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an address to the\n * base58-encoded representation of that address.\n *\n * @example\n * ```ts\n * import { getAddressDecoder } from '@solana/addresses';\n *\n * const addressBytes = new Uint8Array([\n * 150, 183, 190, 48, 171, 8, 39, 156,\n * 122, 213, 172, 108, 193, 95, 26, 158,\n * 149, 243, 115, 254, 20, 200, 36, 30,\n * 248, 179, 178, 232, 220, 89, 53, 127\n * ]);\n * const addressDecoder = getAddressDecoder();\n * const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka\n * ```\n */\nexport function getAddressDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded address.\n *\n * @see {@link getAddressDecoder}\n * @see {@link getAddressEncoder}\n */\nexport function getAddressCodec(): FixedSizeCodec {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\n\nimport { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: ReadonlyUint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport function compressedPointBytesAreOnCurve(bytes: ReadonlyUint8Array): boolean {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SolanaError } from '@solana/errors';\nimport type { AffinePoint } from '@solana/nominal-types';\n\nimport { type Address, getAddressCodec } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * Represents an {@link Address} that validates as being off-curve. Functions that require off-curve\n * addresses should specify their inputs in terms of this type.\n *\n * Whenever you need to validate an address as being off-curve, use the {@link offCurveAddress},\n * {@link assertIsOffCurveAddress}, or {@link isOffCurveAddress} functions in this package.\n */\nexport type OffCurveAddress = AffinePoint, 'invalid'>;\n\n/**\n * A type guard that returns `true` if the input address conforms to the {@link OffCurveAddress}\n * type, and refines its type for use in your application.\n *\n * @example\n * ```ts\n * import { isOffCurveAddress } from '@solana/addresses';\n *\n * if (isOffCurveAddress(accountAddress)) {\n * // At this point, `accountAddress` has been refined to a\n * // `OffCurveAddress` that can be used within your business logic.\n * const { value: account } = await rpc.getAccountInfo(accountAddress).send();\n * } else {\n * setError(`${accountAddress} is not off-curve`);\n * }\n * ```\n */\nexport function isOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): putativeOffCurveAddress is OffCurveAddress {\n const addressBytes = getAddressCodec().encode(putativeOffCurveAddress);\n return compressedPointBytesAreOnCurve(addressBytes) === false;\n}\n\n/**\n * From time to time you might acquire an {@link Address}, that you expect to validate as an\n * off-curve address, from an untrusted source. Use this function to assert that such an address is\n * off-curve.\n *\n * @example\n * ```ts\n * import { assertIsOffCurveAddress } from '@solana/addresses';\n *\n * // Imagine a function that fetches an account's balance when a user submits a form.\n * function handleSubmit() {\n * // We know only that the input conforms to the `string` type.\n * const address: string = accountAddressInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `Address`.\n * assertIsAddress(address);\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `address` to `OffCurveAddress`.\n * assertIsOffCurveAddress(address);\n * // At this point, `address` is an `OffCurveAddress` that can be used with the RPC.\n * const balanceInLamports = await rpc.getBalance(address).send();\n * } catch (e) {\n * // `address` turned out to NOT be a base58-encoded off-curve address\n * }\n * }\n * ```\n */\nexport function assertIsOffCurveAddress(\n putativeOffCurveAddress: TAddress,\n): asserts putativeOffCurveAddress is OffCurveAddress {\n if (!isOffCurveAddress(putativeOffCurveAddress)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS);\n }\n}\n\n/**\n * Combines _asserting_ that an {@link Address} is off-curve with _coercing_ it to the\n * {@link OffCurveAddress} type. It's most useful with untrusted input.\n */\nexport function offCurveAddress(\n putativeOffCurveAddress: TAddress,\n): OffCurveAddress {\n assertIsOffCurveAddress(putativeOffCurveAddress);\n return putativeOffCurveAddress;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\nimport { bytesEqual, type ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nimport { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve-internal';\n\n/**\n * A tuple representing a program derived address (derived from the address of some program and a\n * set of seeds) and the associated bump seed used to ensure that the address, as derived, does not\n * fall on the Ed25519 curve.\n *\n * Whenever you need to validate an arbitrary tuple as one that represents a program derived\n * address, use the {@link assertIsProgramDerivedAddress} or {@link isProgramDerivedAddress}\n * functions in this package.\n */\nexport type ProgramDerivedAddress = Readonly<\n [Address, ProgramDerivedAddressBump]\n>;\n\n/**\n * Represents an integer in the range [0,255] used in the derivation of a program derived address to\n * ensure that it does not fall on the Ed25519 curve.\n */\nexport type ProgramDerivedAddressBump = Brand;\n\n/**\n * A type guard that returns `true` if the input tuple conforms to the {@link ProgramDerivedAddress}\n * type, and refines its type for use in your program.\n *\n * @see The {@link isAddress} function for an example of how to use a type guard.\n */\nexport function isProgramDerivedAddress(\n value: unknown,\n): value is ProgramDerivedAddress {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * In the event that you receive an address/bump-seed tuple from some untrusted source, use this\n * function to assert that it conforms to the {@link ProgramDerivedAddress} interface.\n *\n * @see The {@link assertIsAddress} function for an example of how to use an assertion function.\n */\nexport function assertIsProgramDerivedAddress(\n value: unknown,\n): asserts value is ProgramDerivedAddress {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {\n bump: value[1],\n });\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = ReadonlyUint8Array | string;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise
{\n assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {\n actual: seeds.length,\n maxSeeds: MAX_SEEDS,\n });\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: bytes.byteLength,\n index: ii,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (compressedPointBytesAreOnCurve(addressBytes)) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\n\n/**\n * Given a program's {@link Address} and up to 16 {@link Seed | Seeds}, this method will return the\n * program derived address (PDA) associated with each.\n *\n * @example\n * ```ts\n * import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses';\n *\n * const addressEncoder = getAddressEncoder();\n * const [pda, bumpSeed] = await getProgramDerivedAddress({\n * programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address,\n * seeds: [\n * // Owner\n * addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address),\n * // Token program\n * addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address),\n * // Mint\n * addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address),\n * ],\n * });\n * ```\n */\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);\n}\n\n/**\n * Returns a base58-encoded address derived from some base address, some program address, and a seed\n * string or byte array.\n *\n * @example\n * ```ts\n * import { createAddressWithSeed } from '@solana/addresses';\n *\n * const derivedAddress = await createAddressWithSeed({\n * // The private key associated with this address will be able to sign for `derivedAddress`.\n * baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address,\n * // Only this program will be able to write data to this account.\n * programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address,\n * seed: 'data-account',\n * });\n * ```\n */\nexport async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise
{\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: seedBytes.byteLength,\n index: 0,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES.length), new Uint8Array(PDA_MARKER_BYTES))\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';\n\nimport { Address, getAddressDecoder, getAddressEncoder } from './address';\n\n/**\n * Given a public {@link CryptoKey}, this method will return its associated {@link Address}.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const address = await getAddressFromPublicKey(publicKey);\n * ```\n */\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise
{\n assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n\n/**\n * Given an {@link Address}, return a {@link CryptoKey} that can be used to verify signatures.\n *\n * @example\n * ```ts\n * import { getAddressFromPublicKey } from '@solana/addresses';\n *\n * const publicKey = await getPublicKeyFromAddress(address);\n * ```\n */\nexport async function getPublicKeyFromAddress(address: Address) {\n const addressBytes = getAddressEncoder().encode(address);\n return await crypto.subtle.importKey('raw', addressBytes, { name: 'Ed25519' }, true /* extractable */, ['verify']);\n}\n","import { SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\n/**\n * Ensures that a given number falls within a specified range.\n *\n * If the number is outside the allowed range, an error is thrown.\n * This function is primarily used to validate values before encoding them in a codec.\n *\n * @param codecDescription - A string describing the codec that is performing the validation.\n * @param min - The minimum allowed value (inclusive).\n * @param max - The maximum allowed value (inclusive).\n * @param value - The number to validate.\n *\n * @throws {@link SolanaError} if the value is out of range.\n *\n * @example\n * Validating a number within range.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 42); // Passes\n * ```\n *\n * @example\n * Throwing an error for an out-of-range value.\n * ```ts\n * assertNumberIsBetweenForCodec('u8', 0, 255, 300); // Throws\n * ```\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: bigint | number,\n max: bigint | number,\n value: bigint | number,\n) {\n if (value < min || value > max) {\n throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {\n codecDescription,\n max,\n min,\n value,\n });\n }\n}\n","import { Codec, Decoder, Encoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n/**\n * Represents an encoder for numbers and bigints.\n *\n * This type allows encoding values that are either `number` or `bigint`.\n * Depending on the specific implementation, the encoded output may have a fixed or variable size.\n *\n * @see {@link FixedSizeNumberEncoder}\n */\nexport type NumberEncoder = Encoder;\n\n/**\n * Represents a fixed-size encoder for numbers and bigints.\n *\n * This encoder serializes values using an exact number of bytes, defined by `TSize`.\n *\n * @typeParam TSize - The number of bytes used for encoding.\n *\n * @see {@link NumberEncoder}\n */\nexport type FixedSizeNumberEncoder = FixedSizeEncoder;\n\n/**\n * Represents a decoder for numbers and bigints.\n *\n * This type supports decoding values as either `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberDecoder}\n */\nexport type NumberDecoder = Decoder | Decoder;\n\n/**\n * Represents a fixed-size decoder for numbers and bigints.\n *\n * This decoder reads a fixed number of bytes (`TSize`) and converts them into a `number` or `bigint`.\n *\n * @typeParam TSize - The number of bytes expected for decoding.\n *\n * @see {@link NumberDecoder}\n */\nexport type FixedSizeNumberDecoder =\n | FixedSizeDecoder\n | FixedSizeDecoder;\n\n/**\n * Represents a codec for encoding and decoding numbers and bigints.\n *\n * - The encoded value can be either a `number` or a `bigint`.\n * - The decoded value will always be either a `number` or `bigint`, depending on the implementation.\n *\n * @see {@link FixedSizeNumberCodec}\n */\nexport type NumberCodec = Codec | Codec;\n\n/**\n * Represents a fixed-size codec for encoding and decoding numbers and bigints.\n *\n * This codec uses a specific number of bytes (`TSize`) for serialization.\n * The encoded value can be either a `number` or `bigint`, but the decoded value will always be a `number` or `bigint`,\n * depending on the implementation.\n *\n * @typeParam TSize - The number of bytes used for encoding and decoding.\n *\n * @see {@link NumberCodec}\n */\nexport type FixedSizeNumberCodec =\n | FixedSizeCodec\n | FixedSizeCodec;\n\n/**\n * Configuration options for number codecs that use more than one byte.\n *\n * This configuration applies to all number codecs except `u8` and `i8`,\n * allowing the user to specify the endianness of serialization.\n */\nexport type NumberCodecConfig = {\n /**\n * Specifies whether numbers should be encoded in little-endian or big-endian format.\n *\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the byte order used for number serialization.\n *\n * - `Little`: The least significant byte is stored first.\n * - `Big`: The most significant byte is stored first.\n */\nexport enum Endian {\n Little,\n Big,\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n toArrayBuffer,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput = {\n config?: NumberCodecConfig;\n name: string;\n size: TSize;\n};\n\ntype NumberFactoryEncoderInput = NumberFactorySharedInput & {\n range?: [bigint | number, bigint | number];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.Big ? false : true;\n}\n\nexport function numberEncoderFactory(\n input: NumberFactoryEncoderInput,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory(\n input: NumberFactoryDecoderInput,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\n });\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit floating-point numbers (`f32`).\n *\n * This encoder serializes `f32` values using 4 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f32` values.\n *\n * @example\n * Encoding an `f32` value.\n * ```ts\n * const encoder = getF32Encoder();\n * const bytes = encoder.encode(-1.5); // 0x0000c0bf\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit floating-point numbers (`f32`).\n *\n * This decoder deserializes `f32` values from 4 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f32` values.\n *\n * @example\n * Decoding an `f32` value.\n * ```ts\n * const decoder = getF32Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF32Codec}\n */\nexport const getF32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`).\n *\n * This codec serializes `f32` values using 4 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f32` values.\n *\n * @example\n * Encoding and decoding an `f32` value.\n * ```ts\n * const codec = getF32Codec();\n * const bytes = codec.encode(-1.5); // 0x0000c0bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbfc00000\n * ```\n *\n * @remarks\n * `f32` values follow the IEEE 754 single-precision floating-point standard.\n * Precision loss may occur for certain values.\n *\n * - If you need higher precision, consider using {@link getF64Codec}.\n * - If you need integer values, consider using {@link getI32Codec} or {@link getU32Codec}.\n *\n * Separate {@link getF32Encoder} and {@link getF32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF32Encoder().encode(-1.5);\n * const value = getF32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF32Encoder}\n * @see {@link getF32Decoder}\n */\nexport const getF32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit floating-point numbers (`f64`).\n *\n * This encoder serializes `f64` values using 8 bytes.\n * Floating-point values may lose precision when encoded.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `f64` values.\n *\n * @example\n * Encoding an `f64` value.\n * ```ts\n * const encoder = getF64Encoder();\n * const bytes = encoder.encode(-1.5); // 0x000000000000f8bf\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'f64',\n set: (view, value, le) => view.setFloat64(0, Number(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit floating-point numbers (`f64`).\n *\n * This decoder deserializes `f64` values from 8 bytes.\n * Some precision may be lost during decoding due to floating-point representation.\n *\n * For more details, see {@link getF64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `f64` values.\n *\n * @example\n * Decoding an `f64` value.\n * ```ts\n * const decoder = getF64Decoder();\n * const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5\n * ```\n *\n * @see {@link getF64Codec}\n */\nexport const getF64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat64(0, le),\n name: 'f64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`).\n *\n * This codec serializes `f64` values using 8 bytes.\n * Due to the IEEE 754 floating-point representation, some precision loss may occur.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `f64` values.\n *\n * @example\n * Encoding and decoding an `f64` value.\n * ```ts\n * const codec = getF64Codec();\n * const bytes = codec.encode(-1.5); // 0x000000000000f8bf\n * const value = codec.decode(bytes); // -1.5\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getF64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-1.5); // 0xbff8000000000000\n * ```\n *\n * @remarks\n * `f64` values follow the IEEE 754 double-precision floating-point standard.\n * Precision loss may still occur but is significantly lower than `f32`.\n *\n * - If you need smaller floating-point values, consider using {@link getF32Codec}.\n * - If you need integer values, consider using {@link getI64Codec} or {@link getU64Codec}.\n *\n * Separate {@link getF64Encoder} and {@link getF64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getF64Encoder().encode(-1.5);\n * const value = getF64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getF64Encoder}\n * @see {@link getF64Decoder}\n */\nexport const getF64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getF64Encoder(config), getF64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit signed integers (`i128`).\n *\n * This encoder serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i128` values.\n *\n * @example\n * Encoding an `i128` value.\n * ```ts\n * const encoder = getI128Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i128',\n range: [-BigInt('0x7fffffffffffffffffffffffffffffff') - 1n, BigInt('0x7fffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit signed integers (`i128`).\n *\n * This decoder deserializes `i128` values from 16 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI128Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i128` values.\n *\n * @example\n * Decoding an `i128` value.\n * ```ts\n * const decoder = getI128Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n * 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI128Codec}\n */\nexport const getI128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigInt64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'i128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit signed integers (`i128`).\n *\n * This codec serializes `i128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i128` values.\n *\n * @example\n * Encoding and decoding an `i128` value.\n * ```ts\n * const codec = getI128Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffffffffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^127` and `2^127 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI64Codec} or {@link getI32Codec}.\n * - If you need a larger signed integer, consider using a custom codec.\n * - If you need unsigned integers, consider using {@link getU128Codec}.\n *\n * Separate {@link getI128Encoder} and {@link getI128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI128Encoder().encode(-42);\n * const value = getI128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI128Encoder}\n * @see {@link getI128Decoder}\n */\nexport const getI128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI128Encoder(config), getI128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit signed integers (`i16`).\n *\n * This encoder serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i16` values.\n *\n * @example\n * Encoding an `i16` value.\n * ```ts\n * const encoder = getI16Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ff\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i16',\n range: [-Number('0x7fff') - 1, Number('0x7fff')],\n set: (view, value, le) => view.setInt16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit signed integers (`i16`).\n *\n * This decoder deserializes `i16` values from 2 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI16Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i16` values.\n *\n * @example\n * Decoding an `i16` value.\n * ```ts\n * const decoder = getI16Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff])); // -42\n * ```\n *\n * @see {@link getI16Codec}\n */\nexport const getI16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt16(0, le),\n name: 'i16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit signed integers (`i16`).\n *\n * This codec serializes `i16` values using 2 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i16` values.\n *\n * @example\n * Encoding and decoding an `i16` value.\n * ```ts\n * const codec = getI16Codec();\n * const bytes = codec.encode(-42); // 0xd6ff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^15` (`-32,768`) and `2^15 - 1` (`32,767`).\n *\n * - If you need a smaller signed integer, consider using {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI32Codec}.\n * - If you need unsigned integers, consider using {@link getU16Codec}.\n *\n * Separate {@link getI16Encoder} and {@link getI16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI16Encoder().encode(-42);\n * const value = getI16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI16Encoder}\n * @see {@link getI16Decoder}\n */\nexport const getI16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI16Encoder(config), getI16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit signed integers (`i32`).\n *\n * This encoder serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i32` values.\n *\n * @example\n * Encoding an `i32` value.\n * ```ts\n * const encoder = getI32Encoder();\n * const bytes = encoder.encode(-42); // 0xd6ffffff\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i32',\n range: [-Number('0x7fffffff') - 1, Number('0x7fffffff')],\n set: (view, value, le) => view.setInt32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit signed integers (`i32`).\n *\n * This decoder deserializes `i32` values from 4 bytes.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI32Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i32` values.\n *\n * @example\n * Decoding an `i32` value.\n * ```ts\n * const decoder = getI32Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6, 0xff, 0xff, 0xff])); // -42\n * ```\n *\n * @see {@link getI32Codec}\n */\nexport const getI32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getInt32(0, le),\n name: 'i32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit signed integers (`i32`).\n *\n * This codec serializes `i32` values using 4 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i32` values.\n *\n * @example\n * Encoding and decoding an `i32` value.\n * ```ts\n * const codec = getI32Codec();\n * const bytes = codec.encode(-42); // 0xd6ffffff\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42); // 0xffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^31` (`-2,147,483,648`) and `2^31 - 1` (`2,147,483,647`).\n *\n * - If you need a smaller signed integer, consider using {@link getI16Codec} or {@link getI8Codec}.\n * - If you need a larger signed integer, consider using {@link getI64Codec}.\n * - If you need unsigned integers, consider using {@link getU32Codec}.\n *\n * Separate {@link getI32Encoder} and {@link getI32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI32Encoder().encode(-42);\n * const value = getI32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI32Encoder}\n * @see {@link getI32Decoder}\n */\nexport const getI32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI32Encoder(config), getI32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit signed integers (`i64`).\n *\n * This encoder serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `i64` values.\n *\n * @example\n * Encoding an `i64` value.\n * ```ts\n * const encoder = getI64Encoder();\n * const bytes = encoder.encode(-42n); // 0xd6ffffffffffffff\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'i64',\n range: [-BigInt('0x7fffffffffffffff') - 1n, BigInt('0x7fffffffffffffff')],\n set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit signed integers (`i64`).\n *\n * This decoder deserializes `i64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getI64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `i64` values.\n *\n * @example\n * Decoding an `i64` value.\n * ```ts\n * const decoder = getI64Decoder();\n * const value = decoder.decode(new Uint8Array([\n * 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n * ])); // -42n\n * ```\n *\n * @see {@link getI64Codec}\n */\nexport const getI64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigInt64(0, le),\n name: 'i64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit signed integers (`i64`).\n *\n * This codec serializes `i64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `i64` values.\n *\n * @example\n * Encoding and decoding an `i64` value.\n * ```ts\n * const codec = getI64Codec();\n * const bytes = codec.encode(-42n); // 0xd6ffffffffffffff\n * const value = codec.decode(bytes); // -42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getI64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(-42n); // 0xffffffffffffffd6\n * ```\n *\n * @remarks\n * This codec supports values between `-2^63` and `2^63 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller signed integer, consider using {@link getI32Codec} or {@link getI16Codec}.\n * - If you need a larger signed integer, consider using {@link getI128Codec}.\n * - If you need unsigned integers, consider using {@link getU64Codec}.\n *\n * Separate {@link getI64Encoder} and {@link getI64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI64Encoder().encode(-42);\n * const value = getI64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI64Encoder}\n * @see {@link getI64Decoder}\n */\nexport const getI64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getI64Encoder(config), getI64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit signed integers (`i8`).\n *\n * This encoder serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `i8` values.\n *\n * @example\n * Encoding an `i8` value.\n * ```ts\n * const encoder = getI8Encoder();\n * const bytes = encoder.encode(-42); // 0xd6\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'i8',\n range: [-Number('0x7f') - 1, Number('0x7f')],\n set: (view, value) => view.setInt8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit signed integers (`i8`).\n *\n * This decoder deserializes `i8` values from 1 byte.\n * The decoded value is always a `number`.\n *\n * For more details, see {@link getI8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `i8` values.\n *\n * @example\n * Decoding an `i8` value.\n * ```ts\n * const decoder = getI8Decoder();\n * const value = decoder.decode(new Uint8Array([0xd6])); // -42\n * ```\n *\n * @see {@link getI8Codec}\n */\nexport const getI8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getInt8(0),\n name: 'i8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit signed integers (`i8`).\n *\n * This codec serializes `i8` values using 1 byte.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `i8` values.\n *\n * @example\n * Encoding and decoding an `i8` value.\n * ```ts\n * const codec = getI8Codec();\n * const bytes = codec.encode(-42); // 0xd6\n * const value = codec.decode(bytes); // -42\n * ```\n *\n * @remarks\n * This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`).\n *\n * - If you need a larger signed integer, consider using {@link getI16Codec}.\n * - If you need an unsigned integer, consider using {@link getU8Codec}.\n *\n * Separate {@link getI8Encoder} and {@link getI8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getI8Encoder().encode(-42);\n * const value = getI8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getI8Encoder}\n * @see {@link getI8Decoder}\n */\nexport const getI8Codec = (): FixedSizeCodec =>\n combineCodec(getI8Encoder(), getI8Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n Offset,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\n\n/**\n * Returns an encoder for `shortU16` values.\n *\n * This encoder serializes `shortU16` values using **1 to 3 bytes**.\n * Smaller values use fewer bytes, while larger values take up more space.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding `shortU16` values.\n *\n * @example\n * Encoding a `shortU16` value.\n * ```ts\n * const encoder = getShortU16Encoder();\n * encoder.encode(42); // 0x2a\n * encoder.encode(128); // 0x8001\n * encoder.encode(16384); // 0x808001\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: bigint | number): number => {\n if (value <= 0b01111111) return 1;\n if (value <= 0b0011111111111111) return 2;\n return 3;\n },\n maxSize: 3,\n write: (value: bigint | number, bytes: Uint8Array, offset: Offset): Offset => {\n assertNumberIsBetweenForCodec('shortU16', 0, 65535, value);\n const shortU16Bytes = [0];\n for (let ii = 0; ; ii += 1) {\n // Shift the bits of the value over such that the next 7 bits are at the right edge.\n const alignedValue = Number(value) >> (ii * 7);\n if (alignedValue === 0) {\n // No more bits to consume.\n break;\n }\n // Extract those 7 bits using a mask.\n const nextSevenBits = 0b1111111 & alignedValue;\n shortU16Bytes[ii] = nextSevenBits;\n if (ii > 0) {\n // Set the continuation bit of the previous slice.\n shortU16Bytes[ii - 1] |= 0b10000000;\n }\n }\n bytes.set(shortU16Bytes, offset);\n return offset + shortU16Bytes.length;\n },\n });\n\n/**\n * Returns a decoder for `shortU16` values.\n *\n * This decoder deserializes `shortU16` values from **1 to 3 bytes**.\n * The number of bytes used depends on the encoded value.\n *\n * For more details, see {@link getShortU16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding `shortU16` values.\n *\n * @example\n * Decoding a `shortU16` value.\n * ```ts\n * const decoder = getShortU16Decoder();\n * decoder.decode(new Uint8Array([0x2a])); // 42\n * decoder.decode(new Uint8Array([0x80, 0x01])); // 128\n * decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384\n * ```\n *\n * @see {@link getShortU16Codec}\n */\nexport const getShortU16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n maxSize: 3,\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset): [number, Offset] => {\n let value = 0;\n let byteCount = 0;\n while (++byteCount) {\n const byteIndex = byteCount - 1;\n const currentByte = bytes[offset + byteIndex];\n const nextSevenBits = 0b1111111 & currentByte;\n // Insert the next group of seven bits into the correct slot of the output value.\n value |= nextSevenBits << (byteIndex * 7);\n if ((currentByte & 0b10000000) === 0) {\n // This byte does not have its continuation bit set. We're done.\n break;\n }\n }\n return [value, offset + byteCount];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding `shortU16` values.\n *\n * It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.\n * The larger the value, the more bytes it uses.\n *\n * - If the value is `<= 0x7f` (127), it is stored in a **single byte**\n * and the first bit is set to `0` to indicate the end of the value.\n * - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.\n * - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.\n *\n * In other words, the encoding scheme follows this structure:\n *\n * ```txt\n * 0XXXXXXX <- Values 0 to 127 (1 byte)\n * 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)\n * 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)\n * ```\n *\n * @returns A `VariableSizeCodec` for encoding and decoding `shortU16` values.\n *\n * @example\n * Encoding and decoding `shortU16` values.\n * ```ts\n * const codec = getShortU16Codec();\n * const bytes1 = codec.encode(42); // 0x2a\n * const bytes2 = codec.encode(128); // 0x8001\n * const bytes3 = codec.encode(16384); // 0x808001\n *\n * codec.decode(bytes1); // 42\n * codec.decode(bytes2); // 128\n * codec.decode(bytes3); // 16384\n * ```\n *\n * @remarks\n * This codec efficiently stores small numbers, making it useful for transactions and compact representations.\n *\n * If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.\n *\n * Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getShortU16Encoder().encode(42);\n * const value = getShortU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getShortU16Encoder}\n * @see {@link getShortU16Decoder}\n */\nexport const getShortU16Codec = (): VariableSizeCodec =>\n combineCodec(getShortU16Encoder(), getShortU16Decoder());\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 128-bit unsigned integers (`u128`).\n *\n * This encoder serializes `u128` values using sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u128` values.\n *\n * @example\n * Encoding a `u128` value.\n * ```ts\n * const encoder = getU128Encoder();\n * const bytes = encoder.encode(42n); // 0x2a000000000000000000000000000000\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0n, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\n/**\n * Returns a decoder for 128-bit unsigned integers (`u128`).\n *\n * This decoder deserializes `u128` values from sixteen bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU128Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u128` values.\n *\n * @example\n * Decoding a `u128` value.\n * ```ts\n * const decoder = getU128Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU128Codec}\n */\nexport const getU128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\n/**\n * Returns a codec for encoding and decoding 128-bit unsigned integers (`u128`).\n *\n * This codec serializes `u128` values using 16 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u128` values.\n *\n * @example\n * Encoding and decoding a `u128` value.\n * ```ts\n * const codec = getU128Codec();\n * const bytes = codec.encode(42); // 0x2a000000000000000000000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU128Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000000000000000000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^128 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU64Codec} or {@link getU32Codec}.\n * - If you need signed integers, consider using {@link getI128Codec}.\n *\n * Separate {@link getU128Encoder} and {@link getU128Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU128Encoder().encode(42);\n * const value = getU128Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU128Encoder}\n * @see {@link getU128Decoder}\n */\nexport const getU128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 16-bit unsigned integers (`u16`).\n *\n * This encoder serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u16` values.\n *\n * @example\n * Encoding a `u16` value.\n * ```ts\n * const encoder = getU16Encoder();\n * const bytes = encoder.encode(42); // 0x2a00\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u16',\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, Number(value), le),\n size: 2,\n });\n\n/**\n * Returns a decoder for 16-bit unsigned integers (`u16`).\n *\n * This decoder deserializes `u16` values from two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU16Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u16` values.\n *\n * @example\n * Decoding a `u16` value.\n * ```ts\n * const decoder = getU16Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @see {@link getU16Codec}\n */\nexport const getU16Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n size: 2,\n });\n\n/**\n * Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`).\n *\n * This codec serializes `u16` values using two bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u16` values.\n *\n * @example\n * Encoding and decoding a `u16` value.\n * ```ts\n * const codec = getU16Codec();\n * const bytes = codec.encode(42); // 0x2a00 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU16Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^16 - 1`.\n * If you need a larger range, consider using {@link getU32Codec} or {@link getU64Codec}.\n * For signed integers, use {@link getI16Codec}.\n *\n * Separate {@link getU16Encoder} and {@link getU16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU16Encoder().encode(42);\n * const value = getU16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU16Encoder}\n * @see {@link getU16Decoder}\n */\nexport const getU16Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU16Encoder(config), getU16Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 32-bit unsigned integers (`u32`).\n *\n * This encoder serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeEncoder` for encoding `u32` values.\n *\n * @example\n * Encoding a `u32` value.\n * ```ts\n * const encoder = getU32Encoder();\n * const bytes = encoder.encode(42); // 0x2a000000\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u32',\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n size: 4,\n });\n\n/**\n * Returns a decoder for 32-bit unsigned integers (`u32`).\n *\n * This decoder deserializes `u32` values from four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * For more details, see {@link getU32Codec}.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeDecoder` for decoding `u32` values.\n *\n * @example\n * Decoding a `u32` value.\n * ```ts\n * const decoder = getU32Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getU32Codec}\n */\nexport const getU32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n size: 4,\n });\n\n/**\n * Returns a codec for encoding and decoding 32-bit unsigned integers (`u32`).\n *\n * This codec serializes `u32` values using four bytes in little-endian format by default.\n * You may specify big-endian storage using the `endian` option.\n *\n * @param config - Optional settings for endianness.\n * @returns A `FixedSizeCodec` for encoding and decoding `u32` values.\n *\n * @example\n * Encoding and decoding a `u32` value.\n * ```ts\n * const codec = getU32Codec();\n * const bytes = codec.encode(42); // 0x2a000000 (little-endian)\n * const value = codec.decode(bytes); // 42\n * ```\n *\n * @example\n * Storing values in big-endian format.\n * ```ts\n * const codec = getU32Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x0000002a\n * ```\n *\n * @remarks\n * This codec only supports values between `0` and `2^32 - 1`.\n * If you need a larger range, consider using {@link getU64Codec} or {@link getU128Codec}.\n * For signed integers, use {@link getI32Codec}.\n *\n * Separate {@link getU32Encoder} and {@link getU32Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU32Encoder().encode(42);\n * const value = getU32Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU32Encoder}\n * @see {@link getU32Decoder}\n */\nexport const getU32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU32Encoder(config), getU32Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 64-bit unsigned integers (`u64`).\n *\n * This encoder serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeEncoder` for encoding `u64` values.\n *\n * @example\n * Encoding a `u64` value.\n * ```ts\n * const encoder = getU64Encoder();\n * const bytes = encoder.encode(42); // 0x2a00000000000000\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder =>\n numberEncoderFactory({\n config,\n name: 'u64',\n range: [0n, BigInt('0xffffffffffffffff')],\n set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),\n size: 8,\n });\n\n/**\n * Returns a decoder for 64-bit unsigned integers (`u64`).\n *\n * This decoder deserializes `u64` values from 8 bytes.\n * The decoded value is always a `bigint`.\n *\n * For more details, see {@link getU64Codec}.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeDecoder` for decoding `u64` values.\n *\n * @example\n * Decoding a `u64` value.\n * ```ts\n * const decoder = getU64Decoder();\n * const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n\n * ```\n *\n * @see {@link getU64Codec}\n */\nexport const getU64Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getBigUint64(0, le),\n name: 'u64',\n size: 8,\n });\n\n/**\n * Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`).\n *\n * This codec serializes `u64` values using 8 bytes.\n * Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.\n *\n * @param config - Optional configuration to specify endianness (little by default).\n * @returns A `FixedSizeCodec` for encoding and decoding `u64` values.\n *\n * @example\n * Encoding and decoding a `u64` value.\n * ```ts\n * const codec = getU64Codec();\n * const bytes = codec.encode(42); // 0x2a00000000000000\n * const value = codec.decode(bytes); // 42n\n * ```\n *\n * @example\n * Using big-endian encoding.\n * ```ts\n * const codec = getU64Codec({ endian: Endian.Big });\n * const bytes = codec.encode(42); // 0x000000000000002a\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^64 - 1`.\n * Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.\n *\n * - If you need a smaller unsigned integer, consider using {@link getU32Codec} or {@link getU16Codec}.\n * - If you need a larger unsigned integer, consider using {@link getU128Codec}.\n * - If you need signed integers, consider using {@link getI64Codec}.\n *\n * Separate {@link getU64Encoder} and {@link getU64Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU64Encoder().encode(42);\n * const value = getU64Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU64Encoder}\n * @see {@link getU64Decoder}\n */\nexport const getU64Codec = (config: NumberCodecConfig = {}): FixedSizeCodec =>\n combineCodec(getU64Encoder(config), getU64Decoder(config));\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\n/**\n * Returns an encoder for 8-bit unsigned integers (`u8`).\n *\n * This encoder serializes `u8` values using a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeEncoder` for encoding `u8` values.\n *\n * @example\n * Encoding a `u8` value.\n * ```ts\n * const encoder = getU8Encoder();\n * const bytes = encoder.encode(42); // 0x2a\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Encoder = (): FixedSizeEncoder =>\n numberEncoderFactory({\n name: 'u8',\n range: [0, Number('0xff')],\n set: (view, value) => view.setUint8(0, Number(value)),\n size: 1,\n });\n\n/**\n * Returns a decoder for 8-bit unsigned integers (`u8`).\n *\n * This decoder deserializes `u8` values from a single byte.\n *\n * For more details, see {@link getU8Codec}.\n *\n * @returns A `FixedSizeDecoder` for decoding `u8` values.\n *\n * @example\n * Decoding a `u8` value.\n * ```ts\n * const decoder = getU8Decoder();\n * const value = decoder.decode(new Uint8Array([0xff])); // 255\n * ```\n *\n * @see {@link getU8Codec}\n */\nexport const getU8Decoder = (): FixedSizeDecoder =>\n numberDecoderFactory({\n get: view => view.getUint8(0),\n name: 'u8',\n size: 1,\n });\n\n/**\n * Returns a codec for encoding and decoding 8-bit unsigned integers (`u8`).\n *\n * This codec serializes `u8` values using a single byte.\n *\n * @returns A `FixedSizeCodec` for encoding and decoding `u8` values.\n *\n * @example\n * Encoding and decoding a `u8` value.\n * ```ts\n * const codec = getU8Codec();\n * const bytes = codec.encode(255); // 0xff\n * const value = codec.decode(bytes); // 255\n * ```\n *\n * @remarks\n * This codec supports values between `0` and `2^8 - 1` (0 to 255).\n * If you need larger integers, consider using {@link getU16Codec}, {@link getU32Codec}, or {@link getU64Codec}.\n * For signed integers, use {@link getI8Codec}.\n *\n * Separate {@link getU8Encoder} and {@link getU8Decoder} functions are available.\n *\n * ```ts\n * const bytes = getU8Encoder().encode(42);\n * const value = getU8Decoder().decode(bytes);\n * ```\n *\n * @see {@link getU8Encoder}\n * @see {@link getU8Decoder}\n */\nexport const getU8Codec = (): FixedSizeCodec =>\n combineCodec(getU8Encoder(), getU8Decoder());\n","import { SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SolanaError } from '@solana/errors';\n\n/** Checks the number of items in an array-like structure is expected. */\nexport function assertValidNumberOfItemsForCodec(\n codecDescription: string,\n expected: bigint | number,\n actual: bigint | number,\n) {\n if (expected !== actual) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {\n actual,\n codecDescription,\n expected,\n });\n }\n}\n","import { isFixedSize } from '@solana/codecs-core';\n\n/**\n * Functionally, this type helper is equivalent to the identity type — i.e. `type Identity = T`.\n * However, wrapping generic object mappings in this type significantly reduces the number\n * of instantiation expressions processed, which increases TypeScript performance and\n * prevents \"Type instantiation is excessively deep and possibly infinite\" errors.\n *\n * This works because TypeScript doesn't create a new level of nesting when encountering conditional generic types.\n * @see https://github.com/microsoft/TypeScript/issues/34933\n * @see https://github.com/kysely-org/kysely/pull/483\n */\nexport type DrainOuterGeneric = [T] extends [unknown] ? T : never;\n\nexport function maxCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce(\n (all, size) => (all === null || size === null ? null : Math.max(all, size)),\n 0 as number | null,\n );\n}\n\nexport function sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nexport function getFixedSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : null;\n}\n\nexport function getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : (codec.maxSize ?? null);\n}\n","import {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getU32Decoder, getU32Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { getFixedSize, getMaxSize } from './utils';\n\n/**\n * Defines the possible size strategies for array-like codecs (`array`, `map`, and `set`).\n *\n * The size of the collection can be determined using one of the following approaches:\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} to store a size prefix.\n * - A fixed `number` of items, enforcing an exact length.\n * - The string `\"remainder\"`, which infers the number of items by consuming the rest of the available bytes.\n * This option is only available when encoding fixed-size items.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayLikeCodecSize =\n | TPrefix\n | number\n | 'remainder';\n\n/**\n * Defines the configuration options for array codecs.\n *\n * @typeParam TPrefix - A number codec, decoder, or encoder used for size prefixing.\n */\nexport type ArrayCodecConfig = {\n /**\n * Specifies how the size of the array is determined.\n *\n * - A {@link NumberCodec}, {@link NumberDecoder}, or {@link NumberEncoder} stores a size prefix before encoding the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length (only for fixed-size items).\n *\n * @defaultValue A `u32` size prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for arrays of values.\n *\n * This encoder serializes arrays by encoding each element using the provided item encoder.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TFrom - The type of the elements in the array.\n *\n * @param item - The encoder for each item in the array.\n * @param config - Optional configuration for the size encoding strategy.\n * @returns A `VariableSizeEncoder` for encoding arrays.\n *\n * @example\n * Encoding an array of `u8` numbers.\n * ```ts\n * const encoder = getArrayEncoder(getU8Encoder());\n * const bytes = encoder.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: FixedSizeEncoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config?: ArrayCodecConfig,\n): VariableSizeEncoder;\nexport function getArrayEncoder(\n item: Encoder,\n config: ArrayCodecConfig = {},\n): Encoder {\n const size = config.size ?? getU32Encoder();\n const fixedSize = computeArrayLikeCodecSize(size, getFixedSize(item));\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize !== null\n ? { fixedSize }\n : {\n getSizeFromValue: (array: TFrom[]) => {\n const prefixSize = typeof size === 'object' ? getEncodedSize(array.length, size) : 0;\n return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);\n },\n maxSize,\n }),\n write: (array: TFrom[], bytes, offset) => {\n if (typeof size === 'number') {\n assertValidNumberOfItemsForCodec('array', size, array.length);\n }\n if (typeof size === 'object') {\n offset = size.write(array.length, bytes, offset);\n }\n array.forEach(value => {\n offset = item.write(value, bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for arrays of values.\n *\n * This decoder deserializes arrays by decoding each element using the provided item decoder.\n * By default, a `u32` size prefix is expected to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * For more details, see {@link getArrayCodec}.\n *\n * @typeParam TTo - The type of the decoded elements in the array.\n *\n * @param item - The decoder for each item in the array.\n * @param config - Optional configuration for the size decoding strategy.\n * @returns A `VariableSizeDecoder` for decoding arrays.\n *\n * @example\n * Decoding an array of `u8` numbers.\n * ```ts\n * const decoder = getArrayDecoder(getU8Decoder());\n * const array = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // [1, 2, 3]\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n * ```\n *\n * @see {@link getArrayCodec}\n */\nexport function getArrayDecoder(\n item: Decoder,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: FixedSizeDecoder,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeDecoder;\nexport function getArrayDecoder(\n item: Decoder,\n config?: ArrayCodecConfig,\n): VariableSizeDecoder;\nexport function getArrayDecoder(item: Decoder, config: ArrayCodecConfig = {}): Decoder {\n const size = config.size ?? getU32Decoder();\n const itemSize = getFixedSize(item);\n const fixedSize = computeArrayLikeCodecSize(size, itemSize);\n const maxSize = computeArrayLikeCodecSize(size, getMaxSize(item)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize !== null ? { fixedSize } : { maxSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const array: TTo[] = [];\n if (typeof size === 'object' && bytes.slice(offset).length === 0) {\n return [array, offset];\n }\n\n if (size === 'remainder') {\n while (offset < bytes.length) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n }\n\n const [resolvedSize, newOffset] = typeof size === 'number' ? [size, offset] : size.read(bytes, offset);\n offset = newOffset;\n for (let i = 0; i < resolvedSize; i += 1) {\n const [value, newOffset] = item.read(bytes, offset);\n offset = newOffset;\n array.push(value);\n }\n return [array, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding arrays of values.\n *\n * This codec serializes arrays by encoding each element using the provided item codec.\n * By default, a `u32` size prefix is included to indicate the number of items in the array.\n * The `size` option can be used to modify this behaviour.\n *\n * @typeParam TFrom - The type of the elements to encode.\n * @typeParam TTo - The type of the decoded elements.\n *\n * @param item - The codec for each item in the array.\n * @param config - Optional configuration for the size encoding/decoding strategy.\n * @returns A `VariableSizeCodec` for encoding and decoding arrays.\n *\n * @example\n * Encoding and decoding an array of `u8` numbers.\n * ```ts\n * const codec = getArrayCodec(getU8Codec());\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix telling us to read 3 items.\n *\n * const array = codec.decode(bytes);\n * // [1, 2, 3]\n * ```\n *\n * @example\n * Using a `u16` size prefix instead of `u32`.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode([1, 2, 3]);\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix telling us to read 3 items.\n * ```\n *\n * @example\n * Using a fixed-size array of 3 items.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 3 });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. There must always be 3 items in the array.\n * ```\n *\n * @example\n * Using the `\"remainder\"` size strategy.\n * ```ts\n * const codec = getArrayCodec(getU8Codec(), { size: 'remainder' });\n * codec.encode([1, 2, 3]);\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.\n * ```\n *\n * @remarks\n * The size of the array can be controlled using the `size` option:\n * - A `Codec` (e.g. `getU16Codec()`) stores a size prefix before the array.\n * - A `number` enforces a fixed number of elements.\n * - `\"remainder\"` uses all remaining bytes to infer the array length.\n *\n * Separate {@link getArrayEncoder} and {@link getArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);\n * const array = getArrayDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getArrayEncoder}\n * @see {@link getArrayDecoder}\n */\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig & { size: 0 },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: FixedSizeCodec,\n config: ArrayCodecConfig & { size: number },\n): FixedSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config?: ArrayCodecConfig,\n): VariableSizeCodec;\nexport function getArrayCodec(\n item: Codec,\n config: ArrayCodecConfig = {},\n): Codec {\n return combineCodec(getArrayEncoder(item, config as object), getArrayDecoder(item, config as object));\n}\n\nfunction computeArrayLikeCodecSize(size: number | object | 'remainder', itemSize: number | null): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n return itemSize === null ? null : itemSize * size;\n}\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Defines the configuration options for bit array codecs.\n *\n * A bit array codec encodes an array of booleans into bits, packing them into bytes.\n * This configuration allows adjusting the bit ordering.\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n * @see {@link getBitArrayCodec}\n */\nexport type BitArrayCodecConfig = {\n /**\n * Determines whether the bits should be read in reverse order.\n *\n * - `false` (default): The first boolean is stored in the most significant bit (MSB-first).\n * - `true`: The first boolean is stored in the least significant bit (LSB-first).\n *\n * @defaultValue `false`\n */\n backward?: boolean;\n};\n\n/**\n * Returns an encoder that packs an array of booleans into bits.\n *\n * This encoder converts a list of `boolean` values into a compact bit representation,\n * storing 8 booleans per byte.\n *\n * The `backward` config option determines whether the bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding the bit array.\n * @returns A `FixedSizeEncoder` for encoding bit arrays.\n *\n * @example\n * Encoding a bit array.\n * ```ts\n * const encoder = getBitArrayEncoder(1);\n *\n * encoder.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayEncoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeEncoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createEncoder({\n fixedSize: size,\n write(value: boolean[], bytes, offset) {\n const bytesToAdd: number[] = [];\n\n for (let i = 0; i < size; i += 1) {\n let byte = 0;\n for (let j = 0; j < 8; j += 1) {\n const feature = Number(value[i * 8 + j] ?? 0);\n byte |= feature << (backward ? j : 7 - j);\n }\n if (backward) {\n bytesToAdd.unshift(byte);\n } else {\n bytesToAdd.push(byte);\n }\n }\n\n bytes.set(bytesToAdd, offset);\n return size;\n },\n });\n}\n\n/**\n * Returns a decoder that unpacks bits into an array of booleans.\n *\n * This decoder converts a compact bit representation back into a list of `boolean` values.\n * Each byte is expanded into 8 booleans.\n *\n * The `backward` config option determines whether the bits are read in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * For more details, see {@link getBitArrayCodec}.\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for decoding the bit array.\n * @returns A `FixedSizeDecoder` for decoding bit arrays.\n *\n * @example\n * Decoding a bit array.\n * ```ts\n * const decoder = getBitArrayDecoder(1);\n *\n * decoder.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @see {@link getBitArrayCodec}\n */\nexport function getBitArrayDecoder(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeDecoder {\n const parsedConfig: BitArrayCodecConfig = typeof config === 'boolean' ? { backward: config } : config;\n const backward = parsedConfig.backward ?? false;\n return createDecoder({\n fixedSize: size,\n read(bytes, offset) {\n assertByteArrayHasEnoughBytesForCodec('bitArray', size, bytes, offset);\n const booleans: boolean[] = [];\n let slice = bytes.slice(offset, offset + size);\n slice = backward ? slice.reverse() : slice;\n\n slice.forEach(byte => {\n for (let i = 0; i < 8; i += 1) {\n if (backward) {\n booleans.push(Boolean(byte & 1));\n byte >>= 1;\n } else {\n booleans.push(Boolean(byte & 0b1000_0000));\n byte <<= 1;\n }\n }\n });\n\n return [booleans, offset + size];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes boolean arrays as compact bit representations.\n *\n * This codec efficiently stores boolean arrays as bits, packing 8 values per byte.\n * The `backward` config option determines whether bits are stored in MSB-first (`false`)\n * or LSB-first (`true`).\n *\n * @typeParam TSize - The number of bytes used to store the bit array.\n *\n * @param size - The number of bytes allocated for the bit array (must be sufficient for the expected boolean count).\n * @param config - Configuration options for encoding and decoding the bit array.\n * @returns A `FixedSizeCodec` for encoding and decoding bit arrays.\n *\n * @example\n * Encoding and decoding a bit array.\n * ```ts\n * const codec = getBitArrayCodec(1);\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0xa0 (0b10100000)\n *\n * codec.decode(new Uint8Array([0xa0]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @example\n * Encoding and decoding a bit array backwards.\n * ```ts\n * const codec = getBitArrayCodec(1, { backward: true });\n *\n * codec.encode([true, false, true, false, false, false, false, false]);\n * // 0x05 (0b00000101)\n *\n * codec.decode(new Uint8Array([0x05]));\n * // [true, false, true, false, false, false, false, false]\n * ```\n *\n * @remarks\n * Separate {@link getBitArrayEncoder} and {@link getBitArrayDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBitArrayEncoder(1).encode([true, false, true, false]);\n * const value = getBitArrayDecoder(1).decode(bytes);\n * ```\n *\n * @see {@link getBitArrayEncoder}\n * @see {@link getBitArrayDecoder}\n */\nexport function getBitArrayCodec(\n size: TSize,\n config: BitArrayCodecConfig | boolean = {},\n): FixedSizeCodec {\n return combineCodec(getBitArrayEncoder(size, config), getBitArrayDecoder(size, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\n/**\n * Defines the configuration options for boolean codecs.\n *\n * A boolean codec encodes `true` as `1` and `false` as `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * @typeParam TSize - A number codec, encoder, or decoder used for boolean representation.\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n * @see {@link getBooleanCodec}\n */\nexport type BooleanCodecConfig = {\n /**\n * The number codec used to store boolean values.\n *\n * - By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * - A custom number codec can be provided to change the storage size.\n *\n * @defaultValue `u8`\n */\n size?: TSize;\n};\n\n/**\n * Returns an encoder for boolean values.\n *\n * This encoder converts `true` into `1` and `false` into `0`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for encoding booleans.\n * @returns A `FixedSizeEncoder` where `N` is the size of the number codec.\n *\n * @example\n * Encoding booleans.\n * ```ts\n * const encoder = getBooleanEncoder();\n *\n * encoder.encode(false); // 0x00\n * encoder.encode(true); // 0x01\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanEncoder(): FixedSizeEncoder;\nexport function getBooleanEncoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig): VariableSizeEncoder;\nexport function getBooleanEncoder(config: BooleanCodecConfig = {}): Encoder {\n return transformEncoder(config.size ?? getU8Encoder(), (value: boolean) => (value ? 1 : 0));\n}\n\n/**\n * Returns a decoder for boolean values.\n *\n * This decoder reads a number and interprets `1` as `true` and `0` as `false`.\n * The `size` option allows customizing the number codec used for storage.\n *\n * For more details, see {@link getBooleanCodec}.\n *\n * @param config - Configuration options for decoding booleans.\n * @returns A `FixedSizeDecoder` where `N` is the size of the number codec.\n *\n * @example\n * Decoding booleans.\n * ```ts\n * const decoder = getBooleanDecoder();\n *\n * decoder.decode(new Uint8Array([0x00])); // false\n * decoder.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @see {@link getBooleanCodec}\n */\nexport function getBooleanDecoder(): FixedSizeDecoder;\nexport function getBooleanDecoder(\n config: BooleanCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig): VariableSizeDecoder;\nexport function getBooleanDecoder(config: BooleanCodecConfig = {}): Decoder {\n return transformDecoder(config.size ?? getU8Decoder(), (value: bigint | number): boolean => Number(value) === 1);\n}\n\n/**\n * Returns a codec for encoding and decoding boolean values.\n *\n * By default, booleans are stored as a `u8` (`1` for `true`, `0` for `false`).\n * The `size` option allows customizing the number codec used for storage.\n *\n * @param config - Configuration options for encoding and decoding booleans.\n * @returns A `FixedSizeCodec` where `N` is the size of the number codec.\n *\n * @example\n * Encoding and decoding booleans using a `u8` (default).\n * ```ts\n * const codec = getBooleanCodec();\n *\n * codec.encode(false); // 0x00\n * codec.encode(true); // 0x01\n *\n * codec.decode(new Uint8Array([0x00])); // false\n * codec.decode(new Uint8Array([0x01])); // true\n * ```\n *\n * @example\n * Encoding and decoding booleans using a custom number codec.\n * ```ts\n * const codec = getBooleanCodec({ size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * ```\n *\n * @remarks\n * Separate {@link getBooleanEncoder} and {@link getBooleanDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBooleanEncoder().encode(true);\n * const value = getBooleanDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBooleanEncoder}\n * @see {@link getBooleanDecoder}\n */\nexport function getBooleanCodec(): FixedSizeCodec;\nexport function getBooleanCodec(\n config: BooleanCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig): VariableSizeCodec;\nexport function getBooleanCodec(config: BooleanCodecConfig = {}): Codec {\n return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for raw byte arrays.\n *\n * This encoder writes byte arrays exactly as provided without modification.\n *\n * The size of the encoded byte array is determined by the length of the input.\n * - To enforce a fixed size, consider using {@link fixEncoderSize}.\n * - To add a size prefix, use {@link addEncoderSizePrefix}.\n * - To add a sentinel value, use {@link addEncoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeEncoder`.\n *\n * @example\n * Encoding a byte array as-is.\n * ```ts\n * const encoder = getBytesEncoder();\n *\n * encoder.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * encoder.encode(new Uint8Array([255, 0, 127])); // 0xff007f\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => value.length,\n write: (value, bytes, offset) => {\n bytes.set(value, offset);\n return offset + value.length;\n },\n });\n}\n\n/**\n * Returns a decoder for raw byte arrays.\n *\n * This decoder reads byte arrays exactly as provided without modification.\n *\n * The decoded byte array extends from the provided offset to the end of the input.\n * - To enforce a fixed size, consider using {@link fixDecoderSize}.\n * - To add a size prefix, use {@link addDecoderSizePrefix}.\n * - To add a sentinel value, use {@link addDecoderSentinel}.\n *\n * For more details, see {@link getBytesCodec}.\n *\n * @returns A `VariableSizeDecoder`.\n *\n * @example\n * Decoding a byte array as-is.\n * ```ts\n * const decoder = getBytesDecoder();\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Uint8Array([1, 2, 3])\n * decoder.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @see {@link getBytesCodec}\n */\nexport function getBytesDecoder(): VariableSizeDecoder {\n return createDecoder({\n read: (bytes, offset) => {\n const slice = bytes.slice(offset);\n return [slice, offset + slice.length];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding raw byte arrays.\n *\n * This codec serializes and deserializes byte arrays without modification.\n *\n * The size of the encoded and decoded byte array is determined dynamically.\n * This means, when reading, the codec will consume all remaining bytes in the input.\n * - To enforce a fixed size, consider using {@link fixCodecSize}.\n * - To add a size prefix, use {@link addCodecSizePrefix}.\n * - To add a sentinel value, use {@link addCodecSentinel}.\n *\n * @returns A `VariableSizeCodec`.\n *\n * @example\n * Encoding and decoding a byte array.\n * ```ts\n * const codec = getBytesCodec();\n *\n * codec.encode(new Uint8Array([1, 2, 3])); // 0x010203\n * codec.decode(new Uint8Array([255, 0, 127])); // Uint8Array([255, 0, 127])\n * ```\n *\n * @remarks\n * Separate {@link getBytesEncoder} and {@link getBytesDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBytesEncoder().encode(new Uint8Array([1, 2, 3]));\n * const value = getBytesDecoder().decode(bytes);\n * ```\n *\n * @see {@link getBytesEncoder}\n * @see {@link getBytesDecoder}\n */\nexport function getBytesCodec(): VariableSizeCodec {\n return combineCodec(getBytesEncoder(), getBytesDecoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\nconst enum HexC {\n ZERO = 48, // 0\n NINE = 57, // 9\n A_UP = 65, // A\n F_UP = 70, // F\n A_LO = 97, // a\n F_LO = 102, // f\n}\n\nconst INVALID_STRING_ERROR_BASE_CONFIG = {\n alphabet: '0123456789abcdef',\n base: 16,\n} as const;\n\nfunction charCodeToBase16(char: number) {\n if (char >= HexC.ZERO && char <= HexC.NINE) return char - HexC.ZERO;\n if (char >= HexC.A_UP && char <= HexC.F_UP) return char - (HexC.A_UP - 10);\n if (char >= HexC.A_LO && char <= HexC.F_LO) return char - (HexC.A_LO - 10);\n}\n\n/**\n * Returns an encoder for base-16 (hexadecimal) strings.\n *\n * This encoder serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-16 strings.\n *\n * @example\n * Encoding a base-16 string.\n * ```ts\n * const encoder = getBase16Encoder();\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Encoder = (): VariableSizeEncoder =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, bytes, offset) {\n const len = value.length;\n const al = len / 2;\n if (len === 1) {\n const c = value.charCodeAt(0);\n const n = charCodeToBase16(c);\n if (n === undefined) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n bytes.set([n], offset);\n return 1 + offset;\n }\n const hexBytes = new Uint8Array(al);\n for (let i = 0, j = 0; i < al; i++) {\n const c1 = value.charCodeAt(j++);\n const c2 = value.charCodeAt(j++);\n\n const n1 = charCodeToBase16(c1);\n const n2 = charCodeToBase16(c2);\n if (n1 === undefined || (n2 === undefined && !Number.isNaN(c2))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n ...INVALID_STRING_ERROR_BASE_CONFIG,\n value,\n });\n }\n hexBytes[i] = !Number.isNaN(c2) ? (n1 << 4) | (n2 ?? 0) : n1;\n }\n\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/**\n * Returns a decoder for base-16 (hexadecimal) strings.\n *\n * This decoder deserializes base-16 encoded strings from a byte array.\n *\n * For more details, see {@link getBase16Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-16 strings.\n *\n * @example\n * Decoding a base-16 string.\n * ```ts\n * const decoder = getBase16Decoder();\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBase16Codec}\n */\nexport const getBase16Decoder = (): VariableSizeDecoder =>\n createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n });\n\n/**\n * Returns a codec for encoding and decoding base-16 (hexadecimal) strings.\n *\n * This codec serializes strings using a base-16 encoding scheme.\n * The output consists of bytes representing the hexadecimal values of the input string.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-16 strings.\n *\n * @example\n * Encoding and decoding a base-16 string.\n * ```ts\n * const codec = getBase16Codec();\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-16 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase16Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-16 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase16Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase16Encoder} and {@link getBase16Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase16Encoder().encode('deadface');\n * const value = getBase16Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase16Encoder}\n * @see {@link getBase16Decoder}\n */\nexport const getBase16Codec = (): VariableSizeCodec => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n containsBytes,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getBase16Decoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__CODECS__INVALID_CONSTANT, SolanaError } from '@solana/errors';\n\n/**\n * Returns an encoder that always writes a predefined constant byte sequence.\n *\n * This encoder ensures that encoding always produces the specified byte array,\n * ignoring any input values.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence that will be written during encoding.\n *\n * @param constant - The predefined byte array to encode.\n * @returns A `FixedSizeEncoder` where `N` is the length of the constant.\n *\n * @example\n * Encoding a constant magic number.\n * ```ts\n * const encoder = getConstantEncoder(new Uint8Array([1, 2, 3, 4]));\n *\n * const bytes = encoder.encode();\n * // 0x01020304\n * // └──────┘ The predefined 4-byte constant.\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantEncoder(\n constant: TConstant,\n): FixedSizeEncoder {\n return createEncoder({\n fixedSize: constant.length,\n write: (_, bytes, offset) => {\n bytes.set(constant, offset);\n return offset + constant.length;\n },\n });\n}\n\n/**\n * Returns a decoder that verifies a predefined constant byte sequence.\n *\n * This decoder reads the next bytes and checks that they match the provided constant.\n * If the bytes differ, it throws an error.\n *\n * For more details, see {@link getConstantCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence expected during decoding.\n *\n * @param constant - The predefined byte array to verify.\n * @returns A `FixedSizeDecoder` where `N` is the length of the constant.\n *\n * @example\n * Decoding a constant magic number.\n * ```ts\n * const decoder = getConstantDecoder(new Uint8Array([1, 2, 3]));\n *\n * decoder.decode(new Uint8Array([1, 2, 3])); // Passes\n * decoder.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @see {@link getConstantCodec}\n */\nexport function getConstantDecoder(\n constant: TConstant,\n): FixedSizeDecoder {\n return createDecoder({\n fixedSize: constant.length,\n read: (bytes, offset) => {\n const base16 = getBase16Decoder();\n if (!containsBytes(bytes, constant, offset)) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {\n constant,\n data: bytes,\n hexConstant: base16.decode(constant),\n hexData: base16.decode(bytes),\n offset,\n });\n }\n return [undefined, offset + constant.length];\n },\n });\n}\n\n/**\n * Returns a codec that encodes and decodes a predefined constant byte sequence.\n *\n * - **Encoding:** Always writes the specified byte array.\n * - **Decoding:** Asserts that the next bytes match the constant, throwing an error if they do not.\n *\n * This is useful for encoding fixed byte patterns required in a binary format or to use in\n * conjunction with other codecs such as {@link getHiddenPrefixCodec} or {@link getHiddenSuffixCodec}.\n *\n * @typeParam TConstant - The fixed byte sequence to encode and verify during decoding.\n *\n * @param constant - The predefined byte array to encode and assert during decoding.\n * @returns A `FixedSizeCodec` where `N` is the length of the constant.\n *\n * @example\n * Encoding and decoding a constant magic number.\n * ```ts\n * const codec = getConstantCodec(new Uint8Array([1, 2, 3]));\n *\n * codec.encode(); // 0x010203\n * codec.decode(new Uint8Array([1, 2, 3])); // Passes\n * codec.decode(new Uint8Array([1, 2, 4])); // Throws an error\n * ```\n *\n * @remarks\n * Separate {@link getConstantEncoder} and {@link getConstantDecoder} functions are available.\n *\n * ```ts\n * const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode();\n * getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes);\n * ```\n *\n * @see {@link getConstantEncoder}\n * @see {@link getConstantDecoder}\n */\nexport function getConstantCodec(\n constant: TConstant,\n): FixedSizeCodec {\n return combineCodec(getConstantEncoder(constant), getConstantDecoder(constant));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidNumberOfItemsForCodec } from './assertions';\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for a tuple that can be encoded using a tuple codec.\n *\n * This type maps each provided item encoder to its corresponding value type.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n */\ntype GetEncoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for a tuple that can be decoded using a tuple codec.\n *\n * This type maps each provided item decoder to its corresponding value type.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n */\ntype GetDecoderTypeFromItems[]> = DrainOuterGeneric<{\n [I in keyof TItems]: TItems[I] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for tuples.\n *\n * This encoder serializes a fixed-size array (tuple) by encoding its items\n * sequentially using the provided item encoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of encoders, each corresponding to a tuple element.\n *\n * @param items - The encoders for each item in the tuple.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding tuples.\n *\n * @example\n * Encoding a tuple with 2 items.\n * ```ts\n * const encoder = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()]);\n *\n * const bytes = encoder.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleEncoder[]>(\n items: TItems,\n): FixedSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): VariableSizeEncoder>;\nexport function getTupleEncoder[]>(\n items: TItems,\n): Encoder> {\n type TFrom = GetEncoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n items.map((item, index) => getEncodedSize(value[index], item)).reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (value: TFrom, bytes, offset) => {\n assertValidNumberOfItemsForCodec('tuple', items.length, value.length);\n items.forEach((item, index) => {\n offset = item.write(value[index], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for tuples.\n *\n * This decoder deserializes a fixed-size array (tuple) by decoding its items\n * sequentially using the provided item decoders.\n *\n * For more details, see {@link getTupleCodec}.\n *\n * @typeParam TItems - An array of decoders, each corresponding to a tuple element.\n *\n * @param items - The decoders for each item in the tuple.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding tuples.\n *\n * @example\n * Decoding a tuple with 2 items.\n * ```ts\n * const decoder = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()]);\n *\n * const tuple = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // ['Alice', 42]\n * ```\n *\n * @see {@link getTupleCodec}\n */\nexport function getTupleDecoder[]>(\n items: TItems,\n): FixedSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): VariableSizeDecoder>;\nexport function getTupleDecoder[]>(\n items: TItems,\n): Decoder> {\n type TTo = GetDecoderTypeFromItems;\n const fixedSize = sumCodecSizes(items.map(getFixedSize));\n const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const values = [] as Array & TTo;\n items.forEach(item => {\n const [newValue, newOffset] = item.read(bytes, offset);\n values.push(newValue);\n offset = newOffset;\n });\n return [values, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding tuples.\n *\n * This codec serializes tuples by encoding and decoding each item sequentially.\n *\n * Unlike the {@link getArrayCodec} codec, each item in the tuple has its own codec\n * and, therefore, can be of a different type.\n *\n * @typeParam TItems - An array of codecs, each corresponding to a tuple element.\n *\n * @param items - The codecs for each item in the tuple.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding tuples.\n *\n * @example\n * Encoding and decoding a tuple with 2 items.\n * ```ts\n * const codec = getTupleCodec([fixCodecSize(getUtf8Codec(), 5), getU8Codec()]);\n *\n * const bytes = codec.encode(['Alice', 42]);\n * // 0x416c6963652a\n * // | └── Second item (42)\n * // └── First item (\"Alice\")\n *\n * const tuple = codec.decode(bytes);\n * // ['Alice', 42]\n * ```\n *\n * @remarks\n * Separate {@link getTupleEncoder} and {@link getTupleDecoder} functions are available.\n *\n * ```ts\n * const bytes = getTupleEncoder([fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()])\n * .encode(['Alice', 42]);\n *\n * const tuple = getTupleDecoder([fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()])\n * .decode(bytes);\n * ```\n *\n * @see {@link getTupleEncoder}\n * @see {@link getTupleDecoder}\n */\nexport function getTupleCodec[]>(\n items: TItems,\n): FixedSizeCodec, GetDecoderTypeFromItems & GetEncoderTypeFromItems>;\nexport function getTupleCodec[]>(\n items: TItems,\n): VariableSizeCodec<\n GetEncoderTypeFromItems,\n GetDecoderTypeFromItems & GetEncoderTypeFromItems\n>;\nexport function getTupleCodec[]>(\n items: TItems,\n): Codec, GetDecoderTypeFromItems & GetEncoderTypeFromItems> {\n return combineCodec(\n getTupleEncoder(items),\n getTupleDecoder(items) as Decoder & GetEncoderTypeFromItems>,\n );\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n Offset,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SolanaError } from '@solana/errors';\n\nimport { DrainOuterGeneric, getMaxSize, maxCodecSizes } from './utils';\n\n/**\n * Infers the TypeScript type for values that can be encoded using a union codec.\n *\n * This type maps the provided variant encoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n */\ntype GetEncoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Encoder ? TFrom : never;\n}>[number];\n\n/**\n * Infers the TypeScript type for values that can be decoded using a union codec.\n *\n * This type maps the provided variant decoders to their corresponding value types.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n */\ntype GetDecoderTypeFromVariants[]> = DrainOuterGeneric<{\n [I in keyof TVariants]: TVariants[I] extends Decoder ? TFrom : never;\n}>[number];\n\ntype UnionEncoder[]> = TVariants extends readonly FixedSizeEncoder[]\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder[]> = TVariants extends readonly FixedSizeDecoder[]\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec[]> = TVariants extends readonly FixedSizeCodec[]\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for union types.\n *\n * This encoder serializes values by selecting the correct variant encoder\n * based on the `getIndexFromValue` function.\n *\n * Unlike other codecs, this encoder does not store the variant index.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of encoders, each corresponding to a union variant.\n *\n * @param variants - The encoders for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @returns An `Encoder` for encoding union values.\n *\n * @example\n * Encoding a union of numbers and booleans.\n * ```ts\n * const encoder = getUnionEncoder(\n * [getU16Encoder(), getBooleanEncoder()],\n * value => (typeof value === 'number' ? 0 : 1)\n * );\n *\n * encoder.encode(42);\n * // 0x2a00\n * // └── Encoded number (42) as `u16`\n *\n * encoder.encode(true);\n * // 0x01\n * // └── Encoded boolean (`true`) as `u8`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionEncoder[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const write: Encoder['write'] = (variant, bytes, offset) => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return variants[index].write(variant, bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createEncoder({ fixedSize, write }) as UnionEncoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createEncoder({\n ...(maxSize !== null ? { maxSize } : {}),\n getSizeFromValue: variant => {\n const index = getIndexFromValue(variant);\n assertValidVariantIndex(variants, index);\n return getEncodedSize(variant, variants[index]);\n },\n write,\n }) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for union types.\n *\n * This decoder deserializes values by selecting the correct variant decoder\n * based on the `getIndexFromBytes` function.\n *\n * Unlike other codecs, this decoder does not assume a stored discriminator.\n * It is the user's responsibility to manage discriminators separately.\n *\n * For more details, see {@link getUnionCodec}.\n *\n * @typeParam TVariants - An array of decoders, each corresponding to a union variant.\n *\n * @param variants - The decoders for each variant of the union.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Decoder` for decoding union values.\n *\n * @example\n * Decoding a union of numbers and booleans.\n * ```ts\n * const decoder = getUnionDecoder(\n * [getU16Decoder(), getBooleanDecoder()],\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * decoder.decode(new Uint8Array([0x2a, 0x00])); // 42\n * decoder.decode(new Uint8Array([0x01])); // true\n * // Type is inferred as `number | boolean`\n * ```\n *\n * @see {@link getUnionCodec}\n */\nexport function getUnionDecoder[]>(\n variants: TVariants,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionDecoder {\n type TTo = GetDecoderTypeFromVariants;\n const fixedSize = getUnionFixedSize(variants);\n const read: Decoder['read'] = (bytes, offset) => {\n const index = getIndexFromBytes(bytes, offset);\n assertValidVariantIndex(variants, index);\n return variants[index].read(bytes, offset);\n };\n\n if (fixedSize !== null) {\n return createDecoder({ fixedSize, read }) as UnionDecoder;\n }\n\n const maxSize = getUnionMaxSize(variants);\n return createDecoder({ ...(maxSize !== null ? { maxSize } : {}), read }) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding union types.\n *\n * This codec serializes and deserializes union values by selecting the correct variant\n * based on the provided index functions.\n *\n * Unlike the {@link getDiscriminatedUnionCodec}, this codec does not assume a stored\n * discriminator and must be used with an explicit mechanism for managing discriminators.\n *\n * @typeParam TVariants - An array of codecs, each corresponding to a union variant.\n *\n * @param variants - The codecs for each variant of the union.\n * @param getIndexFromValue - A function that determines the variant index from the provided value.\n * @param getIndexFromBytes - A function that determines the variant index from the byte array.\n * @returns A `Codec` for encoding and decoding union values.\n *\n * @example\n * Encoding and decoding a union of numbers and booleans.\n * ```ts\n * const codec = getUnionCodec(\n * [getU16Codec(), getBooleanCodec()],\n * value => (typeof value === 'number' ? 0 : 1),\n * (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)\n * );\n *\n * const bytes1 = codec.encode(42); // 0x2a00\n * const value1: number | boolean = codec.decode(bytes1); // 42\n *\n * const bytes2 = codec.encode(true); // 0x01\n * const value2: number | boolean = codec.decode(bytes2); // true\n * ```\n *\n * @remarks\n * If you need a codec that includes a stored discriminator,\n * consider using {@link getDiscriminatedUnionCodec}.\n *\n * Separate {@link getUnionEncoder} and {@link getUnionDecoder} functions are also available.\n *\n * ```ts\n * const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42);\n * const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes);\n * ```\n *\n * @see {@link getUnionEncoder}\n * @see {@link getUnionDecoder}\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getUnionCodec[]>(\n variants: TVariants,\n getIndexFromValue: (value: GetEncoderTypeFromVariants) => number,\n getIndexFromBytes: (bytes: ReadonlyUint8Array, offset: Offset) => number,\n): UnionCodec {\n return combineCodec(\n getUnionEncoder(variants, getIndexFromValue),\n getUnionDecoder(variants as readonly Decoder[], getIndexFromBytes) as Decoder<\n GetDecoderTypeFromVariants & GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction assertValidVariantIndex(variants: readonly unknown[], index: number) {\n if (typeof variants[index] === 'undefined') {\n throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {\n maxRange: variants.length - 1,\n minRange: 0,\n variant: index,\n });\n }\n}\n\nfunction getUnionFixedSize | Encoder)[]>(variants: TVariants) {\n if (variants.length === 0) return 0;\n if (!isFixedSize(variants[0])) return null;\n const variantSize = variants[0].fixedSize;\n const sameSizedVariants = variants.every(variant => isFixedSize(variant) && variant.fixedSize === variantSize);\n return sameSizedVariants ? variantSize : null;\n}\n\nfunction getUnionMaxSize | Encoder)[]>(variants: TVariants) {\n return maxCodecSizes(variants.map(variant => getMaxSize(variant)));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SolanaError } from '@solana/errors';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { DrainOuterGeneric } from './utils';\n\n/**\n * Represents a discriminated union using a specific discriminator property.\n *\n * A discriminated union is a TypeScript-friendly way to represent Rust-like enums.\n * Each variant in the union is distinguished by a shared discriminator property.\n *\n * @typeParam TDiscriminatorProperty - The name of the discriminator property.\n * @typeParam TDiscriminatorValue - The type of the discriminator value.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant\n * | { __kind: 'Write'; fields: [string] } // Tuple variant\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant\n * ```\n */\nexport type DiscriminatedUnion<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorValue extends string = string,\n> = {\n [P in TDiscriminatorProperty]: TDiscriminatorValue;\n};\n\n/**\n * Extracts a variant from a discriminated union based on its discriminator value.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type ClickEvent = GetDiscriminatedUnionVariant;\n * // -> { __kind: 'Move'; x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariant<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Extract>;\n\n/**\n * Extracts a variant from a discriminated union without its discriminator property.\n *\n * @typeParam TUnion - The discriminated union type.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n * @typeParam TDiscriminatorValue - The specific variant to extract.\n *\n * @example\n * ```ts\n * type Message =\n * | { __kind: 'Quit' }\n * | { __kind: 'Write'; fields: [string] }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * type MoveContent = GetDiscriminatedUnionVariantContent;\n * // -> { x: number; y: number }\n * ```\n */\nexport type GetDiscriminatedUnionVariantContent<\n TUnion extends DiscriminatedUnion,\n TDiscriminatorProperty extends string,\n TDiscriminatorValue extends TUnion[TDiscriminatorProperty],\n> = Omit, TDiscriminatorProperty>;\n\n/**\n * Defines the configuration for discriminated union codecs.\n *\n * This configuration controls how the discriminator is stored and named.\n *\n * @typeParam TDiscriminatorProperty - The property name of the discriminator.\n * @typeParam TDiscriminatorSize - The codec used for the discriminator prefix.\n */\nexport type DiscriminatedUnionCodecConfig<\n TDiscriminatorProperty extends string = '__kind',\n TDiscriminatorSize = NumberCodec | NumberDecoder | NumberEncoder,\n> = {\n /**\n * The property name of the discriminator.\n * @defaultValue `__kind`\n */\n discriminator?: TDiscriminatorProperty;\n /**\n * The codec used to encode/decode the discriminator prefix.\n * @defaultValue `u8` prefix\n */\n size?: TDiscriminatorSize;\n};\n\ntype DiscriminatorValue = bigint | boolean | number | string | null | undefined;\ntype Variants = readonly (readonly [DiscriminatorValue, T])[];\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\ntype GetEncoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Encoder\n ? TFrom extends object\n ? TFrom\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype GetDecoderTypeFromVariants<\n TVariants extends Variants>,\n TDiscriminatorProperty extends string,\n> = DrainOuterGeneric<{\n [I in ArrayIndices]: (TVariants[I][1] extends Decoder\n ? TTo extends object\n ? TTo\n : object\n : never) & { [P in TDiscriminatorProperty]: TVariants[I][0] };\n}>[ArrayIndices];\n\ntype UnionEncoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeEncoder>\n : Encoder>;\n\ntype UnionDecoder>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeDecoder>\n : Decoder>;\n\ntype UnionCodec>, TDiscriminatorProperty extends string> =\n TVariants extends Variants>\n ? FixedSizeCodec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >\n : Codec<\n GetEncoderTypeFromVariants,\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >;\n\n/**\n * Returns an encoder for discriminated unions.\n *\n * This encoder serializes objects that follow the discriminated union pattern\n * by prefixing them with a numerical discriminator that represents their variant.\n *\n * Unlike {@link getUnionEncoder}, this encoder automatically extracts and processes\n * the discriminator property (default: `__kind`) from each variant.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant encoders as `[discriminator, encoder]` pairs.\n * @param config - Configuration options for encoding.\n * @returns An `Encoder` for encoding discriminated union objects.\n *\n * @example\n * Encoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageEncoder = getDiscriminatedUnionEncoder([\n * ['Quit', getUnitEncoder()],\n * ['Write', getStructEncoder([['fields', getTupleEncoder([addCodecSizePrefix(getUtf8Encoder(), getU32Encoder())])]])],\n * ['Move', getStructEncoder([['x', getI32Encoder()], ['y', getI32Encoder()]])]\n * ]);\n *\n * messageEncoder.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionEncoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionEncoder {\n type TFrom = GetEncoderTypeFromVariants;\n const discriminatorProperty = (config.discriminator ?? '__kind') as TDiscriminatorProperty;\n const prefix = config.size ?? getU8Encoder();\n return getUnionEncoder(\n variants.map(([, variant], index) =>\n transformEncoder(getTupleEncoder([prefix, variant]), (value: TFrom): [number, TFrom] => [index, value]),\n ),\n value => getVariantDiscriminator(variants, value[discriminatorProperty]),\n ) as UnionEncoder;\n}\n\n/**\n * Returns a decoder for discriminated unions.\n *\n * This decoder deserializes objects that follow the discriminated union pattern\n * by **reading a numerical discriminator** and mapping it to the corresponding variant.\n *\n * Unlike {@link getUnionDecoder}, this decoder automatically inserts the discriminator\n * property (default: `__kind`) into the decoded object.\n *\n * For more details, see {@link getDiscriminatedUnionCodec}.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant decoders as `[discriminator, decoder]` pairs.\n * @param config - Configuration options for decoding.\n * @returns A `Decoder` for decoding discriminated union objects.\n *\n * @example\n * Decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageDecoder = getDiscriminatedUnionDecoder([\n * ['Quit', getUnitDecoder()],\n * ['Write', getStructDecoder([['fields', getTupleDecoder([addCodecSizePrefix(getUtf8Decoder(), getU32Decoder())])]])],\n * ['Move', getStructDecoder([['x', getI32Decoder()], ['y', getI32Decoder()]])]\n * ]);\n *\n * messageDecoder.decode(new Uint8Array([0x02,0x05,0x00,0x00,0x00,0x06,0x00,0x00,0x00]));\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @see {@link getDiscriminatedUnionCodec}\n */\nexport function getDiscriminatedUnionDecoder<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionDecoder {\n const discriminatorProperty = config.discriminator ?? '__kind';\n const prefix = config.size ?? getU8Decoder();\n return getUnionDecoder(\n variants.map(([discriminator, variant]) =>\n transformDecoder(getTupleDecoder([prefix, variant]), ([, value]) => ({\n [discriminatorProperty]: discriminator,\n ...value,\n })),\n ),\n (bytes, offset) => Number(prefix.read(bytes, offset)[0]),\n ) as UnionDecoder;\n}\n\n/**\n * Returns a codec for encoding and decoding {@link DiscriminatedUnion}.\n *\n * A {@link DiscriminatedUnion} is a TypeScript representation of Rust-like enums, where\n * each variant is distinguished by a discriminator field (default: `__kind`).\n *\n * This codec inserts a numerical prefix to represent the variant index.\n *\n * @typeParam TVariants - The variants of the discriminated union.\n * @typeParam TDiscriminatorProperty - The property used as the discriminator.\n *\n * @param variants - The variant codecs as `[discriminator, codec]` pairs.\n * @param config - Configuration options for encoding/decoding.\n * @returns A `Codec` for encoding and decoding discriminated union objects.\n *\n * @example\n * Encoding and decoding a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Quit' } // Empty variant.\n * | { __kind: 'Write'; fields: [string] } // Tuple variant.\n * | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Quit', getUnitCodec()],\n * ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],\n * ['Move', getStructCodec([['x', getI32Codec()], ['y', getI32Codec()]])]\n * ]);\n *\n * messageCodec.encode({ __kind: 'Move', x: 5, y: 6 });\n * // 0x020500000006000000\n * // | | └── Field y (6)\n * // | └── Field x (5)\n * // └── 1-byte discriminator (Index 2 — the \"Move\" variant)\n *\n * const value = messageCodec.decode(bytes);\n * // { __kind: 'Move', x: 5, y: 6 }\n * ```\n *\n * @example\n * Using a `u32` discriminator instead of `u8`.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { size: getU32Codec() });\n *\n * codec.encode({ __kind: 'Quit' });\n * // 0x00000000\n * // └------┘ 4-byte discriminator (Index 0)\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00]));\n * // { __kind: 'Quit' }\n * ```\n *\n * @example\n * Customizing the discriminator property.\n * ```ts\n * const codec = getDiscriminatedUnionCodec([...], { discriminator: 'message' });\n *\n * codec.encode({ message: 'Quit' }); // 0x00\n * codec.decode(new Uint8Array([0x00])); // { message: 'Quit' }\n * ```\n *\n * @remarks\n * Separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available.\n *\n * ```ts\n * const bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' });\n * const message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes);\n * ```\n *\n * @see {@link getDiscriminatedUnionEncoder}\n * @see {@link getDiscriminatedUnionDecoder}\n */\nexport function getDiscriminatedUnionCodec<\n const TVariants extends Variants>,\n const TDiscriminatorProperty extends string = '__kind',\n>(\n variants: TVariants,\n config: DiscriminatedUnionCodecConfig = {},\n): UnionCodec {\n return combineCodec(\n getDiscriminatedUnionEncoder(variants, config) as Encoder<\n GetEncoderTypeFromVariants\n >,\n getDiscriminatedUnionDecoder(variants, config) as Decoder<\n GetDecoderTypeFromVariants &\n GetEncoderTypeFromVariants\n >,\n ) as UnionCodec;\n}\n\nfunction getVariantDiscriminator | Encoder>>(\n variants: TVariants,\n discriminatorValue: DiscriminatorValue,\n) {\n const discriminator = variants.findIndex(([key]) => discriminatorValue === key);\n if (discriminator < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, {\n value: discriminatorValue,\n variants: variants.map(([key]) => key),\n });\n }\n return discriminator;\n}\n","/**\n * Defines the \"lookup object\" of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * ```\n */\nexport type EnumLookupObject = { [key: string]: number | string };\n\n/**\n * Returns the allowed input for an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionInput = GetEnumFrom; // \"Left\" | \"Right\" | 0 | 1\n * ```\n */\nexport type GetEnumFrom = TEnum[keyof TEnum] | keyof TEnum;\n\n/**\n * Returns all the available variants of an enum.\n *\n * @example\n * ```ts\n * enum Direction { Left, Right };\n * type DirectionOutput = GetEnumTo; // 0 | 1\n * ```\n */\nexport type GetEnumTo = TEnum[keyof TEnum];\n\nexport function getEnumStats(constructor: EnumLookupObject) {\n const numericalValues = [...new Set(Object.values(constructor).filter(v => typeof v === 'number'))].sort();\n const enumRecord = Object.fromEntries(Object.entries(constructor).slice(numericalValues.length)) as Record<\n string,\n number | string\n >;\n const enumKeys = Object.keys(enumRecord);\n const enumValues = Object.values(enumRecord);\n const stringValues: string[] = [\n ...new Set([...enumKeys, ...enumValues.filter((v): v is string => typeof v === 'string')]),\n ];\n\n return { enumKeys, enumRecord, enumValues, numericalValues, stringValues };\n}\n\nexport function getEnumIndexFromVariant({\n enumKeys,\n enumValues,\n variant,\n}: {\n enumKeys: string[];\n enumValues: (number | string)[];\n variant: number | string | symbol;\n}): number {\n const valueIndex = findLastIndex(enumValues, value => value === variant);\n if (valueIndex >= 0) return valueIndex;\n return enumKeys.findIndex(key => key === variant);\n}\n\nexport function getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n}: {\n discriminator: number;\n enumKeys: string[];\n enumValues: (number | string)[];\n useValuesAsDiscriminators: boolean;\n}): number {\n if (!useValuesAsDiscriminators) {\n return discriminator >= 0 && discriminator < enumKeys.length ? discriminator : -1;\n }\n return findLastIndex(enumValues, value => value === discriminator);\n}\n\nfunction findLastIndex(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): number {\n let l = array.length;\n while (l--) {\n if (predicate(array[l], l, array)) return l;\n }\n return -1;\n}\n\nexport function formatNumericalValues(values: number[]): string {\n if (values.length === 0) return '';\n let range: [number, number] = [values[0], values[0]];\n const ranges: string[] = [];\n for (let index = 1; index < values.length; index++) {\n const value = values[index];\n if (range[1] + 1 === value) {\n range[1] = value;\n } else {\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n range = [value, value];\n }\n }\n ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);\n return ranges.join(', ');\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,\n SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,\n SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,\n SolanaError,\n} from '@solana/errors';\n\nimport {\n EnumLookupObject,\n formatNumericalValues,\n GetEnumFrom,\n getEnumIndexFromDiscriminator,\n getEnumIndexFromVariant,\n getEnumStats,\n GetEnumTo,\n} from './enum-helpers';\n\n/**\n * Defines the configuration options for enum codecs.\n *\n * The `size` option determines the numerical encoding used for the enum's discriminant.\n * By default, enums are stored as a `u8` (1 byte).\n *\n * The `useValuesAsDiscriminators` option allows mapping the actual enum values\n * as discriminators instead of using their positional index.\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type EnumCodecConfig = {\n /**\n * The codec used to encode/decode the enum discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n\n /**\n * If set to `true`, the enum values themselves will be used as discriminators.\n * This is only valid for numerical enum values.\n *\n * @defaultValue `false`\n */\n useValuesAsDiscriminators?: boolean;\n};\n\n/**\n * Returns an encoder for enums.\n *\n * This encoder serializes enums as a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding the enum.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding enums.\n *\n * @example\n * Encoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const encoder = getEnumEncoder(Direction);\n *\n * encoder.encode(Direction.Up); // 0x00\n * encoder.encode(Direction.Down); // 0x01\n * encoder.encode(Direction.Left); // 0x02\n * encoder.encode(Direction.Right); // 0x03\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeEncoder, 1>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeEncoder>;\nexport function getEnumEncoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Encoder> {\n const prefix = config.size ?? getU8Encoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues, stringValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformEncoder(prefix, (variant: GetEnumFrom): number => {\n const index = getEnumIndexFromVariant({ enumKeys, enumValues, variant });\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, {\n formattedNumericalValues: formatNumericalValues(numericalValues),\n numericalValues,\n stringValues,\n variant,\n });\n }\n return useValuesAsDiscriminators ? (enumValues[index] as number) : index;\n });\n}\n\n/**\n * Returns a decoder for enums.\n *\n * This decoder deserializes enums from a numerical discriminator.\n * By default, the discriminator is based on the positional index of the enum variants.\n *\n * For more details, see {@link getEnumCodec}.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for decoding the enum.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding enums.\n *\n * @example\n * Decoding enum values.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const decoder = getEnumDecoder(Direction);\n *\n * decoder.decode(new Uint8Array([0x00])); // Direction.Up\n * decoder.decode(new Uint8Array([0x01])); // Direction.Down\n * decoder.decode(new Uint8Array([0x02])); // Direction.Left\n * decoder.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @see {@link getEnumCodec}\n */\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeDecoder, 1>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeDecoder>;\nexport function getEnumDecoder(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Decoder> {\n const prefix = config.size ?? getU8Decoder();\n const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;\n const { enumKeys, enumValues, numericalValues } = getEnumStats(constructor);\n if (useValuesAsDiscriminators && enumValues.some(value => typeof value === 'string')) {\n throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {\n stringValues: enumValues.filter((v): v is string => typeof v === 'string'),\n });\n }\n return transformDecoder(prefix, (value: bigint | number): GetEnumTo => {\n const discriminator = Number(value);\n const index = getEnumIndexFromDiscriminator({\n discriminator,\n enumKeys,\n enumValues,\n useValuesAsDiscriminators,\n });\n if (index < 0) {\n const validDiscriminators = useValuesAsDiscriminators\n ? numericalValues\n : [...Array(enumKeys.length).keys()];\n throw new SolanaError(SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator,\n formattedValidDiscriminators: formatNumericalValues(validDiscriminators),\n validDiscriminators,\n });\n }\n return enumValues[index] as GetEnumTo;\n });\n}\n\n/**\n * Returns a codec for encoding and decoding enums.\n *\n * This codec serializes enums as a numerical discriminator, allowing them\n * to be efficiently stored and reconstructed from binary data.\n *\n * By default, the discriminator is derived from the positional index\n * of the enum variant, but it can be configured to use the enum's numeric values instead.\n *\n * @typeParam TEnum - The TypeScript enum or object mapping enum keys to values.\n *\n * @param constructor - The constructor of the enum.\n * @param config - Configuration options for encoding and decoding the enum.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding enums.\n *\n * @example\n * Encoding and decoding enums using positional indexes.\n * ```ts\n * enum Direction { Up, Down, Left, Right }\n * const codec = getEnumCodec(Direction);\n *\n * codec.encode(Direction.Up); // 0x00\n * codec.encode(Direction.Down); // 0x01\n * codec.encode(Direction.Left); // 0x02\n * codec.encode(Direction.Right); // 0x03\n *\n * codec.decode(new Uint8Array([0x00])); // Direction.Up\n * codec.decode(new Uint8Array([0x01])); // Direction.Down\n * codec.decode(new Uint8Array([0x02])); // Direction.Left\n * codec.decode(new Uint8Array([0x03])); // Direction.Right\n * ```\n *\n * @example\n * Encoding and decoding enums using their numeric values.\n * ```ts\n * enum GameDifficulty { Easy = 1, Normal = 4, Hard = 7, Expert = 9 }\n * const codec = getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true });\n *\n * codec.encode(GameDifficulty.Easy); // 0x01\n * codec.encode(GameDifficulty.Normal); // 0x04\n * codec.encode(GameDifficulty.Hard); // 0x07\n * codec.encode(GameDifficulty.Expert); // 0x09\n *\n * codec.decode(new Uint8Array([0x01])); // GameDifficulty.Easy\n * codec.decode(new Uint8Array([0x04])); // GameDifficulty.Normal\n * codec.decode(new Uint8Array([0x07])); // GameDifficulty.Hard\n * codec.decode(new Uint8Array([0x09])); // GameDifficulty.Expert\n * ```\n *\n * Note that, when using values as discriminators, the enum values must be numerical.\n * Otherwise, an error will be thrown.\n *\n * ```ts\n * enum GameDifficulty { Easy = 'EASY', Normal = 'NORMAL', Hard = 'HARD' }\n * getEnumCodec(GameDifficulty, { useValuesAsDiscriminators: true }); // Throws an error.\n * ```\n *\n * @example\n * Using a custom discriminator size.\n * ```ts\n * enum Status { Pending, Approved, Rejected }\n * const codec = getEnumCodec(Status, { size: getU16Codec() });\n *\n * codec.encode(Status.Pending); // 0x0000\n * codec.encode(Status.Approved); // 0x0100\n * codec.encode(Status.Rejected); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // Status.Pending\n * codec.decode(new Uint8Array([0x01, 0x00])); // Status.Approved\n * codec.decode(new Uint8Array([0x02, 0x00])); // Status.Rejected\n * ```\n *\n * @remarks\n * Separate {@link getEnumEncoder} and {@link getEnumDecoder} functions are available.\n *\n * ```ts\n * const bytes = getEnumEncoder(Direction).encode(Direction.Up);\n * const value = getEnumDecoder(Direction).decode(bytes);\n * ```\n *\n * @see {@link getEnumEncoder}\n * @see {@link getEnumDecoder}\n */\nexport function getEnumCodec(\n constructor: TEnum,\n config?: Omit, 'size'>,\n): FixedSizeCodec, GetEnumTo, 1>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetEnumTo, TSize>;\nexport function getEnumCodec(\n constructor: TEnum,\n config?: EnumCodecConfig,\n): VariableSizeCodec, GetEnumTo>;\nexport function getEnumCodec(\n constructor: TEnum,\n config: EnumCodecConfig = {},\n): Codec, GetEnumTo> {\n return combineCodec(getEnumEncoder(constructor, config), getEnumDecoder(constructor, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that prefixes encoded values with hidden data.\n *\n * This encoder applies a list of void encoders before encoding the main value.\n * The prefixed data is encoded before the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param prefixedEncoders - A list of void encoders that produce the hidden prefix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden prefix.\n *\n * @example\n * Prefixing a value with constants.\n * ```ts\n * const encoder = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixEncoder(\n encoder: FixedSizeEncoder,\n prefixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenPrefixEncoder(\n encoder: Encoder,\n prefixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([...prefixedEncoders, encoder]) as Encoder,\n (value: TFrom) => [...prefixedEncoders.map(() => undefined), value] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden prefixed data before decoding the main value.\n *\n * This decoder applies a list of void decoders before decoding the main value.\n * The prefixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenPrefixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param prefixedDecoders - A list of void decoders that produce the hidden prefix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden prefix.\n *\n * @example\n * Decoding a value with prefixed constants.\n * ```ts\n * const decoder = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 0x48, 0x65, 0x6C, 0x6C, 0x6F]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenPrefixCodec}\n */\nexport function getHiddenPrefixDecoder(\n decoder: FixedSizeDecoder,\n prefixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenPrefixDecoder(\n decoder: Decoder,\n prefixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([...prefixedDecoders, decoder]) as Decoder,\n tuple => tuple[tuple.length - 1] as TTo,\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden prefix.\n *\n * - **Encoding:** Prefixes the value with hidden data before encoding.\n * - **Decoding:** Skips the hidden prefix before decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param prefixedCodecs - A list of void codecs that produce the hidden prefix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden prefix.\n *\n * @example\n * Encoding and decoding a value with prefixed constants.\n * ```ts\n * const codec = getHiddenPrefixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x01020304050648656c6c6f\n * // | | └-- Our encoded value (\"Hello\").\n * // | └-- Our second hidden prefix.\n * // └-- Our first hidden prefix.\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes before a value, consider using {@link padLeftCodec} instead.\n *\n * Separate {@link getHiddenPrefixEncoder} and {@link getHiddenPrefixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenPrefixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenPrefixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenPrefixEncoder}\n * @see {@link getHiddenPrefixDecoder}\n */\nexport function getHiddenPrefixCodec(\n codec: FixedSizeCodec,\n prefixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenPrefixCodec(\n codec: Codec,\n prefixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenPrefixEncoder(codec, prefixedCodecs), getHiddenPrefixDecoder(codec, prefixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Returns an encoder that appends hidden data after the encoded value.\n *\n * This encoder applies a list of void encoders after encoding the main value.\n * The suffixed data is encoded after the main value without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param encoder - The encoder for the main value.\n * @param suffixedEncoders - A list of void encoders that produce the hidden suffix.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` that encodes the value with a hidden suffix.\n *\n * @example\n * Suffixing a value with constants.\n * ```ts\n * const encoder = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * encoder.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixEncoder(\n encoder: FixedSizeEncoder,\n suffixedEncoders: readonly FixedSizeEncoder[],\n): FixedSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): VariableSizeEncoder;\nexport function getHiddenSuffixEncoder(\n encoder: Encoder,\n suffixedEncoders: readonly Encoder[],\n): Encoder {\n return transformEncoder(\n getTupleEncoder([encoder, ...suffixedEncoders]) as Encoder,\n (value: TFrom) => [value, ...suffixedEncoders.map(() => undefined)] as const,\n );\n}\n\n/**\n * Returns a decoder that skips hidden suffixed data after decoding the main value.\n *\n * This decoder applies a list of void decoders after decoding the main value.\n * The suffixed data is skipped during decoding without being exposed to the user.\n *\n * For more details, see {@link getHiddenSuffixCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param decoder - The decoder for the main value.\n * @param suffixedDecoders - A list of void decoders that produce the hidden suffix.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` that decodes values while ignoring the hidden suffix.\n *\n * @example\n * Decoding a value with suffixed constants.\n * ```ts\n * const decoder = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * decoder.decode(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F, 1, 2, 3, 4, 5, 6]));\n * // 'Hello'\n * ```\n *\n * @see {@link getHiddenSuffixCodec}\n */\nexport function getHiddenSuffixDecoder(\n decoder: FixedSizeDecoder,\n suffixedDecoders: readonly FixedSizeDecoder[],\n): FixedSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): VariableSizeDecoder;\nexport function getHiddenSuffixDecoder(\n decoder: Decoder,\n suffixedDecoders: readonly Decoder[],\n): Decoder {\n return transformDecoder(\n getTupleDecoder([decoder, ...suffixedDecoders]) as Decoder,\n tuple => tuple[0],\n );\n}\n\n/**\n * Returns a codec that encodes and decodes values with a hidden suffix.\n *\n * - **Encoding:** Appends hidden data after encoding the main value.\n * - **Decoding:** Skips the hidden suffix after decoding the main value.\n *\n * This is useful for any implicit metadata that should be present in\n * binary formats but omitted from the API.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param codec - The codec for the main value.\n * @param suffixedCodecs - A list of void codecs that produce the hidden suffix.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding values with a hidden suffix.\n *\n * @example\n * Encoding and decoding a value with suffixed constants.\n * ```ts\n * const codec = getHiddenSuffixCodec(getUtf8Codec(), [\n * getConstantCodec(new Uint8Array([1, 2, 3])),\n * getConstantCodec(new Uint8Array([4, 5, 6])),\n * ]);\n *\n * const bytes = codec.encode('Hello');\n * // 0x48656c6c6f010203040506\n * // | | └-- Our second hidden suffix.\n * // | └-- Our first hidden suffix.\n * // └-- Our encoded value (\"Hello\").\n *\n * codec.decode(bytes);\n * // 'Hello'\n * ```\n *\n * @remarks\n * If all you need is padding zeroes after a value, consider using {@link padRightCodec} instead.\n *\n * Separate {@link getHiddenSuffixEncoder} and {@link getHiddenSuffixDecoder} functions are available.\n *\n * ```ts\n * const bytes = getHiddenSuffixEncoder(getUtf8Encoder(), [\n * getConstantEncoder(new Uint8Array([1, 2, 3])),\n * getConstantEncoder(new Uint8Array([4, 5, 6])),\n * ]).encode('Hello');\n *\n * const value = getHiddenSuffixDecoder(getUtf8Decoder(), [\n * getConstantDecoder(new Uint8Array([1, 2, 3])),\n * getConstantDecoder(new Uint8Array([4, 5, 6])),\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getHiddenSuffixEncoder}\n * @see {@link getHiddenSuffixDecoder}\n */\nexport function getHiddenSuffixCodec(\n codec: FixedSizeCodec,\n suffixedCodecs: readonly FixedSizeCodec[],\n): FixedSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): VariableSizeCodec;\nexport function getHiddenSuffixCodec(\n codec: Codec,\n suffixedCodecs: readonly Codec[],\n): Codec {\n return combineCodec(getHiddenSuffixEncoder(codec, suffixedCodecs), getHiddenSuffixDecoder(codec, suffixedCodecs));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,\n SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\n/**\n * Defines the configuration options for literal union codecs.\n *\n * A literal union codec encodes values from a predefined set of literals.\n * The `size` option determines the numerical encoding used for the discriminant.\n * By default, literals are stored as a `u8` (1 byte).\n *\n * @typeParam TDiscriminator - A number codec, encoder, or decoder used for the discriminant.\n */\nexport type LiteralUnionCodecConfig = {\n /**\n * The codec used to encode/decode the discriminator.\n * @defaultValue `u8` discriminator.\n */\n size?: TDiscriminator;\n};\n\ntype Variant = bigint | boolean | number | string | null | undefined;\ntype GetTypeFromVariants = TVariants[number];\n\n/**\n * Returns an encoder for literal unions.\n *\n * This encoder serializes a value from a predefined set of literals\n * as a numerical index representing its position in the `variants` array.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding the literal union.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding literal unions.\n *\n * @example\n * Encoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeEncoder = getLiteralUnionEncoder(['small', 'medium', 'large']);\n *\n * sizeEncoder.encode('small'); // 0x00\n * sizeEncoder.encode('medium'); // 0x01\n * sizeEncoder.encode('large'); // 0x02\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n): FixedSizeEncoder, 1>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberEncoder },\n): FixedSizeEncoder, TSize>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeEncoder>;\nexport function getLiteralUnionEncoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Encoder> {\n const discriminator = config.size ?? getU8Encoder();\n return transformEncoder(discriminator, variant => {\n const index = variants.indexOf(variant);\n if (index < 0) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, {\n value: variant,\n variants,\n });\n }\n return index;\n });\n}\n\n/**\n * Returns a decoder for literal unions.\n *\n * This decoder deserializes a numerical index into a corresponding\n * value from a predefined set of literals.\n *\n * For more details, see {@link getLiteralUnionCodec}.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for decoding the literal union.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding literal unions.\n *\n * @example\n * Decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeDecoder = getLiteralUnionDecoder(['small', 'medium', 'large']);\n *\n * sizeDecoder.decode(new Uint8Array([0x00])); // 'small'\n * sizeDecoder.decode(new Uint8Array([0x01])); // 'medium'\n * sizeDecoder.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @see {@link getLiteralUnionCodec}\n */\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n): FixedSizeDecoder, 1>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberDecoder },\n): FixedSizeDecoder, TSize>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeDecoder>;\nexport function getLiteralUnionDecoder(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Decoder> {\n const discriminator = config.size ?? getU8Decoder();\n return transformDecoder(discriminator, (index: bigint | number) => {\n if (index < 0 || index >= variants.length) {\n throw new SolanaError(SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, {\n discriminator: index,\n maxRange: variants.length - 1,\n minRange: 0,\n });\n }\n return variants[Number(index)];\n });\n}\n\n/**\n * Returns a codec for encoding and decoding literal unions.\n *\n * A literal union codec serializes and deserializes values\n * from a predefined set of literals, using a numerical index\n * to represent each value in the `variants` array.\n *\n * This allows efficient storage and retrieval of common\n * predefined values such as enum-like structures in TypeScript.\n *\n * @typeParam TVariants - A tuple of allowed literal values.\n *\n * @param variants - The possible literal values for the union.\n * @param config - Configuration options for encoding and decoding the literal union.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding literal unions.\n *\n * @example\n * Encoding and decoding a union of string literals.\n * ```ts\n * type Size = 'small' | 'medium' | 'large';\n * const sizeCodec = getLiteralUnionCodec(['small', 'medium', 'large']);\n *\n * sizeCodec.encode('small'); // 0x00\n * sizeCodec.encode('medium'); // 0x01\n * sizeCodec.encode('large'); // 0x02\n *\n * sizeCodec.decode(new Uint8Array([0x00])); // 'small'\n * sizeCodec.decode(new Uint8Array([0x01])); // 'medium'\n * sizeCodec.decode(new Uint8Array([0x02])); // 'large'\n * ```\n *\n * @example\n * Encoding and decoding a union of number literals.\n * ```ts\n * type Level = 10 | 20 | 30;\n * const levelCodec = getLiteralUnionCodec([10, 20, 30]);\n *\n * levelCodec.encode(10); // 0x00\n * levelCodec.encode(20); // 0x01\n * levelCodec.encode(30); // 0x02\n *\n * levelCodec.decode(new Uint8Array([0x00])); // 10\n * levelCodec.decode(new Uint8Array([0x01])); // 20\n * levelCodec.decode(new Uint8Array([0x02])); // 30\n * ```\n *\n * @example\n * Using a custom discriminator size with different variant types.\n * ```ts\n * type MaybeBoolean = false | true | \"either\";\n * const codec = getLiteralUnionCodec([false, true, 'either'], { size: getU16Codec() });\n *\n * codec.encode(false); // 0x0000\n * codec.encode(true); // 0x0100\n * codec.encode('either'); // 0x0200\n *\n * codec.decode(new Uint8Array([0x00, 0x00])); // false\n * codec.decode(new Uint8Array([0x01, 0x00])); // true\n * codec.decode(new Uint8Array([0x02, 0x00])); // 'either'\n * ```\n *\n * @remarks\n * Separate {@link getLiteralUnionEncoder} and {@link getLiteralUnionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getLiteralUnionEncoder(['red', 'green', 'blue']).encode('green');\n * const value = getLiteralUnionDecoder(['red', 'green', 'blue']).decode(bytes);\n * ```\n *\n * @see {@link getLiteralUnionEncoder}\n * @see {@link getLiteralUnionDecoder}\n */\nexport function getLiteralUnionCodec(\n variants: TVariants,\n): FixedSizeCodec, GetTypeFromVariants, 1>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig & { size: FixedSizeNumberCodec },\n): FixedSizeCodec, GetTypeFromVariants, TSize>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config?: LiteralUnionCodecConfig,\n): VariableSizeCodec>;\nexport function getLiteralUnionCodec(\n variants: TVariants,\n config: LiteralUnionCodecConfig = {},\n): Codec> {\n return combineCodec(getLiteralUnionEncoder(variants, config), getLiteralUnionDecoder(variants, config));\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\n\n/**\n * Defines the configuration options for map codecs.\n *\n * The `size` option determines how the number of entries in the map is stored.\n * It can be:\n * - A {@link NumberCodec} to prefix the map with its size.\n * - A fixed number of entries.\n * - `'remainder'`, which infers the number of entries based on the remaining bytes.\n * This option is only available for fixed-size keys and values.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used for the size prefix.\n */\nexport type MapCodecConfig = {\n /**\n * The size of the map.\n * @defaultValue u32 prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for maps.\n *\n * This encoder serializes maps where the keys and values are encoded\n * using the provided key and value encoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n *\n * @param key - The encoder for the map's keys.\n * @param value - The encoder for the map's values.\n * @param config - Configuration options for encoding the map.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding maps.\n *\n * @example\n * Encoding a map with a `u32` size prefix.\n * ```ts\n * const encoder = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder());\n * const bytes = encoder.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getMapEncoder(\n key: FixedSizeEncoder,\n value: FixedSizeEncoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config?: MapCodecConfig,\n): VariableSizeEncoder>;\nexport function getMapEncoder(\n key: Encoder,\n value: Encoder,\n config: MapCodecConfig = {},\n): Encoder> {\n return transformEncoder(\n getArrayEncoder(getTupleEncoder([key, value]), config as object),\n (map: Map): [TFromKey, TFromValue][] => [...map.entries()],\n );\n}\n\n/**\n * Returns a decoder for maps.\n *\n * This decoder deserializes maps where the keys and values are decoded\n * using the provided key and value decoders. The number of entries\n * is determined by the `size` configuration.\n *\n * For more details, see {@link getMapCodec}.\n *\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The decoder for the map's keys.\n * @param value - The decoder for the map's values.\n * @param config - Configuration options for decoding the map.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding maps.\n *\n * @example\n * Decoding a map with a `u32` size prefix.\n * ```ts\n * const decoder = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder());\n * const map = decoder.decode(new Uint8Array([\n * 0x02,0x00,0x00,0x00,0x61,0x6c,0x69,0x63,0x65,0x2a,0x62,0x6f,0x62,0x00,0x00,0x05\n * ]));\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @see {@link getMapCodec}\n */\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getMapDecoder(\n key: FixedSizeDecoder,\n value: FixedSizeDecoder,\n config: MapCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config?: MapCodecConfig,\n): VariableSizeDecoder>;\nexport function getMapDecoder(\n key: Decoder,\n value: Decoder,\n config: MapCodecConfig = {},\n): Decoder> {\n return transformDecoder(\n getArrayDecoder(getTupleDecoder([key, value]), config as object) as Decoder<[TToKey, TToValue][]>,\n (entries: [TToKey, TToValue][]): Map => new Map(entries),\n );\n}\n\n/**\n * Returns a codec for encoding and decoding maps.\n *\n * This codec serializes maps where the key/value pairs are encoded\n * and decoded one after another using the provided key and value codecs.\n * The number of entries is determined by the `size` configuration and\n * defaults to a `u32` size prefix.\n *\n * @typeParam TFromKey - The type of the keys before encoding.\n * @typeParam TFromValue - The type of the values before encoding.\n * @typeParam TToKey - The type of the keys after decoding.\n * @typeParam TToValue - The type of the values after decoding.\n *\n * @param key - The codec for the map's keys.\n * @param value - The codec for the map's values.\n * @param config - Configuration options for encoding and decoding the map.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding maps.\n *\n * @example\n * Encoding and decoding a map with a `u32` size prefix (default).\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec());\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x02000000616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 4-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with a `u16` size prefix.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x0200616c6963652a626f62000005\n * // | | | | └── Value (5)\n * // | | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | | └── Value (42)\n * // | └── Key (\"alice\", 5 bytes fixed)\n * // └── 2-byte prefix (2 entries)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a fixed-size map.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 2 });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @example\n * Encoding and decoding a map with remainder size.\n * ```ts\n * const codec = getMapCodec(fixCodecSize(getUtf8Codec(), 5), getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Map([['alice', 42], ['bob', 5]]));\n * // 0x616c6963652a626f62000005\n * // | | | └── Value (5)\n * // | | └── Key (\"bob\", 5 bytes fixed, null-padded)\n * // | └── Value (42)\n * // └── Key (\"alice\", 5 bytes fixed)\n * // No size prefix, the size is inferred from the remaining bytes.\n *\n * const map = codec.decode(bytes);\n * // new Map([['alice', 42], ['bob', 5]])\n * ```\n *\n * @remarks\n * Separate {@link getMapEncoder} and {@link getMapDecoder} functions are available.\n * ```ts\n * const bytes = getMapEncoder(fixCodecSize(getUtf8Encoder(), 5), getU8Encoder()).encode(new Map([['alice', 42]]));\n * const map = getMapDecoder(fixCodecSize(getUtf8Decoder(), 5), getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getMapEncoder}\n * @see {@link getMapDecoder}\n */\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig & { size: 0 },\n): FixedSizeCodec, Map, 0>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: FixedSizeCodec,\n value: FixedSizeCodec,\n config: MapCodecConfig & { size: number },\n): FixedSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config?: MapCodecConfig,\n): VariableSizeCodec, Map>;\nexport function getMapCodec<\n TFromKey,\n TFromValue,\n TToKey extends TFromKey = TFromKey,\n TToValue extends TFromValue = TFromValue,\n>(\n key: Codec,\n value: Codec,\n config: MapCodecConfig = {},\n): Codec, Map> {\n return combineCodec(getMapEncoder(key, value, config as object), getMapDecoder(key, value, config as object));\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\n\n/**\n * Returns an encoder for `void` values.\n *\n * This encoder writes nothing to the byte array and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op encoder,\n * such as empty variants in {@link getDiscriminatedUnionEncoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeEncoder`, representing an empty encoder.\n *\n * @example\n * Encoding a `void` value.\n * ```ts\n * getUnitEncoder().encode(undefined); // Produces an empty byte array.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitEncoder(): FixedSizeEncoder {\n return createEncoder({\n fixedSize: 0,\n write: (_value, _bytes, offset) => offset,\n });\n}\n\n/**\n * Returns a decoder for `void` values.\n *\n * This decoder always returns `undefined` and has a fixed size of 0 bytes.\n * It is useful when working with structures that require a no-op decoder,\n * such as empty variants in {@link getDiscriminatedUnionDecoder}.\n *\n * For more details, see {@link getUnitCodec}.\n *\n * @returns A `FixedSizeDecoder`, representing an empty decoder.\n *\n * @example\n * Decoding a `void` value.\n * ```ts\n * getUnitDecoder().decode(anyBytes); // Returns `undefined`.\n * ```\n *\n * @see {@link getUnitCodec}\n */\nexport function getUnitDecoder(): FixedSizeDecoder {\n return createDecoder({\n fixedSize: 0,\n read: (_bytes: ReadonlyUint8Array | Uint8Array, offset) => [undefined, offset],\n });\n}\n\n/**\n * Returns a codec for `void` values.\n *\n * This codec does nothing when encoding or decoding and has a fixed size of 0 bytes.\n * Namely, it always returns `undefined` when decoding and produces an empty byte array when encoding.\n *\n * This can be useful when working with structures that require a no-op codec,\n * such as empty variants in {@link getDiscriminatedUnionCodec}.\n *\n * @returns A `FixedSizeCodec`, representing an empty codec.\n *\n * @example\n * Encoding and decoding a `void` value.\n * ```ts\n * const codec = getUnitCodec();\n *\n * codec.encode(undefined); // Produces an empty byte array.\n * codec.decode(new Uint8Array([])); // Returns `undefined`.\n * ```\n *\n * @example\n * Using unit codecs as empty variants in a discriminated union.\n * ```ts\n * type Message =\n * | { __kind: 'Enter' }\n * | { __kind: 'Leave' }\n * | { __kind: 'Move'; x: number; y: number };\n *\n * const messageCodec = getDiscriminatedUnionCodec([\n * ['Enter', getUnitCodec()], // <- No-op codec for empty data\n * ['Leave', getUnitCodec()], // <- No-op codec for empty data\n * ['Move', getStructCodec([...])]\n * ]);\n * ```\n *\n * @remarks\n * Separate {@link getUnitEncoder} and {@link getUnitDecoder} functions are available.\n *\n * ```ts\n * const bytes = getUnitEncoder().encode();\n * const value = getUnitDecoder().decode(bytes);\n * ```\n *\n * @see {@link getUnitEncoder}\n * @see {@link getUnitDecoder}\n */\nexport function getUnitCodec(): FixedSizeCodec {\n return combineCodec(getUnitEncoder(), getUnitDecoder());\n}\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { getBooleanDecoder, getBooleanEncoder } from './boolean';\nimport { getConstantDecoder, getConstantEncoder } from './constant';\nimport { getTupleDecoder, getTupleEncoder } from './tuple';\nimport { getUnionDecoder, getUnionEncoder } from './union';\nimport { getUnitDecoder, getUnitEncoder } from './unit';\n\n/**\n * Defines the configuration options for nullable codecs.\n *\n * This configuration controls how nullable values are encoded and decoded.\n *\n * By default, nullable values are prefixed with a `u8` (0 = `null`, 1 = present).\n * The `noneValue` and `prefix` options allow customizing this behavior.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n * @see {@link getNullableCodec}\n */\nexport type NullableCodecConfig = {\n /**\n * Specifies how `null` values are represented in the encoded data.\n *\n * - By default, `null` values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec.\n * - Custom byte array: `null` values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; `null` values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between `null` and present values.\n *\n * - By default, a `u8` prefix is used (`0 = null`, `1 = present`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines `null`.\n * If no `noneValue` is set, `null` is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values, allowing `null` values to be encoded.\n *\n * This encoder serializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are replaced with the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding nullable values.\n *\n * @example\n * Encoding an optional number.\n * ```ts\n * const encoder = getNullableEncoder(getU32Encoder());\n *\n * encoder.encode(null); // 0x00\n * encoder.encode(42); // 0x012a000000\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder;\nexport function getNullableEncoder(\n item: FixedSizeEncoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder;\nexport function getNullableEncoder(\n item: Encoder,\n config: NullableCodecConfig = {},\n): Encoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: TFrom): [boolean, TFrom] => [true, value]),\n ],\n variant => Number(variant !== null),\n );\n}\n\n/**\n * Returns a decoder for optional values, allowing `null` values to be recognized.\n *\n * This decoder deserializes an optional value using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `null` values are identified by zeroes.\n * - If `noneValue` is a byte array, `null` values match the provided constant.\n *\n * For more details, see {@link getNullableCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding nullable values.\n *\n * @example\n * Decoding an optional number.\n * ```ts\n * const decoder = getNullableDecoder(getU32Decoder());\n *\n * decoder.decode(new Uint8Array([0x00])); // null\n * decoder.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @see {@link getNullableCodec}\n */\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder;\nexport function getNullableDecoder(\n item: FixedSizeDecoder,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder;\nexport function getNullableDecoder(\n item: Decoder,\n config: NullableCodecConfig = {},\n): Decoder {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => null),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]): TTo => value),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values, allowing `null` values to be handled.\n *\n * This codec serializes and deserializes optional values using a configurable approach:\n * - By default, a `u8` prefix is used (0 = `null`, 1 = present).\n * This can be customized using a custom number codec or even disabled by setting\n * the `prefix` to `null`.\n * - If `noneValue: 'zeroes'` is set, `null` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `null` values are represented by the provided constant.\n *\n * For more details on the configuration options, see {@link NullableCodecConfig}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding optional values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding nullable values.\n *\n * @example\n * Encoding and decoding an optional number using a `u8` prefix (default).\n * ```ts\n * const codec = getNullableCodec(getU32Codec());\n *\n * codec.encode(null); // 0x00\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding an optional number using a fixed-size codec, by filling `null` values with zeroes.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), { noneValue: 'zeroes' });\n *\n * codec.encode(null); // 0x0000000000\n * codec.encode(42); // 0x012a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x01, 0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with zeroes and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU32Codec(), {\n * noneValue: 'zeroes',\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0x00000000\n * codec.encode(42); // 0x2a000000\n *\n * codec.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00])); // 42\n * ```\n *\n * @example\n * Encoding and decoding `null` values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * codec.encode(null); // 0xffff\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([0xff, 0xff])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @example\n * Identifying `null` values by the absence of bytes.\n * ```ts\n * const codec = getNullableCodec(getU16Codec(), { prefix: null });\n *\n * codec.encode(null); // Empty bytes\n * codec.encode(42); // 0x2a00\n *\n * codec.decode(new Uint8Array([])); // null\n * codec.decode(new Uint8Array([0x2a, 0x00])); // 42\n * ```\n *\n * @remarks\n * Separate {@link getNullableEncoder} and {@link getNullableDecoder} functions are available.\n *\n * ```ts\n * const bytes = getNullableEncoder(getU32Encoder()).encode(42);\n * const value = getNullableDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getNullableEncoder}\n * @see {@link getNullableDecoder}\n */\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec;\nexport function getNullableCodec(\n item: FixedSizeCodec,\n config: NullableCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config?: NullableCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec;\nexport function getNullableCodec(\n item: Codec,\n config: NullableCodecConfig = {},\n): Codec {\n type ConfigCast = NullableCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getNullableEncoder(item, config as ConfigCast),\n getNullableDecoder(item, config as ConfigCast),\n );\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { ArrayLikeCodecSize, getArrayDecoder, getArrayEncoder } from './array';\n\n/**\n * Defines the configuration options for set codecs.\n *\n * This configuration allows specifying how the size of the set is encoded.\n * The `size` option can be:\n *\n * - A {@link NumberCodec}, {@link NumberEncoder}, or {@link NumberDecoder} to store the size as a prefix.\n * - A fixed number of items, enforcing a strict length.\n * - The string `'remainder'` to infer the set size from the remaining bytes (only for fixed-size items).\n *\n * @typeParam TPrefix - The type used for encoding the size of the set.\n */\nexport type SetCodecConfig = {\n /**\n * The size encoding strategy for the set.\n * @defaultValue Uses a `u32` prefix.\n */\n size?: ArrayLikeCodecSize;\n};\n\n/**\n * Returns an encoder for sets of items.\n *\n * This encoder serializes `Set` values by encoding each item using the provided item encoder.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n *\n * @param item - The encoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns An `Encoder>` for encoding sets of items.\n *\n * @example\n * Encoding a set of `u8` numbers.\n * ```ts\n * const encoder = getSetEncoder(getU8Encoder());\n * const bytes = encoder.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeEncoder, 0>;\nexport function getSetEncoder(\n item: FixedSizeEncoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config?: SetCodecConfig,\n): VariableSizeEncoder>;\nexport function getSetEncoder(\n item: Encoder,\n config: SetCodecConfig = {},\n): Encoder> {\n return transformEncoder(getArrayEncoder(item, config as object), (set: Set): TFrom[] => [...set]);\n}\n\n/**\n * Returns a decoder for sets of items.\n *\n * This decoder deserializes a `Set` from a byte array by decoding each item using the provided item decoder.\n * The number of items is determined by a `u32` size prefix by default.\n *\n * For more details, see {@link getSetCodec}.\n *\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The decoder to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Decoder>` for decoding sets of items.\n *\n * @example\n * Decoding a set of `u8` numbers.\n * ```ts\n * const decoder = getSetDecoder(getU8Decoder());\n * const value = decoder.decode(new Uint8Array([0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03]));\n * // new Set([1, 2, 3])\n * ```\n *\n * @see {@link getSetCodec}\n */\nexport function getSetDecoder(\n item: Decoder,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeDecoder, 0>;\nexport function getSetDecoder(\n item: FixedSizeDecoder,\n config: SetCodecConfig & { size: number },\n): FixedSizeDecoder>;\nexport function getSetDecoder(\n item: Decoder,\n config?: SetCodecConfig,\n): VariableSizeDecoder>;\nexport function getSetDecoder(item: Decoder, config: SetCodecConfig = {}): Decoder> {\n return transformDecoder(getArrayDecoder(item, config as object), (entries: TTo[]): Set => new Set(entries));\n}\n\n/**\n * Returns a codec for encoding and decoding sets of items.\n *\n * This codec serializes `Set` values by encoding each item using the provided item codec.\n * The number of items is stored as a prefix using a `u32` codec by default.\n *\n * @typeParam TFrom - The type of the items in the set before encoding.\n * @typeParam TTo - The type of the items in the set after decoding.\n *\n * @param item - The codec to use for each set item.\n * @param config - Optional configuration specifying the size strategy.\n * @returns A `Codec, Set>` for encoding and decoding sets.\n *\n * @example\n * Encoding and decoding a set of `u8` numbers.\n * ```ts\n * const codec = getSetCodec(getU8Codec());\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x03000000010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 4-byte prefix indicating 3 items.\n *\n * const value = codec.decode(bytes);\n * // new Set([1, 2, 3])\n * ```\n *\n * @example\n * Using a `u16` prefix for size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: getU16Codec() });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x0300010203\n * // | └-- 3 items of 1 byte each.\n * // └-- 2-byte prefix indicating 3 items.\n * ```\n *\n * @example\n * Using a fixed-size set.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 3 });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- Exactly 3 items of 1 byte each.\n * ```\n *\n * @example\n * Using remainder to infer set size.\n * ```ts\n * const codec = getSetCodec(getU8Codec(), { size: 'remainder' });\n * const bytes = codec.encode(new Set([1, 2, 3]));\n * // 0x010203\n * // └-- 3 items of 1 byte each. The size is inferred from the remaining bytes.\n * ```\n *\n * @remarks\n * Separate {@link getSetEncoder} and {@link getSetDecoder} functions are available.\n *\n * ```ts\n * const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3]));\n * const value = getSetDecoder(getU8Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getSetEncoder}\n * @see {@link getSetDecoder}\n */\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig & { size: 0 },\n): FixedSizeCodec, Set, 0>;\nexport function getSetCodec(\n item: FixedSizeCodec,\n config: SetCodecConfig & { size: number },\n): FixedSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config?: SetCodecConfig,\n): VariableSizeCodec, Set>;\nexport function getSetCodec(\n item: Codec,\n config: SetCodecConfig = {},\n): Codec, Set> {\n return combineCodec(getSetEncoder(item, config as object), getSetDecoder(item, config as object));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n ReadonlyUint8Array,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { DrainOuterGeneric, getFixedSize, getMaxSize, sumCodecSizes } from './utils';\n\n/**\n * Represents a collection of named fields used in struct codecs.\n *\n * Each field is defined as a tuple containing:\n * - A string key representing the field name.\n * - A codec used to encode and decode the field's value.\n *\n * @typeParam T - The codec type used for each field.\n */\ntype Fields = readonly (readonly [string, T])[];\n\ntype ArrayIndices = Exclude['length'], T['length']> & number;\n\n/**\n * Infers the TypeScript type for an object that can be encoded using a struct codec.\n *\n * This type maps the provided field encoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n */\ntype GetEncoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Encoder ? TFrom : never;\n}>;\n\n/**\n * Infers the TypeScript type for an object that can be decoded using a struct codec.\n *\n * This type maps the provided field decoders to their corresponding values.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n */\ntype GetDecoderTypeFromFields>> = DrainOuterGeneric<{\n [I in ArrayIndices as TFields[I][0]]: TFields[I][1] extends Decoder ? TTo : never;\n}>;\n\n/**\n * Returns an encoder for custom objects.\n *\n * This encoder serializes an object by encoding its fields sequentially,\n * using the provided field encoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with an encoder.\n *\n * @param fields - The name and encoder of each field.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding custom objects.\n *\n * @example\n * Encoding a custom struct.\n * ```ts\n * const encoder = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]);\n *\n * const bytes = encoder.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructEncoder>>(\n fields: TFields,\n): FixedSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): VariableSizeEncoder>;\nexport function getStructEncoder>>(\n fields: TFields,\n): Encoder> {\n type TFrom = GetEncoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createEncoder({\n ...(fixedSize === null\n ? {\n getSizeFromValue: (value: TFrom) =>\n fields\n .map(([key, codec]) => getEncodedSize(value[key as keyof TFrom], codec))\n .reduce((all, one) => all + one, 0),\n maxSize,\n }\n : { fixedSize }),\n write: (struct: TFrom, bytes, offset) => {\n fields.forEach(([key, codec]) => {\n offset = codec.write(struct[key as keyof TFrom], bytes, offset);\n });\n return offset;\n },\n });\n}\n\n/**\n * Returns a decoder for custom objects.\n *\n * This decoder deserializes an object by decoding its fields sequentially,\n * using the provided field decoders.\n *\n * For more details, see {@link getStructCodec}.\n *\n * @typeParam TFields - The fields of the struct, each paired with a decoder.\n *\n * @param fields - The name and decoder of each field.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding custom objects.\n *\n * @example\n * Decoding a custom struct.\n * ```ts\n * const decoder = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]);\n *\n * const struct = decoder.decode(new Uint8Array([\n * 0x41,0x6c,0x69,0x63,0x65,0x2a\n * ]));\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @see {@link getStructCodec}\n */\nexport function getStructDecoder>>(\n fields: TFields,\n): FixedSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): VariableSizeDecoder>;\nexport function getStructDecoder>>(\n fields: TFields,\n): Decoder> {\n type TTo = GetDecoderTypeFromFields;\n const fieldCodecs = fields.map(([, codec]) => codec);\n const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));\n const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? undefined;\n\n return createDecoder({\n ...(fixedSize === null ? { maxSize } : { fixedSize }),\n read: (bytes: ReadonlyUint8Array | Uint8Array, offset) => {\n const struct = {} as TTo;\n fields.forEach(([key, codec]) => {\n const [value, newOffset] = codec.read(bytes, offset);\n offset = newOffset;\n struct[key as keyof TTo] = value;\n });\n return [struct, offset];\n },\n });\n}\n\n/**\n * Returns a codec for encoding and decoding custom objects.\n *\n * This codec serializes objects by encoding and decoding each field sequentially.\n *\n * @typeParam TFields - The fields of the struct, each paired with a codec.\n *\n * @param fields - The name and codec of each field.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding custom objects.\n *\n * @example\n * Encoding and decoding a custom struct.\n * ```ts\n * const codec = getStructCodec([\n * ['name', fixCodecSize(getUtf8Codec(), 5)],\n * ['age', getU8Codec()]\n * ]);\n *\n * const bytes = codec.encode({ name: 'Alice', age: 42 });\n * // 0x416c6963652a\n * // | └── Age (42)\n * // └── Name (\"Alice\")\n *\n * const struct = codec.decode(bytes);\n * // { name: 'Alice', age: 42 }\n * ```\n *\n * @remarks\n * Separate {@link getStructEncoder} and {@link getStructDecoder} functions are available.\n *\n * ```ts\n * const bytes = getStructEncoder([\n * ['name', fixCodecSize(getUtf8Encoder(), 5)],\n * ['age', getU8Encoder()]\n * ]).encode({ name: 'Alice', age: 42 });\n *\n * const struct = getStructDecoder([\n * ['name', fixCodecSize(getUtf8Decoder(), 5)],\n * ['age', getU8Decoder()]\n * ]).decode(bytes);\n * ```\n *\n * @see {@link getStructEncoder}\n * @see {@link getStructDecoder}\n */\nexport function getStructCodec>>(\n fields: TFields,\n): FixedSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): VariableSizeCodec<\n GetEncoderTypeFromFields,\n GetDecoderTypeFromFields & GetEncoderTypeFromFields\n>;\nexport function getStructCodec>>(\n fields: TFields,\n): Codec, GetDecoderTypeFromFields & GetEncoderTypeFromFields> {\n return combineCodec(\n getStructEncoder(fields),\n getStructDecoder(fields) as Decoder & GetEncoderTypeFromFields>,\n );\n}\n","/**\n * An implementation of the Rust `Option` type in JavaScript.\n *\n * In Rust, optional values are represented using `Option`, which can be either:\n * - `Some(T)`, indicating a present value.\n * - `None`, indicating the absence of a value.\n *\n * In JavaScript, this is typically represented as `T | null`. However, this approach fails with nested options.\n * For example, `Option>` in Rust would translate to `T | null | null` in JavaScript, which is equivalent to `T | null`.\n * This means there is no way to differentiate between `Some(None)` and `None`, making nested options impossible.\n *\n * This `Option` type helps solve this by mirroring Rust’s `Option` type.\n *\n * ```ts\n * type Option = Some | None;\n * type Some = { __option: 'Some'; value: T };\n * type None = { __option: 'None' };\n * ```\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Here's how you can create `Option` values.\n *\n * To improve developer experience, helper functions are available.\n * TypeScript can infer the type of `T` or it can be explicitly provided.\n *\n * ```ts\n * // Create an option with a value.\n * some('Hello World');\n * some(123);\n *\n * // Create an empty option.\n * none();\n * none();\n * ```\n *\n * @see {@link Some}\n * @see {@link None}\n * @see {@link some}\n * @see {@link none}\n */\nexport type Option = None | Some;\n\n/**\n * A flexible type that allows working with {@link Option} values or nullable values.\n *\n * It defines a looser type that can be used when encoding {@link Option | Options}.\n * This allows us to pass `null` or the nested value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Accepting both `Option` and `T | null` as input.\n * ```ts\n * function double(value: OptionOrNullable) {\n * const option = isOption(value) ? value : wrapNullable(value);\n * return isSome(option) ? option.value * 2 : 'No value';\n * }\n *\n * double(42); // 84\n * double(some(21)); // 42\n * double(none()); // \"No value\"\n * double(null); // \"No value\"\n * ```\n *\n * @see {@link Option}\n * @see {@link isOption}\n * @see {@link wrapNullable}\n */\nexport type OptionOrNullable = Option | T | null;\n\n/**\n * Represents an {@link Option} that contains a value.\n *\n * This type mirrors Rust’s `Some(T)`, indicating that a value is present.\n *\n * For more details, see {@link Option}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @example\n * Creating a `Some` value.\n * ```ts\n * const value = some(42);\n * isSome(value); // true\n * isNone(value); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link some}\n * @see {@link isSome}\n */\nexport type Some = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an {@link Option} that contains no value.\n *\n * This type mirrors Rust’s `None`, indicating the absence of a value.\n *\n * For more details, see {@link Option}.\n *\n * @example\n * Creating a `None` value.\n * ```ts\n * const empty = none();\n * isNone(empty); // true\n * isSome(empty); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link none}\n * @see {@link isNone}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} that contains a value.\n *\n * This function explicitly wraps a value in an {@link Option} type.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param value - The value to wrap in an {@link Option}.\n * @returns An {@link Option} containing the provided value.\n *\n * @example\n * Wrapping a value in an `Option`.\n * ```ts\n * const option = some('Hello');\n * option.value; // \"Hello\"\n * isOption(option); // true\n * isSome(option); // true\n * isNone(option); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const some = (value: T): Option => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} that contains no value.\n *\n * This function explicitly represents an absent value.\n *\n * @typeParam T - The type of the expected absent value.\n *\n * @returns An {@link Option} containing no value.\n *\n * @example\n * Creating an empty `Option`.\n * ```ts\n * const empty = none();\n * isOption(empty); // true\n * isSome(empty); // false\n * isNone(empty); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const none = (): Option => ({ __option: 'None' });\n\n/**\n * Checks whether the given value is an {@link Option}.\n *\n * This function determines whether an input follows the `Option` structure.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param input - The value to check.\n * @returns `true` if the value is an {@link Option}, `false` otherwise.\n *\n * @example\n * Checking for `Option` values.\n * ```ts\n * isOption(some(42)); // true\n * isOption(none()); // true\n * isOption(42); // false\n * isOption(null); // false\n * isOption(\"anything else\"); // false\n * ```\n *\n * @see {@link Option}\n */\nexport const isOption = (input: unknown): input is Option =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Checks whether the given {@link Option} contains a value.\n *\n * This function acts as a type guard, ensuring the value is a {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link Some}, `false` otherwise.\n *\n * @example\n * Checking for `Some` values.\n * ```ts\n * isSome(some(42)); // true\n * isSome(none()); // false\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n */\nexport const isSome = (option: Option): option is Some => option.__option === 'Some';\n\n/**\n * Checks whether the given {@link Option} contains no value.\n *\n * This function acts as a type guard, ensuring the value is a {@link None}.\n *\n * @typeParam T - The type of the expected value.\n *\n * @param option - The {@link Option} to check.\n * @returns `true` if the option is a {@link None}, `false` otherwise.\n *\n * @example\n * Checking for `None` values.\n * ```ts\n * isNone(some(42)); // false\n * isNone(none()); // true\n * ```\n *\n * @see {@link Option}\n * @see {@link None}\n */\nexport const isNone = (option: Option): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option}, returning its contained value or a fallback.\n *\n * This function extracts the value `T` from an `Option` type.\n * - If the option is {@link Some}, it returns the contained value `T`.\n * - If the option is {@link None}, it returns the fallback value `U`, which defaults to `null`.\n *\n * @typeParam T - The type of the contained value.\n * @typeParam U - The type of the fallback value (defaults to `null`).\n *\n * @param option - The {@link Option} to unwrap.\n * @param fallback - A function that provides a fallback value if the option is {@link None}.\n * @returns The contained value if {@link Some}, otherwise the fallback value.\n *\n * @example\n * Unwrapping an `Option` with no fallback.\n * ```ts\n * unwrapOption(some('Hello World')); // \"Hello World\"\n * unwrapOption(none()); // null\n * ```\n *\n * @example\n * Providing a custom fallback value.\n * ```ts\n * unwrapOption(some('Hello World'), () => 'Default'); // \"Hello World\"\n * unwrapOption(none(), () => 'Default'); // \"Default\"\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport function unwrapOption(option: Option): T | null;\nexport function unwrapOption(option: Option, fallback: () => U): T | U;\nexport function unwrapOption(option: Option, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n *\n * - If the input value is `null`, this function returns {@link None}.\n * - Otherwise, it wraps the value in {@link Some}.\n *\n * @typeParam T - The type of the contained value.\n *\n * @param nullable - The nullable value to wrap.\n * @returns An {@link Option} wrapping the value.\n *\n * @example\n * Wrapping nullable values.\n * ```ts\n * wrapNullable('Hello World'); // Option (Some)\n * wrapNullable(null); // Option (None)\n * ```\n *\n * @see {@link Option}\n * @see {@link Some}\n * @see {@link None}\n */\nexport const wrapNullable = (nullable: T | null): Option => (nullable !== null ? some(nullable) : none());\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n containsBytes,\n Decoder,\n Encoder,\n fixDecoderSize,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n fixEncoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getUnionDecoder,\n getUnionEncoder,\n getUnitDecoder,\n getUnitEncoder,\n} from '@solana/codecs-data-structures';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, None, none, Option, OptionOrNullable, Some, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/**\n * Defines the configuration options for {@link Option} codecs.\n *\n * The `getOptionCodec` function behaves similarly to {@link getNullableCodec}\n * but encodes `Option` types instead of `T | null` types.\n *\n * This configuration controls how {@link None} values are encoded and how presence\n * is determined when decoding.\n *\n * @typeParam TPrefix - A number codec, encoder, or decoder used as the presence prefix.\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n * @see {@link getOptionCodec}\n */\nexport type OptionCodecConfig = {\n /**\n * Specifies how {@link None} values are represented in the encoded data.\n *\n * - By default, {@link None} values are omitted from encoding.\n * - `'zeroes'`: The bytes allocated for the value are filled with zeroes. This requires a fixed-size codec for the item.\n * - Custom byte array: {@link None} values are replaced with a predefined byte sequence. This results in a variable-size codec.\n *\n * @defaultValue No explicit `noneValue` is used; {@link None} values are omitted.\n */\n noneValue?: ReadonlyUint8Array | 'zeroes';\n\n /**\n * The presence prefix used to distinguish between {@link None} and present values.\n *\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - Custom number codec: Allows defining a different number size for the prefix.\n * - `null`: No prefix is used; `noneValue` (if provided) determines {@link None}.\n * If no `noneValue` is set, {@link None} is identified by the absence of bytes.\n *\n * @defaultValue `u8` prefix.\n */\n prefix?: TPrefix | null;\n};\n\n/**\n * Returns an encoder for optional values using the {@link Option} type.\n *\n * This encoder serializes an {@link OptionOrNullable} value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, {@link None} values are encoded as zeroes.\n * - If `noneValue` is a byte array, {@link None} values are replaced with the provided constant.\n *\n * Unlike {@link getNullableEncoder}, this encoder accepts both {@link Option} and {@link Nullable} values.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n *\n * @param item - The encoder for the value that may be present.\n * @param config - Configuration options for encoding optional values.\n * @returns A `FixedSizeEncoder` or `VariableSizeEncoder` for encoding option values.\n *\n * @example\n * Encoding an optional string.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const encoder = getOptionEncoder(stringCodec);\n *\n * encoder.encode(some('Hi'));\n * encoder.encode('Hi');\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * encoder.encode(none());\n * encoder.encode(null);\n * // 0x00\n * // └-- 1-byte prefix (None).\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeEncoder, TSize>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeEncoder>;\nexport function getOptionEncoder(\n item: FixedSizeEncoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeEncoder>;\nexport function getOptionEncoder(\n item: Encoder,\n config: OptionCodecConfig = {},\n): Encoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformEncoder(getUnitEncoder(), (_boolean: boolean) => undefined);\n }\n return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixEncoderSize(getUnitEncoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitEncoder();\n }\n return getConstantEncoder(config.noneValue);\n })();\n\n return getUnionEncoder(\n [\n transformEncoder(getTupleEncoder([prefix, noneValue]), (_value: None | null): [boolean, void] => [\n false,\n undefined,\n ]),\n transformEncoder(getTupleEncoder([prefix, item]), (value: Some | TFrom): [boolean, TFrom] => [\n true,\n isOption(value) && isSome(value) ? value.value : value,\n ]),\n ],\n variant => {\n const option = isOption(variant) ? variant : wrapNullable(variant);\n return Number(isSome(option));\n },\n );\n}\n\n/**\n * Returns a decoder for optional values using the {@link Option} type.\n *\n * This decoder deserializes an `Option` value using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`). This can be customized or disabled.\n * - If `noneValue: 'zeroes'` is set, `None` values are identified by zeroes.\n * - If `noneValue` is a byte array, `None` values match the provided constant.\n *\n * Unlike {@link getNullableDecoder}, this decoder always outputs an {@link Option} type.\n *\n * For more details, see {@link getOptionCodec}.\n *\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The decoder for the value that may be present.\n * @param config - Configuration options for decoding optional values.\n * @returns A `FixedSizeDecoder` or `VariableSizeDecoder` for decoding option values.\n *\n * @example\n * Decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const decoder = getOptionDecoder(stringCodec);\n *\n * decoder.decode(new Uint8Array([0x01, 0x02, 0x00, 0x00, 0x00, 0x48, 0x69]));\n * // some('Hi')\n *\n * decoder.decode(new Uint8Array([0x00]));\n * // none()\n * ```\n *\n * @see {@link getOptionCodec}\n */\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeDecoder, TSize>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeDecoder>;\nexport function getOptionDecoder(\n item: FixedSizeDecoder,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeDecoder>;\nexport function getOptionDecoder(\n item: Decoder,\n config: OptionCodecConfig = {},\n): Decoder> {\n const prefix = (() => {\n if (config.prefix === null) {\n return transformDecoder(getUnitDecoder(), () => false);\n }\n return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });\n })();\n const noneValue = (() => {\n if (config.noneValue === 'zeroes') {\n assertIsFixedSize(item);\n return fixDecoderSize(getUnitDecoder(), item.fixedSize);\n }\n if (!config.noneValue) {\n return getUnitDecoder();\n }\n return getConstantDecoder(config.noneValue);\n })();\n\n return getUnionDecoder(\n [\n transformDecoder(getTupleDecoder([prefix, noneValue]), () => none()),\n transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value)),\n ],\n (bytes, offset) => {\n if (config.prefix === null && !config.noneValue) {\n return Number(offset < bytes.length);\n }\n if (config.prefix === null && config.noneValue != null) {\n const zeroValue =\n config.noneValue === 'zeroes' ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;\n return containsBytes(bytes, zeroValue, offset) ? 0 : 1;\n }\n return Number(prefix.read(bytes, offset)[0]);\n },\n );\n}\n\n/**\n * Returns a codec for encoding and decoding optional values using the {@link Option} type.\n *\n * This codec serializes and deserializes `Option` values using a configurable approach:\n * - By default, a `u8` prefix is used (`0 = None`, `1 = Some`).\n * - If `noneValue: 'zeroes'` is set, `None` values are encoded/decoded as zeroes.\n * - If `noneValue` is a byte array, `None` values are represented by the provided constant.\n * - If `prefix: null` is set, the codec determines `None` values solely from `noneValue` or the presence of bytes.\n *\n * For more details on the configuration options, see {@link OptionCodecConfig}.\n *\n * Note that this behaves similarly to {@link getNullableCodec}, except it\n * encodes {@link OptionOrNullable} values and decodes {@link Option} values.\n *\n * @typeParam TFrom - The type of the main value being encoded.\n * @typeParam TTo - The type of the main value being decoded.\n *\n * @param item - The codec for the value that may be present.\n * @param config - Configuration options for encoding and decoding option values.\n * @returns A `FixedSizeCodec` or `VariableSizeCodec` for encoding and decoding option values.\n *\n * @example\n * Encoding and decoding an optional string with a size prefix.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode(some('Hi'));\n * // 0x01020000004869\n * // | | └-- utf8 string content (\"Hi\").\n * // | └-- u32 string prefix (2 characters).\n * // └-- 1-byte prefix (Some).\n *\n * const noneBytes = codec.encode(none());\n * // 0x00\n * // └-- 1-byte prefix (None).\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding nullable values.\n * ```ts\n * const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n * const codec = getOptionCodec(stringCodec);\n *\n * const someBytes = codec.encode('Hi'); // 0x01020000004869\n * const noneBytes = codec.encode(null); // 0x00\n *\n * codec.decode(someBytes); // some('Hi')\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding an optional number with a fixed size.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { noneValue: 'zeroes' });\n *\n * const someBytes = codec.encode(some(42)); // 0x012a00\n * const noneBytes = codec.encode(none()); // 0x000000\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Encoding and decoding {@link None} values with a custom byte sequence and no prefix.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), {\n * noneValue: new Uint8Array([0xff, 0xff]),\n * prefix: null,\n * });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // 0xffff\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @example\n * Identifying {@link None} values by the absence of bytes.\n * ```ts\n * const codec = getOptionCodec(getU16Codec(), { prefix: null });\n *\n * const someBytes = codec.encode(some(42)); // 0x2a00\n * const noneBytes = codec.encode(none()); // new Uint8Array(0)\n *\n * codec.decode(someBytes); // some(42)\n * codec.decode(noneBytes); // none()\n * ```\n *\n * @remarks\n * Separate {@link getOptionEncoder} and {@link getOptionDecoder} functions are available.\n *\n * ```ts\n * const bytes = getOptionEncoder(getU32Encoder()).encode(some(42));\n * const value = getOptionDecoder(getU32Decoder()).decode(bytes);\n * ```\n *\n * @see {@link getOptionEncoder}\n * @see {@link getOptionDecoder}\n */\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes'; prefix: null },\n): FixedSizeCodec, Option, TSize>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): FixedSizeCodec, Option>;\nexport function getOptionCodec(\n item: FixedSizeCodec,\n config: OptionCodecConfig & { noneValue: 'zeroes' },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config?: OptionCodecConfig & { noneValue?: ReadonlyUint8Array },\n): VariableSizeCodec, Option>;\nexport function getOptionCodec(\n item: Codec,\n config: OptionCodecConfig = {},\n): Codec, Option> {\n type ConfigCast = OptionCodecConfig & { noneValue?: ReadonlyUint8Array };\n return combineCodec(\n getOptionEncoder(item, config as ConfigCast),\n getOptionDecoder(item, config as ConfigCast),\n );\n}\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Defines types that should not be recursively unwrapped.\n *\n * These types are preserved as-is when using {@link unwrapOptionRecursively}.\n *\n * @see {@link unwrapOptionRecursively}\n */\ntype UnUnwrappables =\n | Date\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | bigint\n | boolean\n | number\n | string\n | symbol\n | null\n | undefined;\n\n/**\n * A type that recursively unwraps nested {@link Option} types.\n *\n * This type resolves all nested {@link Option} values, ensuring\n * that deeply wrapped values are properly extracted.\n *\n * - If `T` is an {@link Option}, it resolves to the contained value.\n * - If `T` is a known primitive or immutable type, it remains unchanged.\n * - If `T` is an object or array, it recursively unwraps any options found.\n *\n * The fallback type `U` (default: `null`) is used in place of `None` values.\n *\n * @typeParam T - The type to be unwrapped.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @example\n * Resolving nested `Option` types.\n * ```ts\n * UnwrappedOption>>; // string\n * UnwrappedOption; // null\n * ```\n *\n * @example\n * Resolving options inside objects and arrays.\n * ```ts\n * UnwrappedOption<{ a: Some; b: None }>; // { a: number; b: null }\n * UnwrappedOption<[Some, None]>; // [number, null]\n * ```\n *\n * @see {@link unwrapOptionRecursively}\n */\nexport type UnwrappedOption =\n T extends Some\n ? UnwrappedOption\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption }\n : T extends Array\n ? Array>\n : T;\n\n/**\n * Recursively unwraps all nested {@link Option} types within a value.\n *\n * This function traverses a given value and removes all instances\n * of {@link Option}, replacing them with their contained values.\n *\n * - If an {@link Option} is encountered, its value is extracted.\n * - If an array or object is encountered, its elements are traversed recursively.\n * - If `None` is encountered, it is replaced with the fallback value (default: `null`).\n *\n * @typeParam T - The type of the input value.\n * @typeParam U - The fallback type for `None` values (defaults to `null`).\n *\n * @param input - The value to unwrap.\n * @param fallback - A function that provides a fallback value for `None` options.\n * @returns The recursively unwrapped value.\n *\n * @example\n * Recursively unwrapping nested options.\n * ```ts\n * unwrapOptionRecursively(some(some('Hello World'))); // \"Hello World\"\n * unwrapOptionRecursively(some(none())); // null\n * ```\n *\n * @example\n * Recursively unwrapping options inside objects and arrays.\n * ```ts\n * unwrapOptionRecursively({\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * });\n * // { a: \"hello\", b: null, c: [{ c1: 42 }, { c2: null }] }\n * ```\n *\n * @example\n * Using a fallback value for `None` options.\n * ```ts\n * unwrapOptionRecursively(\n * {\n * a: 'hello',\n * b: none(),\n * c: [{ c1: some(42) }, { c2: none() }],\n * },\n * () => 'Default',\n * );\n * // { a: \"hello\", b: \"Default\", c: [{ c1: 42 }, { c2: \"Default\" }] }\n * ```\n *\n * @remarks\n * This function does not mutate objects or arrays.\n *\n * @see {@link Option}\n * @see {@link UnwrappedOption}\n */\nexport function unwrapOptionRecursively(input: T): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback: () => U): UnwrappedOption;\nexport function unwrapOptionRecursively(input: T, fallback?: () => U): UnwrappedOption {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption;\n }\n\n const next = (x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption;\n return (fallback ? fallback() : null) as UnwrappedOption;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption;\n }\n return input as UnwrappedOption;\n}\n","export * from '@solana/codecs-core';\nexport * from '@solana/codecs-data-structures';\nexport * from '@solana/codecs-numbers';\nexport * from '@solana/codecs-strings';\nexport * from '@solana/options';\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","/**\n * A pipeline is a solution that allows you to perform successive transforms of a value using functions. This is useful when building up a transaction message.\n *\n * Until the [pipeline operator](https://github.com/tc39/proposal-pipeline-operator) becomes part of JavaScript you can use this utility to create pipelines.\n *\n * Following common implementations of pipe functions that use TypeScript, this function supports a maximum arity of 10 for type safety.\n *\n * Note you can use nested pipes to extend this limitation, like so:\n * ```ts\n * const myValue = pipe(\n * pipe(\n * 1,\n * (x) => x + 1,\n * (x) => x * 2,\n * (x) => x - 1,\n * ),\n * (y) => y / 3,\n * (y) => y + 1,\n * );\n * ```\n *\n * @see https://github.com/ramda/ramda/blob/master/source/pipe.js\n * @see https://github.com/darky/rocket-pipes/blob/master/index.ts\n *\n * @example Basic\n * ```ts\n * const add = (a, b) => a + b;\n * const add10 = x => add(x, 10);\n * const add100 = x => add(x, 100);\n * const sum = pipe(1, add10, add100);\n * sum === 111; // true\n * ```\n *\n * @example Building a Solana transaction message\n * ```ts\n * const transferTransactionMessage = pipe(\n * // The result of the first expression...\n * createTransactionMessage({ version: 0 }),\n * // ...gets passed as the sole argument to the next function in the pipeline.\n * tx => setTransactionMessageFeePayer(myAddress, tx),\n * // The return value of that function gets passed to the next...\n * tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n * // ...and so on.\n * tx => appendTransactionMessageInstruction(createTransferInstruction(myAddress, toAddress, amountInLamports), tx),\n * );\n * ```\n *\n * @returns The initial value\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n): TInitial;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n): R1;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n): R2;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n): R3;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n): R4;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n): R5;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n): R6;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n): R7;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n): R8;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n): R9;\n/**\n * @returns The return value of the final transform function\n */\nexport function pipe(\n /** The initial value */\n init: TInitial,\n /** The function with which to transform the initial value */\n init_r1: (init: TInitial) => R1,\n /** The function with which to transform the return value of the prior function */\n r1_r2: (r1: R1) => R2,\n /** The function with which to transform the return value of the prior function */\n r2_r3: (r2: R2) => R3,\n /** The function with which to transform the return value of the prior function */\n r3_r4: (r3: R3) => R4,\n /** The function with which to transform the return value of the prior function */\n r4_r5: (r4: R4) => R5,\n /** The function with which to transform the return value of the prior function */\n r5_r6: (r5: R5) => R6,\n /** The function with which to transform the return value of the prior function */\n r6_r7: (r6: R6) => R7,\n /** The function with which to transform the return value of the prior function */\n r7_r8: (r7: R7) => R8,\n /** The function with which to transform the return value of the prior function */\n r8_r9: (r8: R8) => R9,\n /** The function with which to transform the return value of the prior function */\n r9_r10: (r9: R9) => R10,\n): R10;\nexport function pipe(init: TInitial, ...fns: CallableFunction[]) {\n return fns.reduce((acc, fn) => fn(acc), init);\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,\n SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,\n SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { AccountLookupMeta, AccountMeta } from './accounts';\n\n/**\n * An instruction destined for a given program.\n *\n * @example\n * ```ts\n * type StakeProgramInstruction = Instruction<'StakeConfig11111111111111111111111111111111'>;\n * ```\n */\nexport interface Instruction<\n TProgramAddress extends string = string,\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n> {\n readonly accounts?: TAccounts;\n readonly data?: ReadonlyUint8Array;\n readonly programAddress: Address;\n}\n\n/**\n * An instruction that loads certain accounts.\n *\n * @example\n * ```ts\n * type InstructionWithTwoAccounts = InstructionWithAccounts<\n * [\n * WritableAccount, // First account\n * RentSysvar, // Second account\n * ]\n * >;\n * ```\n */\nexport interface InstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[],\n> extends Instruction {\n readonly accounts: TAccounts;\n}\n\nexport function isInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): instruction is TInstruction & { programAddress: Address } {\n return instruction.programAddress === programAddress;\n}\n\nexport function assertIsInstructionForProgram(\n instruction: TInstruction,\n programAddress: Address,\n): asserts instruction is TInstruction & { programAddress: Address } {\n if (instruction.programAddress !== programAddress) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, {\n actualProgramAddress: instruction.programAddress,\n expectedProgramAddress: programAddress,\n });\n }\n}\n\nexport function isInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithAccounts & TInstruction {\n return instruction.accounts !== undefined;\n}\n\nexport function assertIsInstructionWithAccounts<\n TAccounts extends readonly (AccountLookupMeta | AccountMeta)[] = readonly (AccountLookupMeta | AccountMeta)[],\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithAccounts & TInstruction {\n if (instruction.accounts === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, {\n data: instruction.data,\n programAddress: instruction.programAddress,\n });\n }\n}\n\n/**\n * An instruction whose data conforms to a certain type.\n *\n * This is most useful when you have a branded `Uint8Array` that represents a particular\n * instruction's data.\n *\n * @example A type for the \\`AdvanceNonce\\` instruction of the System program\n * ```ts\n * type AdvanceNonceAccountInstruction<\n * TNonceAccountAddress extends string = string,\n * TNonceAuthorityAddress extends string = string,\n * > = Instruction<'11111111111111111111111111111111'> &\n * InstructionWithAccounts<\n * [\n * WritableAccount,\n * ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n * ReadonlySignerAccount,\n * ]\n * > &\n * InstructionWithData;\n * ```\n */\nexport interface InstructionWithData extends Instruction {\n readonly data: TData;\n}\n\nexport function isInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): instruction is InstructionWithData & TInstruction {\n return instruction.data !== undefined;\n}\n\nexport function assertIsInstructionWithData<\n TData extends ReadonlyUint8Array = ReadonlyUint8Array,\n TInstruction extends Instruction = Instruction,\n>(instruction: TInstruction): asserts instruction is InstructionWithData & TInstruction {\n if (instruction.data === undefined) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, {\n accountAddresses: instruction.accounts?.map(a => a.address),\n programAddress: instruction.programAddress,\n });\n }\n}\n","/**\n * Describes the purpose for which an account participates in a transaction.\n *\n * Every account that participates in a transaction can be read from, but only ones that you mark as\n * writable may be written to, and only ones that you indicate must sign the transaction will gain\n * the privileges associated with signers at runtime.\n *\n * | | `isSigner` | `isWritable` |\n * | ----------------------------- | ---------- | ------------ |\n * | `AccountRole.READONLY` | ❌ | ❌ |\n * | `AccountRole.WRITABLE` | ❌ | ✅ |\n * | `AccountRole.READONLY_SIGNER` | ✅ | ❌ |\n * | `AccountRole.WRITABLE_SIGNER` | ✅ | ✅ |\n */\nexport enum AccountRole {\n // Bitflag guide: is signer ⌄⌄ is writable\n WRITABLE_SIGNER = /* 3 */ 0b11, // prettier-ignore\n READONLY_SIGNER = /* 2 */ 0b10, // prettier-ignore\n WRITABLE = /* 1 */ 0b01, // prettier-ignore\n READONLY = /* 0 */ 0b00, // prettier-ignore\n}\n\n// Quick primer on bitwise operations: https://stackoverflow.com/a/1436448/802047\nconst IS_SIGNER_BITMASK = 0b10;\nconst IS_WRITABLE_BITMASK = 0b01;\n\n/**\n * @returns An {@link AccountRole} representing the non-signer variant of the supplied role.\n */\nexport function downgradeRoleToNonSigner(role: AccountRole.READONLY_SIGNER): AccountRole.READONLY;\nexport function downgradeRoleToNonSigner(role: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole;\nexport function downgradeRoleToNonSigner(role: AccountRole): AccountRole {\n return role & ~IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the read-only variant of the supplied role.\n */\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE): AccountRole.READONLY;\nexport function downgradeRoleToReadonly(role: AccountRole.WRITABLE_SIGNER): AccountRole.READONLY_SIGNER;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole;\nexport function downgradeRoleToReadonly(role: AccountRole): AccountRole {\n return role & ~IS_WRITABLE_BITMASK;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a signer. Also refines the\n * TypeScript type of the supplied role.\n */\nexport function isSignerRole(role: AccountRole): role is AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER {\n return role >= AccountRole.READONLY_SIGNER;\n}\n\n/**\n * Returns `true` if the {@link AccountRole} given represents that of a writable account. Also\n * refines the TypeScript type of the supplied role.\n */\nexport function isWritableRole(role: AccountRole): role is AccountRole.WRITABLE | AccountRole.WRITABLE_SIGNER {\n return (role & IS_WRITABLE_BITMASK) !== 0;\n}\n\n/**\n * Given two {@link AccountRole | AccountRoles}, will return the {@link AccountRole} that grants the\n * highest privileges of both.\n *\n * @example\n * ```ts\n * // Returns `AccountRole.WRITABLE_SIGNER`\n * mergeRoles(AccountRole.READONLY_SIGNER, AccountRole.WRITABLE);\n * ```\n */\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE_SIGNER): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE_SIGNER, roleB: AccountRole): AccountRole.WRITABLE_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.READONLY_SIGNER): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY_SIGNER, roleB: AccountRole): AccountRole.READONLY_SIGNER; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole.WRITABLE): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.WRITABLE, roleB: AccountRole): AccountRole.WRITABLE; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole.READONLY, roleB: AccountRole.READONLY): AccountRole.READONLY; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole; // prettier-ignore\nexport function mergeRoles(roleA: AccountRole, roleB: AccountRole): AccountRole {\n return roleA | roleB;\n}\n\n/**\n * @returns An {@link AccountRole} representing the signer variant of the supplied role.\n */\nexport function upgradeRoleToSigner(role: AccountRole.READONLY): AccountRole.READONLY_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole.WRITABLE): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole;\nexport function upgradeRoleToSigner(role: AccountRole): AccountRole {\n return role | IS_SIGNER_BITMASK;\n}\n\n/**\n * @returns An {@link AccountRole} representing the writable variant of the supplied role.\n */\nexport function upgradeRoleToWritable(role: AccountRole.READONLY): AccountRole.WRITABLE;\nexport function upgradeRoleToWritable(role: AccountRole.READONLY_SIGNER): AccountRole.WRITABLE_SIGNER;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole;\nexport function upgradeRoleToWritable(role: AccountRole): AccountRole {\n return role | IS_WRITABLE_BITMASK;\n}\n","import { Address, assertIsAddress, getAddressDecoder, getAddressEncoder, isAddress } from '@solana/addresses';\nimport { combineCodec, createEncoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nexport type Blockhash = Brand, 'Blockhash'>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the {@link Blockhash} type, and\n * refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isBlockhash } from '@solana/rpc-types';\n *\n * if (isBlockhash(blockhash)) {\n * // At this point, `blockhash` has been refined to a\n * // `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsFresh(isValid);\n * } else {\n * setError(`${blockhash} is not a blockhash`);\n * }\n * ```\n */\nexport function isBlockhash(putativeBlockhash: string): putativeBlockhash is Blockhash {\n return isAddress(putativeBlockhash);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as a blockhash, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string is\n * a base58-encoded blockhash.\n *\n * @example\n * ```ts\n * import { assertIsBlockhash } from '@solana/rpc-types';\n *\n * // Imagine a function that determines whether a blockhash is fresh when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const blockhash: string = blockhashInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `blockhash` to `Blockhash`.\n * assertIsBlockhash(blockhash);\n * // At this point, `blockhash` is a `Blockhash` that can be used with the RPC.\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `blockhash` turned out not to be a base58-encoded blockhash\n * }\n * }\n * ```\n */\nexport function assertIsBlockhash(putativeBlockhash: string): asserts putativeBlockhash is Blockhash {\n try {\n assertIsAddress(putativeBlockhash);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, error.context);\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, error.context);\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is a blockhash with _coercing_ it to the {@link Blockhash}\n * type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { blockhash } from '@solana/rpc-types';\n *\n * const { value: isValid } = await rpc.isBlockhashValid(blockhash(blockhashFromUserInput)).send();\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good blockhash as a string, it's more efficient to typecast it\n * rather than to use the {@link blockhash} helper, because the helper unconditionally performs\n * validation on its input.\n * >\n * > ```ts\n * > import { Blockhash } from '@solana/rpc-types';\n * >\n * > const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * > ```\n */\nexport function blockhash(putativeBlockhash: string): Blockhash {\n assertIsBlockhash(putativeBlockhash);\n return putativeBlockhash;\n}\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded blockhash to a byte array.\n *\n * @example\n * ```ts\n * import { getBlockhashEncoder } from '@solana/rpc-types';\n *\n * const blockhash = 'ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48' as Blockhash;\n * const blockhashEncoder = getBlockhashEncoder();\n * const blockhashBytes = blockhashEncoder.encode(blockhash);\n * // Uint8Array(32) [\n * // 136, 123, 44, 249, 43, 19, 60, 14,\n * // 144, 16, 168, 241, 121, 111, 70, 232,\n * // 186, 26, 140, 202, 213, 64, 231, 82,\n * // 179, 66, 103, 237, 52, 117, 217, 93\n * // ]\n * ```\n */\nexport function getBlockhashEncoder(): FixedSizeEncoder {\n const addressEncoder = getAddressEncoder();\n return createEncoder({\n fixedSize: 32,\n write: (value: string, bytes, offset) => {\n assertIsBlockhash(value);\n return addressEncoder.write(value as string as Address, bytes, offset);\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing a blockhash to\n * the base58-encoded representation of that blockhash.\n *\n * @example\n * ```ts\n * import { getBlockhashDecoder } from '@solana/rpc-types';\n *\n * const blockhashBytes = new Uint8Array([\n * 136, 123, 44, 249, 43, 19, 60, 14,\n * 144, 16, 168, 241, 121, 111, 70, 232,\n * 186, 26, 140, 202, 213, 64, 231, 82,\n * 179, 66, 103, 237, 52, 117, 217, 93\n * ]);\n * const blockhashDecoder = getBlockhashDecoder();\n * const blockhash = blockhashDecoder.decode(blockhashBytes); // ABmPH5KDXX99u6woqFS5vfBGSNyKG42SzpvBMWWqAy48\n * ```\n */\nexport function getBlockhashDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded blockhash.\n *\n * @see {@link getBlockhashDecoder}\n * @see {@link getBlockhashEncoder}\n */\nexport function getBlockhashCodec(): FixedSizeCodec {\n return combineCodec(getBlockhashEncoder(), getBlockhashDecoder());\n}\n\nexport function getBlockhashComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","export type MainnetUrl = string & { '~cluster': 'mainnet' };\nexport type DevnetUrl = string & { '~cluster': 'devnet' };\nexport type TestnetUrl = string & { '~cluster': 'testnet' };\nexport type ClusterUrl = DevnetUrl | MainnetUrl | TestnetUrl | string;\n\n/** Given a URL casts it to a type that is only accepted where mainnet URLs are expected. */\nexport function mainnet(putativeString: string): MainnetUrl {\n return putativeString as MainnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where devnet URLs are expected. */\nexport function devnet(putativeString: string): DevnetUrl {\n return putativeString as DevnetUrl;\n}\n/** Given a URL casts it to a type that is only accepted where testnet URLs are expected. */\nexport function testnet(putativeString: string): TestnetUrl {\n return putativeString as TestnetUrl;\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\n\n/**\n * A union of all possible commitment statuses -- each a measure of the network confirmation and\n * stake levels on a particular block.\n *\n * Read more about the statuses themselves, [here](https://docs.solana.com/cluster/commitments).\n */\nexport type Commitment = 'confirmed' | 'finalized' | 'processed';\n\nfunction getCommitmentScore(commitment: Commitment): number {\n switch (commitment) {\n case 'finalized':\n return 2;\n case 'confirmed':\n return 1;\n case 'processed':\n return 0;\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: commitment satisfies never,\n });\n }\n}\n\nexport function commitmentComparator(a: Commitment, b: Commitment): -1 | 0 | 1 {\n if (a === b) {\n return 0;\n }\n return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;\n}\n","import {\n Codec,\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformDecoder,\n} from '@solana/codecs-core';\nimport { getU64Decoder, getU64Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * Represents an integer value denominated in Lamports (ie. $1 \\times 10^{-9}$ ◎).\n *\n * It is represented as a `bigint` in client code and an `u64` in server code.\n */\nexport type Lamports = Brand;\n\n// Largest possible value to be represented by a u64\nconst maxU64Value = 18446744073709551615n; // 2n ** 64n - 1n\n\nlet memoizedU64Encoder: FixedSizeEncoder | undefined;\nlet memoizedU64Decoder: FixedSizeDecoder | undefined;\n\nfunction getMemoizedU64Encoder(): FixedSizeEncoder {\n if (!memoizedU64Encoder) memoizedU64Encoder = getU64Encoder();\n return memoizedU64Encoder;\n}\n\nfunction getMemoizedU64Decoder(): FixedSizeDecoder {\n if (!memoizedU64Decoder) memoizedU64Decoder = getU64Decoder();\n return memoizedU64Decoder;\n}\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link Lamports} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isLamports } from '@solana/rpc-types';\n *\n * if (isLamports(lamports)) {\n * // At this point, `lamports` has been refined to a\n * // `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } else {\n * setError(`${lamports} is not a quantity of Lamports`);\n * }\n * ```\n */\nexport function isLamports(putativeLamports: bigint): putativeLamports is Lamports {\n return putativeLamports >= 0 && putativeLamports <= maxU64Value;\n}\n\n/**\n * Lamport values returned from the RPC API conform to the type {@link Lamports}. You can use a\n * value of that type wherever a quantity of Lamports is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a quantity of Lamports, from\n * an untrusted network API or user input. To assert that such an arbitrary number is usable as a\n * quantity of Lamports, use this function.\n *\n * ```ts\n * import { assertIsLamports } from '@solana/rpc-types';\n *\n * // Imagine a function that creates a transfer instruction when a user submits a form.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `number` type.\n * const lamports: number = parseInt(quantityInput.value, 10);\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `lamports` to `Lamports`.\n * assertIsLamports(lamports);\n * // At this point, `lamports` is a `Lamports` that can be used anywhere Lamports are expected.\n * await transfer(fromAddress, toAddress, lamports);\n * } catch (e) {\n * // `lamports` turned out not to validate as a quantity of Lamports.\n * }\n * }\n * ```\n */\nexport function assertIsLamports(putativeLamports: bigint): asserts putativeLamports is Lamports {\n if (putativeLamports < 0 || putativeLamports > maxU64Value) {\n throw new SolanaError(SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE);\n }\n}\n\n/**\n * This helper combines _asserting_ that a number is a possible number of {@link Lamports} with\n * _coercing_ it to the {@link Lamports} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { lamports } from '@solana/rpc-types';\n *\n * await transfer(address(fromAddress), address(toAddress), lamports(100000n));\n * ```\n */\nexport function lamports(putativeLamports: bigint): Lamports {\n assertIsLamports(putativeLamports);\n return putativeLamports;\n}\n\ntype ExtractAdditionalProps = Omit;\n\n/**\n * Returns an encoder that you can use to encode a 64-bit {@link Lamports} value to 8 bytes in\n * little endian order.\n */\nexport function getDefaultLamportsEncoder(): FixedSizeEncoder {\n return getLamportsEncoder(getMemoizedU64Encoder());\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link Lamports} value to a byte array.\n *\n * You must supply a number decoder that will determine how encode the numeric value.\n *\n * @example\n * ```ts\n * import { getLamportsEncoder } from '@solana/rpc-types';\n * import { getU16Encoder } from '@solana/codecs-numbers';\n *\n * const lamports = lamports(256n);\n * const lamportsEncoder = getLamportsEncoder(getU16Encoder());\n * const lamportsBytes = lamportsEncoder.encode(lamports);\n * // Uint8Array(2) [ 0, 1 ]\n * ```\n */\nexport function getLamportsEncoder(\n innerEncoder: TEncoder,\n): Encoder & ExtractAdditionalProps {\n return innerEncoder;\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a 64-bit little endian\n * number to a {@link Lamports} value.\n */\nexport function getDefaultLamportsDecoder(): FixedSizeDecoder {\n return getLamportsDecoder(getMemoizedU64Decoder());\n}\n\n/**\n * Returns a decoder that you can use to convert an array of bytes representing a number to a\n * {@link Lamports} value.\n *\n * You must supply a number decoder that will determine how many bits to use to decode the numeric\n * value.\n *\n * @example\n * ```ts\n * import { getLamportsDecoder } from '@solana/rpc-types';\n * import { getU16Decoder } from '@solana/codecs-numbers';\n *\n * const lamportsBytes = new Uint8Array([ 0, 1 ]);\n * const lamportsDecoder = getLamportsDecoder(getU16Decoder());\n * const lamports = lamportsDecoder.decode(lamportsBytes); // lamports(256n)\n * ```\n */\nexport function getLamportsDecoder(\n innerDecoder: TDecoder,\n): Decoder & ExtractAdditionalProps {\n return transformDecoder(innerDecoder, value =>\n lamports(typeof value === 'bigint' ? value : BigInt(value)),\n ) as Decoder & ExtractAdditionalProps;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a 64-bit {@link Lamports} value.\n *\n * @see {@link getDefaultLamportsDecoder}\n * @see {@link getDefaultLamportsEncoder}\n */\nexport function getDefaultLamportsCodec(): FixedSizeCodec {\n return combineCodec(getDefaultLamportsEncoder(), getDefaultLamportsDecoder());\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link Lamports} value.\n *\n * @see {@link getLamportsDecoder}\n * @see {@link getLamportsEncoder}\n */\nexport function getLamportsCodec(\n innerCodec: TCodec,\n): Codec & ExtractAdditionalProps {\n return combineCodec(getLamportsEncoder(innerCodec), getLamportsDecoder(innerCodec)) as Codec &\n ExtractAdditionalProps;\n}\n","import { SOLANA_ERROR__MALFORMED_BIGINT_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a `bigint` which has been encoded as a string for transit over a transport\n * that does not support `bigint` values natively. The JSON-RPC is such a transport.\n */\nexport type StringifiedBigInt = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `BigInt`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedBigInt } from '@solana/rpc-types';\n *\n * if (isStringifiedBigInt(bigintString)) {\n * // At this point, `bigintString` has been refined to a `StringifiedBigInt`\n * bigintString satisfies StringifiedBigInt; // OK\n * } else {\n * setError(`${bigintString} does not represent a BigInt`);\n * }\n * ```\n */\nexport function isStringifiedBigInt(putativeBigInt: string): putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `BigInt`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `BigInt`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedBigInt } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents the supply of some token.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `supplyString` to `StringifiedBigInt`.\n * assertIsStringifiedBigInt(supplyString);\n * // At this point, `supplyString` is a `StringifiedBigInt`.\n * supplyString satisfies StringifiedBigInt;\n * } catch (e) {\n * // `supplyString` turned out not to parse as a `BigInt`\n * }\n * ```\n */\nexport function assertIsStringifiedBigInt(putativeBigInt: string): asserts putativeBigInt is StringifiedBigInt {\n try {\n BigInt(putativeBigInt);\n } catch {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_BIGINT_STRING, {\n value: putativeBigInt,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `BigInt` with _coercing_ it to the\n * {@link StringifiedBigInt} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedBigInt } from '@solana/rpc-types';\n *\n * const supplyString = stringifiedBigInt('1000000000');\n * ```\n */\nexport function stringifiedBigInt(putativeBigInt: string): StringifiedBigInt {\n assertIsStringifiedBigInt(putativeBigInt);\n return putativeBigInt;\n}\n","import { SOLANA_ERROR__MALFORMED_NUMBER_STRING, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a number which has been encoded as a string for transit over a transport\n * where loss of precision when using the native number type is a concern. The JSON-RPC is such a\n * transport.\n */\nexport type StringifiedNumber = Brand;\n\n/**\n * A type guard that returns `true` if the input string parses as a `Number`, and refines its type\n * for use in your program.\n *\n * @example\n * ```ts\n * import { isStringifiedNumber } from '@solana/rpc-types';\n *\n * if (isStringifiedNumber(numericString)) {\n * // At this point, `numericString` has been refined to a `StringifiedNumber`\n * numericString satisfies StringifiedNumber; // OK\n * } else {\n * setError(`${numericString} does not represent a number`);\n * }\n * ```\n */\nexport function isStringifiedNumber(putativeNumber: string): putativeNumber is StringifiedNumber {\n return !Number.isNaN(Number(putativeNumber));\n}\n\n/**\n * From time to time you might acquire a string, that you expect to parse as a `Number`, from an\n * untrusted network API or user input. Use this function to assert that such an arbitrary string\n * will in fact parse as a `Number`.\n *\n * @example\n * ```ts\n * import { assertIsStringifiedNumber } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents some decimal number.\n * // At this point we know only that it conforms to the `string` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `decimalNumberString` to `StringifiedNumber`.\n * assertIsStringifiedNumber(decimalNumberString);\n * // At this point, `decimalNumberString` is a `StringifiedNumber`.\n * decimalNumberString satisfies StringifiedNumber;\n * } catch (e) {\n * // `decimalNumberString` turned out not to parse as a number.\n * }\n * ```\n */\nexport function assertIsStringifiedNumber(putativeNumber: string): asserts putativeNumber is StringifiedNumber {\n if (Number.isNaN(Number(putativeNumber))) {\n throw new SolanaError(SOLANA_ERROR__MALFORMED_NUMBER_STRING, {\n value: putativeNumber,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a string will parse as a `Number` with _coercing_ it to the\n * {@link StringifiedNumber} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { stringifiedNumber } from '@solana/rpc-types';\n *\n * const decimalNumberString = stringifiedNumber('-42.1');\n * ```\n */\nexport function stringifiedNumber(putativeNumber: string): StringifiedNumber {\n assertIsStringifiedNumber(putativeNumber);\n return putativeNumber;\n}\n","import { SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SolanaError } from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\n/**\n * This type represents a Unix timestamp in _seconds_.\n *\n * It is represented as a `bigint` in client code and an `i64` in server code.\n */\nexport type UnixTimestamp = Brand;\n\n// Largest possible value to be represented by an i64\nconst maxI64Value = 9223372036854775807n; // 2n ** 63n - 1n\nconst minI64Value = -9223372036854775808n; // -(2n ** 63n)\n\n/**\n * This is a type guard that accepts a `bigint` as input. It will both return `true` if the integer\n * conforms to the {@link UnixTimestamp} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isUnixTimestamp } from '@solana/rpc-types';\n *\n * if (isUnixTimestamp(timestamp)) {\n * // At this point, `timestamp` has been refined to a\n * // `UnixTimestamp` that can be used anywhere timestamps are expected.\n * timestamp satisfies UnixTimestamp;\n * } else {\n * setError(`${timestamp} is not a Unix timestamp`);\n * }\n * ```\n */\n\nexport function isUnixTimestamp(putativeTimestamp: bigint): putativeTimestamp is UnixTimestamp {\n return putativeTimestamp >= minI64Value && putativeTimestamp <= maxI64Value;\n}\n\n/**\n * Timestamp values returned from the RPC API conform to the type {@link UnixTimestamp}. You can use\n * a value of that type wherever a timestamp is expected.\n *\n * @example\n * From time to time you might acquire a number that you expect to be a timestamp, from an untrusted\n * network API or user input. To assert that such an arbitrary number is usable as a Unix timestamp,\n * use this function.\n *\n * ```ts\n * import { assertIsUnixTimestamp } from '@solana/rpc-types';\n *\n * // Imagine having received a value that you presume represents a timestamp.\n * // At this point we know only that it conforms to the `bigint` type.\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `timestamp` to `UnixTimestamp`.\n * assertIsUnixTimestamp(timestamp);\n * // At this point, `timestamp` is a `UnixTimestamp`.\n * timestamp satisfies UnixTimestamp;\n * } catch (e) {\n * // `timestamp` turned out not to be a valid Unix timestamp\n * }\n * ```\n */\nexport function assertIsUnixTimestamp(putativeTimestamp: bigint): asserts putativeTimestamp is UnixTimestamp {\n if (putativeTimestamp < minI64Value || putativeTimestamp > maxI64Value) {\n throw new SolanaError(SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, {\n value: putativeTimestamp,\n });\n }\n}\n\n/**\n * This helper combines _asserting_ that a `bigint` represents a Unix timestamp with _coercing_ it\n * to the {@link UnixTimestamp} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { unixTimestamp } from '@solana/rpc-types';\n *\n * const timestamp = unixTimestamp(-42n); // Wednesday, December 31, 1969 3:59:18 PM GMT-08:00\n * ```\n */\nexport function unixTimestamp(putativeTimestamp: bigint): UnixTimestamp {\n assertIsUnixTimestamp(putativeTimestamp);\n return putativeTimestamp;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SolanaError } from '@solana/errors';\nimport { type Blockhash, isBlockhash } from '@solana/rpc-types';\n\nimport { ExcludeTransactionMessageLifetime, TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network. The transaction message will continue to be eligible to land\n * until the network considers the `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type BlockhashLifetimeConstraint = Readonly<{\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction message will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction message eligible to land.\n */\n lastValidBlockHeight: bigint;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the age of the blockhash it\n * includes.\n *\n * Such a transaction can only be landed on the network if the current block height of the network\n * is less than or equal to the value of\n * `TransactionMessageWithBlockhashLifetime['lifetimeConstraint']['lastValidBlockHeight']`.\n */\nexport interface TransactionMessageWithBlockhashLifetime {\n readonly lifetimeConstraint: BlockhashLifetimeConstraint;\n}\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * if (isTransactionMessageWithBlockhashLifetime(message)) {\n * // At this point, `message` has been refined to a `TransactionMessageWithBlockhashLifetime`.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.blockhash === 'string' &&\n typeof transactionMessage.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transactionMessage.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * blockhash-based lifetime, from an untrusted network API or user input. Use this function to\n * assert that such a transaction message actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithBlockhashLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithBlockhashLifetime`.\n * assertIsTransactionMessageWithBlockhashLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = message.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `message` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithBlockhashLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithBlockhashLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithBlockhashLifetime {\n if (!isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * Given a blockhash and the last block height at which that blockhash is considered usable to land\n * transactions, this method will return a new transaction message having the same type as the one\n * supplied plus the `TransactionMessageWithBlockhashLifetime` type.\n *\n * @example\n * ```ts\n * import { setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages';\n *\n * const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n * const txMessageWithBlockhashLifetime = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, txMessage);\n * ```\n */\nexport function setTransactionMessageLifetimeUsingBlockhash<\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n blockhashLifetimeConstraint: BlockhashLifetimeConstraint,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime {\n type ReturnType = ExcludeTransactionMessageLifetime & TransactionMessageWithBlockhashLifetime;\n\n if (\n 'lifetimeConstraint' in transactionMessage &&\n transactionMessage.lifetimeConstraint &&\n 'blockhash' in transactionMessage.lifetimeConstraint &&\n transactionMessage.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash &&\n transactionMessage.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight\n ) {\n return transactionMessage as ReturnType;\n }\n\n return Object.freeze({\n ...transactionMessage,\n lifetimeConstraint: Object.freeze(blockhashLifetimeConstraint),\n }) as ReturnType;\n}\n","import { SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SolanaError } from '@solana/errors';\n\n/**\n * Asserts that a given string contains only characters from the specified alphabet.\n *\n * This function validates whether a string consists exclusively of characters\n * from the provided `alphabet`. If the validation fails, it throws an error\n * indicating the invalid base string.\n *\n * @param alphabet - The allowed set of characters for the base encoding.\n * @param testValue - The string to validate against the given alphabet.\n * @param givenValue - The original string provided by the user (defaults to `testValue`).\n *\n * @throws {SolanaError} If `testValue` contains characters not present in `alphabet`.\n *\n * @example\n * Validating a base-8 encoded string.\n * ```ts\n * assertValidBaseString('01234567', '123047'); // Passes\n * assertValidBaseString('01234567', '128'); // Throws error\n * ```\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {\n alphabet,\n base: alphabet.length,\n value: givenValue,\n });\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Returns an encoder for base-X encoded strings.\n *\n * This encoder serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process involves converting the input string to a numeric value in base-X, then\n * encoding that value into bytes while preserving leading zeroes.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeEncoder` for encoding base-X strings.\n *\n * @example\n * Encoding a base-X string using a custom alphabet.\n * ```ts\n * const encoder = getBaseXEncoder('0123456789abcdef');\n * const bytes = encoder.encode('deadface'); // 0xdeadface\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (!tailChars) {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Returns a decoder for base-X encoded strings.\n *\n * This decoder deserializes base-X encoded strings from a byte array using a custom alphabet.\n * The decoding process converts the byte array into a numeric value in base-10, then\n * maps that value back to characters in the specified base-X alphabet.\n *\n * For more details, see {@link getBaseXCodec}.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeDecoder` for decoding base-X strings.\n *\n * @example\n * Decoding a base-X string using a custom alphabet.\n * ```ts\n * const decoder = getBaseXDecoder('0123456789abcdef');\n * const value = decoder.decode(new Uint8Array([0xde, 0xad, 0xfa, 0xce])); // \"deadface\"\n * ```\n *\n * @see {@link getBaseXCodec}\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * Returns a codec for encoding and decoding base-X strings.\n *\n * This codec serializes strings using a custom alphabet, treating the length of the alphabet as the base.\n * The encoding process converts the input string into a numeric value in base-X, which is then encoded as bytes.\n * The decoding process reverses this transformation to reconstruct the original string.\n *\n * This codec supports leading zeroes by treating the first character of the alphabet as the zero character.\n *\n * @param alphabet - The set of characters defining the base-X encoding.\n * @returns A `VariableSizeCodec` for encoding and decoding base-X strings.\n *\n * @example\n * Encoding and decoding a base-X string using a custom alphabet.\n * ```ts\n * const codec = getBaseXCodec('0123456789abcdef');\n * const bytes = codec.encode('deadface'); // 0xdeadface\n * const value = codec.decode(bytes); // \"deadface\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-X codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBaseXCodec('0123456789abcdef'), 8);\n * ```\n *\n * If you need a size-prefixed base-X codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBaseXCodec('0123456789abcdef'), getU32Codec());\n * ```\n *\n * Separate {@link getBaseXEncoder} and {@link getBaseXDecoder} functions are available.\n *\n * ```ts\n * const bytes = getBaseXEncoder('0123456789abcdef').encode('deadface');\n * const value = getBaseXDecoder('0123456789abcdef').decode(bytes);\n * ```\n *\n * @see {@link getBaseXEncoder}\n * @see {@link getBaseXDecoder}\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(\n value: string,\n zeroCharacter: string,\n): [leadingZeros: string, tailChars: string | undefined] {\n const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));\n return [leadingZeros, tailChars];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n let sum = 0n;\n for (const char of value) {\n sum *= base;\n sum += BigInt(alphabet.indexOf(char));\n }\n return sum;\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import { getBaseXCodec, getBaseXDecoder, getBaseXEncoder } from './baseX';\n\nconst alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Returns an encoder for base-58 strings.\n *\n * This encoder serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeEncoder` for encoding base-58 strings.\n *\n * @example\n * Encoding a base-58 string.\n * ```ts\n * const encoder = getBase58Encoder();\n * const bytes = encoder.encode('heLLo'); // 0x1b6a3070\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Encoder = () => getBaseXEncoder(alphabet);\n\n/**\n * Returns a decoder for base-58 strings.\n *\n * This decoder deserializes base-58 encoded strings from a byte array.\n *\n * For more details, see {@link getBase58Codec}.\n *\n * @returns A `VariableSizeDecoder` for decoding base-58 strings.\n *\n * @example\n * Decoding a base-58 string.\n * ```ts\n * const decoder = getBase58Decoder();\n * const value = decoder.decode(new Uint8Array([0x1b, 0x6a, 0x30, 0x70])); // \"heLLo\"\n * ```\n *\n * @see {@link getBase58Codec}\n */\nexport const getBase58Decoder = () => getBaseXDecoder(alphabet);\n\n/**\n * Returns a codec for encoding and decoding base-58 strings.\n *\n * This codec serializes strings using a base-58 encoding scheme,\n * commonly used in cryptocurrency addresses and other compact representations.\n *\n * @returns A `VariableSizeCodec` for encoding and decoding base-58 strings.\n *\n * @example\n * Encoding and decoding a base-58 string.\n * ```ts\n * const codec = getBase58Codec();\n * const bytes = codec.encode('heLLo'); // 0x1b6a3070\n * const value = codec.decode(bytes); // \"heLLo\"\n * ```\n *\n * @remarks\n * This codec does not enforce a size boundary. It will encode and decode all bytes necessary to represent the string.\n *\n * If you need a fixed-size base-58 codec, consider using {@link fixCodecSize}.\n *\n * ```ts\n * const codec = fixCodecSize(getBase58Codec(), 8);\n * ```\n *\n * If you need a size-prefixed base-58 codec, consider using {@link addCodecSizePrefix}.\n *\n * ```ts\n * const codec = addCodecSizePrefix(getBase58Codec(), getU32Codec());\n * ```\n *\n * Separate {@link getBase58Encoder} and {@link getBase58Decoder} functions are available.\n *\n * ```ts\n * const bytes = getBase58Encoder().encode('heLLo');\n * const value = getBase58Decoder().decode(bytes);\n * ```\n *\n * @see {@link getBase58Encoder}\n * @see {@link getBase58Decoder}\n */\nexport const getBase58Codec = () => getBaseXCodec(alphabet);\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n type Encoder,\n type VariableSizeCodec,\n type VariableSizeDecoder,\n type VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport type { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\n\ntype AddressTableLookup = ReturnType[number];\n\nlet memoizedAddressTableLookupEncoder: VariableSizeEncoder | undefined;\nexport function getAddressTableLookupEncoder(): VariableSizeEncoder {\n if (!memoizedAddressTableLookupEncoder) {\n const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() }) as Encoder<\n readonly number[]\n >;\n memoizedAddressTableLookupEncoder = getStructEncoder([\n ['lookupTableAddress', getAddressEncoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupEncoder;\n}\n\nlet memoizedAddressTableLookupDecoder: VariableSizeDecoder | undefined;\nexport function getAddressTableLookupDecoder(): VariableSizeDecoder {\n if (!memoizedAddressTableLookupDecoder) {\n const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });\n memoizedAddressTableLookupDecoder = getStructDecoder([\n ['lookupTableAddress', getAddressDecoder()],\n ['writableIndexes', indexEncoder],\n ['readonlyIndexes', indexEncoder],\n ]);\n }\n\n return memoizedAddressTableLookupDecoder;\n}\n\nexport function getAddressTableLookupCodec(): VariableSizeCodec {\n return combineCodec(getAddressTableLookupEncoder(), getAddressTableLookupDecoder());\n}\n","import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getStructCodec, getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport { getU8Codec, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledMessageHeader } from '../compile/header';\n\ntype MessageHeader = ReturnType;\n\nlet memoizedU8Encoder: FixedSizeEncoder | undefined;\nfunction getMemoizedU8Encoder(): FixedSizeEncoder {\n if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();\n return memoizedU8Encoder;\n}\n\nlet memoizedU8Decoder: FixedSizeDecoder | undefined;\nfunction getMemoizedU8Decoder(): FixedSizeDecoder {\n if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();\n return memoizedU8Decoder;\n}\n\nlet memoizedU8Codec: FixedSizeCodec | undefined;\nfunction getMemoizedU8Codec(): FixedSizeCodec {\n if (!memoizedU8Codec) memoizedU8Codec = getU8Codec();\n return memoizedU8Codec;\n}\n\nexport function getMessageHeaderEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['numSignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Encoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Encoder()],\n ]) as FixedSizeEncoder;\n}\n\nexport function getMessageHeaderDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['numSignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlySignerAccounts', getMemoizedU8Decoder()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Decoder()],\n ]) as FixedSizeDecoder;\n}\n\nexport function getMessageHeaderCodec(): FixedSizeCodec {\n return getStructCodec([\n ['numSignerAccounts', getMemoizedU8Codec()],\n ['numReadonlySignerAccounts', getMemoizedU8Codec()],\n ['numReadonlyNonSignerAccounts', getMemoizedU8Codec()],\n ]) as FixedSizeCodec;\n}\n","import {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder, getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\n\nimport { getCompiledInstructions } from '../compile/instructions';\n\ntype Instruction = ReturnType[number];\n\nlet memoizedGetInstructionEncoder: VariableSizeEncoder | undefined;\nexport function getInstructionEncoder(): VariableSizeEncoder {\n if (!memoizedGetInstructionEncoder) {\n memoizedGetInstructionEncoder = transformEncoder, Instruction>(\n getStructEncoder([\n ['programAddressIndex', getU8Encoder()],\n ['accountIndices', getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],\n ['data', addEncoderSizePrefix(getBytesEncoder(), getShortU16Encoder())],\n ]),\n // Convert an instruction to have all fields defined\n (instruction: Instruction): Required => {\n if (instruction.accountIndices !== undefined && instruction.data !== undefined) {\n return instruction as Required;\n }\n return {\n ...instruction,\n accountIndices: instruction.accountIndices ?? [],\n data: instruction.data ?? new Uint8Array(0),\n } as Required;\n },\n );\n }\n\n return memoizedGetInstructionEncoder;\n}\n\nlet memoizedGetInstructionDecoder: VariableSizeDecoder | undefined;\nexport function getInstructionDecoder(): VariableSizeDecoder {\n if (!memoizedGetInstructionDecoder) {\n memoizedGetInstructionDecoder = transformDecoder, Instruction>(\n getStructDecoder([\n ['programAddressIndex', getU8Decoder()],\n ['accountIndices', getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],\n [\n 'data',\n addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder()) as VariableSizeDecoder,\n ],\n ]),\n // Convert an instruction to exclude optional fields if they are empty\n (instruction: Required): Instruction => {\n if (instruction.accountIndices.length && instruction.data.byteLength) {\n return instruction;\n }\n const { accountIndices, data, ...rest } = instruction;\n return {\n ...rest,\n ...(accountIndices.length ? { accountIndices } : null),\n ...(data.byteLength ? { data } : null),\n };\n },\n );\n }\n return memoizedGetInstructionDecoder;\n}\n\nexport function getInstructionCodec(): VariableSizeCodec {\n return combineCodec(getInstructionEncoder(), getInstructionDecoder());\n}\n","import { AccountMeta, Instruction } from '@solana/instructions';\n\n/**\n * @deprecated Use `TransactionMessage` instead.\n */\n// TODO(#1147) Stop exporting this in a future major version.\nexport type BaseTransactionMessage<\n TVersion extends TransactionVersion = TransactionVersion,\n TInstruction extends Instruction = Instruction,\n> = Readonly<{\n instructions: readonly TInstruction[];\n version: TVersion;\n}>;\n\nexport const MAX_SUPPORTED_TRANSACTION_VERSION = 0;\n\ntype LegacyInstruction = Instruction;\ntype LegacyTransactionMessage = BaseTransactionMessage<'legacy', LegacyInstruction>;\ntype V0TransactionMessage = BaseTransactionMessage<0, Instruction>;\n\nexport type TransactionMessage = LegacyTransactionMessage | V0TransactionMessage;\nexport type TransactionVersion = 'legacy' | 0;\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,\n SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nimport { MAX_SUPPORTED_TRANSACTION_VERSION, TransactionVersion } from '../transaction-message';\n\nconst VERSION_FLAG_MASK = 0x80;\n\n/**\n * Returns an encoder that you can use to encode a {@link TransactionVersion} to a byte array.\n *\n * Legacy messages will produce an empty array and will not advance the offset. Versioned messages\n * will produce an array with a single byte.\n */\nexport function getTransactionVersionEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: value => (value === 'legacy' ? 0 : 1),\n maxSize: 1,\n write: (value, bytes, offset) => {\n if (value === 'legacy') {\n return offset;\n }\n if (value < 0 || value > 127) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {\n actualVersion: value,\n });\n }\n\n if (value > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: value,\n });\n }\n bytes.set([value | VERSION_FLAG_MASK], offset);\n return offset + 1;\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link TransactionVersion}.\n *\n * When the byte at the current offset is determined to represent a legacy transaction, this decoder\n * will return `'legacy'` and will not advance the offset.\n */\nexport function getTransactionVersionDecoder(): VariableSizeDecoder {\n return createDecoder({\n maxSize: 1,\n read: (bytes, offset) => {\n const firstByte = bytes[offset];\n if ((firstByte & VERSION_FLAG_MASK) === 0) {\n // No version flag set; it's a legacy (unversioned) transaction.\n return ['legacy', offset];\n } else {\n const version = firstByte ^ VERSION_FLAG_MASK;\n if (version > MAX_SUPPORTED_TRANSACTION_VERSION) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n return [version as TransactionVersion, offset + 1];\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link TransactionVersion}\n *\n * @see {@link getTransactionVersionDecoder}\n * @see {@link getTransactionVersionEncoder}\n */\nexport function getTransactionVersionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n createEncoder,\n Decoder,\n fixDecoderSize,\n fixEncoderSize,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getArrayEncoder,\n getConstantEncoder,\n getStructDecoder,\n getStructEncoder,\n getUnionEncoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getShortU16Encoder } from '@solana/codecs-numbers';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';\n\nimport { getCompiledAddressTableLookups } from '../compile/address-table-lookups';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from '../compile/message';\nimport { getAddressTableLookupDecoder, getAddressTableLookupEncoder } from './address-table-lookup';\nimport { getMessageHeaderDecoder, getMessageHeaderEncoder } from './header';\nimport { getInstructionDecoder, getInstructionEncoder } from './instruction';\nimport { getTransactionVersionDecoder, getTransactionVersionEncoder } from './transaction-version';\n\nfunction getCompiledMessageLegacyEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return getStructEncoder(getPreludeStructEncoderTuple()) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >;\n}\n\nfunction getCompiledMessageVersionedEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return transformEncoder(\n getStructEncoder([\n ...getPreludeStructEncoderTuple(),\n ['addressTableLookups', getAddressTableLookupArrayEncoder()],\n ]) as VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n >,\n value => {\n if (value.version === 'legacy') {\n return value;\n }\n return {\n ...value,\n addressTableLookups: value.addressTableLookups ?? [],\n };\n },\n );\n}\n\nfunction getPreludeStructEncoderTuple() {\n const lifetimeTokenEncoder = getUnionEncoder(\n [\n // Use a 32-byte constant encoder for a missing lifetime token (index 0).\n getConstantEncoder(new Uint8Array(32)),\n // Use a 32-byte base58 encoder for a valid lifetime token (index 1).\n fixEncoderSize(getBase58Encoder(), 32),\n ],\n value => (value === undefined ? 0 : 1),\n );\n\n return [\n ['version', getTransactionVersionEncoder()],\n ['header', getMessageHeaderEncoder()],\n ['staticAccounts', getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],\n ['lifetimeToken', lifetimeTokenEncoder],\n ['instructions', getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })],\n ] as const;\n}\n\nfunction getPreludeStructDecoderTuple() {\n return [\n ['version', getTransactionVersionDecoder() as Decoder],\n ['header', getMessageHeaderDecoder()],\n ['staticAccounts', getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],\n ['lifetimeToken', fixDecoderSize(getBase58Decoder(), 32)],\n ['instructions', getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],\n ['addressTableLookups', getAddressTableLookupArrayDecoder()],\n ] as const;\n}\n\nfunction getAddressTableLookupArrayEncoder() {\n return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });\n}\n\nfunction getAddressTableLookupArrayDecoder() {\n return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });\n}\n\n/**\n * Returns an encoder that you can use to encode a {@link CompiledTransactionMessage} to a byte\n * array.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. The byte array produced by this encoder is the message part.\n */\nexport function getCompiledTransactionMessageEncoder(): VariableSizeEncoder<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime)\n> {\n return createEncoder({\n getSizeFromValue: compiledMessage => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);\n } else {\n return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);\n }\n },\n write: (compiledMessage, bytes, offset) => {\n if (compiledMessage.version === 'legacy') {\n return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);\n } else {\n return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);\n }\n },\n });\n}\n\n/**\n * Returns a decoder that you can use to decode a byte array representing a\n * {@link CompiledTransactionMessage}.\n *\n * The wire format of a Solana transaction consists of signatures followed by a compiled transaction\n * message. You can use this decoder to decode the message part.\n */\nexport function getCompiledTransactionMessageDecoder(): VariableSizeDecoder<\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return transformDecoder(\n getStructDecoder(getPreludeStructDecoderTuple()) as VariableSizeDecoder<\n CompiledTransactionMessage &\n CompiledTransactionMessageWithLifetime & {\n addressTableLookups?: ReturnType;\n }\n >,\n ({ addressTableLookups, ...restOfMessage }) => {\n if (restOfMessage.version === 'legacy' || !addressTableLookups?.length) {\n return restOfMessage;\n }\n return { ...restOfMessage, addressTableLookups };\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to {@link CompiledTransactionMessage}\n *\n * @see {@link getCompiledTransactionMessageDecoder}\n * @see {@link getCompiledTransactionMessageEncoder}\n */\nexport function getCompiledTransactionMessageCodec(): VariableSizeCodec<\n CompiledTransactionMessage | (CompiledTransactionMessage & CompiledTransactionMessageWithLifetime),\n CompiledTransactionMessage & CompiledTransactionMessageWithLifetime\n> {\n return combineCodec(getCompiledTransactionMessageEncoder(), getCompiledTransactionMessageDecoder());\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n SolanaError,\n} from '@solana/errors';\nimport {\n AccountLookupMeta,\n AccountMeta,\n AccountRole,\n Instruction,\n isSignerRole,\n isWritableRole,\n mergeRoles,\n ReadonlyAccount,\n ReadonlyAccountLookup,\n ReadonlySignerAccount,\n WritableAccount,\n WritableAccountLookup,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport const enum AddressMapEntryType {\n FEE_PAYER,\n LOOKUP_TABLE,\n STATIC,\n}\n\ntype AddressMap = {\n [address: string]: FeePayerAccountEntry | LookupTableAccountEntry | StaticAccountEntry;\n};\ntype FeePayerAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.FEE_PAYER;\n};\ntype LookupTableAccountEntry = Omit & {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE;\n};\nexport type OrderedAccounts = Brand<(AccountLookupMeta | AccountMeta)[], 'OrderedAccounts'>;\ntype StaticAccountEntry = Omit<\n ReadonlyAccount | ReadonlySignerAccount | WritableAccount | WritableSignerAccount,\n 'address'\n> & { [TYPE]: AddressMapEntryType.STATIC };\n\nfunction upsert(\n addressMap: AddressMap,\n address: Address,\n update: (\n entry: FeePayerAccountEntry | LookupTableAccountEntry | Record | StaticAccountEntry,\n ) => AddressMap[Address],\n) {\n addressMap[address] = update(addressMap[address] ?? { role: AccountRole.READONLY });\n}\n\nconst TYPE = Symbol('AddressMapTypeProperty');\nexport const ADDRESS_MAP_TYPE_PROPERTY: typeof TYPE = TYPE;\n\nexport function getAddressMapFromInstructions(feePayer: Address, instructions: readonly Instruction[]): AddressMap {\n const addressMap: AddressMap = {\n [feePayer]: { [TYPE]: AddressMapEntryType.FEE_PAYER, role: AccountRole.WRITABLE_SIGNER },\n };\n const addressesOfInvokedPrograms = new Set
();\n for (const instruction of instructions) {\n upsert(addressMap, instruction.programAddress, entry => {\n addressesOfInvokedPrograms.add(instruction.programAddress);\n if (TYPE in entry) {\n if (isWritableRole(entry.role)) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {\n programAddress: instruction.programAddress,\n });\n default:\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {\n programAddress: instruction.programAddress,\n });\n }\n }\n if (entry[TYPE] === AddressMapEntryType.STATIC) {\n return entry;\n }\n }\n return { [TYPE]: AddressMapEntryType.STATIC, role: AccountRole.READONLY };\n });\n let addressComparator: ReturnType;\n if (!instruction.accounts) {\n continue;\n }\n for (const account of instruction.accounts) {\n upsert(addressMap, account.address, entry => {\n const {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n address: _,\n ...accountMeta\n } = account;\n if (TYPE in entry) {\n switch (entry[TYPE]) {\n case AddressMapEntryType.FEE_PAYER:\n // The fee payer already has the highest rank -- it is by definition\n // writable-signer. Return it, no matter how `account` is configured\n return entry;\n case AddressMapEntryType.LOOKUP_TABLE: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if ('lookupTableAddress' in accountMeta) {\n const shouldReplaceEntry =\n // Consider using the new LOOKUP_TABLE if its address is different...\n entry.lookupTableAddress !== accountMeta.lookupTableAddress &&\n // ...and sorts before the existing one.\n (addressComparator ||= getAddressComparator())(\n accountMeta.lookupTableAddress,\n entry.lookupTableAddress,\n ) < 0;\n if (shouldReplaceEntry) {\n return {\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n ...accountMeta,\n role: nextRole,\n } as LookupTableAccountEntry;\n }\n } else if (isSignerRole(accountMeta.role)) {\n // Upgrade this LOOKUP_TABLE entry to a static entry if it must sign.\n return {\n [TYPE]: AddressMapEntryType.STATIC,\n role: nextRole,\n } as StaticAccountEntry;\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n return entry;\n }\n }\n case AddressMapEntryType.STATIC: {\n const nextRole = mergeRoles(entry.role, accountMeta.role);\n if (\n // Check to see if this address represents a program that is invoked\n // in this transaction.\n addressesOfInvokedPrograms.has(account.address)\n ) {\n if (isWritableRole(accountMeta.role)) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,\n {\n programAddress: account.address,\n },\n );\n }\n if (entry.role !== nextRole) {\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n } else if (\n 'lookupTableAddress' in accountMeta &&\n // Static accounts can be 'upgraded' to lookup table accounts as\n // long as they are not require to sign the transaction.\n !isSignerRole(entry.role)\n ) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n role: nextRole,\n } as LookupTableAccountEntry;\n } else {\n if (entry.role !== nextRole) {\n // The account's role ranks higher than the current entry's.\n return {\n ...entry,\n role: nextRole,\n } as StaticAccountEntry;\n } else {\n return entry;\n }\n }\n }\n }\n }\n if ('lookupTableAddress' in accountMeta) {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.LOOKUP_TABLE,\n };\n } else {\n return {\n ...accountMeta,\n [TYPE]: AddressMapEntryType.STATIC,\n };\n }\n });\n }\n }\n return addressMap;\n}\n\nexport function getOrderedAccountsFromAddressMap(addressMap: AddressMap): OrderedAccounts {\n let addressComparator: ReturnType;\n const orderedAccounts: (AccountLookupMeta | AccountMeta)[] = Object.entries(addressMap)\n .sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {\n // STEP 1: Rapid precedence check. Fee payer, then static addresses, then lookups.\n if (leftEntry[TYPE] !== rightEntry[TYPE]) {\n if (leftEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.FEE_PAYER) {\n return 1;\n } else if (leftEntry[TYPE] === AddressMapEntryType.STATIC) {\n return -1;\n } else if (rightEntry[TYPE] === AddressMapEntryType.STATIC) {\n return 1;\n }\n }\n // STEP 2: Sort by signer-writability.\n const leftIsSigner = isSignerRole(leftEntry.role);\n if (leftIsSigner !== isSignerRole(rightEntry.role)) {\n return leftIsSigner ? -1 : 1;\n }\n const leftIsWritable = isWritableRole(leftEntry.role);\n if (leftIsWritable !== isWritableRole(rightEntry.role)) {\n return leftIsWritable ? -1 : 1;\n }\n // STEP 3: Sort by address.\n addressComparator ||= getAddressComparator();\n if (\n leftEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n rightEntry[TYPE] === AddressMapEntryType.LOOKUP_TABLE &&\n leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress\n ) {\n return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);\n } else {\n return addressComparator(leftAddress, rightAddress);\n }\n })\n .map(([address, addressMeta]) => ({\n address: address as Address,\n ...addressMeta,\n }));\n return orderedAccounts as unknown as OrderedAccounts;\n}\n","import { Address, getAddressComparator } from '@solana/addresses';\nimport { AccountRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype AddressTableLookup = Readonly<{\n /** The address of the address lookup table account. */\n lookupTableAddress: Address;\n /** Indexes of accounts in a lookup table to load as read-only. */\n readonlyIndexes: readonly number[];\n /** Indexes of accounts in a lookup table to load as writable. */\n writableIndexes: readonly number[];\n}>;\n\nexport function getCompiledAddressTableLookups(orderedAccounts: OrderedAccounts): AddressTableLookup[] {\n const index: Record<\n Address,\n Readonly<{\n [K in keyof Omit]: number[];\n }>\n > = {};\n for (const account of orderedAccounts) {\n if (!('lookupTableAddress' in account)) {\n continue;\n }\n const entry = (index[account.lookupTableAddress] ||= {\n readonlyIndexes: [],\n writableIndexes: [],\n });\n if (account.role === AccountRole.WRITABLE) {\n entry.writableIndexes.push(account.addressIndex);\n } else {\n entry.readonlyIndexes.push(account.addressIndex);\n }\n }\n return Object.keys(index)\n .sort(getAddressComparator())\n .map(lookupTableAddress => ({\n lookupTableAddress: lookupTableAddress as Address,\n ...index[lookupTableAddress as unknown as Address],\n }));\n}\n","import { isSignerRole, isWritableRole } from '@solana/instructions';\n\nimport { OrderedAccounts } from '../compile/accounts';\n\ntype MessageHeader = Readonly<{\n /**\n * The number of accounts in the static accounts list that are neither writable nor\n * signers.\n *\n * Adding this number to `numSignerAccounts` yields the index of the first read-only non-signer\n * account in the static accounts list.\n */\n numReadonlyNonSignerAccounts: number;\n /**\n * The number of read-only accounts in the static accounts list that must sign this\n * transaction.\n *\n * Subtracting this number from `numSignerAccounts` yields the index of the first read-only\n * signer account in the static accounts list.\n */\n numReadonlySignerAccounts: number;\n /**\n * The number of accounts in the static accounts list that must sign this transaction.\n *\n * Subtracting `numReadonlySignerAccounts` from this number yields the number of\n * writable signer accounts in the static accounts list. Writable signer accounts always\n * begin at index zero in the static accounts list.\n *\n * This number itself is the index of the first non-signer account in the static\n * accounts list.\n */\n numSignerAccounts: number;\n}>;\n\nexport function getCompiledMessageHeader(orderedAccounts: OrderedAccounts): MessageHeader {\n let numReadonlyNonSignerAccounts = 0;\n let numReadonlySignerAccounts = 0;\n let numSignerAccounts = 0;\n for (const account of orderedAccounts) {\n if ('lookupTableAddress' in account) {\n break;\n }\n const accountIsWritable = isWritableRole(account.role);\n if (isSignerRole(account.role)) {\n numSignerAccounts++;\n if (!accountIsWritable) {\n numReadonlySignerAccounts++;\n }\n } else if (!accountIsWritable) {\n numReadonlyNonSignerAccounts++;\n }\n }\n return {\n numReadonlyNonSignerAccounts,\n numReadonlySignerAccounts,\n numSignerAccounts,\n };\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { Instruction } from '@solana/instructions';\n\nimport { OrderedAccounts } from './accounts';\n\ntype CompiledInstruction = Readonly<{\n /**\n * An ordered list of indices that indicate which accounts in the transaction message's\n * accounts list are loaded by this instruction.\n */\n accountIndices?: number[];\n /** The input to the invoked program */\n data?: ReadonlyUint8Array;\n /**\n * The index of the address in the transaction message's accounts list associated with the\n * program to invoke.\n */\n programAddressIndex: number;\n}>;\n\nfunction getAccountIndex(orderedAccounts: OrderedAccounts) {\n const out: Record = {};\n for (const [index, account] of orderedAccounts.entries()) {\n out[account.address] = index;\n }\n return out;\n}\n\nexport function getCompiledInstructions(\n instructions: readonly Instruction[],\n orderedAccounts: OrderedAccounts,\n): CompiledInstruction[] {\n const accountIndex = getAccountIndex(orderedAccounts);\n return instructions.map(({ accounts, data, programAddress }) => {\n return {\n programAddressIndex: accountIndex[programAddress],\n ...(accounts ? { accountIndices: accounts.map(({ address }) => accountIndex[address]) } : null),\n ...(data ? { data } : null),\n };\n });\n}\n","import { TransactionMessageWithBlockhashLifetime, TransactionMessageWithDurableNonceLifetime } from '../index';\n\nexport function getCompiledLifetimeToken(\n lifetimeConstraint: (\n | TransactionMessageWithBlockhashLifetime\n | TransactionMessageWithDurableNonceLifetime\n )['lifetimeConstraint'],\n): string {\n if ('nonce' in lifetimeConstraint) {\n return lifetimeConstraint.nonce;\n }\n return lifetimeConstraint.blockhash;\n}\n","import { Address } from '@solana/addresses';\n\nimport { OrderedAccounts } from './accounts';\n\nexport function getCompiledStaticAccounts(orderedAccounts: OrderedAccounts): Address[] {\n const firstLookupTableAccountIndex = orderedAccounts.findIndex(account => 'lookupTableAddress' in account);\n const orderedStaticAccounts =\n firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);\n return orderedStaticAccounts.map(({ address }) => address);\n}\n","import { TransactionMessageWithFeePayer } from '../fee-payer';\nimport { TransactionMessageWithLifetime } from '../lifetime';\nimport { BaseTransactionMessage } from '../transaction-message';\nimport { getAddressMapFromInstructions, getOrderedAccountsFromAddressMap } from './accounts';\nimport { getCompiledAddressTableLookups } from './address-table-lookups';\nimport { getCompiledMessageHeader } from './header';\nimport { getCompiledInstructions } from './instructions';\nimport { getCompiledLifetimeToken } from './lifetime-token';\nimport { getCompiledStaticAccounts } from './static-accounts';\n\ntype BaseCompiledTransactionMessage = Readonly<{\n /**\n * Information about the version of the transaction message and the role of the accounts it\n * loads.\n */\n header: ReturnType;\n instructions: ReturnType;\n /** A list of addresses indicating which accounts to load */\n staticAccounts: ReturnType;\n}>;\n\n/**\n * A transaction message in a form suitable for encoding for execution on the network.\n *\n * You can not fully reconstruct a source message from a compiled message without extra information.\n * In particular, supporting details about the lifetime constraint and the concrete addresses of\n * accounts sourced from account lookup tables are lost to compilation.\n */\nexport type CompiledTransactionMessage = LegacyCompiledTransactionMessage | VersionedCompiledTransactionMessage;\n\nexport type CompiledTransactionMessageWithLifetime = Readonly<{\n /**\n * 32 bytes of data observed by the transaction proposed that makes a transaction eligible to\n * land on the network.\n *\n * In the case of a transaction message with a nonce lifetime constraint, this will be the value\n * of the nonce itself. In all other cases this will be a recent blockhash.\n */\n lifetimeToken: ReturnType;\n}>;\n\ntype LegacyCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n version: 'legacy';\n }>;\n\ntype VersionedCompiledTransactionMessage = BaseCompiledTransactionMessage &\n Readonly<{\n /** A list of address tables and the accounts that this transaction loads from them */\n addressTableLookups?: ReturnType;\n version: 0;\n }>;\n\n/**\n * Converts the type of transaction message data structure that you create in your application to\n * the type of transaction message data structure that can be encoded for execution on the network.\n *\n * This is a lossy process; you can not fully reconstruct a source message from a compiled message\n * without extra information. In particular, supporting details about the lifetime constraint and\n * the concrete addresses of accounts sourced from account lookup tables will be lost to\n * compilation.\n *\n * @see {@link decompileTransactionMessage}\n */\nexport function compileTransactionMessage<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): CompiledTransactionMessageFromTransactionMessage {\n type ReturnType = CompiledTransactionMessageFromTransactionMessage;\n\n const addressMap = getAddressMapFromInstructions(\n transactionMessage.feePayer.address,\n transactionMessage.instructions,\n );\n const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);\n const lifetimeConstraint = (transactionMessage as Partial).lifetimeConstraint;\n\n return {\n ...(transactionMessage.version !== 'legacy'\n ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) }\n : null),\n ...(lifetimeConstraint ? { lifetimeToken: getCompiledLifetimeToken(lifetimeConstraint) } : null),\n header: getCompiledMessageHeader(orderedAccounts),\n instructions: getCompiledInstructions(transactionMessage.instructions, orderedAccounts),\n staticAccounts: getCompiledStaticAccounts(orderedAccounts),\n version: transactionMessage.version,\n } as ReturnType;\n}\n\ntype CompiledTransactionMessageFromTransactionMessage =\n ForwardTransactionMessageLifetime, TTransactionMessage>;\n\ntype ForwardTransactionMessageVersion =\n TTransactionMessage extends Readonly<{ version: 'legacy' }>\n ? LegacyCompiledTransactionMessage\n : VersionedCompiledTransactionMessage;\n\ntype ForwardTransactionMessageLifetime<\n TCompiledTransactionMessage extends CompiledTransactionMessage,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithLifetime\n ? CompiledTransactionMessageWithLifetime & TCompiledTransactionMessage\n : TCompiledTransactionMessage;\n","import { Address } from '@solana/addresses';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction, isSignerRole } from '@solana/instructions';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BaseTransactionMessage, TransactionMessage } from './transaction-message';\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n// Look up the address in lookup tables, return a lookup meta if it is found in any of them\nfunction findAddressInLookupTables(\n address: Address,\n role: AccountRole.READONLY | AccountRole.WRITABLE,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta | undefined {\n for (const [lookupTableAddress, addresses] of Object.entries(addressesByLookupTableAddress)) {\n for (let i = 0; i < addresses.length; i++) {\n if (address === addresses[i]) {\n return {\n address,\n addressIndex: i,\n lookupTableAddress: lookupTableAddress as Address,\n role,\n };\n }\n }\n }\n}\n\ntype TransactionMessageNotLegacy = Exclude;\n\n// Each account can be AccountLookupMeta | AccountMeta\ntype WidenInstructionAccounts =\n TInstruction extends Instruction\n ? Instruction<\n TProgramAddress,\n {\n [K in keyof TAccounts]: TAccounts[K] extends AccountMeta\n ? AccountLookupMeta | AccountMeta\n : TAccounts[K];\n }\n >\n : TInstruction;\n\ntype ExtractAdditionalProps = Omit;\n\ntype WidenTransactionMessageInstructions =\n TTransactionMessage extends BaseTransactionMessage\n ? BaseTransactionMessage> &\n ExtractAdditionalProps<\n TTransactionMessage,\n BaseTransactionMessage>\n >\n : TTransactionMessage;\n\n/**\n * Given a transaction message and a mapping of lookup tables to the addresses stored in them, this\n * function will return a new transaction message with the same instructions but with all non-signer\n * accounts that are found in the given lookup tables represented by an {@link AccountLookupMeta}\n * instead of an {@link AccountMeta}.\n *\n * This means that these accounts will take up less space in the compiled transaction message. This\n * size reduction is most significant when the transaction includes many accounts from the same\n * lookup table.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import {\n * AddressesByLookupTableAddress,\n * compressTransactionMessageUsingAddressLookupTables,\n * } from '@solana/transaction-messages';\n * import { fetchAddressLookupTable } from '@solana-program/address-lookup-table';\n *\n * const lookupTableAddress = address('4QwSwNriKPrz8DLW4ju5uxC2TN5cksJx6tPUPj7DGLAW');\n * const {\n * data: { addresses },\n * } = await fetchAddressLookupTable(rpc, lookupTableAddress);\n * const addressesByAddressLookupTable: AddressesByLookupTableAddress = {\n * [lookupTableAddress]: addresses,\n * };\n *\n * const compressedTransactionMessage = compressTransactionMessageUsingAddressLookupTables(\n * transactionMessage,\n * addressesByAddressLookupTable,\n * );\n * ```\n */\nexport function compressTransactionMessageUsingAddressLookupTables<\n TTransactionMessage extends TransactionMessageNotLegacy = TransactionMessageNotLegacy,\n>(\n transactionMessage: TTransactionMessage,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): TTransactionMessage | WidenTransactionMessageInstructions {\n const programAddresses = new Set(transactionMessage.instructions.map(ix => ix.programAddress));\n const eligibleLookupAddresses = new Set(\n Object.values(addressesByLookupTableAddress)\n .flatMap(a => a)\n .filter(address => !programAddresses.has(address)),\n );\n const newInstructions: Instruction[] = [];\n let updatedAnyInstructions = false;\n for (const instruction of transactionMessage.instructions) {\n if (!instruction.accounts) {\n newInstructions.push(instruction);\n continue;\n }\n\n const newAccounts: Mutable> = [];\n let updatedAnyAccounts = false;\n for (const account of instruction.accounts) {\n // If the address is already a lookup, is not in any lookup tables, or is a signer role, return as-is\n if (\n 'lookupTableAddress' in account ||\n !eligibleLookupAddresses.has(account.address) ||\n isSignerRole(account.role)\n ) {\n newAccounts.push(account);\n continue;\n }\n\n // We already checked it's in one of the lookup tables\n const lookupMetaAccount = findAddressInLookupTables(\n account.address,\n account.role,\n addressesByLookupTableAddress,\n )!;\n newAccounts.push(Object.freeze(lookupMetaAccount));\n updatedAnyAccounts = true;\n updatedAnyInstructions = true;\n }\n\n newInstructions.push(\n Object.freeze(updatedAnyAccounts ? { ...instruction, accounts: newAccounts } : instruction),\n );\n }\n\n return Object.freeze(\n updatedAnyInstructions ? { ...transactionMessage, instructions: newInstructions } : transactionMessage,\n );\n}\n","import { TransactionMessage, TransactionVersion } from './transaction-message';\nimport { TransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype TransactionConfig = Readonly<{\n version: TVersion;\n}>;\n\ntype EmptyTransactionMessage = Omit<\n Extract,\n 'instructions'\n> &\n TransactionMessageWithinSizeLimit & { instructions: readonly [] };\n\n/**\n * Given a {@link TransactionVersion} this method will return an empty transaction having the\n * capabilities of that version.\n *\n * @example\n * ```ts\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const message = createTransactionMessage({ version: 0 });\n * ```\n */\nexport function createTransactionMessage(\n config: TransactionConfig,\n): EmptyTransactionMessage {\n return Object.freeze({\n instructions: Object.freeze([]),\n version: config.version,\n }) as EmptyTransactionMessage;\n}\n","import { Address } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n AccountRole,\n Instruction,\n InstructionWithAccounts,\n InstructionWithData,\n isSignerRole,\n ReadonlyAccount,\n ReadonlySignerAccount,\n WritableAccount,\n WritableSignerAccount,\n} from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nexport type AdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n> = Instruction<'11111111111111111111111111111111'> &\n InstructionWithAccounts<\n readonly [\n WritableAccount,\n ReadonlyAccount<'SysvarRecentB1ockHashes11111111111111111111'>,\n ReadonlySignerAccount | WritableSignerAccount,\n ]\n > &\n InstructionWithData;\n\ntype AdvanceNonceAccountInstructionData = Brand;\n\nconst RECENT_BLOCKHASHES_SYSVAR_ADDRESS =\n 'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\n/**\n * Creates an instruction for the System program to advance a nonce.\n *\n * This instruction is a prerequisite for a transaction with a nonce-based lifetime to be landed on\n * the network. In order to be considered valid, the transaction must meet all of these criteria.\n *\n * 1. Its lifetime constraint must be a {@link NonceLifetimeConstraint}.\n * 2. The value contained in the on-chain account at the address `nonceAccountAddress` must be equal\n * to {@link NonceLifetimeConstraint.nonce} at the time the transaction is landed.\n * 3. The first instruction in that transaction message must be the one returned by this function.\n *\n * You could also use the `getAdvanceNonceAccountInstruction` method of `@solana-program/system`.\n */\nexport function createAdvanceNonceAccountInstruction<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n>(\n nonceAccountAddress: Address,\n nonceAuthorityAddress: Address,\n): AdvanceNonceAccountInstruction {\n return {\n accounts: [\n { address: nonceAccountAddress, role: AccountRole.WRITABLE },\n {\n address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,\n role: AccountRole.READONLY,\n },\n { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER },\n ],\n data: new Uint8Array([4, 0, 0, 0]) as AdvanceNonceAccountInstructionData,\n programAddress: SYSTEM_PROGRAM_ADDRESS,\n };\n}\n\n/**\n * A type guard that returns `true` if the instruction conforms to the\n * {@link AdvanceNonceAccountInstruction} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isAdvanceNonceAccountInstruction } from '@solana/transaction-messages';\n *\n * if (isAdvanceNonceAccountInstruction(message.instructions[0])) {\n * // At this point, the first instruction in the message has been refined to a\n * // `AdvanceNonceAccountInstruction`.\n * setNonceAccountAddress(message.instructions[0].accounts[0].address);\n * } else {\n * setError('The first instruction is not an `AdvanceNonce` instruction');\n * }\n * ```\n */\nexport function isAdvanceNonceAccountInstruction(\n instruction: Instruction,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.programAddress === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accounts?.length === 3 &&\n // First account is nonce account address\n instruction.accounts[0].address != null &&\n instruction.accounts[0].role === AccountRole.WRITABLE &&\n // Second account is recent blockhashes sysvar\n instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS &&\n instruction.accounts[1].role === AccountRole.READONLY &&\n // Third account is nonce authority account\n instruction.accounts[2].address != null &&\n isSignerRole(instruction.accounts[2].role)\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): data is AdvanceNonceAccountInstructionData {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SolanaError } from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport { Brand } from '@solana/nominal-types';\n\nimport {\n AdvanceNonceAccountInstruction,\n createAdvanceNonceAccountInstruction,\n isAdvanceNonceAccountInstruction,\n} from './durable-nonce-instruction';\nimport { ExcludeTransactionMessageLifetime } from './lifetime';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\ntype DurableNonceConfig<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = Readonly<{\n readonly nonce: Nonce;\n readonly nonceAccountAddress: Address;\n readonly nonceAuthorityAddress: Address;\n}>;\n\n/** Represents a string that is particularly known to be the base58-encoded value of a nonce. */\nexport type Nonce = Brand;\n\n/**\n * A constraint which, when applied to a transaction message, makes that transaction message\n * eligible to land on the network.\n *\n * The transaction message will continue to be eligible to land until the network considers the\n * `nonce` to have advanced. This can happen when the nonce account in which this nonce is found is\n * destroyed, or the nonce value within changes.\n */\nexport type NonceLifetimeConstraint = Readonly<{\n /**\n * A value contained in the related nonce account at the time the transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n}>;\n\n/**\n * Represents a transaction message whose lifetime is defined by the value of a nonce it includes.\n *\n * Such a transaction can only be landed on the network if the nonce is known to the network and has\n * not already been used to land a different transaction.\n */\nexport interface TransactionMessageWithDurableNonceLifetime<\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> {\n readonly instructions: readonly [\n // The first instruction *must* be the system program's `AdvanceNonceAccount` instruction.\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n}\n\n/**\n * A helper type to exclude the durable nonce lifetime constraint from a transaction message.\n */\nexport type ExcludeTransactionMessageDurableNonceLifetime =\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? ExcludeTransactionMessageLifetime\n : TTransactionMessage;\n\n/**\n * A type guard that returns `true` if the transaction message conforms to the\n * {@link TransactionMessageWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionMessageWithDurableNonceLifetime(message)) {\n * // At this point, `message` has been refined to a\n * // `TransactionMessageWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transactionMessage &&\n typeof transactionMessage.lifetimeConstraint.nonce === 'string' &&\n transactionMessage.instructions[0] != null &&\n isAdvanceNonceAccountInstruction(transactionMessage.instructions[0])\n );\n}\n\n/**\n * From time to time you might acquire a transaction message, that you expect to have a\n * nonce-based lifetime, from an untrusted network API or user input. Use this function to assert\n * that such a transaction message actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithDurableNonceLifetime } from '@solana/transaction-messages';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `message` to `TransactionMessageWithDurableNonceLifetime`.\n * assertIsTransactionMessageWithDurableNonceLifetime(message);\n * // At this point, `message` is a `TransactionMessageWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = message.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `message` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionMessageWithDurableNonceLifetime(\n transactionMessage: TransactionMessage | (TransactionMessage & TransactionMessageWithDurableNonceLifetime),\n): asserts transactionMessage is TransactionMessage & TransactionMessageWithDurableNonceLifetime {\n if (!isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n\nfunction isAdvanceNonceAccountInstructionForNonce<\n TNonceAccountAddress extends Address = Address,\n TNonceAuthorityAddress extends Address = Address,\n>(\n instruction: AdvanceNonceAccountInstruction,\n nonceAccountAddress: TNonceAccountAddress,\n nonceAuthorityAddress: TNonceAuthorityAddress,\n): instruction is AdvanceNonceAccountInstruction {\n return (\n instruction.accounts[0].address === nonceAccountAddress &&\n instruction.accounts[2].address === nonceAuthorityAddress\n );\n}\n\n/**\n * Given a nonce, the account where the value of the nonce is stored, and the address of the account\n * authorized to consume that nonce, this method will return a new transaction having the same type\n * as the one supplied plus the {@link TransactionMessageWithDurableNonceLifetime} type.\n *\n * In particular, this method _prepends_ an instruction to the transaction message designed to\n * consume (or 'advance') the nonce in the same transaction whose lifetime is defined by it.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from '@solana/transaction-messages';\n * import { fetchNonce } from '@solana-program/system';\n *\n * const nonceAccountAddress = address('EGtMh4yvXswwHhwVhyPxGrVV2TkLTgUqGodbATEPvojZ');\n * const nonceAuthorityAddress = address('4KD1Rdrd89NG7XbzW3xsX9Aqnx2EExJvExiNme6g9iAT');\n *\n * const {\n * data: { blockhash },\n * } = await fetchNonce(rpc, nonceAccountAddress);\n * const nonce = blockhash as string as Nonce;\n *\n * const durableNonceTransactionMessage = setTransactionMessageLifetimeUsingDurableNonce(\n * { nonce, nonceAccountAddress, nonceAuthorityAddress },\n * tx,\n * );\n * ```\n */\nexport function setTransactionMessageLifetimeUsingDurableNonce<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n>(\n {\n nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n }: DurableNonceConfig,\n transactionMessage: TTransactionMessage,\n): SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n> {\n type ReturnType = SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage,\n TNonceAccountAddress,\n TNonceAuthorityAddress,\n TNonceValue\n >;\n\n let newInstructions: [\n AdvanceNonceAccountInstruction,\n ...Instruction[],\n ];\n\n const firstInstruction = transactionMessage.instructions[0];\n if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {\n if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {\n if (\n isTransactionMessageWithDurableNonceLifetime(transactionMessage) &&\n transactionMessage.lifetimeConstraint.nonce === nonce\n ) {\n return transactionMessage as unknown as ReturnType;\n } else {\n // we already have the right first instruction, leave it as-is\n newInstructions = [firstInstruction, ...transactionMessage.instructions.slice(1)];\n }\n } else {\n // we have a different advance nonce instruction as the first instruction, replace it\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions.slice(1),\n ];\n }\n } else {\n // we don't have an existing advance nonce instruction as the first instruction, prepend one\n newInstructions = [\n Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),\n ...transactionMessage.instructions,\n ];\n }\n\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze(newInstructions),\n lifetimeConstraint: Object.freeze({ nonce }),\n }) as unknown as ReturnType;\n}\n\n/**\n * Helper type that transforms a given transaction message type into a new one that has the\n * `AdvanceNonceAccount` instruction as the first instruction and a lifetime constraint\n * representing the nonce value.\n */\ntype SetTransactionMessageWithDurableNonceLifetime<\n TTransactionMessage extends TransactionMessage,\n TNonceAccountAddress extends string = string,\n TNonceAuthorityAddress extends string = string,\n TNonceValue extends string = string,\n> = TTransactionMessage extends unknown\n ? Omit<\n // 1. The transaction message only grows in size if it currently has a different (or no) lifetime.\n TTransactionMessage extends TransactionMessageWithDurableNonceLifetime\n ? TTransactionMessage\n : ExcludeTransactionMessageWithinSizeLimit,\n // 2. Remove the instructions array as we are going to replace it with a new one.\n 'instructions'\n > & {\n // 3. Replace or prepend the first instruction with the advance nonce account instruction.\n readonly instructions: TTransactionMessage['instructions'] extends readonly [\n AdvanceNonceAccountInstruction,\n ...infer TTail extends readonly Instruction[],\n ]\n ? readonly [AdvanceNonceAccountInstruction, ...TTail]\n : readonly [\n AdvanceNonceAccountInstruction,\n ...TTransactionMessage['instructions'],\n ];\n // 4. Set the lifetime constraint to the nonce value.\n readonly lifetimeConstraint: NonceLifetimeConstraint;\n }\n : never;\n","import { Address } from '@solana/addresses';\n\nimport { TransactionMessage } from './transaction-message';\n\n/**\n * Represents a transaction message for which a fee payer has been declared. A transaction must\n * conform to this type to be compiled and landed on the network.\n */\nexport interface TransactionMessageWithFeePayer {\n readonly feePayer: Readonly<{ address: Address }>;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Given a base58-encoded address of a system account, this method will return a new transaction\n * message having the same type as the one supplied plus the {@link TransactionMessageWithFeePayer}\n * type.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const myAddress = address('mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu');\n * const txPaidByMe = setTransactionMessageFeePayer(myAddress, tx);\n * ```\n */\nexport function setTransactionMessageFeePayer<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial & TransactionMessage,\n>(\n feePayer: Address,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayer {\n if (\n 'feePayer' in transactionMessage &&\n feePayer === transactionMessage.feePayer?.address &&\n isAddressOnlyFeePayer(transactionMessage.feePayer)\n ) {\n return transactionMessage as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n }\n const out = {\n ...transactionMessage,\n feePayer: Object.freeze({ address: feePayer }),\n };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayer;\n}\n\nfunction isAddressOnlyFeePayer(\n feePayer: Partial['feePayer'],\n): feePayer is { address: Address } {\n return (\n !!feePayer &&\n 'address' in feePayer &&\n typeof feePayer.address === 'string' &&\n Object.keys(feePayer).length === 1\n );\n}\n","import { Instruction } from '@solana/instructions';\n\nimport { ExcludeTransactionMessageDurableNonceLifetime } from './durable-nonce';\nimport { TransactionMessage } from './transaction-message';\nimport { ExcludeTransactionMessageWithinSizeLimit } from './transaction-message-size';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype AppendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit, 'instructions'> & {\n readonly instructions: readonly [...TTransactionMessage['instructions'], ...TInstructions];\n }\n : never;\n\n/**\n * A helper type to prepend instructions to a transaction message\n * without losing type information about the current instructions.\n */\ntype PrependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n TInstructions extends readonly Instruction[],\n> = TTransactionMessage extends TransactionMessage\n ? Omit<\n ExcludeTransactionMessageWithinSizeLimit>,\n 'instructions'\n > & {\n readonly instructions: readonly [...TInstructions, ...TTransactionMessage['instructions']];\n }\n : never;\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstructions} if you need to append multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { appendTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransactionMessage = appendTransactionMessageInstruction(\n * {\n * data: getUtf8Encoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * transactionMessage,\n * );\n * ```\n */\nexport function appendTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return appendTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the end of the list of existing instructions.\n *\n * @see {@link appendTransactionInstruction} if you only need to append one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { appendTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = appendTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function appendTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n return Object.freeze({\n ...transactionMessage,\n instructions: Object.freeze([\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ...instructions,\n ] as readonly [...TTransactionMessage['instructions'], ...TInstructions]),\n }) as AppendTransactionMessageInstructions;\n}\n\n/**\n * Given an instruction, this method will return a new transaction message with that instruction\n * having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstructions} if you need to prepend multiple instructions to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstruction } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstruction(\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstruction<\n TTransactionMessage extends TransactionMessage,\n TInstruction extends Instruction,\n>(\n instruction: TInstruction,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return prependTransactionMessageInstructions([instruction], transactionMessage);\n}\n\n/**\n * Given an array of instructions, this method will return a new transaction message with those\n * instructions having been added to the beginning of the list of existing instructions.\n *\n * @see {@link prependTransactionInstruction} if you only need to prepend one instruction to a\n * transaction message.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { prependTransactionMessageInstructions } from '@solana/transaction-messages';\n *\n * const memoTransaction = prependTransactionMessageInstructions(\n * [\n * {\n * data: new TextEncoder().encode('Hello world!'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * {\n * data: new TextEncoder().encode('How are you?'),\n * programAddress: address('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n * },\n * ],\n * tx,\n * );\n * ```\n */\nexport function prependTransactionMessageInstructions<\n TTransactionMessage extends TransactionMessage,\n const TInstructions extends readonly Instruction[],\n>(\n instructions: TInstructions,\n transactionMessage: TTransactionMessage,\n): PrependTransactionMessageInstructions {\n return Object.freeze({\n ...(transactionMessage as ExcludeTransactionMessageDurableNonceLifetime),\n instructions: Object.freeze([\n ...instructions,\n ...(transactionMessage.instructions as TTransactionMessage['instructions']),\n ] as readonly [...TInstructions, ...TTransactionMessage['instructions']]),\n }) as unknown as PrependTransactionMessageInstructions;\n}\n","import { Address, assertIsAddress } from '@solana/addresses';\nimport {\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,\n SolanaError,\n} from '@solana/errors';\nimport { pipe } from '@solana/functional';\nimport { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport type { Blockhash } from '@solana/rpc-types';\n\nimport { AddressesByLookupTableAddress } from './addresses-by-lookup-table-address';\nimport { BlockhashLifetimeConstraint, setTransactionMessageLifetimeUsingBlockhash } from './blockhash';\nimport { CompiledTransactionMessage, CompiledTransactionMessageWithLifetime } from './compile';\nimport type { getCompiledAddressTableLookups } from './compile/address-table-lookups';\nimport { createTransactionMessage } from './create-transaction-message';\nimport { Nonce, setTransactionMessageLifetimeUsingDurableNonce } from './durable-nonce';\nimport { isAdvanceNonceAccountInstruction } from './durable-nonce-instruction';\nimport { setTransactionMessageFeePayer, TransactionMessageWithFeePayer } from './fee-payer';\nimport { appendTransactionMessageInstruction } from './instructions';\nimport { TransactionMessageWithLifetime } from './lifetime';\nimport { TransactionMessage, TransactionVersion } from './transaction-message';\n\nfunction getAccountMetas(message: CompiledTransactionMessage): AccountMeta[] {\n const { header } = message;\n const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;\n const numWritableNonSignerAccounts =\n message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;\n\n const accountMetas: AccountMeta[] = [];\n\n let accountIndex = 0;\n for (let i = 0; i < numWritableSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlySignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY_SIGNER,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < numWritableNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.WRITABLE,\n });\n accountIndex++;\n }\n\n for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {\n accountMetas.push({\n address: message.staticAccounts[accountIndex],\n role: AccountRole.READONLY,\n });\n accountIndex++;\n }\n\n return accountMetas;\n}\n\nfunction getAddressLookupMetas(\n compiledAddressTableLookups: ReturnType,\n addressesByLookupTableAddress: AddressesByLookupTableAddress,\n): AccountLookupMeta[] {\n // check that all message lookups are known\n const compiledAddressTableLookupAddresses = compiledAddressTableLookups.map(l => l.lookupTableAddress);\n const missing = compiledAddressTableLookupAddresses.filter(a => addressesByLookupTableAddress[a] === undefined);\n if (missing.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, {\n lookupTableAddresses: missing,\n });\n }\n\n const readOnlyMetas: AccountLookupMeta[] = [];\n const writableMetas: AccountLookupMeta[] = [];\n\n // we know that for each lookup, knownLookups[lookup.lookupTableAddress] is defined\n for (const lookup of compiledAddressTableLookups) {\n const addresses = addressesByLookupTableAddress[lookup.lookupTableAddress];\n const readonlyIndexes = lookup.readonlyIndexes;\n const writableIndexes = lookup.writableIndexes;\n\n const highestIndex = Math.max(...readonlyIndexes, ...writableIndexes);\n if (highestIndex >= addresses.length) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,\n {\n highestKnownIndex: addresses.length - 1,\n highestRequestedIndex: highestIndex,\n lookupTableAddress: lookup.lookupTableAddress,\n },\n );\n }\n\n const readOnlyForLookup: AccountLookupMeta[] = readonlyIndexes.map(r => ({\n address: addresses[r],\n addressIndex: r,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.READONLY,\n }));\n readOnlyMetas.push(...readOnlyForLookup);\n\n const writableForLookup: AccountLookupMeta[] = writableIndexes.map(w => ({\n address: addresses[w],\n addressIndex: w,\n lookupTableAddress: lookup.lookupTableAddress,\n role: AccountRole.WRITABLE,\n }));\n writableMetas.push(...writableForLookup);\n }\n\n return [...writableMetas, ...readOnlyMetas];\n}\n\nfunction convertInstruction(\n instruction: CompiledTransactionMessage['instructions'][0],\n accountMetas: AccountMeta[],\n): Instruction {\n const programAddress = accountMetas[instruction.programAddressIndex]?.address;\n if (!programAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, {\n index: instruction.programAddressIndex,\n });\n }\n\n const accounts = instruction.accountIndices?.map(accountIndex => accountMetas[accountIndex]);\n const { data } = instruction;\n\n return Object.freeze({\n programAddress,\n ...(accounts && accounts.length ? { accounts: Object.freeze(accounts) } : {}),\n ...(data && data.length ? { data } : {}),\n });\n}\n\ntype LifetimeConstraint =\n | BlockhashLifetimeConstraint\n | {\n nonce: Nonce;\n nonceAccountAddress: Address;\n nonceAuthorityAddress: Address;\n };\n\nfunction getLifetimeConstraint(\n messageLifetimeToken: string,\n firstInstruction?: Instruction,\n lastValidBlockHeight?: bigint,\n): LifetimeConstraint {\n if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {\n // first instruction is not advance durable nonce, so use blockhash lifetime constraint\n return {\n blockhash: messageLifetimeToken as Blockhash,\n lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n, // U64 MAX\n };\n } else {\n // We know these accounts are defined because we checked `isAdvanceNonceAccountInstruction`\n const nonceAccountAddress = firstInstruction.accounts[0].address;\n assertIsAddress(nonceAccountAddress);\n\n const nonceAuthorityAddress = firstInstruction.accounts[2].address;\n assertIsAddress(nonceAuthorityAddress);\n\n return {\n nonce: messageLifetimeToken as Nonce,\n nonceAccountAddress,\n nonceAuthorityAddress,\n };\n }\n}\n\nexport type DecompileTransactionMessageConfig = {\n /**\n * If the compiled message loads addresses from one or more address lookup tables, you will have\n * to supply a map of those tables to an array of the addresses they contained at the time that\n * the transaction message was constructed.\n *\n * @see {@link decompileTransactionMessageFetchingLookupTables} if you do not already have this.\n */\n addressesByLookupTableAddress?: AddressesByLookupTableAddress;\n /**\n * If the compiled message has a blockhash-based lifetime constraint, you will have to supply\n * the block height after which that blockhash is no longer valid for use as a lifetime\n * constraint.\n */\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Converts the type of transaction message data structure appropriate for execution on the network\n * to the type of transaction message data structure designed for use in your application.\n *\n * Because compilation is a lossy process, you can not fully reconstruct a source message from a\n * compiled message without extra information. In order to faithfully reconstruct the original\n * source message you will need to supply supporting details about the lifetime constraint and the\n * concrete addresses of any accounts sourced from account lookup tables.\n *\n * @see {@link compileTransactionMessage}\n */\nexport function decompileTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n config?: DecompileTransactionMessageConfig,\n): TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime {\n const feePayer = compiledTransactionMessage.staticAccounts[0];\n if (!feePayer) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING);\n }\n\n const accountMetas = getAccountMetas(compiledTransactionMessage);\n const accountLookupMetas =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? getAddressLookupMetas(\n compiledTransactionMessage.addressTableLookups,\n config?.addressesByLookupTableAddress ?? {},\n )\n : [];\n const transactionMetas = [...accountMetas, ...accountLookupMetas];\n\n const instructions: Instruction[] = compiledTransactionMessage.instructions.map(compiledInstruction =>\n convertInstruction(compiledInstruction, transactionMetas),\n );\n\n const firstInstruction = instructions[0];\n const lifetimeConstraint = getLifetimeConstraint(\n compiledTransactionMessage.lifetimeToken,\n firstInstruction,\n config?.lastValidBlockHeight,\n );\n\n return pipe(\n createTransactionMessage({ version: compiledTransactionMessage.version as TransactionVersion }),\n m => setTransactionMessageFeePayer(feePayer, m),\n m =>\n instructions.reduce(\n (acc, instruction) => appendTransactionMessageInstruction(instruction, acc),\n m as TransactionMessage,\n ),\n m =>\n 'blockhash' in lifetimeConstraint\n ? setTransactionMessageLifetimeUsingBlockhash(lifetimeConstraint, m)\n : setTransactionMessageLifetimeUsingDurableNonce(lifetimeConstraint, m),\n ) as TransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithLifetime;\n}\n","export const ED25519_ALGORITHM_IDENTIFIER =\n // Resist the temptation to convert this to a simple string; As of version 133.0.3, Firefox\n // requires the object form of `AlgorithmIdentifier` and will throw a `DOMException` otherwise.\n Object.freeze({ name: 'Ed25519' });\n","import { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SolanaError } from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\nfunction addPkcs8Header(bytes: ReadonlyUint8Array): ReadonlyUint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 private key for use\n * with other methods in this package that accept\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]));\n * const extractablePrivateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n * ```\n */\nexport async function createPrivateKeyFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const actualLength = bytes.byteLength;\n if (actualLength !== 32) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, {\n actualLength,\n });\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, ED25519_ALGORITHM_IDENTIFIER, extractable, [\n 'sign',\n ]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SolanaError } from '@solana/errors';\n\n/**\n * Given an extractable [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * private key, gets the corresponding public key as a\n * [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey).\n *\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the public\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createPrivateKeyFromBytes, getPublicKeyFromPrivateKey } from '@solana/keys';\n *\n * const privateKey = await createPrivateKeyFromBytes(new Uint8Array([...]), true);\n *\n * const publicKey = await getPublicKeyFromPrivateKey(privateKey);\n * const extractablePublicKey = await getPublicKeyFromPrivateKey(privateKey, true);\n * ```\n */\nexport async function getPublicKeyFromPrivateKey(\n privateKey: CryptoKey,\n extractable: boolean = false,\n): Promise {\n assertKeyExporterIsAvailable();\n\n if (privateKey.extractable === false) {\n throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, { key: privateKey });\n }\n\n // Export private key.\n const jwk = await crypto.subtle.exportKey('jwk', privateKey);\n\n // Import public key.\n return await crypto.subtle.importKey(\n 'jwk',\n {\n crv /* curve */: 'Ed25519',\n ext /* extractable */: extractable,\n key_ops /* key operations */: ['verify'],\n kty /* key type */: 'OKP' /* octet key pair */,\n x /* public key x-coordinate */: jwk.x,\n },\n 'Ed25519',\n extractable,\n ['verify'],\n );\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder, ReadonlyUint8Array, toArrayBuffer } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\n\n/**\n * A 64-byte Ed25519 signature as a base58-encoded string.\n */\nexport type Signature = Brand, 'Signature'>;\n/**\n * A 64-byte Ed25519 signature.\n *\n * Whenever you need to verify that a particular signature is, in fact, the one that would have been\n * produced by signing some known bytes using the private key associated with some known public key,\n * use the {@link verifySignature} function in this package.\n */\nexport type SignatureBytes = Brand;\n\nlet base58Encoder: Encoder | undefined;\n\n/**\n * Asserts that an arbitrary string is a base58-encoded Ed25519 signature.\n *\n * Useful when you receive a string from user input or an untrusted network API that you expect to\n * represent an Ed25519 signature (eg. of a transaction).\n *\n * @example\n * ```ts\n * import { assertIsSignature } from '@solana/keys';\n *\n * // Imagine a function that asserts whether a user-supplied signature is valid or not.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const signature: string = signatureInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signature` to `Signature`.\n * assertIsSignature(signature);\n * // At this point, `signature` is a `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * } catch (e) {\n * // `signature` turned out not to be a base58-encoded signature\n * }\n * }\n * ```\n */\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeSignature.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n assertIsSignatureBytes(bytes);\n}\n\n/**\n * Asserts that an arbitrary `ReadonlyUint8Array` is an Ed25519 signature.\n *\n * Useful when you receive a `ReadonlyUint8Array` from an external interface (like the browser wallets' `signMessage` API) that you expect to\n * represent an Ed25519 signature.\n *\n * @example\n * ```ts\n * import { assertIsSignatureBytes } from '@solana/keys';\n *\n * // Imagine a function that verifies a signature.\n * function verifySignature() {\n * // We know only that the input conforms to the `ReadonlyUint8Array` type.\n * const signatureBytes: ReadonlyUint8Array = signatureBytesInput;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `signatureBytes` to `SignatureBytes`.\n * assertIsSignatureBytes(signatureBytes);\n * // At this point, `signatureBytes` is a `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } catch (e) {\n * // `signatureBytes` turned out not to be a 64-byte Ed25519 signature\n * }\n * }\n * ```\n */\nexport function assertIsSignatureBytes(\n putativeSignatureBytes: ReadonlyUint8Array,\n): asserts putativeSignatureBytes is SignatureBytes {\n const numBytes = putativeSignatureBytes.byteLength;\n if (numBytes !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\n/**\n * A type guard that accepts a string as input. It will both return `true` if the string conforms to\n * the {@link Signature} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignature } from '@solana/keys';\n *\n * if (isSignature(signature)) {\n * // At this point, `signature` has been refined to a\n * // `Signature` that can be used with the RPC.\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * setSignatureStatus(status);\n * } else {\n * setError(`${signature} is not a transaction signature`);\n * }\n * ```\n */\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n return isSignatureBytes(bytes);\n}\n\n/**\n * A type guard that accepts a `ReadonlyUint8Array` as input. It will both return `true` if the `ReadonlyUint8Array` conforms to\n * the {@link SignatureBytes} type and will refine the type for use in your program.\n *\n * @example\n * ```ts\n * import { isSignatureBytes } from '@solana/keys';\n *\n * if (isSignatureBytes(signatureBytes)) {\n * // At this point, `signatureBytes` has been refined to a\n * // `SignatureBytes` that can be used with `verifySignature`.\n * if (!(await verifySignature(publicKey, signatureBytes, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * } else {\n * setError(`${signatureBytes} is not a 64-byte Ed25519 signature`);\n * }\n * ```\n */\nexport function isSignatureBytes(putativeSignatureBytes: ReadonlyUint8Array): putativeSignatureBytes is SignatureBytes {\n return putativeSignatureBytes.byteLength === 64;\n}\n\n/**\n * Given a private [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and a\n * `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a\n * `Uint8Array`.\n *\n * @example\n * ```ts\n * import { signBytes } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * const signature = await signBytes(privateKey, data);\n * ```\n */\nexport async function signBytes(key: CryptoKey, data: ReadonlyUint8Array): Promise {\n assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(data));\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\n/**\n * This helper combines _asserting_ that a string is an Ed25519 signature with _coercing_ it to the\n * {@link Signature} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signature } from '@solana/keys';\n *\n * const signature = signature(userSuppliedSignature);\n * const {\n * value: [status],\n * } = await rpc.getSignatureStatuses([signature]).send();\n * ```\n */\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\n/**\n * This helper combines _asserting_ that a `ReadonlyUint8Array` is an Ed25519 signature with _coercing_ it to the\n * {@link SignatureBytes} type. It's best used with untrusted input.\n *\n * @example\n * ```ts\n * import { signatureBytes } from '@solana/keys';\n *\n * const signature = signatureBytes(userSuppliedSignatureBytes);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport function signatureBytes(putativeSignatureBytes: ReadonlyUint8Array): SignatureBytes {\n assertIsSignatureBytes(putativeSignatureBytes);\n return putativeSignatureBytes;\n}\n\n/**\n * Given a public [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), some\n * {@link SignatureBytes}, and a `Uint8Array` of data, this method will return `true` if the\n * signature was produced by signing the data using the private key associated with the public key,\n * and `false` otherwise.\n *\n * @example\n * ```ts\n * import { verifySignature } from '@solana/keys';\n *\n * const data = new Uint8Array([1, 2, 3]);\n * if (!(await verifySignature(publicKey, signature, data))) {\n * throw new Error('The data were *not* signed by the private key associated with `publicKey`');\n * }\n * ```\n */\nexport async function verifySignature(\n key: CryptoKey,\n signature: SignatureBytes,\n data: ReadonlyUint8Array,\n): Promise {\n assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(signature), toArrayBuffer(data));\n}\n","import { assertKeyGenerationIsAvailable, assertPRNGIsAvailable } from '@solana/assertions';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,\n SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,\n SolanaError,\n} from '@solana/errors';\n\nimport { ED25519_ALGORITHM_IDENTIFIER } from './algorithm';\nimport { createPrivateKeyFromBytes } from './private-key';\nimport { getPublicKeyFromPrivateKey } from './public-key';\nimport { signBytes, verifySignature } from './signatures';\n\n/**\n * Generates an Ed25519 public/private key pair for use with other methods in this package that\n * accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) objects.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await generateKeyPair();\n * ```\n */\nexport async function generateKeyPair(): Promise {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ ED25519_ALGORITHM_IDENTIFIER, // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify'],\n );\n return keyPair;\n}\n\n/**\n * Given a 64-byte `Uint8Array` secret key, creates an Ed25519 public/private key pair for use with\n * other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 64 bytes, the first 32 of which represent the private key and the last 32 of which\n * represent its associated public key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairFromBytes } from '@solana/keys';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a CryptoKeyPair from the bytes.\n * const { privateKey, publicKey } = await createKeyPairFromBytes(keypairBytes);\n * ```\n */\nexport async function createKeyPairFromBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n assertPRNGIsAvailable();\n\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), ED25519_ALGORITHM_IDENTIFIER, /* extractable */ true, [\n 'verify',\n ]),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n\n // Verify the key pair\n const randomBytes = new Uint8Array(32);\n crypto.getRandomValues(randomBytes);\n const signedData = await signBytes(privateKey, randomBytes);\n const isValid = await verifySignature(publicKey, signedData, randomBytes);\n if (!isValid) {\n throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);\n }\n\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n\n/**\n * Given a private key represented as a 32-byte `Uint8Array`, creates an Ed25519 public/private key\n * pair for use with other methods in this package that accept [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)\n * objects.\n *\n * @param bytes 32 bytes that represent the private key\n * @param extractable Setting this to `true` makes it possible to extract the bytes of the private\n * key using the [`crypto.subtle.exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey)\n * API. Defaults to `false`.\n *\n * @example\n * ```ts\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const { privateKey, publicKey } = await createKeyPairFromPrivateKeyBytes(new Uint8Array([...]));\n * ```\n *\n * This can be useful when you have a private key but not the corresponding public key or when you\n * need to derive key pairs from seeds. For instance, the following code snippet derives a key pair\n * from the hash of a message.\n *\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairFromPrivateKeyBytes } from '@solana/keys';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedKeypair = await createKeyPairFromPrivateKeyBytes(seed);\n * ```\n */\nexport async function createKeyPairFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable: boolean = false,\n): Promise {\n const privateKeyPromise = createPrivateKeyFromBytes(bytes, extractable);\n\n // Here we need the private key to be extractable in order to export\n // it as a public key. Therefore, if the `extractable` parameter\n // is `false`, we need to create two private keys such that:\n // - The extractable one is used to create the public key and\n // - The non-extractable one is the one we will return.\n const [publicKey, privateKey] = await Promise.all([\n // This nested promise makes things efficient by\n // creating the public key in parallel with the\n // second private key creation, if it is needed.\n (extractable ? privateKeyPromise : createPrivateKeyFromBytes(bytes, true /* extractable */)).then(\n async privateKey => await getPublicKeyFromPrivateKey(privateKey, true /* extractable */),\n ),\n privateKeyPromise,\n ]);\n\n return { privateKey, publicKey };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getShortU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { SignaturesMap } from '../transaction';\n\nfunction getSignaturesToEncode(signaturesMap: SignaturesMap): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { getAddressDecoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n padRightDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n} from '@solana/codecs-data-structures';\nimport { getShortU16Decoder, getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { getTransactionVersionDecoder } from '@solana/transaction-messages';\n\nimport { SignaturesMap, Transaction, TransactionMessageBytes } from '../transaction';\nimport { getSignaturesEncoder } from './signatures-encoder';\n\n/**\n * Returns an encoder that you can use to encode a {@link Transaction} to a byte array in a wire\n * format appropriate for sending to the Solana network for execution.\n */\nexport function getTransactionEncoder(): VariableSizeEncoder {\n return getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['messageBytes', getBytesEncoder()],\n ]);\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana transaction wire format\n * to a {@link Transaction} object.\n *\n * @example\n * ```ts\n * import { getTransactionDecoder } from '@solana/transactions';\n *\n * const transactionDecoder = getTransactionDecoder();\n * const transaction = transactionDecoder.decode(wireTransactionBytes);\n * for (const [address, signature] in Object.entries(transaction.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\n\nexport function getTransactionDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getShortU16Decoder() })],\n ['messageBytes', getBytesDecoder()],\n ]),\n decodePartiallyDecodedTransaction,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a {@link Transaction}\n *\n * @see {@link getTransactionDecoder}\n * @see {@link getTransactionEncoder}\n */\nexport function getTransactionCodec(): VariableSizeCodec {\n return combineCodec(getTransactionEncoder(), getTransactionDecoder());\n}\n\ntype PartiallyDecodedTransaction = {\n messageBytes: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedTransaction(transaction: PartiallyDecodedTransaction): Transaction {\n const { messageBytes, signatures } = transaction;\n\n /*\n Relevant message structure is at the start:\n - transaction version (0 bytes for legacy transactions, 1 byte for versioned transactions)\n - `numRequiredSignatures` (1 byte, we verify this matches the length of signatures)\n - `numReadOnlySignedAccounts` (1 byte, not used here)\n - `numReadOnlyUnsignedAccounts` (1 byte, not used here)\n - static addresses, with signers first. This is an array of addresses, prefixed with a short-u16 length\n */\n\n const signerAddressesDecoder = getTupleDecoder([\n // read transaction version\n getTransactionVersionDecoder(),\n // read first byte of header, `numSignerAccounts`\n // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need\n padRightDecoder(getU8Decoder(), 2),\n // read static addresses\n getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() }),\n ]);\n const [_txVersion, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);\n\n const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);\n\n // signer addresses and signatures must be the same length\n // we encode an all-zero signature when the signature is missing\n if (signerAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, {\n numRequiredSignatures,\n signaturesLength: signatures.length,\n signerAddresses,\n });\n }\n\n // combine the signer addresses + signatures into the signatures map\n const signaturesMap: SignaturesMap = {};\n signerAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return {\n messageBytes: messageBytes as TransactionMessageBytes,\n signatures: Object.freeze(signaturesMap),\n };\n}\n","import { type Address, isAddress } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,\n SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,\n SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,\n SolanaError,\n} from '@solana/errors';\nimport { type Blockhash, isBlockhash, type Slot } from '@solana/rpc-types';\nimport type {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n Nonce,\n TransactionMessage,\n TransactionMessageWithBlockhashLifetime,\n TransactionMessageWithDurableNonceLifetime,\n} from '@solana/transaction-messages';\n\nimport type { Transaction } from './transaction';\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network. The transaction will continue to be eligible to land until the network considers the\n * `blockhash` to be expired.\n *\n * This can happen when the network proceeds past the `lastValidBlockHeight` for which the blockhash\n * is considered valid, or when the network switches to a fork where that blockhash is not present.\n */\nexport type TransactionBlockhashLifetime = {\n /**\n * A recent blockhash observed by the transaction proposer.\n *\n * The transaction will be considered eligible to land until the network determines this\n * blockhash to be too old, or has switched to a fork where it is not present.\n */\n blockhash: Blockhash;\n /**\n * This is the block height beyond which the network will consider the blockhash to be too old\n * to make a transaction eligible to land.\n */\n lastValidBlockHeight: Slot;\n};\n\n/**\n * A constraint which, when applied to a transaction, makes that transaction eligible to land on the\n * network.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionDurableNonceLifetime = {\n /**\n * A value contained in the account with address `nonceAccountAddress` at the time the\n * transaction was prepared.\n *\n * The transaction will be considered eligible to land until the nonce account ceases to exist\n * or contain this value.\n */\n nonce: Nonce;\n /** The account that contains the `nonce` value */\n nonceAccountAddress: Address;\n};\n\n/**\n * A transaction whose ability to land on the network is determined by some evanescent criteria.\n *\n * This describes a window of time after which a transaction is constructed and before which it will\n * no longer be accepted by the network.\n *\n * No transaction can land on Solana without having a `lifetimeConstraint` set.\n */\nexport type TransactionWithLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime | TransactionDurableNonceLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by the age of a blockhash observed on the network.\n *\n * The transaction will continue to be eligible to land until the network considers the `blockhash`\n * to be expired.\n */\nexport type TransactionWithBlockhashLifetime = {\n readonly lifetimeConstraint: TransactionBlockhashLifetime;\n};\n\n/**\n * A transaction whose lifetime is determined by a nonce.\n *\n * The transaction will continue to be eligible to land until the network considers the `nonce` to\n * have advanced. This can happen when the nonce account in which this nonce is found is destroyed,\n * or the nonce value within changes.\n */\nexport type TransactionWithDurableNonceLifetime = {\n readonly lifetimeConstraint: TransactionDurableNonceLifetime;\n};\n\n/**\n * Helper type that sets the lifetime constraint of a transaction to be the same as the\n * lifetime constraint of the provided transaction message.\n *\n * If the transaction message has no explicit lifetime constraint, neither will the transaction.\n */\nexport type SetTransactionLifetimeFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends TransactionMessage,\n> = TTransactionMessage extends { lifetimeConstraint: unknown }\n ? TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithBlockhashLifetime['lifetimeConstraint']\n ? TransactionWithBlockhashLifetime & TTransaction\n : TTransactionMessage['lifetimeConstraint'] extends TransactionMessageWithDurableNonceLifetime['lifetimeConstraint']\n ? TransactionWithDurableNonceLifetime & TTransaction\n : TransactionWithLifetime & TTransaction\n : TTransaction;\n\nconst SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address;\n\nfunction compiledInstructionIsAdvanceNonceInstruction(\n instruction: CompiledTransactionMessage['instructions'][number],\n staticAddresses: Address[],\n): instruction is typeof instruction & { accountIndices: [number, number, number] } {\n return (\n staticAddresses[instruction.programAddressIndex] === SYSTEM_PROGRAM_ADDRESS &&\n // Test for `AdvanceNonceAccount` instruction data\n instruction.data != null &&\n isAdvanceNonceAccountInstructionData(instruction.data) &&\n // Test for exactly 3 accounts\n instruction.accountIndices?.length === 3\n );\n}\n\nfunction isAdvanceNonceAccountInstructionData(data: ReadonlyUint8Array): boolean {\n // AdvanceNonceAccount is the fifth instruction in the System Program (index 4)\n return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;\n}\n\n/**\n * Get the lifetime constraint for a transaction from a compiled transaction message that includes a lifetime token.\n * @param compiledTransactionMessage A compiled transaction message that includes a lifetime token\n * @returns A lifetime constraint for the transaction\n * Note that this is less precise than checking a decompiled instruction, as we can't inspect\n * the address or role of input accounts (which may be in lookup tables). However, this is\n * sufficient for all valid advance durable nonce instructions.\n * Note that the program address must not be in a lookup table, see [this answer on StackExchange](https://solana.stackexchange.com/a/16224/289)\n * @see {@link isAdvanceNonceAccountInstruction}\n * Note that this function is async to allow for future implementations that may fetch `lastValidBlockHeight` using an RPC\n */\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function getTransactionLifetimeConstraintFromCompiledTransactionMessage(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n): Promise {\n const firstInstruction = compiledTransactionMessage.instructions[0];\n const { staticAccounts } = compiledTransactionMessage;\n\n // We need to check if the first instruction is an AdvanceNonceAccount instruction\n if (firstInstruction && compiledInstructionIsAdvanceNonceInstruction(firstInstruction, staticAccounts)) {\n const nonceAccountAddress = staticAccounts[firstInstruction.accountIndices[0]];\n if (!nonceAccountAddress) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, {\n nonce: compiledTransactionMessage.lifetimeToken,\n });\n }\n return {\n nonce: compiledTransactionMessage.lifetimeToken as Nonce,\n nonceAccountAddress,\n };\n } else {\n return {\n blockhash: compiledTransactionMessage.lifetimeToken as Blockhash,\n // This is not known from the compiled message, so we set it to the maximum possible value\n lastValidBlockHeight: 0xffffffffffffffffn,\n };\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithBlockhashLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * if (isTransactionWithBlockhashLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a `TransactionWithBlockhashLifetime`.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * setBlockhashIsValid(blockhashIsValid);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a blockhash-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithBlockhashLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'blockhash' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.blockhash === 'string' &&\n typeof transaction.lifetimeConstraint.lastValidBlockHeight === 'bigint' &&\n isBlockhash(transaction.lifetimeConstraint.blockhash)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * blockhash-based lifetime, from for example a wallet. Use this function to\n * assert that such a transaction actually has a blockhash-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithBlockhashLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithBlockhashLifetime`.\n * assertIsTransactionWithBlockhashLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithBlockhashLifetime` that can be used\n * // with the RPC.\n * const { blockhash } = transaction.lifetimeConstraint;\n * const { value: blockhashIsValid } = await rpc.isBlockhashValid(blockhash).send();\n * } catch (e) {\n * // `transaction` turned out not to have a blockhash-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithBlockhashLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithBlockhashLifetime {\n if (!isTransactionWithBlockhashLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);\n }\n}\n\n/**\n * A type guard that returns `true` if the transaction conforms to the\n * {@link TransactionWithDurableNonceLifetime} type, and refines its type for use in your\n * program.\n *\n * @example\n * ```ts\n * import { isTransactionWithDurableNonceLifetime } from '@solana/transactions';\n * import { fetchNonce } from \"@solana-program/system\";\n *\n * if (isTransactionWithDurableNonceLifetime(transaction)) {\n * // At this point, `transaction` has been refined to a\n * // `TransactionWithDurableNonceLifetime`.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * setNonceIsValid(nonce === actualNonce);\n * } else {\n * setError(\n * `${getSignatureFromTransaction(transaction)} does not have a nonce-based lifetime`,\n * );\n * }\n * ```\n */\nexport function isTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): transaction is Transaction & TransactionWithDurableNonceLifetime {\n return (\n 'lifetimeConstraint' in transaction &&\n 'nonce' in transaction.lifetimeConstraint &&\n typeof transaction.lifetimeConstraint.nonce === 'string' &&\n typeof transaction.lifetimeConstraint.nonceAccountAddress === 'string' &&\n isAddress(transaction.lifetimeConstraint.nonceAccountAddress)\n );\n}\n\n/**\n * From time to time you might acquire a transaction, that you expect to have a\n * nonce-based lifetime, from for example a wallet. Use this function to assert\n * that such a transaction actually has a nonce-based lifetime.\n *\n * @example\n * ```ts\n * import { assertIsTransactionWithDurableNonceLifetime } from '@solana/transactions';\n *\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `transaction` to `TransactionWithDurableNonceLifetime`.\n * assertIsTransactionWithDurableNonceLifetime(transaction);\n * // At this point, `transaction` is a `TransactionWithDurableNonceLifetime` that can be used\n * // with the RPC.\n * const { nonce, nonceAccountAddress } = transaction.lifetimeConstraint;\n * const { data: { blockhash: actualNonce } } = await fetchNonce(nonceAccountAddress);\n * } catch (e) {\n * // `transaction` turned out not to have a nonce-based lifetime\n * }\n * ```\n */\nexport function assertIsTransactionWithDurableNonceLifetime(\n transaction: Transaction | (Transaction & TransactionWithLifetime),\n): asserts transaction is Transaction & TransactionWithDurableNonceLifetime {\n if (!isTransactionWithDurableNonceLifetime(transaction)) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);\n }\n}\n","import {\n compileTransactionMessage,\n getCompiledTransactionMessageEncoder,\n isTransactionMessageWithBlockhashLifetime,\n isTransactionMessageWithDurableNonceLifetime,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport type { TransactionWithLifetime } from './lifetime';\nimport type { SignaturesMap, TransactionFromTransactionMessage, TransactionMessageBytes } from './transaction';\n\n/**\n * Returns a {@link Transaction} object for a given {@link TransactionMessage}.\n *\n * This includes the compiled bytes of the transaction message, and a map of signatures. This map\n * will have a key for each address that is required to sign the transaction. The transaction will\n * not yet have signatures for any of these addresses.\n *\n * Whether a transaction message is ready to be compiled or not is enforced for you at the type\n * level. In order to be signable, a transaction message must:\n *\n * - have a version and a list of zero or more instructions (ie. conform to\n * {@link TransactionMessage})\n * - have a fee payer set (ie. conform to {@link TransactionMessageWithFeePayer})\n * - have a lifetime specified (ie. conform to {@link TransactionMessageWithBlockhashLifetime} or\n * {@link TransactionMessageWithDurableNonceLifetime})\n */\nexport function compileTransaction(\n transactionMessage: TTransactionMessage,\n): Readonly> {\n type ReturnType = Readonly>;\n\n const compiledMessage = compileTransactionMessage(transactionMessage);\n const messageBytes = getCompiledTransactionMessageEncoder().encode(compiledMessage) as TransactionMessageBytes;\n\n const transactionSigners = compiledMessage.staticAccounts.slice(0, compiledMessage.header.numSignerAccounts);\n const signatures: SignaturesMap = {};\n for (const signerAddress of transactionSigners) {\n signatures[signerAddress] = null;\n }\n\n let lifetimeConstraint: TransactionWithLifetime['lifetimeConstraint'] | undefined;\n if (isTransactionMessageWithBlockhashLifetime(transactionMessage)) {\n lifetimeConstraint = {\n blockhash: transactionMessage.lifetimeConstraint.blockhash,\n lastValidBlockHeight: transactionMessage.lifetimeConstraint.lastValidBlockHeight,\n };\n } else if (isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {\n lifetimeConstraint = {\n nonce: transactionMessage.lifetimeConstraint.nonce,\n nonceAccountAddress: transactionMessage.instructions[0].accounts[0].address,\n };\n }\n\n return Object.freeze({\n ...(lifetimeConstraint ? { lifetimeConstraint } : undefined),\n messageBytes: messageBytes,\n signatures: Object.freeze(signatures),\n }) as ReturnType;\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { bytesEqual, Decoder } from '@solana/codecs-core';\nimport { getBase58Decoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,\n SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,\n SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Signature, SignatureBytes, signBytes } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { Transaction } from './transaction';\n\n/**\n * Represents a transaction that is signed by all of its required signers. Being fully signed is a\n * prerequisite of functions designed to land transactions on the network.\n */\nexport type FullySignedTransaction = NominalType<'transactionSignedness', 'fullySigned'>;\n\nlet base58Decoder: Decoder | undefined;\n\n/**\n * Given a transaction signed by its fee payer, this method will return the {@link Signature} that\n * uniquely identifies it. This string can be used to look up transactions at a later date, for\n * example on a Solana block explorer.\n *\n * @example\n * ```ts\n * import { getSignatureFromTransaction } from '@solana/transactions';\n *\n * const signature = getSignatureFromTransaction(tx);\n * console.debug(`Inspect this transaction at https://explorer.solana.com/tx/${signature}`);\n * ```\n */\nexport function getSignatureFromTransaction(transaction: Transaction): Signature {\n if (!base58Decoder) base58Decoder = getBase58Decoder();\n\n // We have ordered signatures from the compiled message accounts\n // first signature is the fee payer\n const signatureBytes = Object.values(transaction.signatures)[0];\n if (!signatureBytes) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);\n }\n const transactionSignature = base58Decoder.decode(signatureBytes);\n return transactionSignature as Signature;\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link Transaction}.\n *\n * Though the resulting transaction might have every signature it needs to land on the network, this\n * function will not assert that it does. A partially signed transaction cannot be landed on the\n * network, but can be serialized and deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignTransaction } from '@solana/transactions';\n *\n * const partiallySignedTransaction = await partiallySignTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link signTransaction} if you want to assert that the transaction has all of its required\n * signatures after signing.\n */\nexport async function partiallySignTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const existingSignature = transaction.signatures[address];\n\n // Check if the address is expected to sign the transaction\n if (existingSignature === undefined) {\n // address is not an expected signer for this transaction\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);\n\n if (existingSignature !== null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n const expectedSigners = Object.keys(transaction.signatures);\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {\n expectedAddresses: expectedSigners,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return transaction;\n }\n\n return Object.freeze({\n ...transaction,\n signatures: Object.freeze({\n ...transaction.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign a transaction, this method will return a new signed transaction of type\n * {@link FullySignedTransaction}.\n *\n * This function will throw unless the resulting transaction is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signTransaction } from '@solana/transactions';\n *\n * const signedTransaction = await signTransaction([myPrivateKey], tx);\n * ```\n *\n * @see {@link partiallySignTransaction} if you want to sign the transaction without asserting that\n * the resulting transaction is fully signed.\n */\nexport async function signTransaction(\n keyPairs: CryptoKeyPair[],\n transaction: TTransaction,\n): Promise {\n const out = await partiallySignTransaction(keyPairs, transaction);\n assertIsFullySignedTransaction(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * Checks whether a given {@link Transaction} is fully signed.\n *\n * @example\n * ```ts\n * import { isFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isFullySignedTransaction(transaction)) {\n * // At this point we know that the transaction is signed and can be sent to the network.\n * }\n * ```\n */\nexport function isFullySignedTransaction(\n transaction: TTransaction,\n): transaction is FullySignedTransaction & TTransaction {\n return Object.entries(transaction.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link Transaction}, that you expect to be fully signed,\n * from an untrusted network API or user input. Use this function to assert that such a transaction\n * is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `FullySignedTransaction`.\n * assertIsFullySignedTransaction(transaction);\n * // At this point we know that the transaction is signed and can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsFullySignedTransaction(\n transaction: TTransaction,\n): asserts transaction is FullySignedTransaction & TTransaction {\n const missingSigs: Address[] = [];\n Object.entries(transaction.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n","import { getBase64Decoder } from '@solana/codecs-strings';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/** Represents the wire format of a transaction as a base64-encoded string. */\nexport type Base64EncodedWireTransaction = Brand, 'Base64EncodedWireTransaction'>;\n\n/**\n * Given a signed transaction, this method returns the transaction as a string that conforms to the\n * {@link Base64EncodedWireTransaction} type.\n *\n * @example\n * ```ts\n * import { getBase64EncodedWireTransaction, signTransaction } from '@solana/transactions';\n *\n * const serializedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * const signature = await rpc.sendTransaction(serializedTransaction, { encoding: 'base64' }).send();\n * ```\n */\nexport function getBase64EncodedWireTransaction(transaction: Transaction): Base64EncodedWireTransaction {\n const wireTransactionBytes = getTransactionEncoder().encode(transaction);\n return getBase64Decoder().decode(wireTransactionBytes) as Base64EncodedWireTransaction;\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type { NominalType } from '@solana/nominal-types';\nimport type { BaseTransactionMessage, TransactionMessageWithinSizeLimit } from '@solana/transaction-messages';\n\nimport { getTransactionEncoder } from './codecs';\nimport { Transaction } from './transaction';\n\n/**\n * The maximum size of a transaction packet in bytes.\n */\nexport const TRANSACTION_PACKET_SIZE = 1280;\n\n/**\n * The size of the transaction packet header in bytes.\n * This includes the IPv6 header and the fragment header.\n */\nexport const TRANSACTION_PACKET_HEADER =\n 40 /* 40 bytes is the size of the IPv6 header. */ + 8; /* 8 bytes is the size of the fragment header. */\n\n/**\n * The maximum size of a transaction in bytes.\n *\n * Note that this excludes the transaction packet header.\n * In other words, this is how much content we can fit in a transaction packet.\n */\nexport const TRANSACTION_SIZE_LIMIT = TRANSACTION_PACKET_SIZE - TRANSACTION_PACKET_HEADER;\n\n/**\n * Gets the size of a given transaction in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionSize(transaction);\n * ```\n */\nexport function getTransactionSize(transaction: Transaction): number {\n return getTransactionEncoder().getSizeFromValue(transaction);\n}\n\n/**\n * A type guard that checks if a transaction is within the size limit.\n */\nexport type TransactionWithinSizeLimit = NominalType<'transactionSize', 'withinLimit'>;\n\n/**\n * Helper type that adds the `TransactionWithinSizeLimit` flag to\n * a transaction if and only if the provided transaction message\n * is also within the size limit.\n */\nexport type SetTransactionWithinSizeLimitFromTransactionMessage<\n TTransaction extends Transaction,\n TTransactionMessage extends BaseTransactionMessage,\n> = TTransactionMessage extends TransactionMessageWithinSizeLimit\n ? TransactionWithinSizeLimit & TTransaction\n : TTransaction;\n\n/**\n * Checks if a transaction is within the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * if (isTransactionWithinSizeLimit(transaction)) {\n * transaction satisfies TransactionWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionWithinSizeLimit(\n transaction: TTransaction,\n): transaction is TransactionWithinSizeLimit & TTransaction {\n return getTransactionSize(transaction) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction is within the size limit.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction exceeds the size limit.\n *\n * @typeParam TTransaction - The type of the given transaction.\n *\n * @example\n * ```ts\n * assertIsTransactionWithinSizeLimit(transaction);\n * transaction satisfies TransactionWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionWithinSizeLimit(\n transaction: TTransaction,\n): asserts transaction is TransactionWithinSizeLimit & TTransaction {\n const transactionSize = getTransactionSize(transaction);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","import { assertIsFullySignedTransaction, FullySignedTransaction, isFullySignedTransaction } from './signatures';\nimport { Transaction } from './transaction';\nimport {\n assertIsTransactionWithinSizeLimit,\n isTransactionWithinSizeLimit,\n TransactionWithinSizeLimit,\n} from './transaction-size';\n\n/**\n * Helper type that includes all transaction types required\n * for the transaction to be sent to the network.\n *\n * @see {@link isSendableTransaction}\n * @see {@link assertIsSendableTransaction}\n */\nexport type SendableTransaction = FullySignedTransaction & TransactionWithinSizeLimit;\n\n/**\n * Checks if a transaction has all the required\n * conditions to be sent to the network.\n *\n * @example\n * ```ts\n * import { isSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * if (isSendableTransaction(transaction)) {\n * // At this point we know that the transaction can be sent to the network.\n * }\n * ```\n *\n * @see {@link assertIsSendableTransaction}\n */\nexport function isSendableTransaction(\n transaction: TTransaction,\n): transaction is SendableTransaction & TTransaction {\n return isFullySignedTransaction(transaction) && isTransactionWithinSizeLimit(transaction);\n}\n\n/**\n * Asserts that a given transaction has all the\n * required conditions to be sent to the network.\n *\n * From time to time you might acquire a {@link Transaction}\n * from an untrusted network API or user input and you are not sure\n * that it has all the required conditions to be sent to the network\n * — such as being fully signed and within the size limit.\n * This function can be used to assert that such a transaction\n * is in fact sendable.\n *\n * @example\n * ```ts\n * import { assertIsSendableTransaction } from '@solana/transactions';\n *\n * const transaction = getTransactionDecoder().decode(transactionBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast `transaction`\n * // to `SendableTransaction`.\n * assertIsSendableTransaction(transaction);\n * // At this point we know that the transaction can be sent to the network.\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else if (isSolanaError(e, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT)) {\n * setError(`Transaction exceeds size limit of ${e.context.transactionSizeLimit} bytes`);\n * }\n * throw;\n * }\n * ```\n */\nexport function assertIsSendableTransaction(\n transaction: TTransaction,\n): asserts transaction is SendableTransaction & TTransaction {\n assertIsFullySignedTransaction(transaction);\n assertIsTransactionWithinSizeLimit(transaction);\n}\n","import { SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SolanaError } from '@solana/errors';\nimport type {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithinSizeLimit,\n} from '@solana/transaction-messages';\n\nimport { compileTransaction } from './compile-transaction';\nimport { getTransactionSize, TRANSACTION_SIZE_LIMIT } from './transaction-size';\n\n/**\n * Gets the compiled transaction size of a given transaction message in bytes.\n *\n * @example\n * ```ts\n * const transactionSize = getTransactionMessageSize(transactionMessage);\n * ```\n */\nexport function getTransactionMessageSize(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n): number {\n return getTransactionSize(compileTransaction(transactionMessage));\n}\n\n/**\n * Checks if a transaction message is within the size limit\n * when compiled into a transaction.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * if (isTransactionMessageWithinSizeLimit(transactionMessage)) {\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * }\n * ```\n */\nexport function isTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n return getTransactionMessageSize(transactionMessage) <= TRANSACTION_SIZE_LIMIT;\n}\n\n/**\n * Asserts that a given transaction message is within the size limit\n * when compiled into a transaction.\n *\n * Throws a {@link SolanaError} of code {@link SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT}\n * if the transaction message exceeds the size limit.\n *\n * @typeParam TTransactionMessage - The type of the given transaction message.\n *\n * @example\n * ```ts\n * assertIsTransactionMessageWithinSizeLimit(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithinSizeLimit;\n * ```\n */\nexport function assertIsTransactionMessageWithinSizeLimit<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n): asserts transactionMessage is TransactionMessageWithinSizeLimit & TTransactionMessage {\n const transactionSize = getTransactionMessageSize(transactionMessage);\n if (transactionSize > TRANSACTION_SIZE_LIMIT) {\n throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {\n transactionSize,\n transactionSizeLimit: TRANSACTION_SIZE_LIMIT,\n });\n }\n}\n","/**\n * Forked from https://github.com/digitalloggers/race-as-promised/tree/master\n *\n * Authored by Brian Kim:\n * https://github.com/nodejs/node/issues/17469#issuecomment-685216777\n *\n * Adapted to module structure.\n *\n * This is free and unencumbered software released into the public domain.\n *\n * Anyone is free to copy, modify, publish, use, compile, sell, or\n * distribute this software, either in source code form or as a compiled\n * binary, for any purpose, commercial or non-commercial, and by any\n * means.\n *\n * In jurisdictions that recognize copyright laws, the author or authors\n * of this software dedicate any and all copyright interest in the\n * software to the public domain. We make this dedication for the benefit\n * of the public at large and to the detriment of our heirs and\n * successors. We intend this dedication to be an overt act of\n * relinquishment in perpetuity of all present and future rights to this\n * software under copyright law.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * For more information, please refer to \n */\n\ntype Deferred = Readonly<{\n reject: (reason?: unknown) => void;\n resolve: (value: unknown) => void;\n}>;\n\nfunction isObject(value: unknown): value is object {\n return value !== null && (typeof value === 'object' || typeof value === 'function');\n}\n\nfunction addRaceContender(contender: object) {\n const deferreds = new Set();\n const record = { deferreds, settled: false };\n\n // This call to `then` happens once for the lifetime of the value.\n Promise.resolve(contender).then(\n value => {\n for (const { resolve } of deferreds) {\n resolve(value);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n err => {\n for (const { reject } of deferreds) {\n reject(err);\n }\n\n deferreds.clear();\n record.settled = true;\n },\n );\n return record;\n}\n\n// Keys are the values passed to race, values are a record of data containing a\n// set of deferreds and whether the value has settled.\nconst wm = new WeakMap; settled: boolean }>();\n/**\n * An implementation of [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)\n * that causes all of the losing promises to settle. This allows them to be released and garbage\n * collected, preventing memory leaks.\n *\n * Read more here: https://github.com/nodejs/node/issues/17469\n */\nexport async function safeRace(contenders: T): Promise> {\n let deferred: Deferred;\n const result = new Promise((resolve, reject) => {\n deferred = { reject, resolve };\n for (const contender of contenders) {\n if (!isObject(contender)) {\n // If the contender is a primitive, attempting to use it as a key in the\n // weakmap would throw an error. Luckily, it is safe to call\n // `Promise.resolve(contender).then` on a primitive value multiple times\n // because the promise fulfills immediately.\n Promise.resolve(contender).then(resolve, reject);\n continue;\n }\n\n let record = wm.get(contender);\n if (record === undefined) {\n record = addRaceContender(contender);\n record.deferreds.add(deferred);\n wm.set(contender, record);\n } else if (record.settled) {\n // If the value has settled, it is safe to call\n // `Promise.resolve(contender).then` on it.\n Promise.resolve(contender).then(resolve, reject);\n } else {\n record.deferreds.add(deferred);\n }\n }\n });\n\n // The finally callback executes when any value settles, preventing any of\n // the unresolved values from retaining a reference to the resolved value.\n return await (result.finally(() => {\n for (const contender of contenders) {\n if (isObject(contender)) {\n const record = wm.get(contender)!;\n record.deferreds.delete(deferred);\n }\n }\n }) as Promise>);\n}\n","import { safeRace } from './race';\n\n/**\n * Returns a new promise that will reject if the abort signal fires before the original promise\n * settles. Resolves or rejects with the value of the original promise otherwise.\n *\n * @example\n * ```ts\n * const result = await getAbortablePromise(\n * // Resolves or rejects when `fetch` settles.\n * fetch('https://example.com/json').then(r => r.json()),\n * // ...unless it takes longer than 5 seconds, after which the `AbortSignal` is triggered.\n * AbortSignal.timeout(5000),\n * );\n * ```\n */\nexport function getAbortablePromise(promise: Promise, abortSignal?: AbortSignal): Promise {\n if (!abortSignal) {\n return promise;\n } else {\n return safeRace([\n // This promise only ever rejects if the signal is aborted. Otherwise it idles forever.\n // It's important that this come before the input promise; in the event of an abort, we\n // want to throw even if the input promise's result is ready\n new Promise((_, reject) => {\n if (abortSignal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(abortSignal.reason);\n } else {\n abortSignal.addEventListener('abort', function () {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n });\n }\n }),\n promise,\n ]);\n }\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,\n SolanaError,\n} from '@solana/errors';\nimport { Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\n/**\n * A set of instructions with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans in order to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely the following plans are supported:\n * - {@link SingleInstructionPlan} - A plan that contains a single instruction.\n * This is a simple instruction wrapper and the simplest leaf in this tree.\n * - {@link ParallelInstructionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialInstructionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that instructions inside it can be split into separate transactions.\n * - {@link MessagePackerInstructionPlan} - A plan that can dynamically pack\n * instructions into transaction messages.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myInstructionPlan: InstructionPlan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * instructionC,\n * instructionD,\n * ]);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link ParallelInstructionPlan}\n * @see {@link SequentialInstructionPlan}\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type InstructionPlan =\n | MessagePackerInstructionPlan\n | ParallelInstructionPlan\n | SequentialInstructionPlan\n | SingleInstructionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the instructions inside them can be split into separate transactions.\n * When `divisible` is `false`, the instructions inside the plan should\n * all be executed atomically — either in a single transaction or in a\n * transaction bundle.\n *\n * You may use the {@link sequentialInstructionPlan} and {@link nonDivisibleSequentialInstructionPlan}\n * helpers to create objects of this type.\n *\n * @example Simple sequential plan with two instructions.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan;\n * ```\n *\n * @example Non-divisible sequential plan with two instructions.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @example Sequential plan with nested parallel plans.\n * Here, instructions A and B can be executed in parallel, but they must both be finalized\n * before instructions C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * parallelInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies SequentialInstructionPlan & { divisible: false };\n * ```\n *\n * @see {@link sequentialInstructionPlan}\n * @see {@link nonDivisibleSequentialInstructionPlan}\n */\nexport type SequentialInstructionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without consequence.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialInstructionPlan}.\n *\n * You may use the {@link parallelInstructionPlan} helper to create objects of this type.\n *\n * @example Simple parallel plan with two instructions.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @example Parallel plan with nested sequential plans.\n * Here, instructions A and B must be executed sequentially and so must instructions C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n * plan satisfies ParallelInstructionPlan;\n * ```\n *\n * @see {@link parallelInstructionPlan}\n */\nexport type ParallelInstructionPlan = Readonly<{\n kind: 'parallel';\n plans: InstructionPlan[];\n}>;\n\n/**\n * A plan that contains a single instruction.\n *\n * This is a simple instruction wrapper that transforms an instruction into a plan.\n *\n * You may use the {@link singleInstructionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * plan satisfies SingleInstructionPlan;\n * ```\n *\n * @see {@link singleInstructionPlan}\n */\nexport type SingleInstructionPlan = Readonly<{\n instruction: TInstruction;\n kind: 'single';\n}>;\n\n/**\n * A plan that can dynamically pack instructions into transaction messages.\n *\n * This plan provides a {@link MessagePacker} via the `getMessagePacker`\n * method, which enables instructions to be dynamically packed into the\n * provided transaction message until there are no more instructions to pack.\n * The returned {@link MessagePacker} offers a `packMessageToCapacity(message)`\n * method that packs the provided message — when possible — and a `done()` method\n * that checks whether there are more instructions to pack.\n *\n * Several helper functions are provided to create objects of this type such as\n * {@link getLinearMessagePackerInstructionPlan} or {@link getMessagePackerInstructionPlanFromInstructions}.\n *\n * @example An message packer plan for a write instruction that uses as many bytes as possible.\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example A message packer plan for multiple realloc instructions.\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @example Using a message packer plan.\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link getLinearMessagePackerInstructionPlan}\n * @see {@link getMessagePackerInstructionPlanFromInstructions}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport type MessagePackerInstructionPlan = Readonly<{\n getMessagePacker: () => MessagePacker;\n kind: 'messagePacker';\n}>;\n\n/**\n * The message packer returned by the {@link MessagePackerInstructionPlan}.\n *\n * It offers a `packMessageToCapacity(transactionMessage)` method that packs as many instructions\n * as possible into the provided transaction message, while still being able to fit into the\n * transaction size limit. It returns the updated transaction message with the packed instructions\n * or throws an error if the current transaction message cannot accommodate this plan.\n *\n * The `done()` method checks whether there are more instructions to pack into\n * transaction messages.\n *\n * @example\n * ```ts\n * let plan: MessagePackerInstructionPlan;\n * const messagePacker = plan.getMessagePacker();\n *\n * while (!messagePacker.done()) {\n * try {\n * transactionMessage = messagePacker.packMessageToCapacity(transactionMessage);\n * } catch (error) {\n * // The current transaction message cannot be used to pack this plan.\n * // We should create a new one and try again.\n * }\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport type MessagePacker = Readonly<{\n /** Checks whether the message packer has more instructions to pack into transaction messages. */\n done: () => boolean;\n /**\n * Packs the provided transaction message with instructions or throws if not possible.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN}\n * if the provided transaction message cannot be used to fill the next instructions.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE}\n * if the message packer is already done and no more instructions can be packed.\n */\n packMessageToCapacity: (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer;\n}>;\n\n/**\n * Creates a {@link ParallelInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = parallelInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n */\nexport function parallelInstructionPlan(plans: (Instruction | InstructionPlan)[]): ParallelInstructionPlan {\n return Object.freeze({\n kind: 'parallel',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function sequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: true } {\n return Object.freeze({\n divisible: true,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a non-divisible {@link SequentialInstructionPlan} from an array of nested plans.\n *\n * It can accept {@link Instruction} objects directly, which will be wrapped\n * in {@link SingleInstructionPlan | SingleInstructionPlans} automatically.\n *\n * @example Using explicit {@link SingleInstructionPlan | SingleInstructionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([\n * singleInstructionPlan(instructionA),\n * singleInstructionPlan(instructionB),\n * ]);\n * ```\n *\n * @example Using {@link Instruction | Instructions} directly.\n * ```ts\n * const plan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n */\nexport function nonDivisibleSequentialInstructionPlan(\n plans: (Instruction | InstructionPlan)[],\n): SequentialInstructionPlan & { divisible: false } {\n return Object.freeze({\n divisible: false,\n kind: 'sequential',\n plans: parseSingleInstructionPlans(plans),\n });\n}\n\n/**\n * Creates a {@link SingleInstructionPlan} from an {@link Instruction} object.\n *\n * @example\n * ```ts\n * const plan = singleInstructionPlan(instructionA);\n * ```\n *\n * @see {@link SingleInstructionPlan}\n */\nexport function singleInstructionPlan(instruction: Instruction): SingleInstructionPlan {\n return Object.freeze({ instruction, kind: 'single' });\n}\n\nfunction parseSingleInstructionPlans(plans: (Instruction | InstructionPlan)[]): InstructionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleInstructionPlan(plan)));\n}\n\n/**\n * Checks if the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a single instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * if (isSingleInstructionPlan(plan)) {\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * }\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link assertIsSingleInstructionPlan}\n */\nexport function isSingleInstructionPlan(plan: InstructionPlan): plan is SingleInstructionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SingleInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a single instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = singleInstructionPlan(myInstruction);\n *\n * assertIsSingleInstructionPlan(plan);\n * console.log(plan.instruction); // TypeScript knows this is a SingleInstructionPlan.\n * ```\n *\n * @see {@link SingleInstructionPlan}\n * @see {@link isSingleInstructionPlan}\n */\nexport function assertIsSingleInstructionPlan(plan: InstructionPlan): asserts plan is SingleInstructionPlan {\n if (!isSingleInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a message packer instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * if (isMessagePackerInstructionPlan(plan)) {\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * }\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link assertIsMessagePackerInstructionPlan}\n */\nexport function isMessagePackerInstructionPlan(plan: InstructionPlan): plan is MessagePackerInstructionPlan {\n return plan.kind === 'messagePacker';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link MessagePackerInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a message packer instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = getLinearMessagePackerInstructionPlan({ /* ... *\\/ });\n *\n * assertIsMessagePackerInstructionPlan(plan);\n * const packer = plan.getMessagePacker(); // TypeScript knows this is a MessagePackerInstructionPlan.\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link isMessagePackerInstructionPlan}\n */\nexport function assertIsMessagePackerInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is MessagePackerInstructionPlan {\n if (!isMessagePackerInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'messagePacker',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isSequentialInstructionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsSequentialInstructionPlan}\n */\nexport function isSequentialInstructionPlan(plan: InstructionPlan): plan is SequentialInstructionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link SequentialInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsSequentialInstructionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialInstructionPlan.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isSequentialInstructionPlan}\n */\nexport function assertIsSequentialInstructionPlan(plan: InstructionPlan): asserts plan is SequentialInstructionPlan {\n if (!isSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a non-divisible sequential instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * if (isNonDivisibleSequentialInstructionPlan(plan)) {\n * // All instructions must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link assertIsNonDivisibleSequentialInstructionPlan}\n */\nexport function isNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): plan is SequentialInstructionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given instruction plan is a non-divisible {@link SequentialInstructionPlan}.\n *\n * A non-divisible sequential plan requires all its instructions to be executed\n * atomically — either in a single transaction or in a transaction bundle.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a non-divisible sequential instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = nonDivisibleSequentialInstructionPlan([instructionA, instructionB]);\n *\n * assertIsNonDivisibleSequentialInstructionPlan(plan);\n * // All instructions must be executed atomically.\n * ```\n *\n * @see {@link SequentialInstructionPlan}\n * @see {@link isNonDivisibleSequentialInstructionPlan}\n */\nexport function assertIsNonDivisibleSequentialInstructionPlan(\n plan: InstructionPlan,\n): asserts plan is SequentialInstructionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to check.\n * @return `true` if the plan is a parallel instruction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * if (isParallelInstructionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * }\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link assertIsParallelInstructionPlan}\n */\nexport function isParallelInstructionPlan(plan: InstructionPlan): plan is ParallelInstructionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given instruction plan is a {@link ParallelInstructionPlan}.\n *\n * @param plan - The instruction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN` if the plan is not a parallel instruction plan.\n *\n * @example\n * ```ts\n * const plan: InstructionPlan = parallelInstructionPlan([instructionA, instructionB]);\n *\n * assertIsParallelInstructionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelInstructionPlan.\n * ```\n *\n * @see {@link ParallelInstructionPlan}\n * @see {@link isParallelInstructionPlan}\n */\nexport function assertIsParallelInstructionPlan(plan: InstructionPlan): asserts plan is ParallelInstructionPlan {\n if (!isParallelInstructionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n instructionPlan: plan,\n });\n }\n}\n\n/**\n * Finds the first instruction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the instruction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param instructionPlan - The instruction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @returns The first matching instruction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const nonDivisible = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing instructionC and instructionD.\n * ```\n *\n * @example\n * Finding a specific single instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const found = findInstructionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.instruction === instructionB,\n * );\n * // Returns the SingleInstructionPlan wrapping instructionB.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function findInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): InstructionPlan | undefined {\n if (predicate(instructionPlan)) {\n return instructionPlan;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return undefined;\n }\n for (const subPlan of instructionPlan.plans) {\n const foundPlan = findInstructionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every instruction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the instruction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param instructionPlan - The instruction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialInstructionPlan([\n * parallelInstructionPlan([instructionA, instructionB]),\n * sequentialInstructionPlan([instructionC, instructionD]),\n * ]);\n *\n * const allDivisible = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single instructions use a specific program.\n * ```ts\n * const plan = parallelInstructionPlan([instructionA, instructionB, instructionC]);\n *\n * const allUseSameProgram = everyInstructionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.instruction.programAddress === myProgramAddress,\n * );\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link transformInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function everyInstructionPlan(\n instructionPlan: InstructionPlan,\n predicate: (plan: InstructionPlan) => boolean,\n): boolean {\n if (!predicate(instructionPlan)) {\n return false;\n }\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return true;\n }\n return instructionPlan.plans.every(p => everyInstructionPlan(p, predicate));\n}\n\n/**\n * Transforms an instruction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the instruction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param instructionPlan - The instruction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed instruction plan tree.\n *\n * @example\n * Making all sequential plans non-divisible to ensure atomicity.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' && p.divisible) {\n * return nonDivisibleSequentialInstructionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Filtering out debug instructions before production execution.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, debugInstruction, instructionB]);\n *\n * const transformed = transformInstructionPlan(plan, (p) => {\n * if (p.kind === 'sequential' || p.kind === 'parallel') {\n * return { ...p, plans: p.plans.filter((p) => !isDebugInstruction(p)) };\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function transformInstructionPlan(\n instructionPlan: InstructionPlan,\n fn: (plan: InstructionPlan) => InstructionPlan,\n): InstructionPlan {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return Object.freeze(fn(instructionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...instructionPlan,\n plans: instructionPlan.plans.map(p => transformInstructionPlan(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleInstructionPlan} and {@link MessagePackerInstructionPlan}\n * instances from an instruction plan tree.\n *\n * This function recursively traverses any nested structure of instruction plans and extracts\n * all the leaf plans they contain. It's useful when you need to access all the individual\n * instructions or message packers that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param instructionPlan - The instruction plan to extract leaf plans from\n * @returns An array of all single and message packer instruction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelInstructionPlan([\n * sequentialInstructionPlan([instructionA, instructionB]),\n * nonDivisibleSequentialInstructionPlan([instructionC, instructionD]),\n * instructionE,\n * ]);\n *\n * const leafPlans = flattenInstructionPlan(plan);\n * // Array of `SingleInstructionPlan` containing:\n * // instructionA, instructionB, instructionC, instructionD and instructionE.\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link findInstructionPlan}\n * @see {@link everyInstructionPlan}\n * @see {@link transformInstructionPlan}\n */\nexport function flattenInstructionPlan(\n instructionPlan: InstructionPlan,\n): (MessagePackerInstructionPlan | SingleInstructionPlan)[] {\n if (instructionPlan.kind === 'single' || instructionPlan.kind === 'messagePacker') {\n return [instructionPlan];\n }\n return instructionPlan.plans.flatMap(flattenInstructionPlan);\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs instructions\n * such that each instruction consumes as many bytes as possible from the given\n * `totalLength` while still being able to fit into the given transaction messages.\n *\n * This is particularly useful for instructions that write data to accounts and must\n * span multiple transactions due to their size limit.\n *\n * This message packer will first call `getInstruction` with a length of zero to\n * determine the base size of the instruction before figuring out how many\n * additional bytes can be packed into the transaction message. That remaining space\n * will then be used to call `getInstruction` again with the appropriate length.\n *\n * @param getInstruction - A function that returns an instruction for a given offset and length.\n * @param totalLength - The total length of the data to write, in bytes.\n *\n * @example\n * ```ts\n * const plan = getLinearMessagePackerInstructionPlan({\n * totalLength: dataToWrite.length,\n * getInstruction: (offset, length) =>\n * getWriteInstruction({\n * offset,\n * data: dataToWrite.slice(offset, offset + length),\n * }),\n * });\n * plan satisfies MessagePackerInstructionPlan;\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getLinearMessagePackerInstructionPlan({\n getInstruction,\n totalLength: totalBytes,\n}: {\n getInstruction: (offset: number, length: number) => Instruction;\n totalLength: number;\n}): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let offset = 0;\n return Object.freeze({\n done: () => offset >= totalBytes,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (offset >= totalBytes) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const messageSizeWithBaseInstruction = getTransactionMessageSize(\n appendTransactionMessageInstruction(getInstruction(offset, 0), message),\n );\n const freeSpace =\n TRANSACTION_SIZE_LIMIT -\n messageSizeWithBaseInstruction /* Includes the base instruction (length: 0). */ -\n 1; /* Leeway for shortU16 numbers in transaction headers. */\n\n if (freeSpace <= 0) {\n const messageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n // (+1) We need to pack at least one byte of data otherwise\n // there is no point packing the base instruction alone.\n numBytesRequired: messageSizeWithBaseInstruction - messageSize + 1,\n // (-1) Leeway for shortU16 numbers in transaction headers.\n numFreeBytes: TRANSACTION_SIZE_LIMIT - messageSize - 1,\n });\n }\n\n const length = Math.min(totalBytes - offset, freeSpace);\n const instruction = getInstruction(offset, length);\n offset += length;\n return appendTransactionMessageInstruction(instruction, message);\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} from a list of instructions.\n *\n * This can be useful to prepare a set of instructions that can be iterated over\n * — e.g. to pack a list of instructions that gradually reallocate the size of an account\n * one `REALLOC_LIMIT` (10'240 bytes) at a time.\n *\n * @example\n * ```ts\n * const plan = getMessagePackerInstructionPlanFromInstructions([\n * instructionA,\n * instructionB,\n * instructionC,\n * ]);\n *\n * const messagePacker = plan.getMessagePacker();\n * firstTransactionMessage = messagePacker.packMessageToCapacity(firstTransactionMessage);\n * // Contains instruction A and instruction B.\n * secondTransactionMessage = messagePacker.packMessageToCapacity(secondTransactionMessage);\n * // Contains instruction C.\n * messagePacker.done(); // true\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n * @see {@link getReallocMessagePackerInstructionPlan}\n */\nexport function getMessagePackerInstructionPlanFromInstructions(\n instructions: TInstruction[],\n): MessagePackerInstructionPlan {\n return Object.freeze({\n getMessagePacker: () => {\n let instructionIndex = 0;\n return Object.freeze({\n done: () => instructionIndex >= instructions.length,\n packMessageToCapacity: (message: TransactionMessage & TransactionMessageWithFeePayer) => {\n if (instructionIndex >= instructions.length) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);\n }\n\n const originalMessageSize = getTransactionMessageSize(message);\n\n for (let index = instructionIndex; index < instructions.length; index++) {\n message = appendTransactionMessageInstruction(instructions[index], message);\n const messageSize = getTransactionMessageSize(message);\n\n if (messageSize > TRANSACTION_SIZE_LIMIT) {\n if (index === instructionIndex) {\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n {\n numBytesRequired: messageSize - originalMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - originalMessageSize,\n },\n );\n }\n instructionIndex = index;\n return message;\n }\n }\n\n instructionIndex = instructions.length;\n return message;\n },\n });\n },\n kind: 'messagePacker',\n });\n}\n\nconst REALLOC_LIMIT = 10_240;\n\n/**\n * Creates a {@link MessagePackerInstructionPlan} that packs a list of realloc instructions.\n *\n * That is, it splits instruction by chunks of `REALLOC_LIMIT` (10'240) bytes until\n * the given total size is reached.\n *\n * @example\n * ```ts\n * const plan = getReallocMessagePackerInstructionPlan({\n * totalSize: additionalDataSize,\n * getInstruction: (size) => getExtendInstruction({ length: size }),\n * });\n * ```\n *\n * @see {@link MessagePackerInstructionPlan}\n */\nexport function getReallocMessagePackerInstructionPlan({\n getInstruction,\n totalSize,\n}: {\n getInstruction: (size: number) => Instruction;\n totalSize: number;\n}): MessagePackerInstructionPlan {\n const numberOfInstructions = Math.ceil(totalSize / REALLOC_LIMIT);\n const lastInstructionSize = totalSize % REALLOC_LIMIT;\n const instructions = new Array(numberOfInstructions)\n .fill(0)\n .map((_, i) => getInstruction(i === numberOfInstructions - 1 ? lastInstructionSize : REALLOC_LIMIT));\n\n return getMessagePackerInstructionPlanFromInstructions(instructions);\n}\n","import { SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, SolanaError } from '@solana/errors';\nimport { type Instruction } from '@solana/instructions';\nimport {\n appendTransactionMessageInstruction,\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\n\nimport { flattenInstructionPlan, InstructionPlan } from './instruction-plan';\n\n/**\n * A helper type to append instructions to a transaction message\n * without losing type information about the current instructions.\n */\n\ntype AppendTransactionMessageInstructions = ReturnType<\n typeof appendTransactionMessageInstructions\n>;\n\n/**\n * Appends all instructions from an instruction plan to a transaction message.\n *\n * This function flattens the instruction plan into its leaf plans and sequentially\n * appends each instruction to the provided transaction message. It handles both\n * single instructions and message packer plans.\n *\n * Note that any {@link MessagePackerInstructionPlan} is assumed to only append\n * instructions. If it modifies other properties of the transaction message, the\n * type of the returned transaction message may not accurately reflect those changes.\n *\n * @typeParam TTransactionMessage - The type of transaction message being modified.\n *\n * @param transactionMessage - The transaction message to append instructions to.\n * @param instructionPlan - The instruction plan containing the instructions to append.\n * @returns The transaction message with all instructions from the plan appended.\n *\n * @example\n * Appending a simple instruction plan to a transaction message.\n * ```ts\n * import { appendTransactionMessageInstructionPlan } from '@solana/instruction-plans';\n * import { createTransactionMessage, setTransactionMessageFeePayer } from '@solana/transaction-messages';\n *\n * const message = setTransactionMessageFeePayer(feePayer, createTransactionMessage({ version: 0 }));\n * const plan = singleInstructionPlan(myInstruction);\n *\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @example\n * Appending a sequential instruction plan.\n * ```ts\n * const plan = sequentialInstructionPlan([instructionA, instructionB, instructionC]);\n * const messageWithInstructions = appendTransactionMessageInstructionPlan(message, plan);\n * ```\n *\n * @see {@link InstructionPlan}\n * @see {@link flattenInstructionPlan}\n */\nexport function appendTransactionMessageInstructionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer,\n>(\n instructionPlan: InstructionPlan,\n transactionMessage: TTransactionMessage,\n): AppendTransactionMessageInstructions {\n type Out = AppendTransactionMessageInstructions;\n\n const leafInstructionPlans = flattenInstructionPlan(instructionPlan);\n\n return leafInstructionPlans.reduce(\n (messageSoFar, plan) => {\n const kind = plan.kind;\n if (kind === 'single') {\n return appendTransactionMessageInstruction(plan.instruction, messageSoFar) as unknown as Out;\n }\n if (kind === 'messagePacker') {\n const messagerPacker = plan.getMessagePacker();\n let nextMessage: Out = messageSoFar;\n while (!messagerPacker.done()) {\n nextMessage = messagerPacker.packMessageToCapacity(nextMessage) as Out;\n }\n return nextMessage;\n }\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, {\n kind,\n });\n },\n transactionMessage as unknown as Out,\n );\n}\n","import { SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, SolanaError } from '@solana/errors';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\n/**\n * A set of transaction messages with constraints on how they can be executed.\n *\n * This is structured as a recursive tree of plans to allow for\n * parallel execution, sequential execution and combinations of both.\n *\n * Namely, the following plans are supported:\n * - {@link SingleTransactionPlan} - A plan that contains a single transaction message.\n * This is the simplest leaf in this tree.\n * - {@link ParallelTransactionPlan} - A plan that contains other plans that\n * can be executed in parallel.\n * - {@link SequentialTransactionPlan} - A plan that contains other plans that\n * must be executed sequentially. It also defines whether the plan is divisible\n * meaning that transaction messages inside it can be split into separate batches.\n *\n * Helpers are provided for each of these plans to make it easier to create them.\n *\n * @example\n * ```ts\n * const myTransactionPlan: TransactionPlan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * messageC,\n * ]);\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link ParallelTransactionPlan}\n * @see {@link SequentialTransactionPlan}\n */\nexport type TransactionPlan = ParallelTransactionPlan | SequentialTransactionPlan | SingleTransactionPlan;\n\n/**\n * A plan wrapping other plans that must be executed sequentially.\n *\n * It also defines whether nested plans are divisible — meaning that\n * the transaction messages inside them can be split into separate batches.\n * When `divisible` is `false`, the transaction messages inside the plan should\n * all be executed atomically — usually in a transaction bundle.\n *\n * You may use the {@link sequentialTransactionPlan} and {@link nonDivisibleSequentialTransactionPlan}\n * helpers to create objects of this type.\n *\n * @example\n * Simple sequential plan with two transaction messages.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan;\n * ```\n *\n * @example\n * Non-divisible sequential plan with two transaction messages.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * plan satisfies SequentialTransactionPlan & { divisible: false };\n * ```\n *\n * @example\n * Sequential plan with nested parallel plans.\n * Here, messages A and B can be executed in parallel, but they must both be finalized\n * before messages C and D can be sent — which can also be executed in parallel.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * parallelTransactionPlan([messageC, messageD]),\n * ]);\n * ```\n *\n * @see {@link sequentialTransactionPlan}\n * @see {@link nonDivisibleSequentialTransactionPlan}\n */\nexport type SequentialTransactionPlan = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan wrapping other plans that can be executed in parallel.\n *\n * This means direct children of this plan can be executed in separate\n * parallel transactions without causing any side effects.\n * However, the children themselves can define additional constraints\n * for that specific branch of the tree — such as the {@link SequentialTransactionPlan}.\n *\n * You may use the {@link parallelTransactionPlan} helper to create objects of this type.\n *\n * @example\n * Simple parallel plan with two transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @example\n * Parallel plan with nested sequential plans.\n * Here, messages A and B must be executed sequentially and so must messages C and D,\n * but both pairs can be executed in parallel.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n * plan satisfies ParallelTransactionPlan;\n * ```\n *\n * @see {@link parallelTransactionPlan}\n */\nexport type ParallelTransactionPlan = Readonly<{\n kind: 'parallel';\n plans: TransactionPlan[];\n}>;\n\n/**\n * A plan that contains a single transaction message.\n *\n * This is a simple transaction message wrapper that transforms a message into a plan.\n *\n * You may use the {@link singleTransactionPlan} helper to create objects of this type.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link singleTransactionPlan}\n */\nexport type SingleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n}>;\n\n/**\n * Creates a {@link ParallelTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = parallelTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n */\nexport function parallelTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): ParallelTransactionPlan {\n return Object.freeze({ kind: 'parallel', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function sequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlan} from an array of nested plans.\n *\n * It can accept {@link TransactionMessage} objects directly, which will be wrapped\n * in {@link SingleTransactionPlan | SingleTransactionPlans} automatically.\n *\n * @example\n * Using explicit {@link SingleTransactionPlan | SingleTransactionPlans}.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([\n * singleTransactionPlan(messageA),\n * singleTransactionPlan(messageB),\n * ]);\n * ```\n *\n * @example\n * Using {@link TransactionMessage | TransactionMessages} directly.\n * ```ts\n * const plan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n */\nexport function nonDivisibleSequentialTransactionPlan(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): SequentialTransactionPlan & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans: parseSingleTransactionPlans(plans) });\n}\n\n/**\n * Creates a {@link SingleTransactionPlan} from a {@link TransactionMessage} object.\n *\n * @example\n * ```ts\n * const plan = singleTransactionPlan(transactionMessage);\n * plan satisfies SingleTransactionPlan;\n * ```\n *\n * @see {@link SingleTransactionPlan}\n */\nexport function singleTransactionPlan<\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlan {\n return Object.freeze({ kind: 'single', message: transactionMessage });\n}\n\nfunction parseSingleTransactionPlans(\n plans: (TransactionPlan | (TransactionMessage & TransactionMessageWithFeePayer))[],\n): TransactionPlan[] {\n return plans.map(plan => ('kind' in plan ? plan : singleTransactionPlan(plan)));\n}\n\n/**\n * Checks if the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a single transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * if (isSingleTransactionPlan(plan)) {\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link assertIsSingleTransactionPlan}\n */\nexport function isSingleTransactionPlan(plan: TransactionPlan): plan is SingleTransactionPlan {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SingleTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a single transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = singleTransactionPlan(transactionMessage);\n *\n * assertIsSingleTransactionPlan(plan);\n * console.log(plan.message); // TypeScript knows this is a SingleTransactionPlan.\n * ```\n *\n * @see {@link SingleTransactionPlan}\n * @see {@link isSingleTransactionPlan}\n */\nexport function assertIsSingleTransactionPlan(plan: TransactionPlan): asserts plan is SingleTransactionPlan {\n if (!isSingleTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * if (isSequentialTransactionPlan(plan)) {\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsSequentialTransactionPlan}\n */\nexport function isSequentialTransactionPlan(plan: TransactionPlan): plan is SequentialTransactionPlan {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link SequentialTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = sequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsSequentialTransactionPlan(plan);\n * console.log(plan.divisible); // TypeScript knows this is a SequentialTransactionPlan.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isSequentialTransactionPlan}\n */\nexport function assertIsSequentialTransactionPlan(plan: TransactionPlan): asserts plan is SequentialTransactionPlan {\n if (!isSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a non-divisible sequential transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * if (isNonDivisibleSequentialTransactionPlan(plan)) {\n * // All transaction messages must be executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlan}\n */\nexport function isNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): plan is SequentialTransactionPlan & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan is a non-divisible {@link SequentialTransactionPlan}.\n *\n * A non-divisible sequential plan requires all its transaction messages to be executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a non-divisible sequential transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = nonDivisibleSequentialTransactionPlan([messageA, messageB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlan(plan);\n * // All transaction messages must be executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlan}\n * @see {@link isNonDivisibleSequentialTransactionPlan}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlan(\n plan: TransactionPlan,\n): asserts plan is SequentialTransactionPlan & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to check.\n * @return `true` if the plan is a parallel transaction plan, `false` otherwise.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * if (isParallelTransactionPlan(plan)) {\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link assertIsParallelTransactionPlan}\n */\nexport function isParallelTransactionPlan(plan: TransactionPlan): plan is ParallelTransactionPlan {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan is a {@link ParallelTransactionPlan}.\n *\n * @param plan - The transaction plan to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN` if the plan is not a parallel transaction plan.\n *\n * @example\n * ```ts\n * const plan: TransactionPlan = parallelTransactionPlan([messageA, messageB]);\n *\n * assertIsParallelTransactionPlan(plan);\n * console.log(plan.plans.length); // TypeScript knows this is a ParallelTransactionPlan.\n * ```\n *\n * @see {@link ParallelTransactionPlan}\n * @see {@link isParallelTransactionPlan}\n */\nexport function assertIsParallelTransactionPlan(plan: TransactionPlan): asserts plan is ParallelTransactionPlan {\n if (!isParallelTransactionPlan(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlan: plan,\n });\n }\n}\n\n/**\n * @deprecated Use {@link flattenTransactionPlan} instead.\n */\nexport const getAllSingleTransactionPlans = flattenTransactionPlan;\n\n/**\n * Retrieves all individual {@link SingleTransactionPlan} instances from a transaction plan tree.\n *\n * This function recursively traverses any nested structure of transaction plans and extracts\n * all the single transaction plans they contain. It's useful when you need to access all\n * the actual transaction messages that will be executed, regardless of their organization\n * in the plan tree (parallel or sequential).\n *\n * @param transactionPlan - The transaction plan to extract single plans from\n * @returns An array of all single transaction plans contained in the tree\n *\n * @example\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * messageE,\n * ]);\n *\n * const singlePlans = flattenTransactionPlan(plan);\n * // Array of `SingleTransactionPlan` containing:\n * // messageA, messageB, messageC and messageD.\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * ```\n */\nexport function flattenTransactionPlan(transactionPlan: TransactionPlan): SingleTransactionPlan[] {\n if (transactionPlan.kind === 'single') {\n return [transactionPlan];\n }\n return transactionPlan.plans.flatMap(flattenTransactionPlan);\n}\n\n/**\n * Finds the first transaction plan in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan tree,\n * returning the first plan that satisfies the predicate. It checks the root plan\n * first, then recursively searches through nested plans.\n *\n * @param transactionPlan - The transaction plan tree to search.\n * @param predicate - A function that returns `true` for the plan to find.\n * @return The first matching transaction plan, or `undefined` if no match is found.\n *\n * @example\n * Finding a non-divisible sequential plan.\n * ```ts\n * const plan = parallelTransactionPlan([\n * sequentialTransactionPlan([messageA, messageB]),\n * nonDivisibleSequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const nonDivisible = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'sequential' && !p.divisible,\n * );\n * // Returns the non-divisible sequential plan containing messageC and messageD.\n * ```\n *\n * @example\n * Finding a specific single transaction plan.\n * ```ts\n * const plan = sequentialTransactionPlan([messageA, messageB, messageC]);\n *\n * const found = findTransactionPlan(\n * plan,\n * (p) => p.kind === 'single' && p.message === messageB,\n * );\n * // Returns the SingleTransactionPlan wrapping messageB.\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function findTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): TransactionPlan | undefined {\n if (predicate(transactionPlan)) {\n return transactionPlan;\n }\n if (transactionPlan.kind === 'single') {\n return undefined;\n }\n for (const subPlan of transactionPlan.plans) {\n const foundPlan = findTransactionPlan(subPlan, predicate);\n if (foundPlan) {\n return foundPlan;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if every transaction plan in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan tree,\n * returning `true` only if the predicate returns `true` for every plan in the tree\n * (including the root plan and all nested plans).\n *\n * @param transactionPlan - The transaction plan tree to check.\n * @param predicate - A function that returns `true` if the plan satisfies the condition.\n * @return `true` if every plan in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all plans are divisible.\n * ```ts\n * const plan = sequentialTransactionPlan([\n * parallelTransactionPlan([messageA, messageB]),\n * sequentialTransactionPlan([messageC, messageD]),\n * ]);\n *\n * const allDivisible = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'sequential' || p.divisible,\n * );\n * // Returns true because all sequential plans are divisible.\n * ```\n *\n * @example\n * Checking if all single plans have a specific fee payer.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const allUseSameFeePayer = everyTransactionPlan(\n * plan,\n * (p) => p.kind !== 'single' || p.message.feePayer.address === myFeePayer,\n * );\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link transformTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function everyTransactionPlan(\n transactionPlan: TransactionPlan,\n predicate: (plan: TransactionPlan) => boolean,\n): boolean {\n if (!predicate(transactionPlan)) {\n return false;\n }\n if (transactionPlan.kind === 'single') {\n return true;\n }\n return transactionPlan.plans.every(p => everyTransactionPlan(p, predicate));\n}\n\n/**\n * Transforms a transaction plan tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan tree, applying the\n * transformation function to each plan. The transformation is applied bottom-up,\n * meaning nested plans are transformed first, then the parent plans receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed plans are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlan - The transaction plan tree to transform.\n * @param fn - A function that transforms each plan and returns a new plan.\n * @return A new transformed transaction plan tree.\n *\n * @example\n * Removing parallelism by converting parallel plans to sequential.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB, messageC]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'parallel') {\n * return sequentialTransactionPlan(p.plans);\n * }\n * return p;\n * });\n * ```\n *\n * @example\n * Updating the fee payer on all transaction messages.\n * ```ts\n * const plan = parallelTransactionPlan([messageA, messageB]);\n *\n * const transformed = transformTransactionPlan(plan, (p) => {\n * if (p.kind === 'single') {\n * return singleTransactionPlan({ ...p.message, feePayer: newFeePayer });\n * }\n * return p;\n * });\n * ```\n *\n * @see {@link TransactionPlan}\n * @see {@link findTransactionPlan}\n * @see {@link everyTransactionPlan}\n * @see {@link flattenTransactionPlan}\n */\nexport function transformTransactionPlan(\n transactionPlan: TransactionPlan,\n fn: (plan: TransactionPlan) => TransactionPlan,\n): TransactionPlan {\n if (transactionPlan.kind === 'single') {\n return Object.freeze(fn(transactionPlan));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlan,\n plans: transactionPlan.plans.map(p => transformTransactionPlan(p, fn)),\n }),\n ),\n );\n}\n","import {\n SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { getSignatureFromTransaction, Transaction } from '@solana/transactions';\n\n/**\n * The result of executing a transaction plan.\n *\n * This is structured as a recursive tree of results that mirrors the structure\n * of the original transaction plan, capturing the execution status at each level.\n *\n * Namely, the following result types are supported:\n * - {@link SingleTransactionPlanResult} - A result for a single transaction message\n * containing its execution status.\n * - {@link ParallelTransactionPlanResult} - A result containing other results that\n * were executed in parallel.\n * - {@link SequentialTransactionPlanResult} - A result containing other results that\n * were executed sequentially. It also retains the divisibility property from the\n * original plan.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link TransactionPlanResultStatus}\n */\nexport type TransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = ParallelTransactionPlanResult | SequentialTransactionPlanResult | TSingle;\n\n/**\n * A {@link TransactionPlanResult} where all single transaction results are successful.\n *\n * This type represents a transaction plan result tree where every\n * {@link SingleTransactionPlanResult} has a 'successful' status. It can be used\n * to ensure that an entire execution completed without any failures or cancellations.\n *\n * Note: This is different from {@link SuccessfulSingleTransactionPlanResult} which\n * represents a single successful transaction, whereas this type represents an entire\n * plan result tree (which may contain parallel/sequential structures) where all\n * leaf nodes are successful.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n *\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link SuccessfulSingleTransactionPlanResult}\n */\nexport type SuccessfulTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = TransactionPlanResult>;\n\n/** A context object that may be passed along with successful results. */\nexport type TransactionPlanResultContext = Record;\n\n/**\n * A result for a sequential transaction plan.\n *\n * This represents the execution result of a {@link SequentialTransactionPlan} and\n * contains child results that were executed sequentially. It also retains the\n * divisibility property from the original plan.\n *\n * You may use the {@link sequentialTransactionPlanResult} and\n * {@link nonDivisibleSequentialTransactionPlanResult} helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult;\n * ```\n *\n * @example\n * Non-divisible sequential result.\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link sequentialTransactionPlanResult}\n * @see {@link nonDivisibleSequentialTransactionPlanResult}\n */\nexport type SequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n divisible: boolean;\n kind: 'sequential';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a parallel transaction plan.\n *\n * This represents the execution result of a {@link ParallelTransactionPlan} and\n * contains child results that were executed in parallel.\n *\n * You may use the {@link parallelTransactionPlanResult} helper to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TSingle - The type of single transaction plan results in this tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link parallelTransactionPlanResult}\n */\nexport type ParallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TSingle extends SingleTransactionPlanResult = SingleTransactionPlanResult,\n> = Readonly<{\n kind: 'parallel';\n plans: TransactionPlanResult[];\n}>;\n\n/**\n * A result for a single transaction plan.\n *\n * This represents the execution result of a {@link SingleTransactionPlan} and\n * contains the original transaction message along with its execution status.\n *\n * You may use the {@link successfulSingleTransactionPlanResult},\n * {@link failedSingleTransactionPlanResult}, or {@link canceledSingleTransactionPlanResult}\n * helpers to create objects of this type.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @template TTransactionMessage - The type of the transaction message\n *\n * @example\n * Successful result with a transaction and context.\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Failed result with an error.\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError(SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @example\n * Canceled result.\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link successfulSingleTransactionPlanResult}\n * @see {@link failedSingleTransactionPlanResult}\n * @see {@link canceledSingleTransactionPlanResult}\n */\nexport type SingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n> = Readonly<{\n kind: 'single';\n message: TTransactionMessage;\n status: TransactionPlanResultStatus;\n}>;\n\n/**\n * The status of a single transaction plan execution.\n *\n * This represents the outcome of executing a single transaction message and can be one of:\n * - `successful` - The transaction was successfully executed. Contains the transaction\n * and an optional context object.\n * - `failed` - The transaction execution failed. Contains the error that caused the failure.\n * - `canceled` - The transaction execution was canceled.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n */\nexport type TransactionPlanResultStatus =\n | Readonly<{ context: TContext; kind: 'successful'; signature: Signature; transaction?: Transaction }>\n | Readonly<{ error: Error; kind: 'failed' }>\n | Readonly<{ kind: 'canceled' }>;\n\n/**\n * Creates a divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `true`,\n * indicating that the nested plans were executed sequentially but could have been\n * split into separate transactions or batches.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = sequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: true };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function sequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: true } {\n return Object.freeze({ divisible: true, kind: 'sequential', plans });\n}\n\n/**\n * Creates a non-divisible {@link SequentialTransactionPlanResult} from an array of nested results.\n *\n * This function creates a sequential result with the `divisible` property set to `false`,\n * indicating that the nested plans were executed sequentially and could not have been\n * split into separate transactions or batches (e.g., they were executed as a transaction bundle).\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed sequentially\n *\n * @example\n * ```ts\n * const result = nonDivisibleSequentialTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies SequentialTransactionPlanResult & { divisible: false };\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n */\nexport function nonDivisibleSequentialTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): SequentialTransactionPlanResult & { divisible: false } {\n return Object.freeze({ divisible: false, kind: 'sequential', plans });\n}\n\n/**\n * Creates a {@link ParallelTransactionPlanResult} from an array of nested results.\n *\n * This function creates a parallel result indicating that the nested plans\n * were executed in parallel.\n *\n * @template TContext - The type of the context object that may be passed along with successful results\n * @param plans - The child results that were executed in parallel\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * singleResultA,\n * singleResultB,\n * ]);\n * result satisfies ParallelTransactionPlanResult;\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n */\nexport function parallelTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n>(plans: TransactionPlanResult[]): ParallelTransactionPlanResult {\n return Object.freeze({ kind: 'parallel', plans });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and transaction.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param transaction - The successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * transaction\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n transaction: Transaction,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({\n context: context ?? ({} as TContext),\n kind: 'successful',\n signature: getSignatureFromTransaction(transaction),\n transaction,\n }),\n });\n}\n\n/**\n * Creates a successful {@link SingleTransactionPlanResult} from a transaction message and signature.\n *\n * This function creates a single result with a 'successful' status, indicating that\n * the transaction was successfully executed. It also includes the original transaction\n * message, the signature of the executed transaction, and an optional context object.\n *\n * @template TContext - The type of the context object\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param signature - The signature of the successfully executed transaction\n * @param context - Optional context object to be included with the result\n *\n * @example\n * ```ts\n * const result = successfulSingleTransactionPlanResult(\n * transactionMessage,\n * signature\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function successfulSingleTransactionPlanResultFromSignature<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n signature: Signature,\n context?: TContext,\n): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ context: context ?? ({} as TContext), kind: 'successful', signature }),\n });\n}\n\n/**\n * Creates a failed {@link SingleTransactionPlanResult} from a transaction message and error.\n *\n * This function creates a single result with a 'failed' status, indicating that\n * the transaction execution failed. It includes the original transaction message\n * and the error that caused the failure.\n *\n * @template TContext - The type of the context object (not used in failed results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n * @param error - The error that caused the transaction to fail\n *\n * @example\n * ```ts\n * const result = failedSingleTransactionPlanResult(\n * transactionMessage,\n * new SolanaError({\n * code: 123,\n * message: 'Transaction simulation failed',\n * }),\n * );\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function failedSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage, error: Error): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ error, kind: 'failed' }),\n });\n}\n\n/**\n * Creates a canceled {@link SingleTransactionPlanResult} from a transaction message.\n *\n * This function creates a single result with a 'canceled' status, indicating that\n * the transaction execution was canceled. It includes the original transaction message.\n *\n * @template TContext - The type of the context object (not used in canceled results)\n * @template TTransactionMessage - The type of the transaction message\n * @param transactionMessage - The original transaction message\n *\n * @example\n * ```ts\n * const result = canceledSingleTransactionPlanResult(transactionMessage);\n * result satisfies SingleTransactionPlanResult;\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n */\nexport function canceledSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n TTransactionMessage extends TransactionMessage & TransactionMessageWithFeePayer = TransactionMessage &\n TransactionMessageWithFeePayer,\n>(transactionMessage: TTransactionMessage): SingleTransactionPlanResult {\n return Object.freeze({\n kind: 'single',\n message: transactionMessage,\n status: Object.freeze({ kind: 'canceled' }),\n });\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSingleTransactionPlanResult(result)) {\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link assertIsSingleTransactionPlanResult}\n */\nexport function isSingleTransactionPlanResult(plan: TransactionPlanResult): plan is SingleTransactionPlanResult {\n return plan.kind === 'single';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSingleTransactionPlanResult(result);\n * console.log(result.status.kind); // TypeScript knows this is a SingleTransactionPlanResult.\n * ```\n *\n * @see {@link SingleTransactionPlanResult}\n * @see {@link isSingleTransactionPlanResult}\n */\nexport function assertIsSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SingleTransactionPlanResult {\n if (!isSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a successful single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * if (isSuccessfulSingleTransactionPlanResult(result)) {\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * }\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'successful';\n}\n\n/**\n * Asserts that the given transaction plan result is a successful {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a successful single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = successfulSingleTransactionPlanResult(message, transaction);\n *\n * assertIsSuccessfulSingleTransactionPlanResult(result);\n * console.log(result.status.signature); // TypeScript knows this is a successful result.\n * ```\n *\n * @see {@link SuccessfulSingleTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulSingleTransactionPlanResult {\n if (!isSuccessfulSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'successful single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a failed single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * if (isFailedSingleTransactionPlanResult(result)) {\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * }\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link assertIsFailedSingleTransactionPlanResult}\n */\nexport function isFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is FailedSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'failed';\n}\n\n/**\n * Asserts that the given transaction plan result is a failed {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a failed single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = failedSingleTransactionPlanResult(message, error);\n *\n * assertIsFailedSingleTransactionPlanResult(result);\n * console.log(result.status.error); // TypeScript knows this is a failed result.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link isFailedSingleTransactionPlanResult}\n */\nexport function assertIsFailedSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is FailedSingleTransactionPlanResult {\n if (!isFailedSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'failed single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a canceled single transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * if (isCanceledSingleTransactionPlanResult(result)) {\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * }\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link assertIsCanceledSingleTransactionPlanResult}\n */\nexport function isCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is CanceledSingleTransactionPlanResult {\n return plan.kind === 'single' && plan.status.kind === 'canceled';\n}\n\n/**\n * Asserts that the given transaction plan result is a canceled {@link SingleTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a canceled single transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = canceledSingleTransactionPlanResult(message);\n *\n * assertIsCanceledSingleTransactionPlanResult(result);\n * console.log('Transaction was canceled'); // TypeScript knows this is a canceled result.\n * ```\n *\n * @see {@link CanceledSingleTransactionPlanResult}\n * @see {@link isCanceledSingleTransactionPlanResult}\n */\nexport function assertIsCanceledSingleTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is CanceledSingleTransactionPlanResult {\n if (!isCanceledSingleTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'single' ? `${plan.status.kind} single` : plan.kind,\n expectedKind: 'canceled single',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isSequentialTransactionPlanResult(result)) {\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsSequentialTransactionPlanResult}\n */\nexport function isSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult {\n return plan.kind === 'sequential';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SequentialTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = sequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsSequentialTransactionPlanResult(result);\n * console.log(result.divisible); // TypeScript knows this is a SequentialTransactionPlanResult.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isSequentialTransactionPlanResult}\n */\nexport function assertIsSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult {\n if (!isSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a non-divisible sequential transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * if (isNonDivisibleSequentialTransactionPlanResult(result)) {\n * // Transactions were executed atomically.\n * }\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link assertIsNonDivisibleSequentialTransactionPlanResult}\n */\nexport function isNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SequentialTransactionPlanResult & { divisible: false } {\n return plan.kind === 'sequential' && plan.divisible === false;\n}\n\n/**\n * Asserts that the given transaction plan result is a non-divisible {@link SequentialTransactionPlanResult}.\n *\n * A non-divisible sequential result indicates that the transactions were executed\n * atomically — usually in a transaction bundle.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a non-divisible sequential transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = nonDivisibleSequentialTransactionPlanResult([resultA, resultB]);\n *\n * assertIsNonDivisibleSequentialTransactionPlanResult(result);\n * // Transactions were executed atomically.\n * ```\n *\n * @see {@link SequentialTransactionPlanResult}\n * @see {@link isNonDivisibleSequentialTransactionPlanResult}\n */\nexport function assertIsNonDivisibleSequentialTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SequentialTransactionPlanResult & { divisible: false } {\n if (!isNonDivisibleSequentialTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind === 'sequential' ? 'divisible sequential' : plan.kind,\n expectedKind: 'non-divisible sequential',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if the result is a parallel transaction plan result, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * if (isParallelTransactionPlanResult(result)) {\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * }\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link assertIsParallelTransactionPlanResult}\n */\nexport function isParallelTransactionPlanResult(plan: TransactionPlanResult): plan is ParallelTransactionPlanResult {\n return plan.kind === 'parallel';\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link ParallelTransactionPlanResult}.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT` if the result is not a parallel transaction plan result.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([resultA, resultB]);\n *\n * assertIsParallelTransactionPlanResult(result);\n * console.log(result.plans.length); // TypeScript knows this is a ParallelTransactionPlanResult.\n * ```\n *\n * @see {@link ParallelTransactionPlanResult}\n * @see {@link isParallelTransactionPlanResult}\n */\nexport function assertIsParallelTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is ParallelTransactionPlanResult {\n if (!isParallelTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {\n actualKind: plan.kind,\n expectedKind: 'parallel',\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Checks if the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It recursively checks all nested results\n * to ensure every {@link SingleTransactionPlanResult} has a 'successful' status.\n *\n * Note: This is different from {@link isSuccessfulSingleTransactionPlanResult} which\n * checks if a single result is successful. This function checks that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to check.\n * @return `true` if all single transaction results in the tree are successful, `false` otherwise.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * if (isSuccessfulTransactionPlanResult(result)) {\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * }\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulSingleTransactionPlanResult}\n */\nexport function isSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): plan is SuccessfulTransactionPlanResult {\n return everyTransactionPlanResult(\n plan,\n r => !isSingleTransactionPlanResult(r) || isSuccessfulSingleTransactionPlanResult(r),\n );\n}\n\n/**\n * Asserts that the given transaction plan result is a {@link SuccessfulTransactionPlanResult}.\n *\n * This function verifies that the entire transaction plan result tree contains only\n * successful single transaction results. It throws if any {@link SingleTransactionPlanResult}\n * in the tree has a 'failed' or 'canceled' status.\n *\n * Note: This is different from {@link assertIsSuccessfulSingleTransactionPlanResult} which\n * asserts that a single result is successful. This function asserts that the entire\n * plan result tree (including all nested parallel/sequential structures) contains\n * only successful transactions.\n *\n * @param plan - The transaction plan result to assert.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT` if\n * any single transaction result in the tree is not successful.\n *\n * @example\n * ```ts\n * const result: TransactionPlanResult = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * assertIsSuccessfulTransactionPlanResult(result);\n * // All transactions were successful.\n * result satisfies SuccessfulTransactionPlanResult;\n * ```\n *\n * @see {@link SuccessfulTransactionPlanResult}\n * @see {@link isSuccessfulTransactionPlanResult}\n * @see {@link assertIsSuccessfulSingleTransactionPlanResult}\n */\nexport function assertIsSuccessfulTransactionPlanResult(\n plan: TransactionPlanResult,\n): asserts plan is SuccessfulTransactionPlanResult {\n if (!isSuccessfulTransactionPlanResult(plan)) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT, {\n transactionPlanResult: plan,\n });\n }\n}\n\n/**\n * Finds the first transaction plan result in the tree that matches the given predicate.\n *\n * This function performs a depth-first search through the transaction plan result tree,\n * returning the first result that satisfies the predicate. It checks the root result\n * first, then recursively searches through nested results.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @param predicate - A function that returns `true` for the result to find.\n * @returns The first matching transaction plan result, or `undefined` if no match is found.\n *\n * @example\n * Finding a failed transaction result.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * ]);\n *\n * const failed = findTransactionPlanResult(\n * result,\n * (r) => r.kind === 'single' && r.status.kind === 'failed',\n * );\n * // Returns the failed single transaction plan result for messageB.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function findTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (result: TransactionPlanResult) => boolean,\n): TransactionPlanResult | undefined {\n if (predicate(transactionPlanResult)) {\n return transactionPlanResult;\n }\n if (transactionPlanResult.kind === 'single') {\n return undefined;\n }\n for (const subResult of transactionPlanResult.plans) {\n const foundResult = findTransactionPlanResult(subResult, predicate);\n if (foundResult) {\n return foundResult;\n }\n }\n return undefined;\n}\n\n/**\n * Retrieves the first failed transaction plan result from a transaction plan result tree.\n *\n * This function searches the transaction plan result tree using a depth-first traversal\n * and returns the first single transaction result with a 'failed' status. If no failed\n * result is found, it throws a {@link SolanaError}.\n *\n * @param transactionPlanResult - The transaction plan result tree to search.\n * @return The first failed single transaction plan result.\n * @throws Throws a {@link SolanaError} with code\n * `SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND` if no\n * failed transaction plan result is found. The error context contains a non-enumerable\n * `transactionPlanResult` property for recovery purposes.\n *\n * @example\n * Retrieving the first failed result from a parallel execution.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * failedSingleTransactionPlanResult(messageB, error),\n * failedSingleTransactionPlanResult(messageC, anotherError),\n * ]);\n *\n * const firstFailed = getFirstFailedSingleTransactionPlanResult(result);\n * // Returns the failed result for messageB.\n * ```\n *\n * @see {@link FailedSingleTransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n */\nexport function getFirstFailedSingleTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n): FailedSingleTransactionPlanResult {\n const result = findTransactionPlanResult(\n transactionPlanResult,\n r => r.kind === 'single' && r.status.kind === 'failed',\n );\n\n if (!result) {\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can recover but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n const context = {};\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,\n context,\n );\n }\n\n return result as FailedSingleTransactionPlanResult;\n}\n\n/**\n * Checks if every transaction plan result in the tree satisfies the given predicate.\n *\n * This function performs a depth-first traversal through the transaction plan result tree,\n * returning `true` only if the predicate returns `true` for every result in the tree\n * (including the root result and all nested results).\n *\n * @param transactionPlanResult - The transaction plan result tree to check.\n * @param predicate - A function that returns `true` if the result satisfies the condition.\n * @return `true` if every result in the tree satisfies the predicate, `false` otherwise.\n *\n * @example\n * Checking if all transactions were successful.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * successfulSingleTransactionPlanResult(messageB, transactionB),\n * ]);\n *\n * const allSuccessful = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind === 'successful',\n * );\n * // Returns true because all single results are successful.\n * ```\n *\n * @example\n * Checking if no transactions were canceled.\n * ```ts\n * const result = sequentialTransactionPlanResult([resultA, resultB, resultC]);\n *\n * const noCanceled = everyTransactionPlanResult(\n * result,\n * (r) => r.kind !== 'single' || r.status.kind !== 'canceled',\n * );\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function everyTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n predicate: (plan: TransactionPlanResult) => boolean,\n): boolean {\n if (!predicate(transactionPlanResult)) {\n return false;\n }\n if (transactionPlanResult.kind === 'single') {\n return true;\n }\n return transactionPlanResult.plans.every(p => everyTransactionPlanResult(p, predicate));\n}\n\n/**\n * Transforms a transaction plan result tree using a bottom-up approach.\n *\n * This function recursively traverses the transaction plan result tree, applying the\n * transformation function to each result. The transformation is applied bottom-up,\n * meaning nested results are transformed first, then the parent results receive\n * the already-transformed children before being transformed themselves.\n *\n * All transformed results are frozen using `Object.freeze` to ensure immutability.\n *\n * @param transactionPlanResult - The transaction plan result tree to transform.\n * @param fn - A function that transforms each result and returns a new result.\n * @return A new transformed transaction plan result tree.\n *\n * @example\n * Converting all canceled results to failed results.\n * ```ts\n * const result = parallelTransactionPlanResult([\n * successfulSingleTransactionPlanResult(messageA, transactionA),\n * canceledSingleTransactionPlanResult(messageB),\n * ]);\n *\n * const transformed = transformTransactionPlanResult(result, (r) => {\n * if (r.kind === 'single' && r.status.kind === 'canceled') {\n * return failedSingleTransactionPlanResult(r.message, new Error('Execution canceled'));\n * }\n * return r;\n * });\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link flattenTransactionPlanResult}\n */\nexport function transformTransactionPlanResult(\n transactionPlanResult: TransactionPlanResult,\n fn: (plan: TransactionPlanResult) => TransactionPlanResult,\n): TransactionPlanResult {\n if (transactionPlanResult.kind === 'single') {\n return Object.freeze(fn(transactionPlanResult));\n }\n return Object.freeze(\n fn(\n Object.freeze({\n ...transactionPlanResult,\n plans: transactionPlanResult.plans.map(p => transformTransactionPlanResult(p, fn)),\n }),\n ),\n );\n}\n\n/**\n * Retrieves all individual {@link SingleTransactionPlanResult} instances from a transaction plan result tree.\n *\n * This function recursively traverses any nested structure of transaction plan results and extracts\n * all the single results they contain. It's useful when you need to access all the individual\n * transaction results, regardless of their organization in the result tree (parallel or sequential).\n *\n * @param result - The transaction plan result to extract single results from\n * @returns An array of all single transaction plan results contained in the tree\n *\n * @example\n * ```ts\n * const result = parallelTransactionPlanResult([\n * sequentialTransactionPlanResult([resultA, resultB]),\n * nonDivisibleSequentialTransactionPlanResult([resultC, resultD]),\n * resultE,\n * ]);\n *\n * const singleResults = flattenTransactionPlanResult(result);\n * // Array of `SingleTransactionPlanResult` containing:\n * // resultA, resultB, resultC, resultD and resultE.\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link findTransactionPlanResult}\n * @see {@link everyTransactionPlanResult}\n * @see {@link transformTransactionPlanResult}\n */\nexport function flattenTransactionPlanResult(result: TransactionPlanResult): SingleTransactionPlanResult[] {\n if (result.kind === 'single') {\n return [result];\n }\n return result.plans.flatMap(flattenTransactionPlanResult);\n}\n\n/**\n * A {@link SingleTransactionPlanResult} with 'successful' status.\n */\nexport type SuccessfulSingleTransactionPlanResult<\n TContext extends TransactionPlanResultContext = TransactionPlanResultContext,\n> = SingleTransactionPlanResult & { status: { kind: 'successful' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'failed' status.\n */\nexport type FailedSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'failed' } };\n\n/**\n * A {@link SingleTransactionPlanResult} with 'canceled' status.\n */\nexport type CanceledSingleTransactionPlanResult = SingleTransactionPlanResult & { status: { kind: 'canceled' } };\n\n/**\n * A summary of a {@link TransactionPlanResult}, categorizing transactions by their execution status.\n * - `successful`: Indicates whether all transactions were successful (i.e., no failed or canceled transactions).\n * - `successfulTransactions`: An array of successful transactions, each including its signature.\n * - `failedTransactions`: An array of failed transactions, each including the error that caused the failure.\n * - `canceledTransactions`: An array of canceled transactions.\n */\nexport type TransactionPlanResultSummary = Readonly<{\n canceledTransactions: CanceledSingleTransactionPlanResult[];\n failedTransactions: FailedSingleTransactionPlanResult[];\n successful: boolean;\n successfulTransactions: SuccessfulSingleTransactionPlanResult[];\n}>;\n\n/**\n * Summarize a {@link TransactionPlanResult} into a {@link TransactionPlanResultSummary}.\n * @param result The transaction plan result to summarize\n * @returns A summary of the transaction plan result\n */\nexport function summarizeTransactionPlanResult(result: TransactionPlanResult): TransactionPlanResultSummary {\n const successfulTransactions: TransactionPlanResultSummary['successfulTransactions'] = [];\n const failedTransactions: TransactionPlanResultSummary['failedTransactions'] = [];\n const canceledTransactions: TransactionPlanResultSummary['canceledTransactions'] = [];\n\n const flattenedResults = flattenTransactionPlanResult(result);\n\n for (const singleResult of flattenedResults) {\n switch (singleResult.status.kind) {\n case 'successful': {\n successfulTransactions.push(singleResult as SuccessfulSingleTransactionPlanResult);\n break;\n }\n case 'failed': {\n failedTransactions.push(singleResult as FailedSingleTransactionPlanResult);\n break;\n }\n case 'canceled': {\n canceledTransactions.push(singleResult as CanceledSingleTransactionPlanResult);\n break;\n }\n }\n }\n\n return Object.freeze({\n canceledTransactions,\n failedTransactions,\n successful: failedTransactions.length === 0 && canceledTransactions.length === 0,\n successfulTransactions,\n });\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport { getAbortablePromise } from '@solana/promises';\nimport { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport { Transaction } from '@solana/transactions';\n\nimport type {\n ParallelTransactionPlan,\n SequentialTransactionPlan,\n SingleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\nimport {\n canceledSingleTransactionPlanResult,\n failedSingleTransactionPlanResult,\n parallelTransactionPlanResult,\n sequentialTransactionPlanResult,\n SingleTransactionPlanResult,\n successfulSingleTransactionPlanResult,\n successfulSingleTransactionPlanResultFromSignature,\n type TransactionPlanResult,\n type TransactionPlanResultContext,\n} from './transaction-plan-result';\n\n/**\n * Executes a transaction plan and returns the execution results.\n *\n * This function traverses the transaction plan tree, executing each transaction\n * message and collecting results that mirror the structure of the original plan.\n *\n * @typeParam TContext - The type of the context object that may be passed along with successful results.\n * @param transactionPlan - The transaction plan to execute.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel execution.\n * @return A promise that resolves to the execution results.\n *\n * @see {@link TransactionPlan}\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutor = (\n transactionPlan: TransactionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\ntype ExecuteResult = {\n context?: TContext;\n} & ({ signature: Signature } | { transaction: Transaction });\n\ntype ExecuteTransactionMessage = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) => Promise>;\n\n/**\n * Configuration object for creating a new transaction plan executor.\n *\n * @see {@link createTransactionPlanExecutor}\n */\nexport type TransactionPlanExecutorConfig = {\n /** Called whenever a transaction message must be sent to the blockchain. */\n executeTransactionMessage: ExecuteTransactionMessage;\n};\n\n/**\n * Creates a new transaction plan executor based on the provided configuration.\n *\n * The executor will traverse the provided `TransactionPlan` sequentially or in parallel,\n * executing each transaction message using the `executeTransactionMessage` function.\n *\n * - If that function is successful, the executor will return a successful `TransactionPlanResult`\n * for that message including the transaction and any custom context.\n * - If that function throws an error, the executor will stop processing and cancel all\n * remaining transaction messages in the plan.\n * - If the `abortSignal` is triggered, the executor will immediately stop processing the plan and\n * return a `TransactionPlanResult` with the status set to `canceled`.\n *\n * @param config - Configuration object containing the transaction message executor function.\n * @return A {@link TransactionPlanExecutor} function that can execute transaction plans.\n *\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * if any transaction in the plan fails to execute. The error context contains a\n * `transactionPlanResult` property with the partial results up to the point of failure.\n * @throws {@link SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED}\n * if the transaction plan contains non-divisible sequential plans, which are not\n * supported by this executor.\n *\n * @example\n * ```ts\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * const transactionPlanExecutor = createTransactionPlanExecutor({\n * executeTransactionMessage: async (message) => {\n * const transaction = await signTransactionMessageWithSigners(message);\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * return { transaction };\n * }\n * });\n * ```\n *\n * @see {@link TransactionPlanExecutorConfig}\n */\nexport function createTransactionPlanExecutor(config: TransactionPlanExecutorConfig): TransactionPlanExecutor {\n return async (plan, { abortSignal } = {}): Promise => {\n const context: TraverseContext = {\n ...config,\n abortSignal: abortSignal,\n canceled: abortSignal?.aborted ?? false,\n };\n\n // Fail early if there are non-divisible sequential plans in the\n // transaction plan as they are not supported by this executor.\n assertDivisibleSequentialPlansOnly(plan);\n\n const cancelHandler = () => {\n context.canceled = true;\n };\n abortSignal?.addEventListener('abort', cancelHandler);\n const transactionPlanResult = await traverse(plan, context);\n abortSignal?.removeEventListener('abort', cancelHandler);\n\n if (context.canceled) {\n const abortReason = abortSignal?.aborted ? abortSignal.reason : undefined;\n const context = { cause: findErrorFromTransactionPlanResult(transactionPlanResult) ?? abortReason };\n // Here we want the `transactionPlanResult` to be available in the error context\n // so applications can create recovery plans but we don't want this object to be\n // serialized with the error. This is why we set it as a non-enumerable property.\n Object.defineProperty(context, 'transactionPlanResult', {\n configurable: false,\n enumerable: false,\n value: transactionPlanResult,\n writable: false,\n });\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, context);\n }\n\n return transactionPlanResult;\n };\n}\n\ntype TraverseContext = TransactionPlanExecutorConfig & {\n abortSignal?: AbortSignal;\n canceled: boolean;\n};\n\nasync function traverse(transactionPlan: TransactionPlan, context: TraverseContext): Promise {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(transactionPlan, context);\n case 'parallel':\n return await traverseParallel(transactionPlan, context);\n case 'single':\n return await traverseSingle(transactionPlan, context);\n default:\n transactionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n transactionPlan: SequentialTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n\n const results: TransactionPlanResult[] = [];\n\n for (const subPlan of transactionPlan.plans) {\n const result = await traverse(subPlan, context);\n results.push(result);\n }\n\n return sequentialTransactionPlanResult(results);\n}\n\nasync function traverseParallel(\n transactionPlan: ParallelTransactionPlan,\n context: TraverseContext,\n): Promise {\n const results = await Promise.all(transactionPlan.plans.map(plan => traverse(plan, context)));\n return parallelTransactionPlanResult(results);\n}\n\nasync function traverseSingle(\n transactionPlan: SingleTransactionPlan,\n context: TraverseContext,\n): Promise {\n if (context.canceled) {\n return canceledSingleTransactionPlanResult(transactionPlan.message);\n }\n\n try {\n const result = await getAbortablePromise(\n context.executeTransactionMessage(transactionPlan.message, { abortSignal: context.abortSignal }),\n context.abortSignal,\n );\n if ('transaction' in result) {\n return successfulSingleTransactionPlanResult(transactionPlan.message, result.transaction, result.context);\n } else {\n return successfulSingleTransactionPlanResultFromSignature(\n transactionPlan.message,\n result.signature,\n result.context,\n );\n }\n } catch (error) {\n context.canceled = true;\n return failedSingleTransactionPlanResult(transactionPlan.message, error as Error);\n }\n}\n\nfunction findErrorFromTransactionPlanResult(result: TransactionPlanResult): Error | undefined {\n if (result.kind === 'single') {\n return result.status.kind === 'failed' ? result.status.error : undefined;\n }\n for (const plan of result.plans) {\n const error = findErrorFromTransactionPlanResult(plan);\n if (error) {\n return error;\n }\n }\n}\n\nfunction assertDivisibleSequentialPlansOnly(transactionPlan: TransactionPlan): void {\n const kind = transactionPlan.kind;\n switch (kind) {\n case 'sequential':\n if (!transactionPlan.divisible) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);\n }\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'parallel':\n for (const subPlan of transactionPlan.plans) {\n assertDivisibleSequentialPlansOnly(subPlan);\n }\n return;\n case 'single':\n default:\n return;\n }\n}\n\n/**\n * Wraps a transaction plan execution promise to return a\n * {@link TransactionPlanResult} even on execution failure.\n *\n * When a transaction plan executor throws a\n * {@link SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN}\n * error, this helper catches it and returns the `TransactionPlanResult`\n * from the error context instead of throwing.\n *\n * This allows us to handle the result of an execution in a single unified way\n * instead of using try/catch and examine the `TransactionPlanResult` in both\n * success and failure cases.\n *\n * Any other errors are re-thrown as normal.\n *\n * @param promise - A promise returned by a transaction plan executor.\n * @return A promise that resolves to the transaction plan result, even if some transactions failed.\n *\n * @example\n * Handling failures using a single result object:\n * ```ts\n * const result = await passthroughFailedTransactionPlanExecution(\n * transactionPlanExecutor(transactionPlan)\n * );\n *\n * const summary = summarizeTransactionPlanResult(result);\n * if (summary.successful) {\n * console.log('All transactions executed successfully');\n * } else {\n * console.log(`${summary.successfulTransactions.length} succeeded`);\n * console.log(`${summary.failedTransactions.length} failed`);\n * console.log(`${summary.canceledTransactions.length} canceled`);\n * }\n * ```\n *\n * @see {@link TransactionPlanResult}\n * @see {@link createTransactionPlanExecutor}\n * @see {@link summarizeTransactionPlanResult}\n */\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise;\nexport async function passthroughFailedTransactionPlanExecution(\n promise: Promise,\n): Promise {\n try {\n return await promise;\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN)) {\n return error.context.transactionPlanResult as TransactionPlanResult;\n }\n throw error;\n }\n}\n","import {\n isSolanaError,\n SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,\n SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,\n SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,\n SolanaError,\n} from '@solana/errors';\nimport { getAbortablePromise } from '@solana/promises';\nimport {\n appendTransactionMessageInstructions,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/transaction-messages';\nimport { getTransactionMessageSize, TRANSACTION_SIZE_LIMIT } from '@solana/transactions';\n\nimport {\n InstructionPlan,\n MessagePackerInstructionPlan,\n ParallelInstructionPlan,\n SequentialInstructionPlan,\n SingleInstructionPlan,\n} from './instruction-plan';\nimport {\n flattenTransactionPlan,\n nonDivisibleSequentialTransactionPlan,\n parallelTransactionPlan,\n sequentialTransactionPlan,\n SingleTransactionPlan,\n singleTransactionPlan,\n TransactionPlan,\n} from './transaction-plan';\n\n/**\n * Plans one or more transactions according to the provided instruction plan.\n *\n * @param instructionPlan - The instruction plan to be planned and executed.\n * @param config - Optional configuration object that can include an `AbortSignal` to cancel the planning process.\n *\n * @see {@link InstructionPlan}\n * @see {@link TransactionPlan}\n */\nexport type TransactionPlanner = (\n instructionPlan: InstructionPlan,\n config?: { abortSignal?: AbortSignal },\n) => Promise;\n\ntype Mutable = { -readonly [P in keyof T]: T[P] };\n\ntype CreateTransactionMessage = (config?: {\n abortSignal?: AbortSignal;\n}) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\ntype OnTransactionMessageUpdated = (\n transactionMessage: TransactionMessage & TransactionMessageWithFeePayer,\n config?: { abortSignal?: AbortSignal },\n) =>\n | Promise\n | (TransactionMessage & TransactionMessageWithFeePayer);\n\n/**\n * Configuration object for creating a new transaction planner.\n *\n * @see {@link createTransactionPlanner}\n */\nexport type TransactionPlannerConfig = {\n /** Called whenever a new transaction message is needed. */\n createTransactionMessage: CreateTransactionMessage;\n /**\n * Called whenever a transaction message is updated — e.g. new instructions were added.\n * This function must return the updated transaction message back — even if no changes were made.\n */\n onTransactionMessageUpdated?: OnTransactionMessageUpdated;\n};\n\n/**\n * Creates a new transaction planner based on the provided configuration.\n *\n * At the very least, the `createTransactionMessage` function must be provided.\n * This function is used to create new transaction messages whenever needed.\n *\n * Additionally, the `onTransactionMessageUpdated` function can be provided\n * to update transaction messages during the planning process. This function will\n * be called whenever a transaction message is updated, e.g. when new instructions\n * are added to a transaction message. It accepts the updated transaction message\n * and must return a transaction message back, even if no changes were made.\n *\n * @example\n * ```ts\n * const transactionPlanner = createTransactionPlanner({\n * createTransactionMessage: () => pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(mySigner, message),\n * )\n * });\n * ```\n *\n * @see {@link TransactionPlannerConfig}\n */\nexport function createTransactionPlanner(config: TransactionPlannerConfig): TransactionPlanner {\n return async (instructionPlan, { abortSignal } = {}): Promise => {\n const plan = await traverse(instructionPlan, {\n abortSignal,\n createTransactionMessage: config.createTransactionMessage,\n onTransactionMessageUpdated: config.onTransactionMessageUpdated ?? (msg => msg),\n parent: null,\n parentCandidates: [],\n });\n\n if (!plan) {\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN);\n }\n\n return freezeTransactionPlan(plan);\n };\n}\n\ntype MutableTransactionPlan = Mutable;\ntype MutableSingleTransactionPlan = Mutable;\n\ntype TraverseContext = {\n abortSignal?: AbortSignal;\n createTransactionMessage: CreateTransactionMessage;\n onTransactionMessageUpdated: OnTransactionMessageUpdated;\n parent: InstructionPlan | null;\n parentCandidates: MutableSingleTransactionPlan[];\n};\n\nasync function traverse(\n instructionPlan: InstructionPlan,\n context: TraverseContext,\n): Promise {\n context.abortSignal?.throwIfAborted();\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n return await traverseSequential(instructionPlan, context);\n case 'parallel':\n return await traverseParallel(instructionPlan, context);\n case 'single':\n return await traverseSingle(instructionPlan, context);\n case 'messagePacker':\n return await traverseMessagePacker(instructionPlan, context);\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n\nasync function traverseSequential(\n instructionPlan: SequentialInstructionPlan,\n context: TraverseContext,\n): Promise {\n let candidate: MutableSingleTransactionPlan | null = null;\n\n // Check if the sequential plan must fit entirely in its parent candidates\n // due to constraints like being inside a parallel plan or not being divisible.\n const mustEntirelyFitInParentCandidate =\n context.parent && (context.parent.kind === 'parallel' || !instructionPlan.divisible);\n\n // If so, try to fit the entire plan inside one of the parent candidates.\n if (mustEntirelyFitInParentCandidate) {\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, message =>\n fitEntirePlanInsideMessage(instructionPlan, message),\n );\n // If that's possible, we the candidate is mutated and we can return null.\n // Otherwise, we proceed with the normal traversal and no parent candidate.\n if (candidate) {\n return null;\n }\n } else {\n // Otherwise, we can use the first parent candidate, if any,\n // since we know it must be a divisible sequential plan.\n candidate = context.parentCandidates.length > 0 ? context.parentCandidates[0] : null;\n }\n\n const transactionPlans: TransactionPlan[] = [];\n for (const plan of instructionPlan.plans) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidate ? [candidate] : [],\n });\n if (transactionPlan) {\n candidate = getSequentialCandidate(transactionPlan);\n const newPlans =\n transactionPlan.kind === 'sequential' && (transactionPlan.divisible || !instructionPlan.divisible)\n ? transactionPlan.plans\n : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a sequential plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return {\n divisible: instructionPlan.divisible,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nasync function traverseParallel(\n instructionPlan: ParallelInstructionPlan,\n context: TraverseContext,\n): Promise {\n const candidates: MutableSingleTransactionPlan[] = [...context.parentCandidates];\n const transactionPlans: TransactionPlan[] = [];\n\n // Reorder children so message packer plans are last.\n const sortedChildren = Array.from(instructionPlan.plans).sort(\n (a, b) => Number(a.kind === 'messagePacker') - Number(b.kind === 'messagePacker'),\n );\n\n for (const plan of sortedChildren) {\n const transactionPlan = await traverse(plan, {\n ...context,\n parent: instructionPlan,\n parentCandidates: candidates,\n });\n if (transactionPlan) {\n candidates.push(...getParallelCandidates(transactionPlan));\n const newPlans = transactionPlan.kind === 'parallel' ? transactionPlan.plans : [transactionPlan];\n transactionPlans.push(...newPlans);\n }\n }\n\n // Wrap in a parallel plan or simplify.\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n return { kind: 'parallel', plans: transactionPlans };\n}\n\nasync function traverseSingle(\n instructionPlan: SingleInstructionPlan,\n context: TraverseContext,\n): Promise {\n const predicate = (message: TransactionMessage & TransactionMessageWithFeePayer) =>\n appendTransactionMessageInstructions([instructionPlan.instruction], message);\n const candidate = await selectAndMutateCandidate(context, context.parentCandidates, predicate);\n if (candidate) {\n return null;\n }\n const message = await createNewMessage(context, predicate);\n return { kind: 'single', message };\n}\n\nasync function traverseMessagePacker(\n instructionPlan: MessagePackerInstructionPlan,\n context: TraverseContext,\n): Promise {\n const messagePacker = instructionPlan.getMessagePacker();\n const transactionPlans: SingleTransactionPlan[] = [];\n const candidates = [...context.parentCandidates];\n\n while (!messagePacker.done()) {\n const candidate = await selectAndMutateCandidate(context, candidates, messagePacker.packMessageToCapacity);\n if (!candidate) {\n const message = await createNewMessage(context, messagePacker.packMessageToCapacity);\n const newPlan: MutableSingleTransactionPlan = { kind: 'single', message };\n transactionPlans.push(newPlan);\n }\n }\n\n if (transactionPlans.length === 1) {\n return transactionPlans[0];\n }\n if (transactionPlans.length === 0) {\n return null;\n }\n if (context.parent?.kind === 'parallel') {\n return { kind: 'parallel', plans: transactionPlans };\n }\n return {\n divisible: context.parent?.kind === 'sequential' ? context.parent.divisible : true,\n kind: 'sequential',\n plans: transactionPlans,\n };\n}\n\nfunction getSequentialCandidate(latestPlan: MutableTransactionPlan): MutableSingleTransactionPlan | null {\n if (latestPlan.kind === 'single') {\n return latestPlan;\n }\n if (latestPlan.kind === 'sequential' && latestPlan.plans.length > 0) {\n return getSequentialCandidate(latestPlan.plans[latestPlan.plans.length - 1]);\n }\n return null;\n}\n\nfunction getParallelCandidates(latestPlan: TransactionPlan): MutableSingleTransactionPlan[] {\n return flattenTransactionPlan(latestPlan);\n}\n\nasync function selectAndMutateCandidate(\n context: Pick,\n candidates: MutableSingleTransactionPlan[],\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n for (const candidate of candidates) {\n try {\n const message = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(candidate.message), {\n abortSignal: context.abortSignal,\n }),\n ),\n context.abortSignal,\n );\n if (getTransactionMessageSize(message) <= TRANSACTION_SIZE_LIMIT) {\n candidate.message = message;\n return candidate;\n }\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN)) {\n // Try the next candidate.\n } else {\n throw error;\n }\n }\n }\n return null;\n}\n\nasync function createNewMessage(\n context: Pick,\n predicate: (\n message: TransactionMessage & TransactionMessageWithFeePayer,\n ) => TransactionMessage & TransactionMessageWithFeePayer,\n): Promise {\n const newMessage = await getAbortablePromise(\n Promise.resolve(context.createTransactionMessage({ abortSignal: context.abortSignal })),\n context.abortSignal,\n );\n const updatedMessage = await getAbortablePromise(\n Promise.resolve(\n context.onTransactionMessageUpdated(predicate(newMessage), { abortSignal: context.abortSignal }),\n ),\n context.abortSignal,\n );\n const updatedMessageSize = getTransactionMessageSize(updatedMessage);\n if (updatedMessageSize > TRANSACTION_SIZE_LIMIT) {\n const newMessageSize = getTransactionMessageSize(newMessage);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: updatedMessageSize - newMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - newMessageSize,\n });\n }\n return updatedMessage;\n}\n\nfunction freezeTransactionPlan(plan: MutableTransactionPlan): TransactionPlan {\n const kind = plan.kind;\n switch (kind) {\n case 'single':\n return singleTransactionPlan(plan.message);\n case 'sequential':\n return plan.divisible\n ? sequentialTransactionPlan(plan.plans.map(freezeTransactionPlan))\n : nonDivisibleSequentialTransactionPlan(plan.plans.map(freezeTransactionPlan));\n case 'parallel':\n return parallelTransactionPlan(plan.plans.map(freezeTransactionPlan));\n default:\n plan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });\n }\n}\n\nfunction fitEntirePlanInsideMessage(\n instructionPlan: InstructionPlan,\n message: TransactionMessage & TransactionMessageWithFeePayer,\n): TransactionMessage & TransactionMessageWithFeePayer {\n let newMessage: TransactionMessage & TransactionMessageWithFeePayer = message;\n\n const kind = instructionPlan.kind;\n switch (kind) {\n case 'sequential':\n case 'parallel':\n for (const plan of instructionPlan.plans) {\n newMessage = fitEntirePlanInsideMessage(plan, newMessage);\n }\n return newMessage;\n case 'single':\n newMessage = appendTransactionMessageInstructions([instructionPlan.instruction], message);\n // eslint-disable-next-line no-case-declarations\n const newMessageSize = getTransactionMessageSize(newMessage);\n if (newMessageSize > TRANSACTION_SIZE_LIMIT) {\n const baseMessageSize = getTransactionMessageSize(message);\n throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {\n numBytesRequired: newMessageSize - baseMessageSize,\n numFreeBytes: TRANSACTION_SIZE_LIMIT - baseMessageSize,\n });\n }\n return newMessage;\n case 'messagePacker':\n // eslint-disable-next-line no-case-declarations\n const messagePacker = instructionPlan.getMessagePacker();\n while (!messagePacker.done()) {\n newMessage = messagePacker.packMessageToCapacity(newMessage);\n }\n return newMessage;\n default:\n instructionPlan satisfies never;\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });\n }\n}\n","import { assertIsAddress, isAddress } from '@solana/addresses';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n SolanaError,\n} from '@solana/errors';\nimport { Brand, EncodedString } from '@solana/nominal-types';\n\n/**\n * A 32-byte array identifying the application requesting off-chain message signing.\n *\n * This may be any arbitrary bytes. For instance the on-chain address of a program, DAO instance,\n * Candy Machine, et cetera.\n *\n * This field SHOULD be displayed to users as a base58-encoded ASCII string rather than interpreted\n * otherwise.\n */\nexport type OffchainMessageApplicationDomain = Brand<\n EncodedString,\n 'OffchainMessageApplicationDomain'\n>;\n\n/**\n * A type guard that returns `true` if the input string conforms to the\n * {@link OffchainMessageApplicationDomain} type, and refines its type for use in your program.\n *\n * @example\n * ```ts\n * import { isOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * if (isOffchainMessageApplicationDomain(applicationDomain)) {\n * // At this point, `applicationDomain` has been refined to an\n * // `OffchainMessageApplcationDomain` that can be used to craft a message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } else {\n * setError(`${applicationDomain} is not a valid application domain for an offchain message`);\n * }\n * ```\n */\nexport function isOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): putativeApplicationDomain is OffchainMessageApplicationDomain {\n return isAddress(putativeApplicationDomain);\n}\n\n/**\n * From time to time you might acquire a string, that you expect to validate as an offchain message\n * application domain, from an untrusted network API or user input. Use this function to assert that\n * such an arbitrary string is a base58-encoded application domain.\n *\n * @example\n * ```ts\n * import { assertIsOffchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * // Imagine a function that determines whether an application domain is valid.\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const applicationDomain: string = applicationDomainInput.value;\n * try {\n * // If this type assertion function doesn't throw, then\n * // Typescript will upcast `applicationDomain` to `OffchainMessageApplicationDomain`.\n * assertIsOffchainMessageApplicationDomain(applicationDomain);\n * // At this point, `applicationDomain` is a `OffchainMessageApplicationDomain` that can be\n * // used to craft an offchain message.\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * } catch (e) {\n * // `applicationDomain` turned out not to be a base58-encoded application domain\n * }\n * }\n * ```\n */\nexport function assertIsOffchainMessageApplicationDomain(\n putativeApplicationDomain: string,\n): asserts putativeApplicationDomain is OffchainMessageApplicationDomain {\n try {\n assertIsAddress(putativeApplicationDomain);\n } catch (error) {\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,\n error.context,\n );\n }\n if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {\n throw new SolanaError(\n SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,\n error.context,\n );\n }\n throw error;\n }\n}\n\n/**\n * Combines _asserting_ that a string is an offchain message application domain with _coercing_ it\n * to the {@link OffchainMessageApplicationDomain} type. It's most useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageApplicationDomain, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * const offchainMessage: OffchainMessageV0 = {\n * applicationDomain:\n * offchainMessageApplicationDomain('HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx'),\n * // ...\n * };\n * ```\n *\n * > [!TIP]\n * > When starting from a known-good application domain as a string, it's more efficient to typecast\n * > it rather than to use the {@link offchainMessageApplicationDomain} helper, because the helper\n * > unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageApplicationDomain } from '@solana/offchain-messages';\n * >\n * > const applicationDomain =\n * > 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * > ```\n */\nexport function offchainMessageApplicationDomain(putativeApplicationDomain: string): OffchainMessageApplicationDomain {\n assertIsOffchainMessageApplicationDomain(putativeApplicationDomain);\n return putativeApplicationDomain;\n}\n","import { Address, getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n transformEncoder,\n} from '@solana/codecs-core';\n\nimport { OffchainMessageApplicationDomain, offchainMessageApplicationDomain } from '../application-domain';\n\n/**\n * Returns an encoder that you can use to encode a base58-encoded offchain message application\n * domain to a byte array.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainEncoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomain =\n * 'HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx' as OffchainMessageApplicationDomain;\n * const offchainMessageApplicationDomainEncoder = getOffchainMessageApplicationDomainEncoder();\n * const offchainMessageApplicationDomainBytes =\n * offchainMessageApplicationDomainEncoder.encode(offchainMessageApplicationDomain);\n * // Uint8Array(32) [\n * // 247, 203, 28, 80, 52, 240, 169, 19,\n * // 21, 103, 107, 119, 91, 235, 13, 48,\n * // 194, 169, 148, 160, 78, 105, 235, 37,\n * // 232, 160, 49, 47, 64, 89, 18, 153,\n * // ]\n * ```\n */\nexport function getOffchainMessageApplicationDomainEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getAddressEncoder(),\n putativeApplicationDomain => offchainMessageApplicationDomain(putativeApplicationDomain) as string as Address,\n );\n}\n\n/**\n * Returns a decoder that you can use to convert an array of 32 bytes representing an offchain\n * message application domain to the base58-encoded representation of that application domain.\n *\n * @example\n * ```ts\n * import { getOffchainMessageApplicationDomainDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageApplicationDomainBytes = new Uint8Array([\n * 247, 203, 28, 80, 52, 240, 169, 19,\n * 21, 103, 107, 119, 91, 235, 13, 48,\n * 194, 169, 148, 160, 78, 105, 235, 37,\n * 232, 160, 49, 47, 64, 89, 18, 153,\n * ]);\n * const offchainMessageApplicationDomainDecoder = getOffchainMessageApplicationDomainDecoder();\n * const offchainMessageApplicationDomain =\n * offchainMessageApplicationDomainDecoder.decode(offchainMessageApplicationDomainBytes);\n * // HgHLLXT3BVA5m7x66tEp3YNatXLth1hJwVeCva2T9RNx\n * ```\n */\nexport function getOffchainMessageApplicationDomainDecoder(): FixedSizeDecoder {\n return getAddressDecoder() as FixedSizeDecoder as FixedSizeDecoder<\n OffchainMessageApplicationDomain,\n 32\n >;\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to a base-58 encoded offchain message\n * application domain.\n *\n * @see {@link getOffchainMessageApplicationDomainDecoder}\n * @see {@link getOffchainMessageApplicationDomainEncoder}\n */\nexport function getOffchainMessageApplicationDomainCodec(): FixedSizeCodec<\n OffchainMessageApplicationDomain,\n OffchainMessageApplicationDomain,\n 32\n> {\n return combineCodec(getOffchainMessageApplicationDomainEncoder(), getOffchainMessageApplicationDomainDecoder());\n}\n","import {\n combineCodec,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n ReadonlyUint8Array,\n} from '@solana/codecs-core';\nimport { getConstantDecoder, getConstantEncoder } from '@solana/codecs-data-structures';\n\n// The string `'\\xffsolana offchain'`\nconst OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES: ReadonlyUint8Array = new Uint8Array([\n 0xff, 0x73, 0x6f, 0x6c, 0x61, 0x6e, 0x61, 0x20, 0x6f, 0x66, 0x66, 0x63, 0x68, 0x61, 0x69, 0x6e,\n]);\n\nexport function getOffchainMessageSigningDomainDecoder(): FixedSizeDecoder {\n return getConstantDecoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeDecoder;\n}\n\nexport function getOffchainMessageSigningDomainEncoder(): FixedSizeEncoder {\n return getConstantEncoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES) as FixedSizeEncoder;\n}\n\nexport function getOffchainMessageSigningDomainCodec(): FixedSizeCodec {\n return combineCodec(getOffchainMessageSigningDomainEncoder(), getOffchainMessageSigningDomainDecoder());\n}\n","import { Address, getAddressDecoder } from '@solana/addresses';\nimport {\n FixedSizeDecoder,\n FixedSizeEncoder,\n offsetDecoder,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageVersion } from '../version';\nimport { getOffchainMessageSigningDomainDecoder, getOffchainMessageSigningDomainEncoder } from './signing-domain';\n\ntype TDecoderFields = Parameters[0];\ntype TEncoderFields = Parameters[0];\n\nfunction getSigningDomainPrefixedDecoder(...fields: T) {\n return getHiddenPrefixDecoder(getStructDecoder(fields), [getOffchainMessageSigningDomainDecoder()]);\n}\n\nfunction getSigningDomainPrefixedEncoder(...fields: T) {\n return getHiddenPrefixEncoder(getStructEncoder(fields), [getOffchainMessageSigningDomainEncoder()]);\n}\n\nfunction getVersionTransformer(fixedVersion?: OffchainMessageVersion) {\n return (version: number) => {\n if (version > 1) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n if (fixedVersion != null && version !== fixedVersion) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION, {\n actualVersion: version,\n expectedVersion: fixedVersion,\n });\n }\n return version;\n };\n}\n\nexport function createOffchainMessagePreambleDecoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TDecoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer(version)) as FixedSizeDecoder],\n ...fields,\n );\n}\n\nexport function createOffchainMessagePreambleEncoder<\n const TVersion extends OffchainMessageVersion,\n const TFields extends TEncoderFields,\n>(version: TVersion, ...fields: TFields) {\n return getSigningDomainPrefixedEncoder(\n ['version', transformEncoder(getU8Encoder(), getVersionTransformer(version)) as FixedSizeEncoder],\n ...fields,\n );\n}\n\nexport function decodeRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const { version, bytesAfterVersion } = getSigningDomainPrefixedDecoder(\n ['version', transformDecoder(getU8Decoder(), getVersionTransformer())],\n ['bytesAfterVersion', getBytesDecoder()],\n ).decode(bytes);\n return offsetDecoder(\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses;\n }),\n {\n preOffset: ({ preOffset }) =>\n preOffset +\n (version === 0\n ? 32 + 1 // skip the application domain and message format of v0 messages\n : 0),\n },\n ).decode(bytesAfterVersion);\n}\n\nexport function getSignatoriesComparator(): (a: ReadonlyUint8Array, b: ReadonlyUint8Array) => -1 | 0 | 1 {\n return (x, y) => {\n if (x.length !== y.length) {\n return x.length < y.length ? -1 : 1;\n }\n for (let ii = 0; ii < x.length; ii++) {\n if (x[ii] === y[ii]) {\n continue;\n } else {\n return x[ii] < y[ii] ? -1 : 1;\n }\n }\n return 0;\n };\n}\n","import { fixEncoderSize, transformEncoder, VariableSizeEncoder } from '@solana/codecs-core';\nimport { getArrayEncoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\n\nfunction getSignaturesToEncode(signaturesMap: OffchainMessageEnvelope['signatures']): SignatureBytes[] {\n const signatures = Object.values(signaturesMap);\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n return signatures.map(signature => {\n if (!signature) {\n return new Uint8Array(64).fill(0) as SignatureBytes;\n }\n return signature;\n });\n}\n\nexport function getSignaturesEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getU8Encoder() }),\n getSignaturesToEncode,\n );\n}\n","import { Address, address } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n getArrayDecoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n} from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { OffchainMessageEnvelope } from '../envelope';\nimport { OffchainMessageBytes } from '../message';\nimport { decodeRequiredSignatoryAddresses } from './preamble-common';\nimport { getSignaturesEncoder } from './signatures';\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageEnvelope} to a byte array\n * appropriate for sharing with a third party for validation.\n */\nexport function getOffchainMessageEnvelopeEncoder(): VariableSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['signatures', getSignaturesEncoder()],\n ['content', getBytesEncoder()],\n ]),\n envelope => {\n const signaturesMapAddresses = Object.keys(envelope.signatures).map(address);\n if (signaturesMapAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(envelope.content);\n const missingRequiredSigners = [];\n const unexpectedSigners = [];\n for (const address of signatoryAddresses) {\n if (!signaturesMapAddresses.includes(address)) {\n missingRequiredSigners.push(address);\n }\n }\n for (const address of signaturesMapAddresses) {\n if (!signatoryAddresses.includes(address)) {\n unexpectedSigners.push(address);\n }\n }\n if (missingRequiredSigners.length || unexpectedSigners.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH, {\n missingRequiredSigners,\n unexpectedSigners,\n });\n }\n const orderedSignatureMap: OffchainMessageEnvelope['signatures'] = {};\n for (const address of signatoryAddresses) {\n orderedSignatureMap[address] = envelope.signatures[address];\n }\n return {\n ...envelope,\n signatures: orderedSignatureMap,\n };\n },\n );\n}\n\n/**\n * Returns a decoder that you can use to convert a byte array in the Solana offchain message format\n * to a {@link OffchainMessageEnvelope} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageEnvelopeDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelopeDecoder = getOffchainMessageEnvelopeDecoder();\n * const offchainMessageEnvelope = offchainMessageEnvelopeDecoder.decode(offchainMessageEnvelopeBytes);\n * for (const [address, signature] in Object.entries(offchainMessageEnvelope.signatures)) {\n * console.log(`Signature by ${address}`, signature);\n * }\n * ```\n */\nexport function getOffchainMessageEnvelopeDecoder(): VariableSizeDecoder {\n return transformDecoder(\n getStructDecoder([\n ['signatures', getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getU8Decoder() })],\n ['content', getBytesDecoder()],\n ]),\n decodePartiallyDecodedOffchainMessageEnvelope,\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageEnvelope}\n *\n * @see {@link getOffchainMessageEnvelopeDecoder}\n * @see {@link getOffchainMessageEnvelopeEncoder}\n */\nexport function getOffchainMessageEnvelopeCodec() {\n return combineCodec(getOffchainMessageEnvelopeEncoder(), getOffchainMessageEnvelopeDecoder());\n}\n\ntype PartiallyDecodedOffchainMessageEnvelope = {\n content: ReadonlyUint8Array;\n signatures: ReadonlyUint8Array[];\n};\n\nfunction decodePartiallyDecodedOffchainMessageEnvelope(\n offchainMessageEnvelope: PartiallyDecodedOffchainMessageEnvelope,\n): OffchainMessageEnvelope {\n const { content, signatures } = offchainMessageEnvelope;\n\n if (signatures.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);\n }\n\n const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(content);\n\n // Signer addresses and signatures must be the same length\n // We encode an all-zero signature when the signature is missing\n if (signatoryAddresses.length !== signatures.length) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH, {\n numRequiredSignatures: signatoryAddresses.length,\n signatoryAddresses,\n signaturesLength: signatures.length,\n });\n }\n\n // Combine the signer addresses + signatures into the signatures map\n const signaturesMap: OffchainMessageEnvelope['signatures'] = {};\n signatoryAddresses.forEach((address, index) => {\n const signatureForAddress = signatures[index];\n if (signatureForAddress.every(b => b === 0)) {\n signaturesMap[address] = null;\n } else {\n signaturesMap[address] = signatureForAddress as SignatureBytes;\n }\n });\n\n return Object.freeze({\n content: content as OffchainMessageBytes,\n signatures: Object.freeze(signaturesMap),\n });\n}\n\nfunction decodeAndValidateRequiredSignatoryAddresses(bytes: ReadonlyUint8Array): readonly Address[] {\n const signatoryAddresses = decodeRequiredSignatoryAddresses(bytes);\n\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n\n return signatoryAddresses;\n}\n","import { getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\n\nconst MAX_BODY_BYTES =\n // Largest 16-bit unsigned integer\n 0xffff;\nconst MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE =\n // Space remaining in the mininum IPv6 MTU after network header overhead\n 1232;\n\n/**\n * A restriction on what characters the message text can contain and how long it can be.\n *\n * The aim of this restriction is to make a message more likely to be signable by a hardware wallet\n * that imposes limits on message size. In the case of wanting a message to be clear-signable,\n * restricting the character set to ASCII may ensure that certain models of hardware wallet without\n * extended character sets can display it onscreen.\n *\n * @remarks This only applies to v0 messages.\n */\nexport enum OffchainMessageContentFormat {\n RESTRICTED_ASCII_1232_BYTES_MAX = 0,\n UTF8_1232_BYTES_MAX = 1,\n UTF8_65535_BYTES_MAX = 2,\n}\n\n/**\n * Describes message text that is no more than 1232 bytes long and made up of characters with ASCII\n * character codes in the range [0x20, 0x7e].\n *\n * @remarks This type aims to restrict text to that which can be clear-signed by hardware wallets\n * that can only display ASCII characters onscreen.\n */\nexport type OffchainMessageContentRestrictedAsciiOf1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 1232 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of1232BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX;\n text: Brand;\n}>;\n\n/**\n * Describes message text that is no more than 65535 bytes long and mdae up of any UTF-8 characters.\n */\nexport type OffchainMessageContentUtf8Of65535BytesMax = Readonly<{\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX;\n text: Brand;\n}>;\n\nexport type OffchainMessageContent =\n | OffchainMessageContentRestrictedAsciiOf1232BytesMax\n | OffchainMessageContentUtf8Of1232BytesMax\n | OffchainMessageContentUtf8Of65535BytesMax;\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (isTextRestrictedAscii(putativeContent.text) === false) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX ||\n putativeContent.text.length === 0 ||\n isTextRestrictedAscii(putativeContent.text) === false\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is restricted ASCII with\n * _coercing_ it to the {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type. It's most\n * useful with untrusted input.\n *\n * @example\n * ```ts\n * import { offchainMessageContentRestrictedAsciiOf1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: offchainMessageContentRestrictedAsciiOf1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentRestrictedAsciiOf1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good ASCII content as a string, it's more efficient to typecast it\n * > rather than to use the {@link offchainMessageContentRestrictedAsciiOf1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n * > text: 'Hello world',\n * > } as OffchainMessageContentRestrictedAsciiOf1232BytesMax<'Hello world'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentRestrictedAsciiOf1232BytesMax(\n text: TText,\n): OffchainMessageContentRestrictedAsciiOf1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n });\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of1232BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of1232BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of1232BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_1232_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 1232 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of1232BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of1232BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of1232BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of1232BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 1232 bytes, it's more efficient\n * > to typecast it rather than to use the {@link offchainMessageContentUtf8Of1232BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of1232BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of1232BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of1232BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_1232_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent);\n return putativeContent;\n}\n\n/**\n * In the event that you receive content of a v0 offchain message from an untrusted source, use this\n * function to assert that it conforms to the {@link OffchainMessageContentUtf8Of65535BytesMax}\n * type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): asserts putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {\n actualMessageFormat: putativeContent.format,\n expectedMessageFormat: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n });\n }\n if (putativeContent.text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n if (length > MAX_BODY_BYTES) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {\n actualBytes: length,\n maxBytes: MAX_BODY_BYTES,\n });\n }\n}\n\n/**\n * A type guard that returns `true` when supplied content of a v0 offchain message that conforms to\n * the {@link OffchainMessageContentUtf8Of65535BytesMax} type, and refines its type for use in your\n * program.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function isOffchainMessageContentUtf8Of65535BytesMax(putativeContent: {\n format: OffchainMessageContentFormat;\n text: string;\n}): putativeContent is OffchainMessageContentUtf8Of65535BytesMax {\n if (\n putativeContent.format !== OffchainMessageContentFormat.UTF8_65535_BYTES_MAX ||\n putativeContent.text.length === 0\n ) {\n return false;\n }\n const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);\n return length <= MAX_BODY_BYTES;\n}\n\n/**\n * Combines _asserting_ that the content of a v0 offchain message is UTF-8 of up to 65535 characters\n * with _coercing_ it to the {@link OffchainMessageContentUtf8Of65535BytesMax} type. It's most useful\n * with untrusted input.\n *\n * @example\n * ```ts\n * import { OffchainMessageContentUtf8Of65535BytesMax, OffchainMessageV0 } from '@solana/offchain-messages';\n *\n * function handleSubmit() {\n * // We know only that what the user typed conforms to the `string` type.\n * const text: string = textInput.value;\n * try {\n * const offchainMessage: OffchainMessageV0 = {\n * content: OffchainMessageContentUtf8Of65535BytesMax(text),\n * // ...\n * };\n * } catch (e) {\n * // `text` turned out not to conform to\n * // `OffchainMessageContentUtf8Of65535BytesMax`\n * }\n * }\n * ```\n *\n * > [!TIP]\n * > When starting from known-good UTF-8 content as a string up to 65535 bytes, it's more efficient\n * > to typecast it rather than to use the {@link OffchainMessageContentUtf8Of65535BytesMax} helper,\n * > because the helper unconditionally performs validation on its input.\n * >\n * > ```ts\n * > import { OffchainMessageContentFormat, OffchainMessageV0 } from '@solana/offchain-messages';\n * >\n * > const offchainMessage: OffchainMessageV0 = {\n * > /* ... *\\/\n * > content: Object.freeze({\n * > format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n * > text: '✌🏿cool',\n * > } as OffchainMessageContentUtf8Of65535BytesMax<'✌🏿cool'>),\n * > };\n * > ```\n */\nexport function offchainMessageContentUtf8Of65535BytesMax(\n text: TText,\n): OffchainMessageContentUtf8Of65535BytesMax {\n const putativeContent = Object.freeze({\n format: OffchainMessageContentFormat.UTF8_65535_BYTES_MAX,\n text,\n });\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent);\n return putativeContent;\n}\n\nfunction isTextRestrictedAscii(putativeRestrictedAsciiString: string): boolean {\n return /^[\\x20-\\x7e]+$/.test(putativeRestrictedAsciiString);\n}\n","import {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageContentUtf8Of1232BytesMax,\n assertIsOffchainMessageContentUtf8Of65535BytesMax,\n OffchainMessageContentFormat,\n OffchainMessageContentRestrictedAsciiOf1232BytesMax,\n OffchainMessageContentUtf8Of1232BytesMax,\n OffchainMessageContentUtf8Of65535BytesMax,\n} from './content';\nimport { OffchainMessagePreambleV0 } from './preamble-v0';\nimport { OffchainMessageWithRequiredSignatories } from './signatures';\n\nexport type BaseOffchainMessageV0 = Omit<\n OffchainMessagePreambleV0,\n 'messageFormat' | 'messageLength' | 'requiredSignatories'\n>;\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax}\n */\nexport interface OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent {\n readonly content: OffchainMessageContentRestrictedAsciiOf1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link offchainMessageContentUtf8Of1232BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of1232BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of1232BytesMax;\n}\n\n/**\n * An offchain message whose content conforms to\n * {@link OffchainMessageContentUtf8Of65535BytesMax}\n */\nexport interface OffchainMessageWithUtf8Of65535BytesMaxContent {\n readonly content: OffchainMessageContentUtf8Of65535BytesMax;\n}\n\n/**\n * A union of the formats a v0 message's contents can take.\n *\n * @remarks From v1 and onward, an offchain message has only one format: UTF-8 text of arbitrary\n * length.\n */\nexport type OffchainMessageWithContent =\n | OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent\n | OffchainMessageWithUtf8Of1232BytesMaxContent\n | OffchainMessageWithUtf8Of65535BytesMaxContent;\n\nexport type OffchainMessageV0 = BaseOffchainMessageV0 &\n OffchainMessageWithContent &\n OffchainMessageWithRequiredSignatories;\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} type.\n *\n * @see {@link OffchainMessageContentRestrictedAsciiOf1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }>,\n): asserts putativeMessage is OffchainMessageWithRestrictedAsciiOf1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link offchainMessageContentUtf8Of1232BytesMax} type.\n *\n * @see {@link offchainMessageContentUtf8Of1232BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of1232BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of1232BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeMessage.content);\n}\n\n/**\n * In the event that you receive a v0 offchain message from an untrusted source, use this function\n * to assert that it is one whose content conforms to the\n * {@link OffchainMessageContentUtf8Of65535BytesMax} type.\n *\n * @see {@link OffchainMessageContentUtf8Of65535BytesMax} for more detail.\n */\nexport function assertIsOffchainMessageUtf8Of65535BytesMax(\n putativeMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n version: number;\n }>,\n): asserts putativeMessage is OffchainMessageWithUtf8Of65535BytesMaxContent & Omit {\n assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeMessage.content);\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\nimport { getEnumDecoder, getEnumEncoder } from '@solana/codecs-data-structures';\n\nimport { OffchainMessageContentFormat } from '../content';\n\nexport function getOffchainMessageContentFormatDecoder(): FixedSizeDecoder {\n return getEnumDecoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatEncoder(): FixedSizeEncoder {\n return getEnumEncoder(OffchainMessageContentFormat, {\n useValuesAsDiscriminators: true,\n });\n}\n\nexport function getOffchainMessageContentFormatCodec(): FixedSizeCodec<\n OffchainMessageContentFormat,\n OffchainMessageContentFormat,\n 1\n> {\n return combineCodec(getOffchainMessageContentFormatEncoder(), getOffchainMessageContentFormatDecoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder, getU16Decoder, getU16Encoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO, SolanaError } from '@solana/errors';\n\nimport { OffchainMessagePreambleV0 } from '../preamble-v0';\nimport {\n getOffchainMessageApplicationDomainDecoder,\n getOffchainMessageApplicationDomainEncoder,\n} from './application-domain';\nimport { getOffchainMessageContentFormatDecoder, getOffchainMessageContentFormatEncoder } from './content';\nimport { createOffchainMessagePreambleDecoder, createOffchainMessagePreambleEncoder } from './preamble-common';\n\nexport function getOffchainMessageV0PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainDecoder()],\n ['messageFormat', getOffchainMessageContentFormatDecoder()],\n [\n 'requiredSignatories',\n transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), signatoryAddresses => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(address => Object.freeze({ address }));\n }),\n ],\n ['messageLength', getU16Decoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(\n /* version */ 0,\n ['applicationDomain', getOffchainMessageApplicationDomainEncoder()],\n ['messageFormat', getOffchainMessageContentFormatEncoder()],\n [\n 'requiredSignatories',\n transformEncoder(\n getArrayEncoder(getAddressEncoder(), { size: getU8Encoder() }),\n (signatoryAddresses: OffchainMessagePreambleV0['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n return signatoryAddresses.map(({ address }) => address);\n },\n ),\n ],\n ['messageLength', getU16Encoder()],\n );\n}\n\nexport function getOffchainMessageV0PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0PreambleEncoder(), getOffchainMessageV0PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessageContentFormat } from '../content';\nimport {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax,\n assertIsOffchainMessageUtf8Of1232BytesMax,\n assertIsOffchainMessageUtf8Of65535BytesMax,\n OffchainMessageV0,\n} from '../message-v0';\nimport { getOffchainMessageV0PreambleDecoder, getOffchainMessageV0PreambleEncoder } from './preamble-v0';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV0} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV0Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV0Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v0 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 0.\n */\nexport function getOffchainMessageV0Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV0PreambleDecoder(), getUtf8Decoder()]),\n ([{ messageLength, messageFormat, requiredSignatories, ...preambleRest }, text]) => {\n const actualLength = getUtf8Encoder().getSizeFromValue(text);\n if (messageLength !== actualLength) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH, {\n actualLength: actualLength,\n specifiedLength: messageLength,\n });\n }\n const offchainMessage: Omit &\n Readonly<{\n content: {\n format: OffchainMessageContentFormat;\n text: string;\n };\n }> = Object.freeze({\n ...preambleRest,\n content: Object.freeze({\n format: messageFormat,\n text,\n }),\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n switch (messageFormat) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n return offchainMessage;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n return offchainMessage;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: messageFormat satisfies never,\n });\n }\n }\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV0} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV0Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV0PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...preamble } = offchainMessage;\n switch (offchainMessage.content.format) {\n case OffchainMessageContentFormat.RESTRICTED_ASCII_1232_BYTES_MAX: {\n assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_1232_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);\n break;\n }\n case OffchainMessageContentFormat.UTF8_65535_BYTES_MAX: {\n assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);\n break;\n }\n default: {\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: offchainMessage.content satisfies never,\n });\n }\n }\n const messageLength = getUtf8Encoder().getSizeFromValue(content.text);\n const compiledPreamble = {\n ...preamble,\n messageFormat: content.format,\n messageLength,\n };\n return [compiledPreamble, content.text] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV0}\n *\n * @see {@link getOffchainMessageV0Decoder}\n * @see {@link getOffchainMessageV0Encoder}\n */\nexport function getOffchainMessageV0Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV0Encoder(), getOffchainMessageV0Decoder());\n}\n","import { getAddressDecoder, getAddressEncoder } from '@solana/addresses';\nimport {\n combineCodec,\n fixDecoderSize,\n ReadonlyUint8Array,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getArrayDecoder, getArrayEncoder, getBytesDecoder, getBytesEncoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder, getU8Encoder } from '@solana/codecs-numbers';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,\n SolanaError,\n} from '@solana/errors';\n\nimport { OffchainMessagePreambleV1 } from '../preamble-v1';\nimport {\n createOffchainMessagePreambleDecoder,\n createOffchainMessagePreambleEncoder,\n getSignatoriesComparator,\n} from './preamble-common';\n\nexport function getOffchainMessageV1PreambleDecoder(): VariableSizeDecoder {\n return createOffchainMessagePreambleDecoder(/* version */ 1, [\n 'requiredSignatories',\n transformDecoder(\n getArrayDecoder(fixDecoderSize(getBytesDecoder(), 32), { size: getU8Decoder() }),\n signatoryAddressesBytes => {\n if (signatoryAddressesBytes.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const comparator = getSignatoriesComparator();\n for (let ii = 0; ii < signatoryAddressesBytes.length - 1; ii++) {\n switch (comparator(signatoryAddressesBytes[ii], signatoryAddressesBytes[ii + 1])) {\n case 0:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n case 1:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED);\n }\n }\n const addressDecoder = getAddressDecoder();\n return signatoryAddressesBytes.map(addressBytes =>\n Object.freeze({\n address: addressDecoder.decode(addressBytes),\n }),\n );\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleEncoder(): VariableSizeEncoder {\n return createOffchainMessagePreambleEncoder(/* version */ 1, [\n 'requiredSignatories',\n transformEncoder(\n transformEncoder(\n getArrayEncoder(getBytesEncoder(), { size: getU8Encoder() }),\n (signatoryAddressesBytes: readonly ReadonlyUint8Array[]) => {\n return signatoryAddressesBytes.toSorted(getSignatoriesComparator());\n },\n ),\n (signatoryAddresses: OffchainMessagePreambleV1['requiredSignatories']) => {\n if (signatoryAddresses.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);\n }\n const seenSignatories = new Set();\n for (const { address } of signatoryAddresses) {\n if (seenSignatories.has(address)) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);\n }\n seenSignatories.add(address);\n }\n const addressEncoder = getAddressEncoder();\n return signatoryAddresses.map(({ address }) => addressEncoder.encode(address));\n },\n ),\n ]);\n}\n\nexport function getOffchainMessageV1PreambleCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1PreambleEncoder(), getOffchainMessageV1PreambleDecoder());\n}\n","import {\n combineCodec,\n transformDecoder,\n transformEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getTupleDecoder, getTupleEncoder } from '@solana/codecs-data-structures';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY, SolanaError } from '@solana/errors';\n\nimport { OffchainMessageV1 } from '../message-v1';\nimport { getOffchainMessageV1PreambleDecoder, getOffchainMessageV1PreambleEncoder } from './preamble-v1';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessageV1} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageV1Decoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageV1Decoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded a v1 offchain message`);\n * ```\n *\n * Throws in the event that the message bytes represent a message of a version other than 1.\n */\nexport function getOffchainMessageV1Decoder(): VariableSizeDecoder {\n return transformDecoder(\n getTupleDecoder([getOffchainMessageV1PreambleDecoder(), getUtf8Decoder()]),\n ([{ requiredSignatories, ...preambleRest }, text]) => {\n if (text.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return Object.freeze({\n ...preambleRest,\n content: text,\n requiredSignatories: Object.freeze(requiredSignatories),\n });\n },\n );\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessageV1} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n */\nexport function getOffchainMessageV1Encoder(): VariableSizeEncoder {\n return transformEncoder(\n getTupleEncoder([getOffchainMessageV1PreambleEncoder(), getUtf8Encoder()]),\n offchainMessage => {\n const { content, ...compiledPreamble } = offchainMessage;\n if (content.length === 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);\n }\n return [compiledPreamble, content] as const;\n },\n );\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessageV1}\n *\n * @see {@link getOffchainMessageV1Decoder}\n * @see {@link getOffchainMessageV1Encoder}\n */\nexport function getOffchainMessageV1Codec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageV1Encoder(), getOffchainMessageV1Decoder());\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport { getHiddenPrefixDecoder } from '@solana/codecs-data-structures';\nimport { getU8Decoder } from '@solana/codecs-numbers';\nimport { SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, SolanaError } from '@solana/errors';\n\nimport { OffchainMessage } from '../message';\nimport { getOffchainMessageV0Decoder, getOffchainMessageV0Encoder } from './message-v0';\nimport { getOffchainMessageV1Decoder, getOffchainMessageV1Encoder } from './message-v1';\nimport { getOffchainMessageSigningDomainDecoder } from './signing-domain';\n\n/**\n * Returns a decoder that you can use to convert a byte array (eg. one that conforms to the\n * {@link OffchainMessageBytes} type) to an {@link OffchainMessage} object.\n *\n * @example\n * ```ts\n * import { getOffchainMessageDecoder } from '@solana/offchain-messages';\n *\n * const offchainMessageDecoder = getOffchainMessageDecoder();\n * const offchainMessage = offchainMessageDecoder.decode(\n * offchainMessageEnvelope.content,\n * );\n * console.log(`Decoded an offchain message (version: ${offchainMessage.version}`);\n * ```\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the decoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageDecoder(): VariableSizeDecoder {\n return createDecoder({\n read(bytes, offset): [OffchainMessage, number] {\n const version = getHiddenPrefixDecoder(getU8Decoder(), [\n // Discard the signing domain\n getOffchainMessageSigningDomainDecoder(),\n ]).decode(bytes, offset);\n switch (version) {\n case 0:\n return getOffchainMessageV0Decoder().read(bytes, offset);\n case 1:\n return getOffchainMessageV1Decoder().read(bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version,\n });\n }\n },\n });\n}\n\n/**\n * Returns an encoder that you can use to encode an {@link OffchainMessage} to a byte array\n * appropriate for inclusion in an {@link OffchainMessageEnvelope}.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the encoders specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageEncoder(): VariableSizeEncoder {\n return createEncoder({\n getSizeFromValue: offchainMessage => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().getSizeFromValue(offchainMessage);\n case 1:\n return getOffchainMessageV1Encoder().getSizeFromValue(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n write: (offchainMessage, bytes, offset) => {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return getOffchainMessageV0Encoder().write(offchainMessage, bytes, offset);\n case 1:\n return getOffchainMessageV1Encoder().write(offchainMessage, bytes, offset);\n default:\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {\n unsupportedVersion: version satisfies never,\n });\n }\n },\n });\n}\n\n/**\n * Returns a codec that you can use to encode from or decode to an {@link OffchainMessage}\n *\n * @see {@link getOffchainMessageDecoder}\n * @see {@link getOffchainMessageEncoder}\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the codecs specific to that\n * version so as not to bundle more code than you need.\n */\nexport function getOffchainMessageCodec(): VariableSizeCodec {\n return combineCodec(getOffchainMessageEncoder(), getOffchainMessageDecoder());\n}\n","import { VariableSizeEncoder } from '@solana/codecs-core';\n\nimport { OffchainMessageEnvelope } from './envelope';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\nexport function compileOffchainMessageEnvelopeUsingEncoder(\n offchainMessage: T,\n encoder: VariableSizeEncoder,\n) {\n const offchainMessageBytes = encoder.encode(offchainMessage) as OffchainMessageBytes;\n const signatures: OffchainMessageEnvelope['signatures'] = {};\n for (const { address } of offchainMessage.requiredSignatories) {\n signatures[address] = null;\n }\n return Object.freeze({\n content: offchainMessageBytes,\n signatures: Object.freeze(signatures),\n });\n}\n","import { getOffchainMessageV0Encoder } from './codecs/message-v0';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV0 } from './message-v0';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV0}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV0Envelope(offchainMessage: OffchainMessageV0): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV0Encoder());\n}\n","import { getOffchainMessageV1Encoder } from './codecs/message-v1';\nimport { OffchainMessageEnvelope } from './envelope';\nimport { compileOffchainMessageEnvelopeUsingEncoder } from './envelope-common';\nimport { OffchainMessageV1 } from './message-v1';\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessageV1}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n */\nexport function compileOffchainMessageV1Envelope(offchainMessage: OffchainMessageV1): OffchainMessageEnvelope {\n return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV1Encoder());\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\n\nimport { compileOffchainMessageV0Envelope } from './envelope-v0';\nimport { compileOffchainMessageV1Envelope } from './envelope-v1';\nimport { OffchainMessage, OffchainMessageBytes } from './message';\n\ntype OrderedMap = Record;\ntype OffchainMessageSignaturesMap = OrderedMap;\n\nexport interface OffchainMessageEnvelope {\n /** The bytes of the combined offchain message preamble and content */\n readonly content: OffchainMessageBytes;\n /**\n * A map between the addresses of an offchain message's signers, and the 64-byte Ed25519\n * signature of the combined message preamble and message content by the private key associated\n * with each.\n */\n readonly signatures: OffchainMessageSignaturesMap;\n}\n\n/**\n * Returns an {@link OffchainMessageEnvelope} object for a given {@link OffchainMessage}.\n *\n * This includes the compiled bytes of the offchain message, and a map of signatures. This map will\n * have a key for each address that is required to sign the message. The message envelope will not\n * yet have signatures for any of these signatories.\n *\n * @remarks\n * If the offchain message version is known ahead of time, use one of the compile functions\n * specific to that version so as not to bundle more code than you need.\n */\nexport function compileOffchainMessageEnvelope(offchainMessage: OffchainMessage): OffchainMessageEnvelope {\n const { version } = offchainMessage;\n switch (version) {\n case 0:\n return compileOffchainMessageV0Envelope(offchainMessage);\n case 1:\n return compileOffchainMessageV1Envelope(offchainMessage);\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {\n unexpectedValue: version satisfies never,\n });\n }\n}\n","import { Address, getAddressFromPublicKey, getPublicKeyFromAddress } from '@solana/addresses';\nimport { bytesEqual } from '@solana/codecs-core';\nimport {\n SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,\n SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { SignatureBytes, signBytes, verifySignature } from '@solana/keys';\nimport { NominalType } from '@solana/nominal-types';\n\nimport { decodeRequiredSignatoryAddresses } from './codecs/preamble-common';\nimport { OffchainMessageEnvelope } from './envelope';\n\n/**\n * Represents an offchain message envelope that is signed by all of its required signers.\n */\nexport type FullySignedOffchainMessageEnvelope = NominalType<'offchainMessageEnvelopeSignedness', 'fullySigned'>;\n\n/**\n * Represents an address that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatory = Readonly<{\n address: Address;\n}>;\n\n/**\n * An offchain message having a list of accounts that must sign it in order for it to be valid.\n */\nexport interface OffchainMessageWithRequiredSignatories<\n TSignatory extends OffchainMessageSignatory = OffchainMessageSignatory,\n> {\n requiredSignatories: readonly TSignatory[];\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message, this method will return a new signed offchain message\n * envelope of type {@link OffchainMessageEnvelope}.\n *\n * Though the resulting message might be signed by all required signers, this function will not\n * assert that it is. A partially signed message is not complete, but can be serialized and\n * deserialized.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { partiallySignOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const partiallySignedOffchainMessage = await partiallySignOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link signOffchainMessageEnvelope} if you want to assert that the message is signed by all\n * its required signers after signing.\n */\nexport async function partiallySignOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n let newSignatures: Record | undefined;\n let unexpectedSigners: Set
| undefined;\n\n const requiredSignatoryAddresses = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n\n await Promise.all(\n keyPairs.map(async keyPair => {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n\n // Check if the address is expected to sign the message\n if (!requiredSignatoryAddresses.includes(address)) {\n // address is not an expected signer for this message\n unexpectedSigners ||= new Set();\n unexpectedSigners.add(address);\n return;\n }\n\n // Return if there are any unexpected signers already since we won't be using signatures\n if (unexpectedSigners) {\n return;\n }\n\n const existingSignature = offchainMessageEnvelope.signatures[address];\n const newSignature = await signBytes(keyPair.privateKey, offchainMessageEnvelope.content);\n\n if (existingSignature != null && bytesEqual(newSignature, existingSignature)) {\n // already have the same signature set\n return;\n }\n\n newSignatures ||= {};\n newSignatures[address] = newSignature;\n }),\n );\n\n if (unexpectedSigners && unexpectedSigners.size > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE, {\n expectedAddresses: requiredSignatoryAddresses,\n unexpectedAddresses: [...unexpectedSigners],\n });\n }\n\n if (!newSignatures) {\n return offchainMessageEnvelope;\n }\n\n return Object.freeze({\n ...offchainMessageEnvelope,\n signatures: Object.freeze({\n ...offchainMessageEnvelope.signatures,\n ...newSignatures,\n }),\n });\n}\n\n/**\n * Given an array of `CryptoKey` objects which are private keys pertaining to addresses that are\n * required to sign an offchain message envelope, this method will return a new signed envelope of\n * type {@link FullySignedOffchainMessageEnvelope}.\n *\n * This function will throw unless the resulting message is fully signed.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { signOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const signedOffchainMessage = await signOffchainMessageEnvelope(\n * [myPrivateKey],\n * offchainMessageEnvelope,\n * );\n * ```\n *\n * @see {@link partiallySignOffchainMessageEnvelope} if you want to sign the message without\n * asserting that the resulting message envelope is fully signed.\n */\nexport async function signOffchainMessageEnvelope(\n keyPairs: CryptoKeyPair[],\n offchainMessageEnvelope: TOffchainMessageEnvelope,\n): Promise {\n const out = await partiallySignOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope);\n assertIsFullySignedOffchainMessageEnvelope(out);\n Object.freeze(out);\n return out;\n}\n\n/**\n * A type guard that returns `true` if the input {@link OffchainMessageEnvelope} is fully signed,\n * and refines its type for use in your program, adding the\n * {@link FullySignedOffchainMessageEnvelope} type.\n *\n * @example\n * ```ts\n * import { isFullySignedOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * if (isFullySignedOffchainMessageEnvelope(offchainMessageEnvelope)) {\n * // At this point we know that the offchain message is fully signed.\n * }\n * ```\n */\nexport function isFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n return Object.entries(offchainMessage.signatures).every(([_, signatureBytes]) => !!signatureBytes);\n}\n\n/**\n * From time to time you might acquire a {@link OffchainMessageEnvelope}, that you expect to be\n * fully signed, from an untrusted network API or user input. Use this function to assert that such\n * an offchain message is fully signed.\n *\n * @example\n * ```ts\n * import { assertIsFullySignedOffchainMessage } from '@solana/offchain-messages';\n *\n * const offchainMessageEnvelope = getOffchainMessageDecoder().decode(offchainMessageBytes);\n * try {\n * // If this type assertion function doesn't throw, then Typescript will upcast\n * // `offchainMessageEnvelope` to `FullySignedOffchainMessageEnvelope`.\n * assertIsFullySignedOffchainMessageEnvelope(offchainMessage);\n * // At this point we know that the offchain message is signed by all required signers.\n * } catch(e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING)) {\n * setError(`Missing signatures for ${e.context.addresses.join(', ')}`);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function assertIsFullySignedOffchainMessageEnvelope(\n offchainMessage: TEnvelope,\n): asserts offchainMessage is FullySignedOffchainMessageEnvelope & TEnvelope {\n const missingSigs: Address[] = [];\n Object.entries(offchainMessage.signatures).forEach(([address, signatureBytes]) => {\n if (!signatureBytes) {\n missingSigs.push(address as Address);\n }\n });\n\n if (missingSigs.length > 0) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, {\n addresses: missingSigs,\n });\n }\n}\n\n/**\n * Asserts that there are signatures present for all of an offchain message's required signatories,\n * and that those signatures are valid given the message.\n *\n * @example\n * ```ts\n * import { isSolanaError, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE } from '@solana/errors';\n * import { verifyOffchainMessageEnvelope } from '@solana/offchain-messages';\n *\n * try {\n * await verifyOffchainMessageEnvelope(offchainMessageEnvelope);\n * // At this point the message is valid and signed by all of the required signatories.\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE)) {\n * if (e.context.signatoriesWithMissingSignatures.length) {\n * console.error(\n * 'Missing signatures for the following addresses',\n * e.context.signatoriesWithMissingSignatures,\n * );\n * }\n * if (e.context.signatoriesWithInvalidSignatures.length) {\n * console.error(\n * 'Signatures for the following addresses are invalid',\n * e.context.signatoriesWithInvalidSignatures,\n * );\n * }\n * }\n * throw e;\n * }\n */\nexport async function verifyOffchainMessageEnvelope(offchainMessageEnvelope: OffchainMessageEnvelope): Promise {\n let errorContext;\n const requiredSignatories = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);\n await Promise.all(\n requiredSignatories.map(async address => {\n const signature = offchainMessageEnvelope.signatures[address];\n if (signature == null) {\n errorContext ||= {};\n errorContext.signatoriesWithMissingSignatures ||= [];\n errorContext.signatoriesWithMissingSignatures.push(address);\n } else {\n const publicKey = await getPublicKeyFromAddress(address);\n if (await verifySignature(publicKey, signature, offchainMessageEnvelope.content)) {\n return true;\n } else {\n errorContext ||= {};\n errorContext.signatoriesWithInvalidSignatures ||= [];\n errorContext.signatoriesWithInvalidSignatures.push(address);\n }\n }\n }),\n );\n if (errorContext) {\n throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, errorContext);\n }\n}\n","/**\n * Defines a plugin that transforms or extends a client with additional functionality.\n *\n * For instance, plugins may add RPC capabilities, wallet integration, transaction building,\n * or other features necessary for interacting with the Solana blockchain.\n *\n * Plugins are functions that take a client object as input and return a new client object\n * or a promise that resolves to a new client object. This allows for both synchronous\n * and asynchronous transformations and extensions of the client.\n *\n * Plugins are usually applied using the `use` method on a {@link Client} or {@link AsyncClient}\n * instance, which {@link createEmptyClient} provides as a starting point.\n *\n * @typeParam TInput - The input client object type that this plugin accepts.\n * @typeParam TOutput - The output type. Either a new client object or a promise resolving to one.\n *\n * @example Basic RPC plugin\n * Given an RPC endpoint, this plugin adds an `rpc` property to the client.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc } from '@solana/kit';\n *\n * // Define a simple RPC plugin.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n *\n * // Use the plugin.\n * const client = createEmptyClient().use(rpcPlugin('https://api.mainnet-beta.solana.com'));\n * await client.rpc.getLatestBlockhash().send();\n * ```\n *\n * @example Async plugin that generates a payer wallet\n * The following plugin shows how to create an asynchronous plugin that generates a new keypair signer.\n *\n * ```ts\n * import { createEmptyClient, generateKeypairSigner } from '@solana/kit';\n *\n * // Define a plugin that generates a new keypair signer.\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n *\n * // Use the plugin.\n * const client = await createEmptyClient().use(generatedPayerPlugin());\n * console.log(client.payer.address);\n * ```\n *\n * @example Plugins with input requirements\n * A plugin can specify required properties on the input client. The example below requires the\n * client to already have a `payer` signer attached to the client in order to perform an airdrop.\n *\n * ```ts\n * import { createEmptyClient, TransactionSigner, Lamports, lamports } from '@solana/kit';\n *\n * // Define a plugin that airdrops lamports to the payer set on the client.\n * function airdropPayerPlugin(lamports: Lamports) {\n * return async (client: T) => {\n * await myAirdropFunction(client.payer, lamports);\n * return client;\n * };\n * }\n *\n * // Use the plugins.\n * const client = await createEmptyClient()\n * .use(generatedPayerPlugin()) // This is required before using the airdrop plugin.\n * .use(airdropPayerPlugin(lamports(1_000_000_000n)));\n * ```\n *\n * @example Chaining plugins\n * Multiple plugins — asynchronous or not — can be chained together to build up complex clients.\n * The example below demonstrates how to gradually build a client with multiple plugins.\n * Notice how, despite having multiple asynchronous plugins, we only need to `await` the final result.\n * This is because the `use` method on `AsyncClient` returns another `AsyncClient`, allowing for seamless chaining.\n *\n * ```ts\n * import { createEmptyClient, createSolanaRpc, createSolanaRpcSubscriptions, generateKeypairSigner } from '@solana/kit';\n *\n * // Define multiple plugins.\n * function rpcPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpc(endpoint) });\n * }\n * function rpcSubscriptionsPlugin(endpoint: string) {\n * return (client: T) => ({...client, rpc: createSolanaRpcSubscriptions(endpoint) });\n * }\n * function generatedPayerPlugin() {\n * return async (client: T) => ({...client, payer: await generateKeypairSigner() });\n * }\n * function generatedAuthorityPlugin() {\n * return async (client: T) => ({...client, authority: await generateKeypairSigner() });\n * }\n *\n * // Chain plugins together.\n * const client = await createEmptyClient()\n * .use(rpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(rpcSubscriptionsPlugin('wss://api.mainnet-beta.solana.com'))\n * .use(generatedPayerPlugin())\n * .use(generatedAuthorityPlugin());\n * ```\n */\nexport type ClientPlugin | object> = (input: TInput) => TOutput;\n\n/**\n * A client that can be extended with plugins.\n *\n * The `Client` type represents a client object that can be built up through\n * the application of one or more plugins. It provides a `use` method to\n * apply plugins, either synchronously (returning a new `Client`) or\n * asynchronously (returning an {@link AsyncClient}).\n *\n * @typeParam TSelf - The current shape of the client object including all applied plugins.\n */\nexport type Client = TSelf & {\n /**\n * Applies a plugin to extend or transform the client.\n *\n * @param plugin The plugin function to apply to this client.\n * @returns Either a new `Client` (for sync plugins) or {@link AsyncClient} (for async plugins).\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => TOutput extends Promise ? AsyncClient : Client;\n};\n\n/**\n * An asynchronous wrapper that represents a promise of a client.\n *\n * The `AsyncClient` type is returned when an async plugin is applied to a client.\n * It behaves like a `Promise>` but with an additional `use` method\n * that allows chaining more plugins before the promise resolves.\n *\n * This enables fluent chaining of both synchronous and asynchronous plugins\n * without having to await intermediate promises.\n *\n * @typeParam TSelf - The shape of the client object that this async client will resolve to.\n */\nexport type AsyncClient = Promise> & {\n /**\n * Applies a plugin to the client once it resolves.\n *\n * @param plugin The plugin function to apply to the resolved client.\n * @returns A new `AsyncClient` representing the result of applying the plugin.\n */\n readonly use: | object>(\n plugin: ClientPlugin,\n ) => AsyncClient ? (U extends object ? U : never) : TOutput>;\n};\n\n// TODO(loris): Add examples in this docblock using real plugins once they have been published.\n\n/**\n * Creates a new empty client that can be extended with plugins.\n *\n * This serves as an entry point for building Solana clients.\n * Start with an empty client and chain the `.use()` method\n * to apply plugins that add various functionalities such as RPC\n * connectivity, wallet integration, transaction building, and more.\n *\n * See {@link ClientPlugin} for detailed examples on creating and using plugins.\n *\n * @returns An empty client object with only the `use` method available.\n *\n * @example Basic client setup\n * ```ts\n * import { createEmptyClient } from '@solana/client';\n *\n * const client = createEmptyClient()\n * .use(myRpcPlugin('https://api.mainnet-beta.solana.com'))\n * .use(myWalletPlugin());\n * ```\n */\nexport function createEmptyClient(): Client {\n return addUse({});\n}\n\nfunction addUse(value: TSelf): Client {\n return Object.freeze({\n ...value,\n use | object>(plugin: ClientPlugin) {\n const result = plugin(value);\n return result instanceof Promise ? createAsyncClient(result) : addUse(result);\n },\n } as Client);\n}\n\nfunction createAsyncClient(promise: Promise): AsyncClient {\n return Object.freeze({\n catch(onrejected) {\n return promise.then(v => addUse(v)).catch(onrejected);\n },\n finally(onfinally) {\n return promise.then(v => addUse(v)).finally(onfinally);\n },\n then(onfulfilled, onrejected) {\n return promise.then(v => addUse(v)).then(onfulfilled, onrejected);\n },\n use | object>(plugin: ClientPlugin) {\n return createAsyncClient(promise.then(plugin));\n },\n } as AsyncClient);\n}\n","import type { Address } from '@solana/addresses';\nimport { isSolanaError, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SolanaError } from '@solana/errors';\n\n/**\n * Identifies whether an error -- typically caused by a transaction failure -- is a custom program\n * error from the provided program address.\n *\n * @param transactionMessage The transaction message that failed to execute. Since the RPC response\n * only provides the index of the failed instruction, the transaction message is required to\n * determine its program address\n * @param programAddress The address of the program from which the error is expected to have\n * originated\n * @param code The expected error code of the custom program error. When provided, the function will\n * check that the custom program error code matches the given value.\n *\n * @example\n * ```ts\n * try {\n * // Send and confirm your transaction.\n * } catch (error) {\n * if (isProgramError(error, transactionMessage, myProgramAddress, 42)) {\n * // Handle custom program error 42 from this program.\n * } else if (isProgramError(error, transactionMessage, myProgramAddress)) {\n * // Handle all other custom program errors from this program.\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isProgramError(\n error: unknown,\n transactionMessage: { instructions: Record },\n programAddress: Address,\n code?: TProgramErrorCode,\n): error is Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> &\n SolanaError {\n if (!isSolanaError(error, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM)) {\n return false;\n }\n const instructionProgramAddress = transactionMessage.instructions[error.context.index]?.programAddress;\n if (!instructionProgramAddress || instructionProgramAddress !== programAddress) {\n return false;\n }\n return typeof code === 'undefined' || error.context.code === code;\n}\n","/**\n * This function is a replacement for `JSON.parse` that can handle large\n * unsafe integers by parsing them as BigInts. It transforms every\n * numerical value into a BigInt without loss of precision.\n */\nexport function parseJsonWithBigInts(json: string): unknown {\n return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {\n return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;\n });\n}\n\nfunction wrapIntegersInBigIntValueObject(json: string): string {\n const out = [];\n let inQuote = false;\n for (let ii = 0; ii < json.length; ii++) {\n let isEscaped = false;\n if (json[ii] === '\\\\') {\n out.push(json[ii++]);\n isEscaped = !isEscaped;\n }\n if (json[ii] === '\"') {\n out.push(json[ii]);\n if (!isEscaped) {\n inQuote = !inQuote;\n }\n continue;\n }\n if (!inQuote) {\n const consumedNumber = consumeNumber(json, ii);\n if (consumedNumber?.length) {\n ii += consumedNumber.length - 1;\n // Don't wrap numbers that contain a decimal point or a negative exponent.\n if (consumedNumber.match(/\\.|[eE]-/)) {\n out.push(consumedNumber);\n } else {\n out.push(wrapBigIntValueObject(consumedNumber));\n }\n continue;\n }\n }\n out.push(json[ii]);\n }\n\n return out.join('');\n}\n\nfunction consumeNumber(json: string, ii: number): string | null {\n /** @see https://stackoverflow.com/a/13340826/11440277 */\n const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/;\n\n // Stop early if the first character isn't a digit or a minus sign.\n if (!json[ii]?.match(/[-\\d]/)) {\n return null;\n }\n\n // Otherwise, check if the next characters form a valid JSON number.\n const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);\n return numberMatch ? numberMatch[0] : null;\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: string): string {\n return `{\"$n\":\"${value}\"}`;\n}\n\nfunction unwrapBigIntValueObject({ $n }: BigIntValueObject): bigint {\n if ($n.match(/[eE]/)) {\n const [units, exponent] = $n.split(/[eE]/);\n return BigInt(units) * BigInt(10) ** BigInt(exponent);\n }\n return BigInt($n);\n}\n\nfunction isBigIntValueObject(value: unknown): value is BigIntValueObject {\n return !!value && typeof value === 'object' && '$n' in value && typeof value.$n === 'string';\n}\n","import { RpcRequest } from './rpc-request';\n\nlet _nextMessageId = 0n;\nfunction getNextMessageId(): string {\n const id = _nextMessageId;\n _nextMessageId++;\n return id.toString();\n}\n\n/**\n * Returns a spec-compliant JSON RPC 2.0 message, given a method name and some params.\n *\n * Generates a new `id` on each call by incrementing a `bigint` and casting it to a string.\n */\nexport function createRpcMessage(request: RpcRequest) {\n return {\n id: getNextMessageId(),\n jsonrpc: '2.0',\n method: request.methodName,\n params: request.params,\n };\n}\n","/**\n * Transforms a value into a JSON string, whilst rendering bigints as large unsafe integers.\n */\nexport function stringifyJsonWithBigInts(value: unknown, space?: number | string): string {\n return unwrapBigIntValueObject(\n JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? wrapBigIntValueObject(v) : v), space),\n );\n}\n\ntype BigIntValueObject = {\n // `$` implies 'this is a value object'.\n // `n` implies 'interpret the value as a bigint'.\n $n: string;\n};\n\nfunction wrapBigIntValueObject(value: bigint): BigIntValueObject {\n return { $n: `${value}` };\n}\n\nfunction unwrapBigIntValueObject(value: string): string {\n return value.replace(/\\{\\s*\"\\$n\"\\s*:\\s*\"(-?\\d+)\"\\s*\\}/g, '$1');\n}\n","import { SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\n\nimport { RpcApi, RpcPlan } from './rpc-api';\nimport { RpcTransport } from './rpc-transport';\n\nexport type RpcConfig = Readonly<{\n api: RpcApi;\n transport: TRpcTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcMethods`.\n *\n * Calling each method returns a {@link PendingRpcRequest | PendingRpcRequest} where\n * `TResponse` is that method's response type.\n */\nexport type Rpc = {\n [TMethodName in keyof TRpcMethods]: PendingRpcRequestBuilder>;\n};\n\n/**\n * Pending requests are the result of calling a supported method on a {@link Rpc} object. They\n * encapsulate all of the information necessary to make the request without actually making it.\n *\n * Calling the {@link PendingRpcRequest.send | `send(options)`} method on a\n * {@link PendingRpcRequest | PendingRpcRequest} will trigger the request and return a\n * promise for `TResponse`.\n */\nexport type PendingRpcRequest = {\n send(options?: RpcSendOptions): Promise;\n};\n\nexport type RpcSendOptions = Readonly<{\n /**\n * An optional signal that you can supply when triggering a {@link PendingRpcRequest} that you\n * might later need to abort.\n */\n abortSignal?: AbortSignal;\n}>;\n\ntype PendingRpcRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TMethodImplementations]: PendingRpcRequestReturnTypeMapper;\n }>\n>;\n\ntype PendingRpcRequestReturnTypeMapper =\n // Check that this property of the TRpcMethods interface is, in fact, a function.\n TMethodImplementation extends Callable\n ? (...args: Parameters) => PendingRpcRequest>\n : never;\n\n/**\n * Creates a {@link Rpc} instance given a {@link RpcApi | RpcApi} and a\n * {@link RpcTransport} capable of fulfilling them.\n */\nexport function createRpc(\n rpcConfig: RpcConfig,\n): Rpc {\n return makeProxy(rpcConfig);\n}\n\nfunction makeProxy(\n rpcConfig: RpcConfig,\n): Rpc {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const methodName = p.toString();\n const getApiPlan = Reflect.get(target, methodName, receiver);\n if (!getApiPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {\n method: methodName,\n params: rawParams,\n });\n }\n const apiPlan = getApiPlan(...rawParams);\n return createPendingRpcRequest(rpcConfig, apiPlan);\n };\n },\n }) as Rpc;\n}\n\nfunction createPendingRpcRequest(\n { transport }: RpcConfig,\n plan: RpcPlan,\n): PendingRpcRequest {\n return {\n async send(options?: RpcSendOptions): Promise {\n return await plan.execute({ signal: options?.abortSignal, transport });\n },\n };\n}\n","import {\n Callable,\n createRpcMessage,\n RpcRequestTransformer,\n RpcResponse,\n RpcResponseTransformer,\n} from '@solana/rpc-spec-types';\n\nimport type { RpcTransport } from './rpc-transport';\n\nexport type RpcApiConfig = Readonly<{\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n /**\n * An optional function that transforms the {@link RpcResponse} before it is returned to the\n * caller.\n *\n * Use cases for this include constructing complex data types from serialized data, and throwing\n * exceptions.\n */\n responseTransformer?: RpcResponseTransformer;\n}>;\n\n/**\n * This type allows an {@link RpcApi} to describe how a particular request should be issued to the\n * JSON RPC server.\n *\n * Given a function that was called on a {@link Rpc}, this object exposes an `execute` function that\n * dictates which request will be sent, how the underlying transport will be used, and how the\n * responses will be transformed.\n *\n * This function accepts a {@link RpcTransport} and an `AbortSignal` and asynchronously returns a\n * {@link RpcResponse}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * transport.\n * - call the underlying transport zero, one or multiple times depending on the use-case (e.g.\n * caching or aggregating multiple responses).\n * - transform the response from the JSON RPC server, in case it does not match the `TResponse`\n * specified by the {@link PendingRpcRequest | PendingRpcRequest} returned from that\n * function.\n */\nexport type RpcPlan = {\n execute: (\n config: Readonly<{\n signal?: AbortSignal;\n transport: RpcTransport;\n }>,\n ) => Promise>;\n};\n\n/**\n * For each of `TRpcMethods`, this object exposes a method with the same name that maps between its\n * input arguments and a {@link RpcPlan | RpcPlan} that implements the execution of a\n * JSON RPC request to fetch `TResponse`.\n */\nexport type RpcApi = {\n [MethodName in keyof TRpcMethods]: RpcReturnTypeMapper;\n};\n\ntype RpcReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcApiMethod = (...args: any) => any;\ninterface RpcApiMethods {\n [methodName: string]: RpcApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a {@link RpcPlan} by\n * creating an `execute` function that:\n *\n * - sets the transport payload to a JSON RPC v2 payload object with the requested `methodName` and\n * `params` properties, optionally transformed by {@link RpcApiConfig.requestTransformer}.\n * - transforms the transport's response using the {@link RpcApiConfig.responseTransformer}\n * function, if provided.\n *\n * @example\n * ```ts\n * // For example, given this `RpcApi`:\n * const rpcApi = createJsonRpcApi({\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * responseTransformer: response => response.result,\n * });\n *\n * // ...the following function call:\n * rpcApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Returns the \"result\" property of the RPC response.\n * ```\n */\nexport function createJsonRpcApi(config?: RpcApiConfig): RpcApi {\n return new Proxy({} as RpcApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcMethods as string;\n return function (\n ...rawParams: Parameters<\n TRpcMethods[TMethodName] extends CallableFunction ? TRpcMethods[TMethodName] : never\n >\n ): RpcPlan> {\n const rawRequest = Object.freeze({ methodName, params: rawParams });\n const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;\n return Object.freeze(>>{\n execute: async ({ signal, transport }) => {\n const payload = createRpcMessage(request);\n const response = await transport({ payload, signal });\n if (!config?.responseTransformer) {\n return response;\n }\n return config.responseTransformer(response, request);\n },\n });\n };\n },\n });\n}\n","import { RpcResponse } from '@solana/rpc-spec-types';\n\ntype Config = Readonly<{\n /** A value of arbitrary type to be sent to a RPC server */\n payload: unknown;\n /**\n * An optional `AbortSignal` on which the `'abort'` event will be fired if the request should be\n * cancelled.\n */\n signal?: AbortSignal;\n}>;\n\n/**\n * A function that can act as a transport for a {@link Rpc}. It need only return a promise for a\n * response given the supplied config.\n */\nexport type RpcTransport = {\n (config: Config): Promise>;\n};\n\n/**\n * Returns `true` if the given payload is a JSON RPC v2 payload.\n *\n * This means, the payload is an object such that:\n *\n * - It has a `jsonrpc` property with a value of `'2.0'`.\n * - It has a `method` property that is a string.\n * - It has a `params` property of any type.\n *\n * @example\n * ```ts\n * import { isJsonRpcPayload } from '@solana/rpc-spec';\n *\n * if (isJsonRpcPayload(payload)) {\n * const payloadMethod: string = payload.method;\n * const payloadParams: unknown = payload.params;\n * }\n * ```\n */\nexport function isJsonRpcPayload(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: string;\n params: unknown;\n}> {\n if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n return (\n 'jsonrpc' in payload &&\n payload.jsonrpc === '2.0' &&\n 'method' in payload &&\n typeof payload.method === 'string' &&\n 'params' in payload\n );\n}\n","export function downcastNodeToNumberIfBigint(value: bigint): number;\nexport function downcastNodeToNumberIfBigint(value: T): T;\nexport function downcastNodeToNumberIfBigint(value: unknown): unknown {\n return typeof value === 'bigint'\n ? // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana\n // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely\n // downcasting `bigints` to `numbers`.\n Number(value)\n : value;\n}\n","import { RpcRequest, RpcRequestTransformer, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nexport type KeyPathWildcard = { readonly ['__keyPathWildcard:@solana/kit']: unique symbol };\nexport type KeyPath = ReadonlyArray;\n\nexport const KEYPATH_WILDCARD = {} as KeyPathWildcard;\n\ntype NodeVisitor = (value: unknown, state: TState) => unknown;\nexport type TraversalState = Readonly<{\n keyPath: KeyPath;\n}>;\n\nfunction getTreeWalker(visitors: NodeVisitor[]) {\n return function traverse(node: unknown, state: TState): unknown {\n if (Array.isArray(node)) {\n return node.map((element, ii) => {\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, ii],\n };\n return traverse(element, nextState);\n });\n } else if (typeof node === 'object' && node !== null) {\n const out: Record = {};\n for (const propName in node) {\n if (!Object.prototype.hasOwnProperty.call(node, propName)) {\n continue;\n }\n const nextState = {\n ...state,\n keyPath: [...state.keyPath, propName],\n };\n out[propName] = traverse(node[propName as keyof typeof node], nextState);\n }\n return out;\n } else {\n return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);\n }\n };\n}\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided visitors at\n * each node. A custom initial state can be provided but must at least provide `{ keyPath: [] }`.\n *\n * @example\n * ```ts\n * import { getTreeWalkerRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getTreeWalkerRequestTransformer(\n * [\n * // Replaces foo.bar with \"baz\".\n * (node, state) => (state.keyPath === ['foo', 'bar'] ? 'baz' : node),\n * // Increments all numbers by 1.\n * node => (typeof node === number ? node + 1 : node),\n * ],\n * { keyPath: [] },\n * );\n * ```\n */\nexport function getTreeWalkerRequestTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const traverse = getTreeWalker(visitors);\n return Object.freeze({\n ...request,\n params: traverse(request.params, initialState),\n });\n };\n}\n\nexport function getTreeWalkerResponseTransformer(\n visitors: NodeVisitor[],\n initialState: TState,\n): RpcResponseTransformer {\n return json => getTreeWalker(visitors)(json, initialState);\n}\n","import { downcastNodeToNumberIfBigint } from './request-transformer-bigint-downcast-internal';\nimport { getTreeWalkerRequestTransformer } from './tree-traversal';\n\n/**\n * Creates a transformer that downcasts all `BigInt` values to `Number`.\n *\n * @example\n * ```ts\n * import { getBigIntDowncastRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getBigIntDowncastRequestTransformer();\n * ```\n *\n */\nexport function getBigIntDowncastRequestTransformer() {\n return getTreeWalkerRequestTransformer([downcastNodeToNumberIfBigint], { keyPath: [] });\n}\n","import { Commitment } from '@solana/rpc-types';\n\nexport function applyDefaultCommitment({\n commitmentPropertyName,\n params,\n optionsObjectPositionInParams,\n overrideCommitment,\n}: Readonly<{\n commitmentPropertyName: string;\n optionsObjectPositionInParams: number;\n overrideCommitment?: Commitment;\n params: unknown[];\n}>) {\n const paramInTargetPosition = params[optionsObjectPositionInParams];\n if (\n // There's no config.\n paramInTargetPosition === undefined ||\n // There is a config object.\n (paramInTargetPosition && typeof paramInTargetPosition === 'object' && !Array.isArray(paramInTargetPosition))\n ) {\n if (\n // The config object already has a commitment set.\n paramInTargetPosition &&\n commitmentPropertyName in paramInTargetPosition\n ) {\n if (\n !paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] ||\n paramInTargetPosition[commitmentPropertyName as keyof typeof paramInTargetPosition] === 'finalized'\n ) {\n // Delete the commitment property; `finalized` is already the server default.\n const nextParams = [...params];\n const {\n [commitmentPropertyName as keyof typeof paramInTargetPosition]: _, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...rest\n } = paramInTargetPosition;\n if (Object.keys(rest).length > 0) {\n nextParams[optionsObjectPositionInParams] = rest;\n } else {\n if (optionsObjectPositionInParams === nextParams.length - 1) {\n nextParams.length--;\n } else {\n nextParams[optionsObjectPositionInParams] = undefined;\n }\n }\n return nextParams;\n }\n } else if (overrideCommitment !== 'finalized') {\n // Apply the default commitment.\n const nextParams = [...params];\n nextParams[optionsObjectPositionInParams] = {\n ...paramInTargetPosition,\n [commitmentPropertyName]: overrideCommitment,\n };\n return nextParams;\n }\n }\n return params;\n}\n","import type { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { applyDefaultCommitment } from './request-transformer-default-commitment-internal';\n\n/**\n * Creates a transformer that adds the provided default commitment to the configuration object of the request when applicable.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getDefaultCommitmentRequestTransformer, OPTIONS_OBJECT_POSITION_BY_METHOD } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultCommitmentRequestTransformer({\n * defaultCommitment: 'confirmed',\n * optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n * });\n */\nexport function getDefaultCommitmentRequestTransformer({\n defaultCommitment,\n optionsObjectPositionByMethod,\n}: Readonly<{\n defaultCommitment?: Commitment;\n optionsObjectPositionByMethod: Record;\n}>): RpcRequestTransformer {\n return (request: RpcRequest): RpcRequest => {\n const { params, methodName } = request;\n\n // We only apply default commitment to array parameters.\n if (!Array.isArray(params)) {\n return request;\n }\n\n // Find the position of the options object in the parameters and abort if not found.\n const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];\n if (optionsObjectPositionInParams == null) {\n return request;\n }\n\n return Object.freeze({\n methodName,\n params: applyDefaultCommitment({\n commitmentPropertyName: methodName === 'sendTransaction' ? 'preflightCommitment' : 'commitment',\n optionsObjectPositionInParams,\n overrideCommitment: defaultCommitment,\n params,\n }),\n });\n };\n}\n","import { KeyPath, TraversalState } from './tree-traversal';\n\nexport function getIntegerOverflowNodeVisitor(onIntegerOverflow: (keyPath: KeyPath, value: bigint) => void) {\n return (value: T, { keyPath }: TraversalState): T => {\n if (typeof value === 'bigint') {\n if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {\n onIntegerOverflow(keyPath as (number | string)[], value);\n }\n }\n return value;\n };\n}\n","import { RpcRequest } from '@solana/rpc-spec-types';\n\nimport { getIntegerOverflowNodeVisitor } from './request-transformer-integer-overflow-internal';\nimport { getTreeWalkerRequestTransformer, KeyPath } from './tree-traversal';\n\nexport type IntegerOverflowHandler = (request: RpcRequest, keyPath: KeyPath, value: bigint) => void;\n\n/**\n * Creates a transformer that traverses the request parameters and executes the provided handler\n * when an integer overflow is detected.\n *\n * @example\n * ```ts\n * import { getIntegerOverflowRequestTransformer } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getIntegerOverflowRequestTransformer((request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * });\n * ```\n */\nexport function getIntegerOverflowRequestTransformer(onIntegerOverflow: IntegerOverflowHandler) {\n return (request: RpcRequest): RpcRequest => {\n const transformer = getTreeWalkerRequestTransformer(\n [getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))],\n { keyPath: [] },\n );\n return transformer(request);\n };\n}\n","export const OPTIONS_OBJECT_POSITION_BY_METHOD: Record = {\n accountNotifications: 1,\n blockNotifications: 1,\n getAccountInfo: 1,\n getBalance: 1,\n getBlock: 1,\n getBlockHeight: 0,\n getBlockProduction: 0,\n getBlocks: 2,\n getBlocksWithLimit: 2,\n getEpochInfo: 0,\n getFeeForMessage: 1,\n getInflationGovernor: 0,\n getInflationReward: 1,\n getLargestAccounts: 0,\n getLatestBlockhash: 0,\n getLeaderSchedule: 1,\n getMinimumBalanceForRentExemption: 1,\n getMultipleAccounts: 1,\n getProgramAccounts: 1,\n getSignaturesForAddress: 1,\n getSlot: 0,\n getSlotLeader: 0,\n getStakeMinimumDelegation: 0,\n getSupply: 0,\n getTokenAccountBalance: 1,\n getTokenAccountsByDelegate: 2,\n getTokenAccountsByOwner: 2,\n getTokenLargestAccounts: 1,\n getTokenSupply: 1,\n getTransaction: 1,\n getTransactionCount: 0,\n getVoteAccounts: 0,\n isBlockhashValid: 1,\n logsNotifications: 1,\n programNotifications: 1,\n requestAirdrop: 2,\n sendTransaction: 1,\n signatureNotifications: 1,\n simulateTransaction: 1,\n};\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { Commitment } from '@solana/rpc-types';\n\nimport { getBigIntDowncastRequestTransformer } from './request-transformer-bigint-downcast';\nimport { getDefaultCommitmentRequestTransformer } from './request-transformer-default-commitment';\nimport { getIntegerOverflowRequestTransformer, IntegerOverflowHandler } from './request-transformer-integer-overflow';\nimport { OPTIONS_OBJECT_POSITION_BY_METHOD } from './request-transformer-options-object-position-config';\n\nexport type RequestTransformerConfig = Readonly<{\n /**\n * An optional {@link Commitment} value to use as the default when none is supplied by the\n * caller.\n */\n defaultCommitment?: Commitment;\n /**\n * An optional function that will be called whenever a `bigint` input exceeds that which can be\n * expressed using JavaScript numbers.\n *\n * This is used in the default {@link SolanaRpcSubscriptionsApi} to throw an exception rather\n * than to allow truncated values to propagate through a program.\n */\n onIntegerOverflow?: IntegerOverflowHandler;\n}>;\n\n/**\n * Returns the default request transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcRequestTransformer | RpcRequestTransformers} together such as the\n * {@link getDefaultCommitmentTransformer}, the {@link getIntegerOverflowRequestTransformer} and the\n * {@link getBigIntDowncastRequestTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultRequestTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const requestTransformer = getDefaultRequestTransformerForSolanaRpc({\n * defaultCommitment: 'confirmed',\n * onIntegerOverflow: (request, keyPath, value) => {\n * throw new Error(`Integer overflow at ${keyPath.join('.')}: ${value}`);\n * },\n * });\n * ```\n */\nexport function getDefaultRequestTransformerForSolanaRpc(config?: RequestTransformerConfig): RpcRequestTransformer {\n const handleIntegerOverflow = config?.onIntegerOverflow;\n return (request: RpcRequest): RpcRequest => {\n return pipe(\n request,\n handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : r => r,\n getBigIntDowncastRequestTransformer(),\n getDefaultCommitmentRequestTransformer({\n defaultCommitment: config?.defaultCommitment,\n optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD,\n }),\n );\n };\n}\n","import { KeyPath, KEYPATH_WILDCARD, TraversalState } from './tree-traversal';\n\nexport function getBigIntUpcastVisitor(allowedNumericKeyPaths: readonly KeyPath[]) {\n return function upcastNodeToBigIntIfNumber(value: unknown, { keyPath }: TraversalState) {\n const isInteger = (typeof value === 'number' && Number.isInteger(value)) || typeof value === 'bigint';\n if (!isInteger) return value;\n if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {\n return Number(value);\n } else {\n return BigInt(value);\n }\n };\n}\n\nfunction keyPathIsAllowedToBeNumeric(keyPath: KeyPath, allowedNumericKeyPaths: readonly KeyPath[]) {\n return allowedNumericKeyPaths.some(prohibitedKeyPath => {\n if (prohibitedKeyPath.length !== keyPath.length) {\n return false;\n }\n for (let ii = keyPath.length - 1; ii >= 0; ii--) {\n const keyPathPart = keyPath[ii];\n const prohibitedKeyPathPart = prohibitedKeyPath[ii];\n if (\n prohibitedKeyPathPart !== keyPathPart &&\n (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== 'number')\n ) {\n return false;\n }\n }\n return true;\n });\n}\n","import { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath } from './tree-traversal';\n\n/**\n * Returns a transformer that upcasts all `Number` values to `BigInts` unless they match within the\n * provided {@link KeyPath | KeyPaths}. In other words, the provided {@link KeyPath | KeyPaths} will\n * remain as `Number` values, any other numeric value will be upcasted to a `BigInt`.\n *\n * Note that you can use {@link KEYPATH_WILDCARD} to match any key within a {@link KeyPath}.\n *\n * @example\n * ```ts\n * import { getBigIntUpcastResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getBigIntUpcastResponseTransformer([\n * ['index'],\n * ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n * ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n * ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n * ]);\n * ```\n */\nexport function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths: readonly KeyPath[]) {\n return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });\n}\n","import { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\ntype JsonRpcResponse = { result: unknown };\n\n/**\n * Returns a transformer that extracts the `result` field from the body of the RPC response.\n *\n * For instance, we go from `{ jsonrpc: '2.0', result: 'foo', id: 1 }` to `'foo'`.\n *\n * @example\n * ```ts\n * import { getResultResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getResultResponseTransformer();\n * ```\n */\nexport function getResultResponseTransformer(): RpcResponseTransformer {\n return json => (json as JsonRpcResponse).result;\n}\n","import { KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\nexport type AllowedNumericKeypaths = Partial>;\n\n// Numeric values nested in `jsonParsed` accounts\nexport const jsonParsedTokenAccountsConfigs = [\n // parsed Token/Token22 token account\n ['data', 'parsed', 'info', 'tokenAmount', 'decimals'],\n ['data', 'parsed', 'info', 'tokenAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'decimals'],\n ['data', 'parsed', 'info', 'rentExemptReserve', 'uiAmount'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'decimals'],\n ['data', 'parsed', 'info', 'delegatedAmount', 'uiAmount'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'olderTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'newerTransferFee', 'transferFeeBasisPoints'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'preUpdateAverageRate'],\n ['data', 'parsed', 'info', 'extensions', KEYPATH_WILDCARD, 'state', 'currentRate'],\n];\nexport const jsonParsedAccountsConfigs = [\n ...jsonParsedTokenAccountsConfigs,\n // parsed AddressTableLookup account\n ['data', 'parsed', 'info', 'lastExtendedSlotStartIndex'],\n // parsed Config account\n ['data', 'parsed', 'info', 'slashPenalty'],\n ['data', 'parsed', 'info', 'warmupCooldownRate'],\n // parsed Token/Token22 mint account\n ['data', 'parsed', 'info', 'decimals'],\n // parsed Token/Token22 multisig account\n ['data', 'parsed', 'info', 'numRequiredSigners'],\n ['data', 'parsed', 'info', 'numValidSigners'],\n // parsed Stake account\n ['data', 'parsed', 'info', 'stake', 'delegation', 'warmupCooldownRate'],\n // parsed Sysvar rent account\n ['data', 'parsed', 'info', 'exemptionThreshold'],\n ['data', 'parsed', 'info', 'burnPercent'],\n // parsed Vote account\n ['data', 'parsed', 'info', 'commission'],\n ['data', 'parsed', 'info', 'votes', KEYPATH_WILDCARD, 'confirmationCount'],\n];\nexport const innerInstructionsConfigs = [\n ['index'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n];\nexport const messageConfig = [\n ['addressTableLookups', KEYPATH_WILDCARD, 'writableIndexes', KEYPATH_WILDCARD],\n ['addressTableLookups', KEYPATH_WILDCARD, 'readonlyIndexes', KEYPATH_WILDCARD],\n ['header', 'numReadonlySignedAccounts'],\n ['header', 'numReadonlyUnsignedAccounts'],\n ['header', 'numRequiredSignatures'],\n ['instructions', KEYPATH_WILDCARD, 'accounts', KEYPATH_WILDCARD],\n ['instructions', KEYPATH_WILDCARD, 'programIdIndex'],\n ['instructions', KEYPATH_WILDCARD, 'stackHeight'],\n] as const;\n","import { getSolanaErrorFromJsonRpcError } from '@solana/errors';\nimport { RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { innerInstructionsConfigs, jsonParsedAccountsConfigs } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastVisitor } from './response-transformer-bigint-upcast-internal';\nimport { getTreeWalkerResponseTransformer, KeyPath, KEYPATH_WILDCARD } from './tree-traversal';\n\ntype JsonRpcResponse = { error: Parameters[0] } | { result: unknown };\n\n// Keypaths for simulateTransaction result that should remain as Number (not BigInt)\n// Note: These are relative to the error.data root, not result.value like in success responses\nfunction getSimulateTransactionAllowedNumericKeypaths(): readonly KeyPath[] {\n return [\n ['loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['innerInstructions', KEYPATH_WILDCARD, ...c]),\n ];\n}\n\n/**\n * Returns a transformer that throws a {@link SolanaError} with the appropriate RPC error code if\n * the body of the RPC response contains an error.\n *\n * @example\n * ```ts\n * import { getThrowSolanaErrorResponseTransformer } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getThrowSolanaErrorResponseTransformer();\n * ```\n */\nexport function getThrowSolanaErrorResponseTransformer(): RpcResponseTransformer {\n return (json, request) => {\n const jsonRpcResponse = json as JsonRpcResponse;\n if ('error' in jsonRpcResponse) {\n const { error } = jsonRpcResponse;\n\n // Check if this is a sendTransaction preflight failure (error code -32002)\n // These errors contain RpcSimulateTransactionResult in error.data which needs\n // BigInt values downcast to Number for fields that should be numbers\n const isSendTransactionPreflightFailure =\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n (error.code === -32002 || error.code === -32002n);\n\n if (isSendTransactionPreflightFailure && 'data' in error && error.data) {\n // Apply BigInt downcast transformation to error.data\n const treeWalker = getTreeWalkerResponseTransformer(\n [getBigIntUpcastVisitor(getSimulateTransactionAllowedNumericKeypaths())],\n { keyPath: [] },\n );\n const transformedData = treeWalker(error.data, request);\n\n // Reconstruct error with transformed data\n const transformedError = { ...error, data: transformedData };\n throw getSolanaErrorFromJsonRpcError(transformedError);\n }\n\n throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);\n }\n return jsonRpcResponse;\n };\n}\n","import { pipe } from '@solana/functional';\nimport { RpcRequest, RpcResponse, RpcResponseTransformer } from '@solana/rpc-spec-types';\n\nimport { AllowedNumericKeypaths } from './response-transformer-allowed-numeric-values';\nimport { getBigIntUpcastResponseTransformer } from './response-transformer-bigint-upcast';\nimport { getResultResponseTransformer } from './response-transformer-result';\nimport { getThrowSolanaErrorResponseTransformer } from './response-transformer-throw-solana-error';\n\nexport type ResponseTransformerConfig = Readonly<{\n /**\n * An optional map from the name of an API method to an array of {@link KeyPath | KeyPaths}\n * pointing to values in the response that should materialize in the application as `Number`\n * instead of `BigInt`.\n */\n allowedNumericKeyPaths?: AllowedNumericKeypaths;\n}>;\n\n/**\n * Returns the default response transformer for the Solana RPC API.\n *\n * Under the hood, this function composes multiple\n * {@link RpcResponseTransformer | RpcResponseTransformers} together such as the\n * {@link getThrowSolanaErrorResponseTransformer}, the {@link getResultResponseTransformer} and the\n * {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpc } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpc({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpc(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(\n response,\n r => getThrowSolanaErrorResponseTransformer()(r, request),\n r => getResultResponseTransformer()(r, request),\n r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request),\n );\n };\n}\n\n/**\n * Returns the default response transformer for the Solana RPC Subscriptions API.\n *\n * Under the hood, this function composes the {@link getBigIntUpcastResponseTransformer}.\n *\n * @example\n * ```ts\n * import { getDefaultResponseTransformerForSolanaRpcSubscriptions } from '@solana/rpc-transformers';\n *\n * const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n * allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n * });\n * ```\n */\nexport function getDefaultResponseTransformerForSolanaRpcSubscriptions(\n config?: ResponseTransformerConfig,\n): RpcResponseTransformer {\n return (response: RpcResponse, request: RpcRequest): RpcResponse => {\n const methodName = request.methodName as keyof TApi;\n const keyPaths =\n config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : undefined;\n return pipe(response, r => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));\n };\n}\n","/**\n * This package contains types that describe the [methods](https://solana.com/docs/rpc/http) of the\n * Solana JSON RPC API, and utilities for creating a {@link RpcApi} implementation with sensible\n * defaults. It can be used standalone, but it is also exported as part of Kit\n * [`@solana/kit`](https://github.com/anza-xyz/kit/tree/main/packages/kit).\n *\n * @example\n * Each RPC method is described in terms of a TypeScript type of the following form:\n *\n * ```ts\n * type ExampleApi = {\n * getSomething(address: Address): Something;\n * };\n * ```\n *\n * A {@link RpcApi} that implements `ExampleApi` will ultimately expose its defined methods on any\n * {@link Rpc} that uses it.\n *\n * ```ts\n * const rpc: Rpc = createExampleRpc(/* ... *\\/);\n * const something: Something = await rpc.getSomething(address('95DpK3y3GF7U8s1k4EvZ7xqyeCkhsHeZaE97iZpHUGMN')).send();\n * ```\n *\n * @packageDocumentation\n */\nimport { createJsonRpcApi, RpcApi } from '@solana/rpc-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpc,\n innerInstructionsConfigs,\n jsonParsedAccountsConfigs,\n jsonParsedTokenAccountsConfigs,\n KEYPATH_WILDCARD,\n messageConfig,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { GetAccountInfoApi } from './getAccountInfo';\nimport { GetBalanceApi } from './getBalance';\nimport { GetBlockApi } from './getBlock';\nimport { GetBlockCommitmentApi } from './getBlockCommitment';\nimport { GetBlockHeightApi } from './getBlockHeight';\nimport { GetBlockProductionApi } from './getBlockProduction';\nimport { GetBlocksApi } from './getBlocks';\nimport { GetBlocksWithLimitApi } from './getBlocksWithLimit';\nimport { GetBlockTimeApi } from './getBlockTime';\nimport { GetClusterNodesApi } from './getClusterNodes';\nimport { GetEpochInfoApi } from './getEpochInfo';\nimport { GetEpochScheduleApi } from './getEpochSchedule';\nimport { GetFeeForMessageApi } from './getFeeForMessage';\nimport { GetFirstAvailableBlockApi } from './getFirstAvailableBlock';\nimport { GetGenesisHashApi } from './getGenesisHash';\nimport { GetHealthApi } from './getHealth';\nimport { GetHighestSnapshotSlotApi } from './getHighestSnapshotSlot';\nimport { GetIdentityApi } from './getIdentity';\nimport { GetInflationGovernorApi } from './getInflationGovernor';\nimport { GetInflationRateApi } from './getInflationRate';\nimport { GetInflationRewardApi } from './getInflationReward';\nimport { GetLargestAccountsApi } from './getLargestAccounts';\nimport { GetLatestBlockhashApi } from './getLatestBlockhash';\nimport { GetLeaderScheduleApi } from './getLeaderSchedule';\nimport { GetMaxRetransmitSlotApi } from './getMaxRetransmitSlot';\nimport { GetMaxShredInsertSlotApi } from './getMaxShredInsertSlot';\nimport { GetMinimumBalanceForRentExemptionApi } from './getMinimumBalanceForRentExemption';\nimport { GetMultipleAccountsApi } from './getMultipleAccounts';\nimport { GetProgramAccountsApi } from './getProgramAccounts';\nimport { GetRecentPerformanceSamplesApi } from './getRecentPerformanceSamples';\nimport { GetRecentPrioritizationFeesApi } from './getRecentPrioritizationFees';\nimport { GetSignaturesForAddressApi } from './getSignaturesForAddress';\nimport { GetSignatureStatusesApi } from './getSignatureStatuses';\nimport { GetSlotApi } from './getSlot';\nimport { GetSlotLeaderApi } from './getSlotLeader';\nimport { GetSlotLeadersApi } from './getSlotLeaders';\nimport { GetStakeMinimumDelegationApi } from './getStakeMinimumDelegation';\nimport { GetSupplyApi } from './getSupply';\nimport { GetTokenAccountBalanceApi } from './getTokenAccountBalance';\nimport { GetTokenAccountsByDelegateApi } from './getTokenAccountsByDelegate';\nimport { GetTokenAccountsByOwnerApi } from './getTokenAccountsByOwner';\nimport { GetTokenLargestAccountsApi } from './getTokenLargestAccounts';\nimport { GetTokenSupplyApi } from './getTokenSupply';\nimport { GetTransactionApi } from './getTransaction';\nimport { GetTransactionCountApi } from './getTransactionCount';\nimport { GetVersionApi } from './getVersion';\nimport { GetVoteAccountsApi } from './getVoteAccounts';\nimport { IsBlockhashValidApi } from './isBlockhashValid';\nimport { MinimumLedgerSlotApi } from './minimumLedgerSlot';\nimport { RequestAirdropApi } from './requestAirdrop';\nimport { SendTransactionApi } from './sendTransaction';\nimport { SimulateTransactionApi } from './simulateTransaction';\n\ntype SolanaRpcApiForAllClusters = GetAccountInfoApi &\n GetBalanceApi &\n GetBlockApi &\n GetBlockCommitmentApi &\n GetBlockHeightApi &\n GetBlockProductionApi &\n GetBlocksApi &\n GetBlocksWithLimitApi &\n GetBlockTimeApi &\n GetClusterNodesApi &\n GetEpochInfoApi &\n GetEpochScheduleApi &\n GetFeeForMessageApi &\n GetFirstAvailableBlockApi &\n GetGenesisHashApi &\n GetHealthApi &\n GetHighestSnapshotSlotApi &\n GetIdentityApi &\n GetInflationGovernorApi &\n GetInflationRateApi &\n GetInflationRewardApi &\n GetLargestAccountsApi &\n GetLatestBlockhashApi &\n GetLeaderScheduleApi &\n GetMaxRetransmitSlotApi &\n GetMaxShredInsertSlotApi &\n GetMinimumBalanceForRentExemptionApi &\n GetMultipleAccountsApi &\n GetProgramAccountsApi &\n GetRecentPerformanceSamplesApi &\n GetRecentPrioritizationFeesApi &\n GetSignaturesForAddressApi &\n GetSignatureStatusesApi &\n GetSlotApi &\n GetSlotLeaderApi &\n GetSlotLeadersApi &\n GetStakeMinimumDelegationApi &\n GetSupplyApi &\n GetTokenAccountBalanceApi &\n GetTokenAccountsByDelegateApi &\n GetTokenAccountsByOwnerApi &\n GetTokenLargestAccountsApi &\n GetTokenSupplyApi &\n GetTransactionApi &\n GetTransactionCountApi &\n GetVersionApi &\n GetVoteAccountsApi &\n IsBlockhashValidApi &\n MinimumLedgerSlotApi &\n SendTransactionApi &\n SimulateTransactionApi;\ntype SolanaRpcApiForTestClusters = RequestAirdropApi & SolanaRpcApiForAllClusters;\n/**\n * Represents the RPC methods available on test clusters.\n *\n * For instance, the test clusters support the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApi = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the devnet cluster.\n *\n * For instance, the devnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiDevnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the testnet cluster.\n *\n * For instance, the testnet cluster supports the {@link RequestAirdropApi} while mainnet does not.\n */\nexport type SolanaRpcApiTestnet = SolanaRpcApiForTestClusters;\n/**\n * Represents the RPC methods available on the mainnet cluster.\n *\n * For instance, the mainnet cluster does not support the {@link RequestAirdropApi} whereas test\n * clusters do.\n */\nexport type SolanaRpcApiMainnet = SolanaRpcApiForAllClusters;\n\nexport type {\n GetAccountInfoApi,\n GetBalanceApi,\n GetBlockApi,\n GetBlockCommitmentApi,\n GetBlockHeightApi,\n GetBlockProductionApi,\n GetBlocksApi,\n GetBlocksWithLimitApi,\n GetBlockTimeApi,\n GetClusterNodesApi,\n GetEpochInfoApi,\n GetEpochScheduleApi,\n GetFeeForMessageApi,\n GetFirstAvailableBlockApi,\n GetGenesisHashApi,\n GetHealthApi,\n GetHighestSnapshotSlotApi,\n GetIdentityApi,\n GetInflationGovernorApi,\n GetInflationRateApi,\n GetInflationRewardApi,\n GetLargestAccountsApi,\n GetLatestBlockhashApi,\n GetLeaderScheduleApi,\n GetMaxRetransmitSlotApi,\n GetMaxShredInsertSlotApi,\n GetMinimumBalanceForRentExemptionApi,\n GetMultipleAccountsApi,\n GetProgramAccountsApi,\n GetRecentPerformanceSamplesApi,\n GetRecentPrioritizationFeesApi,\n GetSignaturesForAddressApi,\n GetSignatureStatusesApi,\n GetSlotApi,\n GetSlotLeaderApi,\n GetSlotLeadersApi,\n GetStakeMinimumDelegationApi,\n GetSupplyApi,\n GetTokenAccountBalanceApi,\n GetTokenAccountsByDelegateApi,\n GetTokenAccountsByOwnerApi,\n GetTokenLargestAccountsApi,\n GetTokenSupplyApi,\n GetTransactionApi,\n GetTransactionCountApi,\n GetVersionApi,\n GetVoteAccountsApi,\n IsBlockhashValidApi,\n MinimumLedgerSlotApi,\n RequestAirdropApi,\n SendTransactionApi,\n SimulateTransactionApi,\n};\n\ntype Config = RequestTransformerConfig;\n\n/**\n * Creates a {@link RpcApi} implementation of the Solana JSON RPC API with some default behaviours.\n *\n * The default behaviours include:\n * - A transform that converts `bigint` inputs to `number` for compatibility with version 1.0 of the\n * Solana JSON RPC.\n * - A transform that calls the config's {@link Config.onIntegerOverflow | onIntegerOverflow}\n * handler whenever a `bigint` input would overflow a JavaScript IEEE 754 number. See\n * [this](https://github.com/solana-labs/solana-web3.js/issues/1116) GitHub issue for more\n * information.\n * - A transform that applies a default commitment wherever not specified\n */\nexport function createSolanaRpcApi<\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n TRpcMethods extends SolanaRpcApi | SolanaRpcApiDevnet | SolanaRpcApiMainnet | SolanaRpcApiTestnet = SolanaRpcApi,\n>(config?: Config): RpcApi {\n return createJsonRpcApi({\n requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),\n responseTransformer: getDefaultResponseTransformerForSolanaRpc({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n }),\n });\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n getAccountInfo: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n getBlock: [\n ['transactions', KEYPATH_WILDCARD, 'meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => [\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n ...c,\n ]),\n ...messageConfig.map(c => ['transactions', KEYPATH_WILDCARD, 'transaction', 'message', ...c] as const),\n ['rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n getClusterNodes: [\n [KEYPATH_WILDCARD, 'featureSet'],\n [KEYPATH_WILDCARD, 'shredVersion'],\n ],\n getInflationGovernor: [['initial'], ['foundation'], ['foundationTerm'], ['taper'], ['terminal']],\n getInflationRate: [['foundation'], ['total'], ['validator']],\n getInflationReward: [[KEYPATH_WILDCARD, 'commission']],\n getMultipleAccounts: jsonParsedAccountsConfigs.map(c => ['value', KEYPATH_WILDCARD, ...c]),\n getProgramAccounts: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n getRecentPerformanceSamples: [[KEYPATH_WILDCARD, 'samplePeriodSecs']],\n getTokenAccountBalance: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map(c => [\n 'value',\n KEYPATH_WILDCARD,\n 'account',\n ...c,\n ]),\n getTokenLargestAccounts: [\n ['value', KEYPATH_WILDCARD, 'decimals'],\n ['value', KEYPATH_WILDCARD, 'uiAmount'],\n ],\n getTokenSupply: [\n ['value', 'decimals'],\n ['value', 'uiAmount'],\n ],\n getTransaction: [\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'preTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'accountIndex'],\n ['meta', 'postTokenBalances', KEYPATH_WILDCARD, 'uiTokenAmount', 'decimals'],\n ['meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ...innerInstructionsConfigs.map(c => ['meta', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ...messageConfig.map(c => ['transaction', 'message', ...c] as const),\n ],\n getVersion: [['feature-set']],\n getVoteAccounts: [\n ['current', KEYPATH_WILDCARD, 'commission'],\n ['delinquent', KEYPATH_WILDCARD, 'commission'],\n ],\n simulateTransaction: [\n ['value', 'loadedAccountsDataSize'],\n ...jsonParsedAccountsConfigs.map(c => ['value', 'accounts', KEYPATH_WILDCARD, ...c]),\n ...innerInstructionsConfigs.map(c => ['value', 'innerInstructions', KEYPATH_WILDCARD, ...c]),\n ],\n };\n }\n return memoizedKeypaths;\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SolanaError } from '@solana/errors';\n\nexport type AllowedHttpRequestHeaders = Readonly<\n {\n // Someone can still sneak a forbidden header past Typescript if they do something like\n // fOo-BaR, but at that point they deserve the runtime failure.\n [K in DisallowedHeaders | ForbiddenHeaders as\n | Capitalize> // `Foo-bar`\n | K // `Foo-Bar`\n | Lowercase // `foo-bar`\n | Uncapitalize // `foo-Bar`\n // `FOO-BAR`\n | Uppercase]?: never;\n } & { [headerName: string]: string }\n>;\n// These are headers that we simply don't allow the developer to override because they're\n// fundamental to the operation of the JSON-RPC transport.\ntype DisallowedHeaders = 'Accept' | 'Content-Length' | 'Content-Type' | 'Solana-Client';\ntype ForbiddenHeaders =\n | 'Accept-Charset'\n // Though technically forbidden in non-Node environments, we don't have a way to target\n // TypeScript types depending on which platform you are authoring for. `Accept-Encoding` is\n // therefore omitted from the forbidden headers type, but is still a runtime error in dev mode\n // when supplied in a non-Node context.\n // | 'Accept-Encoding'\n | 'Access-Control-Request-Headers'\n | 'Access-Control-Request-Method'\n | 'Connection'\n | 'Content-Length'\n | 'Cookie'\n | 'Date'\n | 'DNT'\n | 'Expect'\n | 'Host'\n | 'Keep-Alive'\n // Similar to `Accept-Encoding`, we don't have a way to target TypeScript types depending on\n // which platform you are authoring for. `Origin` is therefore omitted from the forbidden\n // headers type, but is still a runtime error in dev mode when supplied in a browser context.\n // | 'Origin'\n | 'Permissions-Policy'\n | 'Referer'\n | 'TE'\n | 'Trailer'\n | 'Transfer-Encoding'\n | 'Upgrade'\n | 'Via'\n | `Proxy-${string}`\n | `Sec-${string}`;\n\n// These are headers which are fundamental to the JSON-RPC transport, and must not be modified.\nconst DISALLOWED_HEADERS: Record = {\n accept: true,\n 'content-length': true,\n 'content-type': true,\n};\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS: Record = /* @__PURE__ */ Object.assign(\n {\n 'accept-charset': true,\n 'access-control-request-headers': true,\n 'access-control-request-method': true,\n connection: true,\n 'content-length': true,\n cookie: true,\n date: true,\n dnt: true,\n expect: true,\n host: true,\n 'keep-alive': true,\n 'permissions-policy': true,\n // Prefix matching is implemented in code, below.\n // 'proxy-': true,\n // 'sec-': true,\n referer: true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n via: true,\n },\n __NODEJS__ ? undefined : { 'accept-encoding': true },\n __BROWSER__ ? { origin: true } : undefined,\n);\n\nexport function assertIsAllowedHttpRequestHeaders(\n headers: Record,\n): asserts headers is AllowedHttpRequestHeaders {\n const badHeaders = Object.keys(headers).filter(headerName => {\n const lowercaseHeaderName = headerName.toLowerCase();\n return (\n DISALLOWED_HEADERS[headerName.toLowerCase()] === true ||\n FORBIDDEN_HEADERS[headerName.toLowerCase()] === true ||\n lowercaseHeaderName.startsWith('proxy-') ||\n lowercaseHeaderName.startsWith('sec-')\n );\n });\n if (badHeaders.length > 0) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, {\n headers: badHeaders,\n });\n }\n}\n\n// Lowercasing header names makes it easier to override user-supplied headers, such as those defined\n// in the `DisallowedHeaders` type.\nexport function normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n","import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError } from '@solana/errors';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\nimport type Dispatcher from 'undici-types/dispatcher';\n\nimport { HttpTransportConfig as Config } from './http-transport-config';\nimport { assertIsAllowedHttpRequestHeaders, normalizeHeaders } from './http-transport-headers';\n\nlet didWarnDispatcherWasSuppliedInNonNodeEnvironment = false;\nfunction warnDispatcherWasSuppliedInNonNodeEnvironment() {\n if (didWarnDispatcherWasSuppliedInNonNodeEnvironment) {\n return;\n }\n didWarnDispatcherWasSuppliedInNonNodeEnvironment = true;\n console.warn(\n 'You have supplied a `Dispatcher` to `createHttpTransport()`. It has been ignored ' +\n 'because Undici dispatchers only work in Node environments. To eliminate this ' +\n 'warning, omit the `dispatcher_NODE_ONLY` property from your config when running in ' +\n 'a non-Node environment.',\n );\n}\n\n/**\n * Creates a function you can use to make `POST` requests with headers suitable for sending JSON\n * data to a server.\n *\n * @example\n * ```ts\n * import { createHttpTransport } from '@solana/rpc-transport-http';\n *\n * const transport = createHttpTransport({ url: 'https://api.mainnet-beta.solana.com' });\n * const response = await transport({\n * payload: { id: 1, jsonrpc: '2.0', method: 'getSlot' },\n * });\n * const data = await response.json();\n * ```\n */\nexport function createHttpTransport(config: Config): RpcTransport {\n if (process.env.NODE_ENV !== \"production\" && !__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n warnDispatcherWasSuppliedInNonNodeEnvironment();\n }\n const { fromJson, headers, toJson, url } = config;\n if (process.env.NODE_ENV !== \"production\" && headers) {\n assertIsAllowedHttpRequestHeaders(headers);\n }\n let dispatcherConfig: { dispatcher: Dispatcher | undefined } | undefined;\n if (__NODEJS__ && 'dispatcher_NODE_ONLY' in config) {\n dispatcherConfig = { dispatcher: config.dispatcher_NODE_ONLY };\n }\n const customHeaders = headers && normalizeHeaders(headers);\n return async function makeHttpRequest({\n payload,\n signal,\n }: Parameters[0]): Promise> {\n const body = toJson ? toJson(payload) : JSON.stringify(payload);\n const requestInfo = {\n ...dispatcherConfig,\n body,\n headers: {\n ...customHeaders,\n // Keep these headers lowercase so they will override any user-supplied headers above.\n accept: 'application/json',\n 'content-length': body.length.toString(),\n 'content-type': 'application/json; charset=utf-8',\n },\n method: 'POST',\n signal,\n };\n const response = await fetch(url, requestInfo);\n if (!response.ok) {\n throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {\n headers: response.headers,\n message: response.statusText,\n statusCode: response.status,\n });\n }\n if (fromJson) {\n return fromJson(await response.text(), payload) as TResponse;\n }\n return await response.json();\n };\n}\n","import { isJsonRpcPayload } from '@solana/rpc-spec';\n\nconst SOLANA_RPC_METHODS = [\n 'getAccountInfo',\n 'getBalance',\n 'getBlock',\n 'getBlockCommitment',\n 'getBlockHeight',\n 'getBlockProduction',\n 'getBlocks',\n 'getBlocksWithLimit',\n 'getBlockTime',\n 'getClusterNodes',\n 'getEpochInfo',\n 'getEpochSchedule',\n 'getFeeForMessage',\n 'getFirstAvailableBlock',\n 'getGenesisHash',\n 'getHealth',\n 'getHighestSnapshotSlot',\n 'getIdentity',\n 'getInflationGovernor',\n 'getInflationRate',\n 'getInflationReward',\n 'getLargestAccounts',\n 'getLatestBlockhash',\n 'getLeaderSchedule',\n 'getMaxRetransmitSlot',\n 'getMaxShredInsertSlot',\n 'getMinimumBalanceForRentExemption',\n 'getMultipleAccounts',\n 'getProgramAccounts',\n 'getRecentPerformanceSamples',\n 'getRecentPrioritizationFees',\n 'getSignaturesForAddress',\n 'getSignatureStatuses',\n 'getSlot',\n 'getSlotLeader',\n 'getSlotLeaders',\n 'getStakeMinimumDelegation',\n 'getSupply',\n 'getTokenAccountBalance',\n 'getTokenAccountsByDelegate',\n 'getTokenAccountsByOwner',\n 'getTokenLargestAccounts',\n 'getTokenSupply',\n 'getTransaction',\n 'getTransactionCount',\n 'getVersion',\n 'getVoteAccounts',\n 'index',\n 'isBlockhashValid',\n 'minimumLedgerSlot',\n 'requestAirdrop',\n 'sendTransaction',\n 'simulateTransaction',\n] as const;\n\n/**\n * Helper function that checks if a given `RpcRequest` comes from the Solana RPC API.\n */\nexport function isSolanaRequest(payload: unknown): payload is Readonly<{\n jsonrpc: '2.0';\n method: (typeof SOLANA_RPC_METHODS)[number];\n params: unknown;\n}> {\n return isJsonRpcPayload(payload) && (SOLANA_RPC_METHODS as readonly string[]).includes(payload.method);\n}\n","import { RpcTransport } from '@solana/rpc-spec';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\n\nimport { createHttpTransport } from './http-transport';\nimport { HttpTransportConfig } from './http-transport-config';\nimport { isSolanaRequest } from './is-solana-request';\n\ntype Config = Pick;\n\n/**\n * Creates a {@link RpcTransport} that uses JSON HTTP requests — much like the\n * {@link createHttpTransport} function - except that it also uses custom `toJson` and `fromJson`\n * functions in order to allow `bigint` values to be serialized and deserialized correctly over the\n * wire.\n *\n * Since this is something specific to the Solana RPC API, these custom JSON functions are only\n * triggered when the request is recognized as a Solana RPC request. Normal RPC APIs should aim to\n * wrap their `bigint` values — e.g. `u64` or `i64` — in special value objects that represent the\n * number as a string to avoid numerical values going above `Number.MAX_SAFE_INTEGER`.\n *\n * It has the same configuration options as {@link createHttpTransport}, but without the `fromJson`\n * and `toJson` options.\n */\nexport function createHttpTransportForSolanaRpc(config: Config): RpcTransport {\n return createHttpTransport({\n ...config,\n fromJson: (rawResponse: string, payload: unknown) =>\n isSolanaRequest(payload) ? parseJsonWithBigInts(rawResponse) : JSON.parse(rawResponse),\n toJson: (payload: unknown) =>\n isSolanaRequest(payload) ? stringifyJsonWithBigInts(payload) : JSON.stringify(payload),\n });\n}\n","/**\n * This project is a fork of [nickyout/fast-stable-stringify](https://github.com/nickyout/fast-stable-stringify)\n *\n * The most popular repository providing this feature is [substack's json-stable-stringify](https://www.npmjs.com/package/json-stable-stringify). The intent of this library is to provide a faster alternative for when performance is more important than features. It assumes you provide basic javascript values without circular references, and returns a non-indented string.\n *\n * Just like substack's, it:\n *\n * - handles all variations of all basic javascript values (number, string, boolean, array, object, null, Date, BigInt)\n * - handles undefined _and_ function in the same way as `JSON.stringify`\n * - **does not support ie8 (and below) with complete certainty**.\n *\n * Unlike substack's, it:\n *\n * - does not implement the 'replacer' or 'space' arguments of the JSON.stringify method\n * - does not check for circular references\n *\n * @example\n * ```js\n * import stringify from '@solana/fast-stable-stringify';\n * stringify({ d: 0, c: 1, a: 2, b: 3, e: 4 }); // '{\"a\":2,\"b\":3,\"c\":1,\"d\":0,\"e\":4}'\n * ```\n *\n * @packageDocumentation\n */\nconst objToString = Object.prototype.toString;\nconst objKeys =\n Object.keys ||\n function (obj) {\n const keys = [];\n for (const name in obj) {\n keys.push(name);\n }\n return keys;\n };\n\nfunction stringify(val: unknown, isArrayProp: boolean) {\n let i, max, str, keys, key, propVal, toStr;\n if (val === true) {\n return 'true';\n }\n if (val === false) {\n return 'false';\n }\n switch (typeof val) {\n case 'object':\n if (val === null) {\n return null;\n } else if ('toJSON' in val && typeof val.toJSON === 'function') {\n return stringify(val.toJSON(), isArrayProp);\n } else {\n toStr = objToString.call(val);\n if (toStr === '[object Array]') {\n str = '[';\n max = (val as unknown[]).length - 1;\n for (i = 0; i < max; i++) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true) + ',';\n }\n if (max > -1) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += stringify((val as unknown[])[i], true);\n }\n return str + ']';\n } else if (toStr === '[object Object]') {\n // only object is left\n keys = objKeys(val).sort();\n max = keys.length;\n str = '';\n i = 0;\n while (i < max) {\n key = keys[i];\n propVal = stringify((val as Record)[key], false);\n if (propVal !== undefined) {\n if (str) {\n str += ',';\n }\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n str += JSON.stringify(key) + ':' + propVal;\n }\n i++;\n }\n return '{' + str + '}';\n } else {\n return JSON.stringify(val);\n }\n }\n case 'function':\n case 'undefined':\n return isArrayProp ? null : undefined;\n case 'bigint':\n return `${val.toString()}n`;\n case 'string':\n return JSON.stringify(val);\n default:\n return isFinite(val as number) ? val : null;\n }\n}\n\nexport default function (\n val:\n | Function // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n | undefined,\n): undefined;\nexport default function (val: unknown): string;\nexport default function (val: unknown): string | undefined {\n const returnVal = stringify(val, false);\n if (returnVal !== undefined) {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n return '' + returnVal;\n }\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcApi } from '@solana/rpc-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\n/**\n * When you create {@link Rpc} instances with custom transports but otherwise the default RPC API\n * behaviours, use this.\n *\n * @example\n * ```ts\n * const myCustomRpc = createRpc({\n * api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n * transport: myCustomTransport,\n * });\n * ```\n */\nexport const DEFAULT_RPC_CONFIG: Partial[0]>> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { AbortController } from '@solana/event-target-impl';\nimport type { RpcTransport } from '@solana/rpc-spec';\nimport type { RpcResponse } from '@solana/rpc-spec-types';\n\ntype CoalescedRequest = {\n readonly abortController: AbortController;\n numConsumers: number;\n readonly responsePromise: Promise;\n};\n\ntype GetDeduplicationKeyFn = (payload: unknown) => string | undefined;\n\n// This used to be a `Symbol()`, but there's a bug in Node <21 where the `undici` library passes\n// the `reason` property of the `AbortSignal` straight to `Error.captureStackTrace()` without first\n// typechecking it. `Error.captureStackTrace()` fatals when given a `Symbol`.\n// See https://github.com/nodejs/undici/pull/2597\nlet EXPLICIT_ABORT_TOKEN: ReturnType;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return process.env.NODE_ENV !== \"production\"\n ? {\n EXPLICIT_ABORT_TOKEN:\n 'This object is thrown from the request that underlies a series of coalesced ' +\n 'requests when the last request in that series aborts',\n }\n : {};\n}\n\nexport function getRpcTransportWithRequestCoalescing(\n transport: TTransport,\n getDeduplicationKey: GetDeduplicationKeyFn,\n): TTransport {\n let coalescedRequestsByDeduplicationKey: Record | undefined;\n return async function makeCoalescedHttpRequest(\n request: Parameters[0],\n ): Promise> {\n const { payload, signal } = request;\n const deduplicationKey = getDeduplicationKey(payload);\n if (deduplicationKey === undefined) {\n return await transport(request);\n }\n if (!coalescedRequestsByDeduplicationKey) {\n queueMicrotask(() => {\n coalescedRequestsByDeduplicationKey = undefined;\n });\n coalescedRequestsByDeduplicationKey = {};\n }\n if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {\n const abortController = new AbortController();\n const responsePromise = (async () => {\n try {\n return await transport({\n ...request,\n signal: abortController.signal,\n });\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n // We triggered this error when the last subscriber aborted. Letting this\n // error bubble up from here would cause runtime fatals where there should\n // be none.\n return;\n }\n throw e;\n }\n })();\n coalescedRequestsByDeduplicationKey[deduplicationKey] = {\n abortController,\n numConsumers: 0,\n responsePromise,\n };\n }\n const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];\n coalescedRequest.numConsumers++;\n if (signal) {\n const responsePromise = coalescedRequest.responsePromise as Promise>;\n return await new Promise>((resolve, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n signal.removeEventListener('abort', handleAbort);\n coalescedRequest.numConsumers -= 1;\n queueMicrotask(() => {\n if (coalescedRequest.numConsumers === 0) {\n const abortController = coalescedRequest.abortController;\n abortController.abort((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n }\n });\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject((e.target as AbortSignal).reason);\n };\n signal.addEventListener('abort', handleAbort);\n responsePromise\n .then(resolve)\n .catch(reject)\n .finally(() => {\n signal.removeEventListener('abort', handleAbort);\n });\n });\n } else {\n return (await coalescedRequest.responsePromise) as RpcResponse;\n }\n } as TTransport;\n}\n","import fastStableStringify from '@solana/fast-stable-stringify';\nimport { isJsonRpcPayload } from '@solana/rpc-spec';\n\nexport function getSolanaRpcPayloadDeduplicationKey(payload: unknown): string | undefined {\n return isJsonRpcPayload(payload) ? fastStableStringify([payload.method, payload.params]) : undefined;\n}\n","import { pipe } from '@solana/functional';\nimport { createHttpTransport, createHttpTransportForSolanaRpc } from '@solana/rpc-transport-http';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { RpcTransportFromClusterUrl } from './rpc-clusters';\nimport { getRpcTransportWithRequestCoalescing } from './rpc-request-coalescer';\nimport { getSolanaRpcPayloadDeduplicationKey } from './rpc-request-deduplication';\n\ntype RpcTransportConfig = Parameters[0];\ninterface DefaultRpcTransportConfig extends RpcTransportConfig {\n url: TClusterUrl;\n}\n\nfunction normalizeHeaders>(\n headers: T,\n): { [K in string & keyof T as Lowercase]: T[K] } {\n const out: Record = {};\n for (const headerName in headers) {\n // Lowercasing header names makes it easier to override user-supplied headers.\n out[headerName.toLowerCase()] = headers[headerName];\n }\n return out as { [K in string & keyof T as Lowercase]: T[K] };\n}\n\n/**\n * Creates a {@link RpcTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - An automatically-set `Solana-Client` request header, containing the version of `@solana/kit`\n * - Logic that coalesces multiple calls in the same runloop, for the same methods with the same\n * arguments, into a single network request.\n * - [node-only] An automatically-set `Accept-Encoding` request header asking the server to compress\n * responses\n *\n * @param config\n */\nexport function createDefaultRpcTransport(\n config: DefaultRpcTransportConfig,\n): RpcTransportFromClusterUrl {\n return pipe(\n createHttpTransportForSolanaRpc({\n ...config,\n headers: {\n ...(__NODEJS__ &&\n ({\n // Keep these headers lowercase so they will be overridden by any user-supplied headers below.\n 'accept-encoding':\n // Natively supported by Node LTS v20.18.0 and above.\n 'br,gzip,deflate', // Brotli, gzip, and Deflate, in that order.\n } as { [overrideHeader: string]: string })),\n ...(config.headers ? normalizeHeaders(config.headers) : undefined),\n ...({\n // Keep these headers lowercase so they will override any user-supplied headers above.\n 'solana-client': __VERSION__ ? `js/${__VERSION__}` : 'UNKNOWN',\n } as { [overrideHeader: string]: string }),\n },\n }) as RpcTransportFromClusterUrl,\n transport => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey),\n );\n}\n","import { createSolanaRpcApi } from '@solana/rpc-api';\nimport { createRpc, RpcTransport } from '@solana/rpc-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport type { RpcFromTransport, SolanaRpcApiFromTransport } from './rpc-clusters';\nimport { DEFAULT_RPC_CONFIG } from './rpc-default-config';\nimport { createDefaultRpcTransport } from './rpc-transport';\n\ntype DefaultRpcTransportConfig = Parameters<\n typeof createDefaultRpcTransport\n>[0];\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given a cluster URL and some\n * optional transport config. See {@link createDefaultRpcTransport} for the shape of the transport\n * config.\n */\nexport function createSolanaRpc(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcFromTransport(createDefaultRpcTransport({ url: clusterUrl, ...config }));\n}\n\n/**\n * Creates a {@link Rpc} instance that exposes the Solana JSON RPC API given the supplied\n * {@link RpcTransport}.\n */\nexport function createSolanaRpcFromTransport(transport: TTransport) {\n return createRpc({\n api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),\n transport,\n }) as RpcFromTransport, TTransport>;\n}\n","\n//# sourceMappingURL=index.node.mjs.map\n//# sourceMappingURL=index.node.mjs.map","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable {\n const iteratorState: Map> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher = Record> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter>(\n eventEmitter: TypedEventEmitter | TypedEventTarget,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\nimport { createAsyncIterableFromDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsApi, RpcSubscriptionsPlan } from './rpc-subscriptions-api';\nimport { PendingRpcSubscriptionsRequest, RpcSubscribeOptions } from './rpc-subscriptions-request';\nimport { RpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsConfig = Readonly<{\n api: RpcSubscriptionsApi;\n transport: RpcSubscriptionsTransport;\n}>;\n\n/**\n * An object that exposes all of the functions described by `TRpcSubscriptionsMethods`.\n *\n * Calling each method returns a\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} where\n * `TNotification` is that method's notification type.\n */\nexport type RpcSubscriptions = {\n [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder<\n OverloadImplementations\n >;\n};\n\ntype PendingRpcSubscriptionsRequestBuilder = UnionToIntersection<\n Flatten<{\n [P in keyof TSubscriptionMethodImplementations]: PendingRpcSubscriptionsRequestReturnTypeMapper<\n TSubscriptionMethodImplementations[P]\n >;\n }>\n>;\n\ntype PendingRpcSubscriptionsRequestReturnTypeMapper =\n // Check that this property of the TRpcSubscriptionMethods interface is, in fact, a function.\n TSubscriptionMethodImplementation extends Callable\n ? (\n ...args: Parameters\n ) => PendingRpcSubscriptionsRequest>\n : never;\n\n/**\n * Creates a {@link RpcSubscriptions} instance given a\n * {@link RpcSubscriptionsApi | RpcSubscriptionsApi} and a\n * {@link RpcSubscriptionsTransport} capable of fulfilling them.\n */\nexport function createSubscriptionRpc(\n rpcConfig: RpcSubscriptionsConfig,\n): RpcSubscriptions {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n if (p === 'then') {\n return undefined;\n }\n return function (...rawParams: unknown[]) {\n const notificationName = p.toString();\n const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);\n if (!createRpcSubscriptionPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {\n notificationName,\n });\n }\n const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);\n return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);\n };\n },\n }) as RpcSubscriptions;\n}\n\nfunction createPendingRpcSubscription(\n transport: RpcSubscriptionsTransport,\n subscriptionsPlan: RpcSubscriptionsPlan,\n): PendingRpcSubscriptionsRequest {\n return {\n async subscribe({ abortSignal }: RpcSubscribeOptions): Promise> {\n const notificationsDataPublisher = await transport({\n signal: abortSignal,\n ...subscriptionsPlan,\n });\n return createAsyncIterableFromDataPublisher({\n abortSignal,\n dataChannelName: 'notification',\n dataPublisher: notificationsDataPublisher,\n errorChannelName: 'error',\n });\n },\n };\n}\n","import { Callable, RpcRequest, RpcRequestTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsTransportDataEvents } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsApiConfig = Readonly<{\n planExecutor: RpcSubscriptionsPlanExecutor>;\n /**\n * An optional function that transforms the {@link RpcRequest} before it is sent to the JSON RPC\n * server.\n *\n * This is useful when the params supplied by the caller need to be transformed before\n * forwarding the message to the server. Use cases for this include applying defaults,\n * forwarding calls to renamed methods, and serializing complex values.\n */\n requestTransformer?: RpcRequestTransformer;\n}>;\n\n/**\n * A function that implements a protocol for subscribing and unsubscribing from notifications given\n * a {@link RpcSubscriptionsChannel}, a {@link RpcRequest}, and an `AbortSignal`.\n *\n * @returns A {@link DataPublisher} that emits {@link RpcSubscriptionsTransportDataEvents}\n */\ntype RpcSubscriptionsPlanExecutor = (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n request: RpcRequest;\n signal: AbortSignal;\n }>,\n) => Promise>>;\n\n/**\n * This type allows an {@link RpcSubscriptionsApi} to describe how a particular subscription should\n * be issued to the JSON RPC server.\n *\n * Given a function that was called on a {@link RpcSubscriptions}, this object exposes an `execute`\n * function that dictates which subscription request will be sent, how the underlying transport will\n * be used, and how the notifications will be transformed.\n *\n * This function accepts a {@link RpcSubscriptionsChannel} and an `AbortSignal` and asynchronously\n * returns a {@link DataPublisher}. This gives us the opportunity to:\n *\n * - define the `payload` from the requested method name and parameters before passing it to the\n * channel.\n * - call the underlying channel zero, one or multiple times depending on the use-case (e.g.\n * caching or coalescing multiple subscriptions).\n * - transform the notification from the JSON RPC server, in case it does not match the\n * `TNotification` specified by the\n * {@link PendingRpcSubscriptionsRequest | PendingRpcSubscriptionsRequest} emitted\n * from the publisher returned.\n */\nexport type RpcSubscriptionsPlan = Readonly<{\n /**\n * This method may be called with a newly-opened channel or a pre-established channel.\n */\n execute: (\n config: Readonly<{\n channel: RpcSubscriptionsChannel;\n signal: AbortSignal;\n }>,\n ) => Promise>>;\n /**\n * This request is used to uniquely identify the subscription.\n * It typically comes from the method name and parameters of the subscription call,\n * after potentially being transformed by the RPC Subscriptions API.\n */\n request: RpcRequest;\n}>;\n\n/**\n * For each of `TRpcSubscriptionsMethods`, this object exposes a method with the same name that maps\n * between its input arguments and a\n * {@link RpcSubscriptionsPlan | RpcSubscriptionsPlan} that implements the execution\n * of a JSON RPC subscription for `TNotifications`.\n */\nexport type RpcSubscriptionsApi = {\n [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper<\n TRpcSubscriptionMethods[MethodName]\n >;\n};\n\ntype RpcSubscriptionsReturnTypeMapper = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcSubscriptionsPlan>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcSubscriptionsApiMethod = (...args: any) => any;\nexport interface RpcSubscriptionsApiMethods {\n [methodName: string]: RpcSubscriptionsApiMethod;\n}\n\n/**\n * Creates a JavaScript proxy that converts _any_ function call called on it to a\n * {@link RpcSubscriptionsPlan} by creating an `execute` function that:\n *\n * - calls the supplied {@link RpcSubscriptionsApiConfig.planExecutor} with a JSON RPC v2 payload\n * object with the requested `methodName` and `params` properties, optionally transformed by\n * {@link RpcSubscriptionsApiConfig.requestTransformer}.\n *\n * @example\n * ```ts\n * // For example, given this `RpcSubscriptionsApi`:\n * const rpcSubscriptionsApi = createJsonRpcSubscriptionsApi({\n * async planExecutor({ channel, request }) {\n * await channel.send(request);\n * return {\n * ...channel,\n * on(type, listener, options) {\n * if (type !== 'message') {\n * return channel.on(type, listener, options);\n * }\n * return channel.on(\n * 'message',\n * function resultGettingListener(message) {\n * listener(message.result);\n * },\n * options,\n * );\n * }\n * }\n * },\n * requestTransformer: (...rawParams) => rawParams.reverse(),\n * });\n *\n * // ...the following function call:\n * rpcSubscriptionsApi.foo('bar', { baz: 'bat' });\n *\n * // ...will produce a `RpcSubscriptionsPlan` that:\n * // - Uses the following payload: { id: 1, jsonrpc: '2.0', method: 'foo', params: [{ baz: 'bat' }, 'bar'] }.\n * // - Emits the \"result\" property of each RPC Subscriptions message.\n * ```\n */\nexport function createRpcSubscriptionsApi(\n config: RpcSubscriptionsApiConfig,\n): RpcSubscriptionsApi {\n return new Proxy({} as RpcSubscriptionsApi, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get>(\n ...args: Parameters>['get']>>\n ) {\n const [_, p] = args;\n const methodName = p.toString() as keyof TRpcSubscriptionsApiMethods as string;\n return function (\n ...params: Parameters<\n TRpcSubscriptionsApiMethods[TNotificationName] extends CallableFunction\n ? TRpcSubscriptionsApiMethods[TNotificationName]\n : never\n >\n ): RpcSubscriptionsPlan> {\n const rawRequest = { methodName, params };\n const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;\n return {\n execute(planConfig) {\n return config.planExecutor({ ...planConfig, request });\n },\n request,\n };\n };\n },\n });\n}\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype RpcSubscriptionsChannelSolanaErrorCode =\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED\n | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT;\n\nexport type RpcSubscriptionChannelEvents = {\n /**\n * Fires when the channel closes unexpectedly.\n * @eventProperty\n */\n error: SolanaError;\n /**\n * Fires on every message received from the remote end.\n * @eventProperty\n */\n message: TInboundMessage;\n};\n\n/**\n * A {@link DataPublisher} on which you can subscribe to events of type\n * {@link RpcSubscriptionChannelEvents | RpcSubscriptionChannelEvents}.\n * Additionally, you can use this object to send messages of type `TOutboundMessage` back to the\n * remote end by calling its {@link RpcSubscriptionsChannel.send | `send(message)`} method.\n */\nexport interface RpcSubscriptionsChannel extends DataPublisher<\n RpcSubscriptionChannelEvents\n> {\n send(message: TOutboundMessage): Promise;\n}\n\n/**\n * A channel creator is a function that accepts an `AbortSignal`, returns a new\n * {@link RpcSubscriptionsChannel}, and tears down the channel when the abort signal fires.\n */\nexport type RpcSubscriptionsChannelCreator = (\n config: Readonly<{\n abortSignal: AbortSignal;\n }>,\n) => Promise>;\n\n/**\n * Given a channel with inbound messages of type `T` and a function of type `T => U`, returns a new\n * channel with inbound messages of type `U`.\n *\n * Note that this only affects messages of type `\"message\"` and thus, does not affect incoming error\n * messages.\n *\n * @example Parsing incoming JSON messages\n * ```ts\n * const transformedChannel = transformChannelInboundMessages(channel, JSON.parse);\n * ```\n */\nexport function transformChannelInboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TInboundMessage) => TNewInboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n on(type, subscriber, options) {\n if (type !== 'message') {\n return channel.on(\n type,\n subscriber as (data: RpcSubscriptionChannelEvents[typeof type]) => void,\n options,\n );\n }\n return channel.on(\n 'message',\n message => (subscriber as (data: TNewInboundMessage) => void)(transform(message)),\n options,\n );\n },\n });\n}\n\n/**\n * Given a channel with outbound messages of type `T` and a function of type `U => T`, returns a new\n * channel with outbound messages of type `U`.\n *\n * @example Stringifying JSON messages before sending them over the wire\n * ```ts\n * const transformedChannel = transformChannelOutboundMessages(channel, JSON.stringify);\n * ```\n */\nexport function transformChannelOutboundMessages(\n channel: RpcSubscriptionsChannel,\n transform: (message: TNewOutboundMessage) => TOutboundMessage,\n): RpcSubscriptionsChannel {\n return Object.freeze>({\n ...channel,\n send: message => channel.send(transform(message)),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import {\n getSolanaErrorFromJsonRpcError,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport { createRpcMessage, RpcRequest, RpcResponseData, RpcResponseTransformer } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\nimport { demultiplexDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionChannelEvents } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\n\ntype Config = Readonly<{\n channel: RpcSubscriptionsChannel | RpcResponseData>;\n responseTransformer?: RpcResponseTransformer;\n signal: AbortSignal;\n subscribeRequest: RpcRequest;\n unsubscribeMethodName: string;\n}>;\n\ntype RpcNotification = Readonly<{\n method: string;\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\n\ntype RpcSubscriptionId = number;\n\ntype RpcSubscriptionNotificationEvents = Omit, 'message'> & {\n notification: TNotification;\n};\n\nconst subscriberCountBySubscriptionIdByChannel = new WeakMap>();\nfunction decrementSubscriberCountAndReturnNewCount(channel: WeakKey, subscriptionId?: number): number | undefined {\n return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);\n}\nfunction incrementSubscriberCount(channel: WeakKey, subscriptionId?: number): void {\n augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);\n}\nfunction getSubscriberCountBySubscriptionIdForChannel(channel: WeakKey): Record {\n let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);\n if (!subscriberCountBySubscriptionId) {\n subscriberCountBySubscriptionIdByChannel.set(channel, (subscriberCountBySubscriptionId = {}));\n }\n return subscriberCountBySubscriptionId;\n}\nfunction augmentSubscriberCountAndReturnNewCount(\n amount: -1 | 1,\n channel: WeakKey,\n subscriptionId?: number,\n): number | undefined {\n if (subscriptionId === undefined) {\n return;\n }\n const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);\n if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) {\n subscriberCountBySubscriptionId[subscriptionId] = 0;\n }\n const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];\n if (newCount <= 0) {\n delete subscriberCountBySubscriptionId[subscriptionId];\n } else {\n subscriberCountBySubscriptionId[subscriptionId] = newCount;\n }\n return newCount;\n}\n\nconst cache = new WeakMap();\nfunction getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel: RpcSubscriptionsChannel>,\n subscribeRequest: RpcRequest,\n responseTransformer?: RpcResponseTransformer,\n): DataPublisher<{\n [channelName: `notification:${number}`]: TNotification;\n}> {\n let publisherByResponseTransformer = cache.get(channel);\n if (!publisherByResponseTransformer) {\n cache.set(channel, (publisherByResponseTransformer = new WeakMap()));\n }\n const responseTransformerKey = responseTransformer ?? channel;\n let publisher = publisherByResponseTransformer.get(responseTransformerKey);\n if (!publisher) {\n publisherByResponseTransformer.set(\n responseTransformerKey,\n (publisher = demultiplexDataPublisher(channel, 'message', rawMessage => {\n const message = rawMessage as RpcNotification | RpcResponseData;\n if (!('method' in message)) {\n return;\n }\n const transformedNotification = responseTransformer\n ? responseTransformer(message.params.result, subscribeRequest)\n : message.params.result;\n return [`notification:${message.params.subscription}`, transformedNotification];\n })),\n );\n }\n return publisher;\n}\n\n/**\n * Given a channel, this function executes the particular subscription plan required by the Solana\n * JSON RPC Subscriptions API.\n *\n * @param config\n *\n * 1. Calls the `subscribeRequest` on the remote RPC\n * 2. Waits for a response containing the subscription id\n * 3. Returns a {@link DataPublisher} that publishes notifications related to that subscriptions id,\n * filtering out all others\n * 4. Calls the `unsubscribeMethodName` on the remote RPC when the abort signal is fired.\n */\nexport async function executeRpcPubSubSubscriptionPlan({\n channel,\n responseTransformer,\n signal,\n subscribeRequest,\n unsubscribeMethodName,\n}: Config): Promise>> {\n let subscriptionId: number | undefined;\n channel.on(\n 'error',\n () => {\n // An error on the channel indicates that the subscriptions are dead.\n // There is no longer any sense hanging on to subscription ids.\n // Erasing it here will prevent the unsubscribe code from running.\n subscriptionId = undefined;\n subscriberCountBySubscriptionIdByChannel.delete(channel);\n },\n { signal },\n );\n /**\n * STEP 1\n * Create a promise that rejects if this subscription is aborted and sends\n * the unsubscribe message if the subscription is active at that time.\n */\n const abortPromise = new Promise((_, reject) => {\n function handleAbort(this: AbortSignal) {\n /**\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they\n * will be assigned the same subscription id, and will occupy one subscription slot. We\n * must be careful not to send the unsubscribe message until the last subscriber aborts.\n */\n if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {\n const unsubscribePayload = createRpcMessage({\n methodName: unsubscribeMethodName,\n params: [subscriptionId],\n });\n subscriptionId = undefined;\n channel.send(unsubscribePayload).catch(() => {});\n }\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(this.reason);\n }\n if (signal.aborted) {\n handleAbort.call(signal);\n } else {\n signal.addEventListener('abort', handleAbort);\n }\n });\n /**\n * STEP 2\n * Send the subscription request.\n */\n const subscribePayload = createRpcMessage(subscribeRequest);\n await channel.send(subscribePayload);\n /**\n * STEP 3\n * Wait for the acknowledgement from the server with the subscription id.\n */\n const subscriptionIdPromise = new Promise((resolve, reject) => {\n const abortController = new AbortController();\n signal.addEventListener('abort', abortController.abort.bind(abortController));\n const options = { signal: abortController.signal } as const;\n channel.on(\n 'error',\n err => {\n abortController.abort();\n reject(err);\n },\n options,\n );\n channel.on(\n 'message',\n message => {\n if (message && typeof message === 'object' && 'id' in message && message.id === subscribePayload.id) {\n abortController.abort();\n if ('error' in message) {\n reject(getSolanaErrorFromJsonRpcError(message.error));\n } else {\n resolve(message.result);\n }\n }\n },\n options,\n );\n });\n subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);\n if (subscriptionId == null) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);\n }\n incrementSubscriberCount(channel, subscriptionId);\n /**\n * STEP 4\n * Filter out notifications unrelated to this subscription.\n */\n const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel,\n subscribeRequest,\n responseTransformer,\n );\n const notificationKey = `notification:${subscriptionId}` as const;\n return {\n on(type, listener, options) {\n switch (type) {\n case 'notification':\n return notificationPublisher.on(\n notificationKey,\n listener as (data: RpcSubscriptionNotificationEvents['notification']) => void,\n options,\n );\n case 'error':\n return channel.on(\n 'error',\n listener as (data: RpcSubscriptionNotificationEvents['error']) => void,\n options,\n );\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {\n channelName: type,\n supportedChannelNames: ['notification', 'error'],\n });\n }\n },\n };\n}\n","import {\n createRpcSubscriptionsApi,\n executeRpcPubSubSubscriptionPlan,\n RpcSubscriptionsApi,\n RpcSubscriptionsApiMethods,\n} from '@solana/rpc-subscriptions-spec';\nimport {\n AllowedNumericKeypaths,\n getDefaultRequestTransformerForSolanaRpc,\n getDefaultResponseTransformerForSolanaRpcSubscriptions,\n jsonParsedAccountsConfigs,\n KEYPATH_WILDCARD,\n RequestTransformerConfig,\n} from '@solana/rpc-transformers';\n\nimport { AccountNotificationsApi } from './account-notifications';\nimport { BlockNotificationsApi } from './block-notifications';\nimport { LogsNotificationsApi } from './logs-notifications';\nimport { ProgramNotificationsApi } from './program-notifications';\nimport { RootNotificationsApi } from './root-notifications';\nimport { SignatureNotificationsApi } from './signature-notifications';\nimport { SlotNotificationsApi } from './slot-notifications';\nimport { SlotsUpdatesNotificationsApi } from './slots-updates-notifications';\nimport { VoteNotificationsApi } from './vote-notifications';\n\nexport type SolanaRpcSubscriptionsApi = AccountNotificationsApi &\n LogsNotificationsApi &\n ProgramNotificationsApi &\n RootNotificationsApi &\n SignatureNotificationsApi &\n SlotNotificationsApi;\nexport type SolanaRpcSubscriptionsApiUnstable = BlockNotificationsApi &\n SlotsUpdatesNotificationsApi &\n VoteNotificationsApi;\n\nexport type {\n AccountNotificationsApi,\n BlockNotificationsApi,\n LogsNotificationsApi,\n ProgramNotificationsApi,\n RootNotificationsApi,\n SignatureNotificationsApi,\n SlotNotificationsApi,\n SlotsUpdatesNotificationsApi,\n VoteNotificationsApi,\n};\n\ntype Config = RequestTransformerConfig;\n\nfunction createSolanaRpcSubscriptionsApi_INTERNAL(\n config?: Config,\n): RpcSubscriptionsApi {\n const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);\n const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({\n allowedNumericKeyPaths: getAllowedNumericKeypaths(),\n });\n return createRpcSubscriptionsApi({\n planExecutor({ request, ...rest }) {\n return executeRpcPubSubSubscriptionPlan({\n ...rest,\n responseTransformer,\n subscribeRequest: { ...request, methodName: request.methodName.replace(/Notifications$/, 'Subscribe') },\n unsubscribeMethodName: request.methodName.replace(/Notifications$/, 'Unsubscribe'),\n });\n },\n requestTransformer,\n });\n}\n\nexport function createSolanaRpcSubscriptionsApi(\n config?: Config,\n): RpcSubscriptionsApi {\n return createSolanaRpcSubscriptionsApi_INTERNAL(config);\n}\n\nexport function createSolanaRpcSubscriptionsApi_UNSTABLE(config?: Config) {\n return createSolanaRpcSubscriptionsApi_INTERNAL(\n config,\n );\n}\n\nlet memoizedKeypaths: AllowedNumericKeypaths<\n RpcSubscriptionsApi\n>;\n\n/**\n * These are keypaths at the end of which you will find a numeric value that should *not* be upcast\n * to a `bigint`. These are values that are legitimately defined as `u8` or `usize` on the backend.\n */\nfunction getAllowedNumericKeypaths(): AllowedNumericKeypaths<\n RpcSubscriptionsApi\n> {\n if (!memoizedKeypaths) {\n memoizedKeypaths = {\n accountNotifications: jsonParsedAccountsConfigs.map(c => ['value', ...c]),\n blockNotifications: [\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'preTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'accountIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'postTokenBalances',\n KEYPATH_WILDCARD,\n 'uiTokenAmount',\n 'decimals',\n ],\n ['value', 'block', 'transactions', KEYPATH_WILDCARD, 'meta', 'rewards', KEYPATH_WILDCARD, 'commission'],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'index',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'meta',\n 'innerInstructions',\n KEYPATH_WILDCARD,\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'writableIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'addressTableLookups',\n KEYPATH_WILDCARD,\n 'readonlyIndexes',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'programIdIndex',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'instructions',\n KEYPATH_WILDCARD,\n 'accounts',\n KEYPATH_WILDCARD,\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlySignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numReadonlyUnsignedAccounts',\n ],\n [\n 'value',\n 'block',\n 'transactions',\n KEYPATH_WILDCARD,\n 'transaction',\n 'message',\n 'header',\n 'numRequiredSignatures',\n ],\n ['value', 'block', 'rewards', KEYPATH_WILDCARD, 'commission'],\n ],\n programNotifications: jsonParsedAccountsConfigs.flatMap(c => [\n ['value', KEYPATH_WILDCARD, 'account', ...c],\n [KEYPATH_WILDCARD, 'account', ...c],\n ]),\n };\n }\n return memoizedKeypaths;\n}\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 CLOSE_TIMEOUT: 30000,\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","'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\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\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\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\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 | String)[]} 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 CLOSE_TIMEOUT,\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 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._closeTimeout = options.closeTimeout;\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 {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\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 closeTimeout: CLOSE_TIMEOUT,\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 websocket._closeTimeout = opts.closeTimeout;\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 websocket._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 //\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. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\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","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\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 { 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 { CLOSE_TIMEOUT, 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 {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\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 closeTimeout: CLOSE_TIMEOUT,\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 !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\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 * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\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, headers);\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","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","// When building the browser bundle, this import gets replaced by `globalThis.WebSocket`.\nimport WebSocketImpl from 'ws';\n\nexport default globalThis.WebSocket\n ? globalThis.WebSocket // Use native `WebSocket` in runtimes that support it (eg. Deno)\n : WebSocketImpl;\n","import {\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,\n SolanaError,\n} from '@solana/errors';\nimport { EventTarget } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport { getDataPublisherFromEventEmitter } from '@solana/subscribable';\nimport WebSocket from '@solana/ws-impl';\n\nexport type Config = Readonly<{\n /**\n * The number of bytes to admit into the WebSocket's send buffer before queueing messages on the\n * client.\n *\n * When you call {@link RpcSubscriptionsChannel.send | `send()`} on a `WebSocket` the runtime\n * might add the message to a buffer rather than send it right away. In the event that\n * `socket.bufferedAmount` exceeds the value configured here, messages will be added to a queue\n * in your application code instead of being sent to the WebSocket, until such time as the\n * `bufferedAmount` falls back below the high watermark.\n */\n sendBufferHighWatermark: number;\n /**\n * An `AbortSignal` to fire when you want to explicitly close the `WebSocket`.\n *\n * If the channel is open it will be closed with a normal closure code\n * (https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1) If the channel has not been\n * established yet, firing this signal will result in the `AbortError` being thrown to the\n * caller who was trying to open the channel.\n */\n signal: AbortSignal;\n /**\n * A string representing the target endpoint.\n *\n * In Node, it must be an absolute URL using the `ws` or `wss` protocol.\n */\n url: string;\n}>;\n\ntype WebSocketMessage = ArrayBufferLike | ArrayBufferView | Blob | string;\n\nconst NORMAL_CLOSURE_CODE = 1000; // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n\n/**\n * Creates an object that represents an open channel to a `WebSocket` server.\n *\n * You can use it to send messages by calling its\n * {@link RpcSubscriptionsChannel.send | `send()`} function and you can receive them by subscribing\n * to the {@link RpcSubscriptionChannelEvents} it emits.\n */\nexport function createWebSocketChannel({\n sendBufferHighWatermark,\n signal,\n url,\n}: Config): Promise> {\n if (signal.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(signal.reason);\n }\n let bufferDrainWatcher: Readonly<{ onCancel(): void; promise: Promise }> | undefined;\n let hasConnected = false;\n const listenerRemovers = new Set<() => void>();\n function cleanupListeners() {\n listenerRemovers.forEach(r => {\n r();\n });\n listenerRemovers.clear();\n }\n function handleAbort() {\n cleanupListeners();\n if (!hasConnected) {\n rejectOpen(signal.reason);\n }\n if (webSocket.readyState !== WebSocket.CLOSED && webSocket.readyState !== WebSocket.CLOSING) {\n webSocket.close(NORMAL_CLOSURE_CODE);\n }\n }\n function handleClose(ev: CloseEvent) {\n cleanupListeners();\n bufferDrainWatcher?.onCancel();\n signal.removeEventListener('abort', handleAbort);\n webSocket.removeEventListener('close', handleClose);\n webSocket.removeEventListener('error', handleError);\n webSocket.removeEventListener('message', handleMessage);\n webSocket.removeEventListener('open', handleOpen);\n if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) {\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, {\n cause: ev,\n }),\n }),\n );\n }\n }\n function handleError(ev: Event) {\n if (signal.aborted) {\n return;\n }\n if (!hasConnected) {\n const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, {\n errorEvent: ev,\n });\n rejectOpen(failedToConnectError);\n eventTarget.dispatchEvent(\n new CustomEvent('error', {\n detail: failedToConnectError,\n }),\n );\n }\n }\n function handleMessage(ev: MessageEvent) {\n if (signal.aborted) {\n return;\n }\n eventTarget.dispatchEvent(new CustomEvent('message', { detail: ev.data }));\n }\n const eventTarget = new EventTarget();\n const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n function handleOpen() {\n hasConnected = true;\n resolveOpen({\n ...dataPublisher,\n async send(message) {\n if (webSocket.readyState !== WebSocket.OPEN) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);\n }\n if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {\n let onCancel!: () => void;\n const promise = new Promise((resolve, reject) => {\n const intervalId = setInterval(() => {\n if (\n webSocket.readyState !== WebSocket.OPEN ||\n !(webSocket.bufferedAmount > sendBufferHighWatermark)\n ) {\n clearInterval(intervalId);\n bufferDrainWatcher = undefined;\n resolve();\n }\n }, 16);\n onCancel = () => {\n bufferDrainWatcher = undefined;\n clearInterval(intervalId);\n reject(\n new SolanaError(\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,\n ),\n );\n };\n });\n bufferDrainWatcher = {\n onCancel,\n promise,\n };\n }\n if (bufferDrainWatcher) {\n if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {\n const TypedArrayConstructor = message.constructor as {\n new (...args: [typeof message]): typeof message;\n };\n // Clone the message to prevent mutation while queued.\n message = new TypedArrayConstructor(message);\n }\n await bufferDrainWatcher.promise;\n }\n webSocket.send(message);\n },\n });\n }\n const webSocket = new WebSocket(url);\n signal.addEventListener('abort', handleAbort);\n webSocket.addEventListener('close', handleClose);\n webSocket.addEventListener('error', handleError);\n webSocket.addEventListener('message', handleMessage);\n webSocket.addEventListener('open', handleOpen);\n let rejectOpen!: (e: SolanaError) => void;\n let resolveOpen!: (value: RpcSubscriptionsChannel) => void;\n return new Promise>((resolve, reject) => {\n rejectOpen = reject;\n resolveOpen = resolve;\n });\n}\n","import { safeCaptureStackTrace, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SolanaError } from '@solana/errors';\nimport type { KeyPath } from '@solana/rpc-transformers';\n\nexport function createSolanaJsonRpcIntegerOverflowError(\n methodName: string,\n keyPath: KeyPath,\n value: bigint,\n): SolanaError {\n let argumentLabel = '';\n if (typeof keyPath[0] === 'number') {\n const argPosition = keyPath[0] + 1;\n const lastDigit = argPosition % 10;\n const lastTwoDigits = argPosition % 100;\n if (lastDigit == 1 && lastTwoDigits != 11) {\n argumentLabel = argPosition + 'st';\n } else if (lastDigit == 2 && lastTwoDigits != 12) {\n argumentLabel = argPosition + 'nd';\n } else if (lastDigit == 3 && lastTwoDigits != 13) {\n argumentLabel = argPosition + 'rd';\n } else {\n argumentLabel = argPosition + 'th';\n }\n } else {\n argumentLabel = `\\`${keyPath[0].toString()}\\``;\n }\n const path =\n keyPath.length > 1\n ? keyPath\n .slice(1)\n .map(pathPart => (typeof pathPart === 'number' ? `[${pathPart}]` : pathPart))\n .join('.')\n : undefined;\n const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {\n argumentLabel,\n keyPath: keyPath as readonly (number | string | symbol)[],\n methodName,\n optionalPathLabel: path ? ` at path \\`${path}\\`` : '',\n value,\n ...(path !== undefined ? { path } : undefined),\n });\n safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);\n return error;\n}\n","import type { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\n\nimport { createSolanaJsonRpcIntegerOverflowError } from './rpc-integer-overflow-error';\n\nexport const DEFAULT_RPC_SUBSCRIPTIONS_CONFIG: Partial<\n NonNullable[0]>\n> = {\n defaultCommitment: 'confirmed',\n onIntegerOverflow(request, keyPath, value) {\n throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);\n },\n};\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { isSolanaError, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\ntype Config> = Readonly<{\n abortSignal: AbortSignal;\n channel: TChannel;\n intervalMs: number;\n}>;\n\nconst PING_PAYLOAD = {\n jsonrpc: '2.0',\n method: 'ping',\n} as const;\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that sends a ping message to\n * the inner channel if a message has not been sent or received in the last `intervalMs`. In web\n * browsers, this implementation sends no ping when the network is down, and sends a ping\n * immediately upon the network coming back up.\n */\nexport function getRpcSubscriptionsChannelWithAutoping>({\n abortSignal: callerAbortSignal,\n channel,\n intervalMs,\n}: Config): TChannel {\n let intervalId: ReturnType | undefined;\n function sendPing() {\n channel.send(PING_PAYLOAD).catch((e: unknown) => {\n if (isSolanaError(e, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED)) {\n pingerAbortController.abort();\n }\n });\n }\n function restartPingTimer() {\n clearInterval(intervalId);\n intervalId = setInterval(sendPing, intervalMs);\n }\n const pingerAbortController = new AbortController();\n pingerAbortController.signal.addEventListener('abort', () => {\n clearInterval(intervalId);\n });\n callerAbortSignal.addEventListener('abort', () => {\n pingerAbortController.abort();\n });\n channel.on(\n 'error',\n () => {\n pingerAbortController.abort();\n },\n { signal: pingerAbortController.signal },\n );\n channel.on('message', restartPingTimer, { signal: pingerAbortController.signal });\n if (!__BROWSER__ || globalThis.navigator.onLine) {\n restartPingTimer();\n }\n if (__BROWSER__) {\n globalThis.addEventListener(\n 'offline',\n function handleOffline() {\n clearInterval(intervalId);\n },\n { signal: pingerAbortController.signal },\n );\n globalThis.addEventListener(\n 'online',\n function handleOnline() {\n sendPing();\n restartPingTimer();\n },\n { signal: pingerAbortController.signal },\n );\n }\n return {\n ...channel,\n send(...args) {\n if (!pingerAbortController.signal.aborted) {\n restartPingTimer();\n }\n return channel.send(...args);\n },\n };\n}\n","import { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\n\nexport type ChannelPoolEntry = {\n channel: PromiseLike> | RpcSubscriptionsChannel;\n readonly dispose: () => void;\n subscriptionCount: number;\n};\n\ntype ChannelPool = { readonly entries: ChannelPoolEntry[]; freeChannelIndex: number };\n\nexport function createChannelPool(): ChannelPool {\n return {\n entries: [],\n freeChannelIndex: -1,\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport { RpcSubscriptionsChannelCreator } from '@solana/rpc-subscriptions-spec';\n\nimport { ChannelPoolEntry, createChannelPool } from './rpc-subscriptions-channel-pool-internal';\n\ntype Config = Readonly<{\n maxSubscriptionsPerChannel: number;\n minChannels: number;\n}>;\n\n/**\n * Given a channel creator, will return a new channel creator with the following behavior.\n *\n * 1. When called, returns a {@link RpcSubscriptionsChannel}. Adds that channel to a pool.\n * 2. When called again, creates and returns new\n * {@link RpcSubscriptionChannel | RpcSubscriptionChannels} up to the number specified by\n * `minChannels`.\n * 3. When `minChannels` channels have been created, subsequent calls vend whichever existing\n * channel from the pool has the fewest subscribers, or the next one in rotation in the event of\n * a tie.\n * 4. Once all channels carry the number of subscribers specified by the number\n * `maxSubscriptionsPerChannel`, new channels in excess of `minChannel` will be created,\n * returned, and added to the pool.\n * 5. A channel will be destroyed once all of its subscribers' abort signals fire.\n */\nexport function getChannelPoolingChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n>(createChannel: TChannelCreator, { maxSubscriptionsPerChannel, minChannels }: Config): TChannelCreator {\n const pool = createChannelPool();\n /**\n * This function advances the free channel index to the pool entry with the most capacity. It\n * sets the index to `-1` if all channels are full.\n */\n function recomputeFreeChannelIndex() {\n if (pool.entries.length < minChannels) {\n // Don't set the free channel index until the pool fills up; we want to keep creating\n // channels before we start rotating among them.\n pool.freeChannelIndex = -1;\n return;\n }\n let mostFreeChannel: Readonly<{ poolIndex: number; subscriptionCount: number }> | undefined;\n for (let ii = 0; ii < pool.entries.length; ii++) {\n const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;\n const nextPoolEntry =\n // Start from the item two positions after the current item. This way, the\n // search will finish on the item after the current one. This ensures that, if\n // any channels tie for having the most capacity, the one that will be chosen is\n // the one immediately to the current one's right (wrapping around).\n pool.entries[nextPoolIndex];\n if (\n nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel &&\n (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)\n ) {\n mostFreeChannel = {\n poolIndex: nextPoolIndex,\n subscriptionCount: nextPoolEntry.subscriptionCount,\n };\n }\n }\n pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;\n }\n return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {\n let poolEntry: ChannelPoolEntry;\n function destroyPoolEntry() {\n const index = pool.entries.findIndex(entry => entry === poolEntry);\n pool.entries.splice(index, 1);\n poolEntry.dispose();\n recomputeFreeChannelIndex();\n }\n if (pool.freeChannelIndex === -1) {\n const abortController = new AbortController();\n const newChannelPromise = createChannel({ abortSignal: abortController.signal });\n newChannelPromise\n .then(newChannel => {\n newChannel.on('error', destroyPoolEntry, { signal: abortController.signal });\n })\n .catch(destroyPoolEntry);\n poolEntry = {\n channel: newChannelPromise,\n dispose() {\n abortController.abort();\n },\n subscriptionCount: 0,\n };\n pool.entries.push(poolEntry);\n } else {\n poolEntry = pool.entries[pool.freeChannelIndex];\n }\n /**\n * A note about subscription counts.\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they will be\n * assigned the same subscription id, and will occupy one subscription slot. We can't tell,\n * from here, whether a subscription will be treated in this way or not, so we\n * unconditionally increment the subscription count every time a subscription request is\n * made. This may result in subscription channels being treated as out-of-capacity when in\n * fact they are not.\n */\n poolEntry.subscriptionCount++;\n abortSignal.addEventListener('abort', function destroyConsumer() {\n poolEntry.subscriptionCount--;\n if (poolEntry.subscriptionCount === 0) {\n destroyPoolEntry();\n } else if (pool.freeChannelIndex !== -1) {\n // Back the free channel index up one position, and recompute it.\n pool.freeChannelIndex--;\n recomputeFreeChannelIndex();\n }\n });\n recomputeFreeChannelIndex();\n return poolEntry.channel;\n } as TChannelCreator;\n}\n","import { pipe } from '@solana/functional';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Given a {@link RpcSubscriptionsChannel}, will return a new channel that parses data published to\n * the `'message'` channel as JSON, and JSON-stringifies messages sent via the\n * {@link RpcSubscriptionsChannel.send | send(message)} method.\n */\nexport function getRpcSubscriptionsChannelWithJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, JSON.parse),\n c => transformChannelOutboundMessages(c, JSON.stringify),\n );\n}\n","import { pipe } from '@solana/functional';\nimport { parseJsonWithBigInts, stringifyJsonWithBigInts } from '@solana/rpc-spec-types';\nimport {\n RpcSubscriptionsChannel,\n transformChannelInboundMessages,\n transformChannelOutboundMessages,\n} from '@solana/rpc-subscriptions-spec';\n\n/**\n * Similarly, to {@link getRpcSubscriptionsChannelWithJSONSerialization}, this function will\n * stringify and parse JSON message to and from the given `string` channel. However, this function\n * parses any integer value as a `BigInt` in order to safely handle numbers that exceed the\n * JavaScript [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\n * value.\n */\nexport function getRpcSubscriptionsChannelWithBigIntJSONSerialization(\n channel: RpcSubscriptionsChannel,\n): RpcSubscriptionsChannel {\n return pipe(\n channel,\n c => transformChannelInboundMessages(c, parseJsonWithBigInts),\n c => transformChannelOutboundMessages(c, stringifyJsonWithBigInts),\n );\n}\n","import { createWebSocketChannel } from '@solana/rpc-subscriptions-channel-websocket';\nimport type { RpcSubscriptionsChannel } from '@solana/rpc-subscriptions-spec';\nimport type { ClusterUrl } from '@solana/rpc-types';\n\nimport { getRpcSubscriptionsChannelWithAutoping } from './rpc-subscriptions-autopinger';\nimport { getChannelPoolingChannelCreator } from './rpc-subscriptions-channel-pool';\nimport { RpcSubscriptionsChannelCreatorFromClusterUrl } from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsChannelWithJSONSerialization } from './rpc-subscriptions-json';\nimport { getRpcSubscriptionsChannelWithBigIntJSONSerialization } from './rpc-subscriptions-json-bigint';\n\nexport type DefaultRpcSubscriptionsChannelConfig = Readonly<{\n /**\n * The number of milliseconds to wait since the last message sent or received over the channel\n * before sending a ping message to keep the channel open.\n */\n intervalMs?: number;\n /**\n * The number of subscribers that may share a channel before a new channel must be created.\n *\n * It is important that you set this to the maximum number of subscriptions that your RPC\n * provider recommends making over a single connection; the default is set deliberately low, so\n * as to comply with the restrictive limits of the public mainnet RPC node.\n *\n * @defaultValue 100\n */\n maxSubscriptionsPerChannel?: number;\n /** The number of channels to create before reusing a channel for a new subscription. */\n minChannels?: number;\n /**\n * The number of bytes of data to admit into the\n * [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) buffer before\n * buffering data on the client.\n */\n sendBufferHighWatermark?: number;\n /** The URL of the web socket server. Must use the `ws` or `wss` protocols. */\n url: TClusterUrl;\n}>;\n\n/**\n * Similar to {@link createDefaultRpcSubscriptionsChannelCreator} with some Solana-specific\n * defaults.\n *\n * For instance, it safely handles `BigInt` values in JSON messages since Solana RPC servers accept\n * and return integers larger than [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER).\n */\nexport function createDefaultSolanaRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization,\n });\n}\n\n/**\n * Creates a function that returns new subscription channels when called.\n */\nexport function createDefaultRpcSubscriptionsChannelCreator(\n config: DefaultRpcSubscriptionsChannelConfig,\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n return createDefaultRpcSubscriptionsChannelCreatorImpl({\n ...config,\n jsonSerializer: getRpcSubscriptionsChannelWithJSONSerialization,\n });\n}\n\nfunction createDefaultRpcSubscriptionsChannelCreatorImpl(\n config: DefaultRpcSubscriptionsChannelConfig & {\n jsonSerializer: (channel: RpcSubscriptionsChannel) => RpcSubscriptionsChannel;\n },\n): RpcSubscriptionsChannelCreatorFromClusterUrl {\n if (/^wss?:/i.test(config.url) === false) {\n const protocolMatch = config.url.match(/^([^:]+):/);\n throw new DOMException(\n protocolMatch\n ? \"Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or \" +\n `'wss'. '${protocolMatch[1]}:' is not allowed.`\n : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`,\n );\n }\n const { intervalMs, ...rest } = config;\n const createDefaultRpcSubscriptionsChannel = (({ abortSignal }) => {\n return createWebSocketChannel({\n ...rest,\n sendBufferHighWatermark:\n config.sendBufferHighWatermark ??\n // Let 128KB of data into the WebSocket buffer before buffering it in the app.\n 131_072,\n signal: abortSignal,\n })\n .then(config.jsonSerializer)\n .then(channel =>\n getRpcSubscriptionsChannelWithAutoping({\n abortSignal,\n channel,\n intervalMs: intervalMs ?? 5_000,\n }),\n );\n }) as RpcSubscriptionsChannelCreatorFromClusterUrl;\n return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {\n maxSubscriptionsPerChannel:\n config.maxSubscriptionsPerChannel ??\n /**\n * A note about this default. The idea here is that, because some RPC providers impose\n * an upper limit on the number of subscriptions you can make per channel, we must\n * choose a number low enough to avoid hitting that limit. Without knowing what provider\n * a given person is using, or what their limit is, we have to choose the lowest of all\n * known limits. As of this writing (October 2024) that is the public mainnet RPC node\n * (api.mainnet-beta.solana.com) at 100 subscriptions.\n */\n 100,\n minChannels: config.minChannels ?? 1,\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport fastStableStringify from '@solana/fast-stable-stringify';\nimport { RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { DataPublisher } from '@solana/subscribable';\n\ntype CacheEntry = {\n readonly abortController: AbortController;\n readonly dataPublisherPromise: Promise;\n numSubscribers: number;\n};\n\n/**\n * Given a {@link RpcSubscriptionsTransport}, will return a new transport that coalesces identical\n * subscriptions into a single subscription request to the server. The determination of whether a\n * subscription is the same as another is based on the `rpcRequest` returned by its\n * {@link RpcSubscriptionsPlan}. The subscription will only be aborted once all subscribers abort,\n * or there is an error.\n */\nexport function getRpcSubscriptionsTransportWithSubscriptionCoalescing(\n transport: TTransport,\n): TTransport {\n const cache = new Map();\n return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {\n const { request, signal } = config;\n const subscriptionConfigurationHash = fastStableStringify([request.methodName, request.params]);\n\n let cachedDataPublisherPromise = cache.get(subscriptionConfigurationHash);\n if (!cachedDataPublisherPromise) {\n const abortController = new AbortController();\n const dataPublisherPromise = transport({\n ...config,\n signal: abortController.signal,\n });\n dataPublisherPromise\n .then(dataPublisher => {\n dataPublisher.on(\n 'error',\n () => {\n cache.delete(subscriptionConfigurationHash);\n abortController.abort();\n },\n { signal: abortController.signal },\n );\n })\n .catch(() => {});\n cache.set(\n subscriptionConfigurationHash,\n (cachedDataPublisherPromise = {\n abortController,\n dataPublisherPromise,\n numSubscribers: 0,\n }),\n );\n }\n cachedDataPublisherPromise.numSubscribers++;\n signal.addEventListener(\n 'abort',\n () => {\n cachedDataPublisherPromise.numSubscribers--;\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n queueMicrotask(() => {\n if (cachedDataPublisherPromise.numSubscribers === 0) {\n cache.delete(subscriptionConfigurationHash);\n cachedDataPublisherPromise.abortController.abort();\n }\n });\n }\n },\n { signal: cachedDataPublisherPromise.abortController.signal },\n );\n return cachedDataPublisherPromise.dataPublisherPromise;\n } as TTransport;\n}\n","import { pipe } from '@solana/functional';\nimport { RpcSubscriptionsChannelCreator, RpcSubscriptionsTransport } from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport {\n RpcSubscriptionsChannelCreatorDevnet,\n RpcSubscriptionsChannelCreatorFromClusterUrl,\n RpcSubscriptionsChannelCreatorMainnet,\n RpcSubscriptionsChannelCreatorTestnet,\n RpcSubscriptionsTransportDevnet,\n RpcSubscriptionsTransportFromClusterUrl,\n RpcSubscriptionsTransportMainnet,\n RpcSubscriptionsTransportTestnet,\n} from './rpc-subscriptions-clusters';\nimport { getRpcSubscriptionsTransportWithSubscriptionCoalescing } from './rpc-subscriptions-coalescer';\n\nexport type DefaultRpcSubscriptionsTransportConfig = Readonly<{\n createChannel: RpcSubscriptionsChannelCreatorFromClusterUrl;\n}>;\n\n/**\n * Creates a {@link RpcSubscriptionsTransport} with some default behaviours.\n *\n * The default behaviours include:\n * - Logic that coalesces multiple subscriptions for the same notifications with the same arguments\n * into a single subscription.\n *\n * @param config\n */\nexport function createDefaultRpcSubscriptionsTransport({\n createChannel,\n}: DefaultRpcSubscriptionsTransportConfig) {\n return pipe(\n createRpcSubscriptionsTransportFromChannelCreator(\n createChannel,\n ) as RpcSubscriptionsTransport as RpcSubscriptionsTransportFromClusterUrl,\n transport => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport),\n );\n}\n\nexport function createRpcSubscriptionsTransportFromChannelCreator<\n TChannelCreator extends RpcSubscriptionsChannelCreator,\n TInboundMessage,\n TOutboundMessage,\n>(createChannel: TChannelCreator) {\n return (async ({ execute, signal }) => {\n const channel = await createChannel({ abortSignal: signal });\n return await execute({ channel, signal });\n }) as TChannelCreator extends RpcSubscriptionsChannelCreatorDevnet\n ? RpcSubscriptionsTransportDevnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorTestnet\n ? RpcSubscriptionsTransportTestnet\n : TChannelCreator extends RpcSubscriptionsChannelCreatorMainnet\n ? RpcSubscriptionsTransportMainnet\n : RpcSubscriptionsTransport;\n}\n","import type { SolanaRpcSubscriptionsApi, SolanaRpcSubscriptionsApiUnstable } from '@solana/rpc-subscriptions-api';\nimport { createSolanaRpcSubscriptionsApi } from '@solana/rpc-subscriptions-api';\nimport {\n createSubscriptionRpc,\n RpcSubscriptionsApiMethods,\n type RpcSubscriptionsTransport,\n} from '@solana/rpc-subscriptions-spec';\nimport { ClusterUrl } from '@solana/rpc-types';\n\nimport { DEFAULT_RPC_SUBSCRIPTIONS_CONFIG } from './rpc-default-config';\nimport {\n createDefaultSolanaRpcSubscriptionsChannelCreator,\n DefaultRpcSubscriptionsChannelConfig,\n} from './rpc-subscriptions-channel';\nimport type { RpcSubscriptionsFromTransport } from './rpc-subscriptions-clusters';\nimport { createDefaultRpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\ntype Config = DefaultRpcSubscriptionsChannelConfig;\n\nfunction createSolanaRpcSubscriptionsImpl(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n const transport = createDefaultRpcSubscriptionsTransport({\n createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ ...config, url: clusterUrl }),\n });\n return createSolanaRpcSubscriptionsFromTransport(transport);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(clusterUrl, config);\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API,\n * including its unstable methods, given a cluster URL and some optional channel config. See\n * {@link createDefaultRpcSubscriptionsChannelCreator} for the shape of the channel config.\n */\nexport function createSolanaRpcSubscriptions_UNSTABLE(\n clusterUrl: TClusterUrl,\n config?: Omit, 'url'>,\n) {\n return createSolanaRpcSubscriptionsImpl(\n clusterUrl,\n config,\n );\n}\n\n/**\n * Creates a {@link RpcSubscriptions} instance that exposes the Solana JSON RPC WebSocket API given\n * the supplied {@link RpcSubscriptionsTransport}.\n */\nexport function createSolanaRpcSubscriptionsFromTransport<\n TTransport extends RpcSubscriptionsTransport,\n TApi extends RpcSubscriptionsApiMethods = SolanaRpcSubscriptionsApi,\n>(transport: TTransport) {\n return createSubscriptionRpc({\n api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_SUBSCRIPTIONS_CONFIG),\n transport,\n }) as RpcSubscriptionsFromTransport;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SolanaError } from '@solana/errors';\n\nimport { MessageSigner } from './message-signer';\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Removes all duplicated {@link MessageSigner | MessageSigners} and\n * {@link TransactionSigner | TransactionSigners} from a provided array\n * by comparing their {@link Address | addresses}.\n *\n * @internal\n */\nexport function deduplicateSigners(\n signers: readonly TSigner[],\n): readonly TSigner[] {\n const deduplicated: Record = {};\n signers.forEach(signer => {\n if (!deduplicated[signer.address]) {\n deduplicated[signer.address] = signer;\n } else if (deduplicated[signer.address] !== signer) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, {\n address: signer.address,\n });\n }\n });\n return Object.values(deduplicated);\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionModifyingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that potentially modifies the provided {@link Transaction | Transactions}\n * before signing them.\n *\n * For instance, this enables wallets to inject additional instructions into the\n * transaction before signing them. For each transaction, instead of returning a\n * {@link SignatureDictionary}, its\n * {@link TransactionModifyingSigner#modifyAndSignTransactions | modifyAndSignTransactions} function\n * returns an updated {@link Transaction} with a potentially modified set of instructions and\n * signature dictionary. The returned transaction must be within the transaction size limit,\n * and include a `lifetimeConstraint`.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignTransactions: async (\n * transactions: Transaction[]\n * ): Promise<(Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[]> => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the provided transactions.\n * - **First signers**. For a given transaction, a modifying signer must always\n * be used before a partial signer as the former will likely modify the\n * transaction and thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided,\n * the second signer may invalidate the signature of the first one. However,\n * modifying signers may decide not to modify a transaction based on the\n * existence of signatures for that transaction.\n *\n * @see {@link isTransactionModifyingSigner}\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport type TransactionModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionModifyingSigner}\n */\nexport function isTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionModifyingSigner {\n return 'modifyAndSignTransactions' in value && typeof value.modifyAndSignTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionModifyingSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionModifyingSigner}\n */\nexport function assertIsTransactionModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionModifyingSigner {\n if (!isTransactionModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\nimport { Transaction, TransactionWithinSizeLimit, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionPartialSigner#signTransactions | signTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionPartialSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link Transaction | Transactions}\n * without modifying their content. It defines a\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * function that returns a {@link SignatureDictionary} for each provided transaction.\n *\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: TransactionPartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signTransactions: async (\n * transactions: Transaction[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. It returns a signature dictionary for each provided\n * transaction without modifying them, making it possible for multiple\n * partial signers to sign the same transaction in parallel.\n * - **Flexible order**. The order in which we use these signers for\n * a given transaction doesn’t matter.\n *\n * @see {@link isTransactionPartialSigner}\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport type TransactionPartialSigner = Readonly<{\n address: Address;\n signTransactions(\n transactions: readonly (Transaction & TransactionWithinSizeLimit & TransactionWithLifetime)[],\n config?: TransactionPartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionPartialSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionPartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionPartialSigner}\n */\nexport function isTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionPartialSigner {\n return 'signTransactions' in value && typeof value.signTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionPartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionPartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionPartialSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionPartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionPartialSigner}\n */\nexport function assertIsTransactionPartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionPartialSigner {\n if (!isTransactionPartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { Transaction, TransactionWithLifetime } from '@solana/transactions';\n\nimport { BaseTransactionSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions} method.\n *\n * @see {@link BaseTransactionSignerConfig}\n */\nexport type TransactionSendingSignerConfig = BaseTransactionSignerConfig;\n\n/**\n * A signer interface that signs one or multiple transactions\n * before sending them immediately to the blockchain.\n *\n * It defines a {@link TransactionSendingSignerConfig#signAndSendTransactions | signAndSendTransactions}\n * function that returns the transaction signature (i.e. its identifier) for each provided\n * {@link Transaction}.\n *\n * This interface is required for PDA wallets and other types of wallets that don't provide an\n * interface for signing transactions without sending them.\n *\n * Note that it is also possible for such signers to modify the provided transactions\n * before signing and sending them. This enables use cases where the modified transactions\n * cannot be shared with the app and thus must be sent directly.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const myTransactionSendingSigner: TransactionSendingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signAndSendTransactions: async (transactions: Transaction[]): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Single signer**. Since this signer also sends the provided transactions,\n * we can only use a single {@link TransactionSendingSigner} for a given set of transactions.\n * - **Last signer**. Trivially, that signer must also be the last one used.\n * - **Potential conflicts**. Since signers may decide to modify the given\n * transactions before sending them, they may invalidate previous signatures.\n * However, signers may decide not to modify a transaction based\n * on the existence of signatures for that transaction.\n * - **Potential confirmation**. Whilst this is not required by this interface,\n * it is also worth noting that most wallets will also wait for the transaction\n * to be confirmed (typically with a `confirmed` commitment)\n * before notifying the app that they are done.\n *\n * @see {@link isTransactionSendingSigner}\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport type TransactionSendingSigner = Readonly<{\n address: Address;\n signAndSendTransactions(\n transactions: readonly (Transaction | (Transaction & TransactionWithLifetime))[],\n config?: TransactionSendingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSendingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSendingSigner}\n */\nexport function isTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSendingSigner {\n return 'signAndSendTransactions' in value && typeof value.signAndSendTransactions === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSendingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSendingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSendingSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSendingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSendingSigner}\n */\nexport function assertIsTransactionSendingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSendingSigner {\n if (!isTransactionSendingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isTransactionModifyingSigner, TransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner, TransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a signer capable of signing transactions.\n *\n * @see {@link TransactionModifyingSigner} For signers that can modify transactions before signing them.\n * @see {@link TransactionPartialSigner} For signers that can be used in parallel.\n * @see {@link TransactionSendingSigner} For signers that send transactions after signing them.\n * @see {@link isTransactionSigner}\n * @see {@link assertIsTransactionSigner}\n */\nexport type TransactionSigner =\n | TransactionModifyingSigner\n | TransactionPartialSigner\n | TransactionSendingSigner;\n\n/**\n * Checks whether the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isTransactionSigner({ address, signTransactions: async () => {} }); // true\n * isTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // true\n * isTransactionSigner({ address, signAndSendTransactions: async () => {} }); // true\n * isTransactionSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsTransactionSigner}\n */\nexport function isTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is TransactionSigner {\n return (\n isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link TransactionSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsTransactionSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsTransactionSigner({ address, signTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, modifyAndSignTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address, signAndSendTransactions: async () => {} }); // void\n * assertIsTransactionSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isTransactionSigner}\n */\nexport function assertIsTransactionSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is TransactionSigner {\n if (!isTransactionSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { AccountLookupMeta, AccountMeta, AccountRole, Instruction } from '@solana/instructions';\nimport {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionVersion,\n} from '@solana/transaction-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { TransactionMessageWithFeePayerSigner } from './fee-payer-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * An extension of the {@link AccountMeta} type that allows us to store {@link TransactionSigner | TransactionSigners} inside it.\n *\n * Note that, because this type represents a signer, it must use one the following two roles:\n * - {@link AccountRole.READONLY_SIGNER}\n * - {@link AccountRole.WRITABLE_SIGNER}\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner} to use within the account meta.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole } from '@solana/instructions';\n * import { generateKeyPairSigner, AccountSignerMeta } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const account: AccountSignerMeta = {\n * address: signer.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer,\n * };\n * ```\n */\nexport interface AccountSignerMeta<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> extends AccountMeta {\n readonly role: AccountRole.READONLY_SIGNER | AccountRole.WRITABLE_SIGNER;\n readonly signer: TSigner;\n}\n\n/**\n * A union type that supports base account metas as well as {@link AccountSignerMeta | signer account metas}.\n */\ntype AccountMetaWithSigner =\n | AccountLookupMeta\n | AccountMeta\n | AccountSignerMeta;\n\n/**\n * Composable type that allows {@link AccountSignerMeta | AccountSignerMetas} to be used inside the instruction's `accounts` array\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @interface\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { generateKeyPairSigner, InstructionWithSigners } from '@solana/signers';\n *\n * const [authority, buffer] = await Promise.all([\n * generateKeyPairSigner(),\n * generateKeyPairSigner(),\n * ]);\n * const instruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [\n * // The authority is a signer account.\n * {\n * address: authority.address,\n * role: AccountRole.READONLY_SIGNER,\n * signer: authority,\n * },\n * // The buffer is a writable account.\n * { address: buffer.address, role: AccountRole.WRITABLE },\n * ],\n * };\n * ```\n */\nexport type InstructionWithSigners<\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Pick, 'accounts'>;\n\n/**\n * A {@link BaseTransactionMessage} type extension that accept {@link TransactionSigner | TransactionSigners}.\n *\n * Namely, it allows:\n * - a {@link TransactionSigner} to be used as the fee payer and\n * - {@link InstructionWithSigners} to be used in its instructions.\n *\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TAccounts - Optionally provide a narrower type for the account metas.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, InstructionWithSigners, TransactionMessageWithSigners } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * const firstInstruction: Instruction = { ... };\n * const secondInstruction: InstructionWithSigners = { ... };\n * const transactionMessage: BaseTransactionMessage & TransactionMessageWithSigners = {\n * feePayer: signer,\n * instructions: [firstInstruction, secondInstruction],\n * }\n * ```\n */\nexport type TransactionMessageWithSigners<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TAccounts extends readonly AccountMetaWithSigner[] = readonly AccountMetaWithSigner[],\n> = Partial | TransactionMessageWithFeePayerSigner> &\n Pick<\n BaseTransactionMessage>,\n 'instructions'\n >;\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside the account metas of an {@link InstructionWithSigners | instruction}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n *\n * @example\n * ```ts\n * import { InstructionWithSigners, getSignersFromInstruction } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const instructionWithSigners: InstructionWithSigners = {\n * accounts: [\n * { address: signerA.address, signer: signerA, ... },\n * { address: signerB.address, signer: signerB, ... },\n * { address: signerA.address, signer: signerA, ... },\n * ],\n * };\n *\n * const instructionSigners = getSignersFromInstruction(instructionWithSigners);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromInstruction(\n instruction: InstructionWithSigners,\n): readonly TSigner[] {\n return deduplicateSigners(\n (instruction.accounts ?? []).flatMap(account => ('signer' in account ? account.signer : [])),\n );\n}\n\n/**\n * Extracts and deduplicates all {@link TransactionSigner | TransactionSigners} stored\n * inside a given {@link TransactionMessageWithSigners | transaction message}.\n *\n * This includes any {@link TransactionSigner | TransactionSigners} stored\n * as the fee payer or in the instructions of the transaction message.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link TransactionSigner | TransactionSigners}.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { Instruction } from '@solana/instructions';\n * import { InstructionWithSigners, TransactionMessageWithSigners, getSignersFromTransactionMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signTransactions: async () => {} };\n * const signerB = { address: address('2222..2222'), signTransactions: async () => {} };\n * const firstInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerA.address, signer: signerA, ... }],\n * };\n * const secondInstruction: Instruction & InstructionWithSigners = {\n * programAddress: address('1234..5678'),\n * accounts: [{ address: signerB.address, signer: signerB, ... }],\n * };\n * const transactionMessage: TransactionMessageWithSigners = {\n * feePayer: signerA,\n * instructions: [firstInstruction, secondInstruction],\n * }\n *\n * const transactionSigners = getSignersFromTransactionMessage(transactionMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromTransactionMessage<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n TTransactionMessage extends TransactionMessageWithSigners = TransactionMessageWithSigners<\n TAddress,\n TSigner\n >,\n>(transaction: TTransactionMessage): readonly TSigner[] {\n return deduplicateSigners([\n ...(transaction.feePayer && isTransactionSigner(transaction.feePayer) ? [transaction.feePayer as TSigner] : []),\n ...transaction.instructions.flatMap(getSignersFromInstruction),\n ]);\n}\n","import { Address } from '@solana/addresses';\nimport { Instruction, isSignerRole } from '@solana/instructions';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { AccountSignerMeta, InstructionWithSigners, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of an instruction when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TInstruction - The inferred type of the instruction provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { addSignersToInstruction, TransactionSigner } from '@solana/signers';\n *\n * const instruction: Instruction = {\n * accounts: [\n * { address: '1111' as Address, role: AccountRole.READONLY_SIGNER },\n * { address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER },\n * ],\n * // ...\n * };\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const instructionWithSigners = addSignersToInstruction(\n * [signerA, signerB],\n * instruction\n * );\n *\n * // instructionWithSigners.accounts[0].signer === signerA\n * // instructionWithSigners.accounts[1].signer === signerB\n * ```\n */\nexport function addSignersToInstruction(\n signers: TransactionSigner[],\n instruction: TInstruction | (InstructionWithSigners & TInstruction),\n): InstructionWithSigners & TInstruction {\n if (!instruction.accounts || instruction.accounts.length === 0) {\n return instruction as InstructionWithSigners & TInstruction;\n }\n\n const signerByAddress = new Map(deduplicateSigners(signers).map(signer => [signer.address, signer]));\n return Object.freeze({\n ...instruction,\n accounts: instruction.accounts.map(account => {\n const signer = signerByAddress.get(account.address);\n if (!isSignerRole(account.role) || 'signer' in account || !signer) {\n return account;\n }\n return Object.freeze({ ...account, signer } as AccountSignerMeta);\n }),\n });\n}\n\n/**\n * Attaches the provided {@link TransactionSigner | TransactionSigners} to the\n * account metas of all instructions inside a transaction message and/or\n * the transaction message fee payer, when applicable.\n *\n * For an account meta to match a provided signer it:\n * - Must have a signer role ({@link AccountRole.READONLY_SIGNER} or {@link AccountRole.WRITABLE_SIGNER}).\n * - Must have the same address as the provided signer.\n * - Must not have an attached signer already.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { AccountRole, Instruction } from '@solana/instructions';\n * import { BaseTransactionMessage } from '@solana/transaction-messages';\n * import { addSignersToTransactionMessage, TransactionSigner } from '@solana/signers';\n *\n * const instructionA: Instruction = {\n * accounts: [{ address: '1111' as Address, role: AccountRole.READONLY_SIGNER }],\n * // ...\n * };\n * const instructionB: Instruction = {\n * accounts: [{ address: '2222' as Address, role: AccountRole.WRITABLE_SIGNER }],\n * // ...\n * };\n * const transactionMessage: BaseTransactionMessage = {\n * instructions: [instructionA, instructionB],\n * // ...\n * }\n *\n * const signerA: TransactionSigner<'1111'>;\n * const signerB: TransactionSigner<'2222'>;\n * const transactionMessageWithSigners = addSignersToTransactionMessage(\n * [signerA, signerB],\n * transactionMessage\n * );\n *\n * // transactionMessageWithSigners.instructions[0].accounts[0].signer === signerA\n * // transactionMessageWithSigners.instructions[1].accounts[0].signer === signerB\n * ```\n */\nexport function addSignersToTransactionMessage(\n signers: TransactionSigner[],\n transactionMessage: TTransactionMessage | (TransactionMessageWithSigners & TTransactionMessage),\n): TransactionMessageWithSigners & TTransactionMessage {\n const feePayerSigner = hasAddressOnlyFeePayer(transactionMessage)\n ? signers.find(signer => signer.address === transactionMessage.feePayer.address)\n : undefined;\n\n if (!feePayerSigner && transactionMessage.instructions.length === 0) {\n return transactionMessage as TransactionMessageWithSigners & TTransactionMessage;\n }\n\n return Object.freeze({\n ...transactionMessage,\n ...(feePayerSigner ? { feePayer: feePayerSigner } : null),\n instructions: transactionMessage.instructions.map(instruction => addSignersToInstruction(signers, instruction)),\n });\n}\n\nfunction hasAddressOnlyFeePayer(\n message: BaseTransactionMessage & Partial,\n): message is BaseTransactionMessage & { feePayer: { address: Address } } {\n return (\n !!message &&\n 'feePayer' in message &&\n !!message.feePayer &&\n typeof message.feePayer.address === 'string' &&\n !isTransactionSigner(message.feePayer)\n );\n}\n","import { TransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { TransactionSigner } from './transaction-signer';\n\n/**\n * Alternative to {@link TransactionMessageWithFeePayer} that uses a {@link TransactionSigner} for the fee payer.\n *\n * @typeParam TAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for the {@link TransactionSigner}.\n *\n * @example\n * ```ts\n * import { TransactionMessage } from '@solana/transaction-messages';\n * import { generateKeyPairSigner, TransactionMessageWithFeePayerSigner } from '@solana/signers';\n *\n * const transactionMessage: TransactionMessage & TransactionMessageWithFeePayerSigner = {\n * feePayer: await generateKeyPairSigner(),\n * instructions: [],\n * version: 0,\n * };\n * ```\n */\nexport interface TransactionMessageWithFeePayerSigner<\n TAddress extends string = string,\n TSigner extends TransactionSigner = TransactionSigner,\n> {\n readonly feePayer: TSigner;\n}\n\n/**\n * A helper type to exclude the fee payer from a transaction message.\n */\ntype ExcludeTransactionMessageFeePayer =\n TTransactionMessage extends unknown ? Omit : never;\n\n/**\n * Sets the fee payer of a {@link TransactionMessage | transaction message}\n * using a {@link TransactionSigner}.\n *\n * @typeParam TFeePayerAddress - Supply a string literal to define a fee payer having a particular address.\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import { pipe } from '@solana/functional';\n * import { generateKeyPairSigner, setTransactionMessageFeePayerSigner } from '@solana/signers';\n * import { createTransactionMessage } from '@solana/transaction-messages';\n *\n * const feePayer = await generateKeyPairSigner();\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * message => setTransactionMessageFeePayerSigner(signer, message),\n * );\n * ```\n */\nexport function setTransactionMessageFeePayerSigner<\n TFeePayerAddress extends string,\n TTransactionMessage extends Partial &\n TransactionMessage,\n>(\n feePayer: TransactionSigner,\n transactionMessage: TTransactionMessage,\n): ExcludeTransactionMessageFeePayer & TransactionMessageWithFeePayerSigner {\n Object.freeze(feePayer);\n const out = { ...transactionMessage, feePayer };\n Object.freeze(out);\n return out as ExcludeTransactionMessageFeePayer &\n TransactionMessageWithFeePayerSigner;\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig, SignatureDictionary } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessagePartialSigner#signMessages | signMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessagePartialSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that signs an array of {@link SignableMessage | SignableMessages}\n * without modifying their content.\n *\n * It defines a {@link MessagePartialSigner#signMessages | signMessages} function\n * that returns a {@link SignatureDictionary} for each provided message.\n * Such signature dictionaries are expected to be merged with the existing ones if any.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessagePartialSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * signMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Parallel**. When multiple signers sign the same message, we can\n * perform this operation in parallel to obtain all their signatures.\n * - **Flexible order**. The order in which we use these signers\n * for a given message doesn’t matter.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessagePartialSigner}\n * @see {@link assertIsMessagePartialSigner}\n */\nexport type MessagePartialSigner = Readonly<{\n address: Address;\n signMessages(\n messages: readonly SignableMessage[],\n config?: MessagePartialSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessagePartialSigner({ address, signMessages: async () => {} }); // true\n * isMessagePartialSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessagePartialSigner}\n */\nexport function isMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessagePartialSigner {\n return 'signMessages' in value && typeof value.signMessages === 'function';\n}\n\n/**\n * Asserts that the provided value implements the {@link MessagePartialSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessagePartialSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessagePartialSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessagePartialSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessagePartialSigner}\n */\nexport function assertIsMessagePartialSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessagePartialSigner {\n if (!isMessagePartialSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address, getAddressFromPublicKey } from '@solana/addresses';\nimport { ReadonlyUint8Array } from '@solana/codecs-core';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SolanaError } from '@solana/errors';\nimport { createKeyPairFromBytes, createKeyPairFromPrivateKeyBytes, generateKeyPair, signBytes } from '@solana/keys';\nimport { partiallySignTransaction } from '@solana/transactions';\n\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\nimport { isTransactionPartialSigner, TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a signer that uses a {@link CryptoKeyPair} to sign messages and transactions.\n *\n * It implements both the {@link MessagePartialSigner} and {@link TransactionPartialSigner}\n * interfaces and keeps track of the {@link CryptoKeyPair} instance used\n * to sign messages and transactions.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = generateKeyPairSigner();\n * signer.address; // Address;\n * signer.keyPair; // CryptoKeyPair;\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * ```\n *\n * @see {@link generateKeyPairSigner}\n * @see {@link createSignerFromKeyPair}\n * @see {@link createKeyPairSignerFromBytes}\n * @see {@link createKeyPairSignerFromPrivateKeyBytes}\n * @see {@link isKeyPairSigner}\n * @see {@link assertIsKeyPairSigner}\n */\nexport type KeyPairSigner = MessagePartialSigner &\n TransactionPartialSigner & { keyPair: CryptoKeyPair };\n\n/**\n * Checks whether the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, isKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * isKeyPairSigner(signer); // true\n * isKeyPairSigner({ address: address('1234..5678') }); // false\n * ```\n */\nexport function isKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is KeyPairSigner {\n return (\n 'keyPair' in value &&\n typeof value.keyPair === 'object' &&\n isMessagePartialSigner(value) &&\n isTransactionPartialSigner(value)\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link KeyPairSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner, assertIsKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * assertIsKeyPairSigner(signer); // void\n * assertIsKeyPairSigner({ address: address('1234..5678') }); // Throws an error.\n * ```\n */\nexport function assertIsKeyPairSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is KeyPairSigner {\n if (!isKeyPairSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, {\n address: value.address,\n });\n }\n}\n\n/**\n * Creates a {@link KeyPairSigner} from a provided {@link CryptoKeyPair}.\n *\n * The {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions}\n * functions of the returned signer will use the private key of the provided\n * key pair to sign messages and transactions.\n *\n * Note that both the {@link MessagePartialSigner#signMessages | signMessages} and\n * {@link TransactionPartialSigner#signTransactions | signTransactions} implementations\n * are parallelized, meaning that they will sign all provided messages and transactions in parallel.\n *\n * @example\n * ```ts\n * import { generateKeyPair } from '@solana/keys';\n * import { createSignerFromKeyPair, KeyPairSigner } from '@solana/signers';\n *\n * const keyPair: CryptoKeyPair = await generateKeyPair();\n * const signer: KeyPairSigner = await createSignerFromKeyPair(keyPair);\n * ```\n */\nexport async function createSignerFromKeyPair(keyPair: CryptoKeyPair): Promise {\n const address = await getAddressFromPublicKey(keyPair.publicKey);\n const out: KeyPairSigner = {\n address,\n keyPair,\n signMessages: messages =>\n Promise.all(\n messages.map(async message =>\n Object.freeze({ [address]: await signBytes(keyPair.privateKey, message.content) }),\n ),\n ),\n signTransactions: transactions =>\n Promise.all(\n transactions.map(async transaction => {\n const signedTransaction = await partiallySignTransaction([keyPair], transaction);\n // we know that the address has signed `signedTransaction` because it comes from the keypair\n return Object.freeze({ [address]: signedTransaction.signatures[address]! });\n }),\n ),\n };\n\n return Object.freeze(out);\n}\n\n/**\n * Generates a signer capable of signing messages and transactions by generating\n * a {@link CryptoKeyPair} and creating a {@link KeyPairSigner} from it.\n *\n * @example\n * ```ts\n * import { generateKeyPairSigner } from '@solana/signers';\n *\n * const signer = await generateKeyPairSigner();\n * ```\n *\n * @see {@link createSignerFromKeyPair}\n */\nexport async function generateKeyPairSigner(): Promise {\n return await createSignerFromKeyPair(await generateKeyPair());\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 64-bytes `Uint8Array` secret key (private key and public key).\n *\n * @example\n * ```ts\n * import fs from 'fs';\n * import { createKeyPairSignerFromBytes } from '@solana/signers';\n *\n * // Get bytes from local keypair file.\n * const keypairFile = fs.readFileSync('~/.config/solana/id.json');\n * const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));\n *\n * // Create a KeyPairSigner from the bytes.\n * const signer = await createKeyPairSignerFromBytes(keypairBytes);\n * ```\n *\n * @see {@link createKeyPairSignerFromPrivateKeyBytes} if you only have the 32-bytes private key instead.\n */\nexport async function createKeyPairSignerFromBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromBytes(bytes, extractable));\n}\n\n/**\n * Creates a new {@link KeyPairSigner} from a 32-bytes `Uint8Array` private key.\n *\n * @example\n * ```ts\n * import { getUtf8Encoder } from '@solana/codecs-strings';\n * import { createKeyPairSignerFromPrivateKeyBytes } from '@solana/signers';\n *\n * const message = getUtf8Encoder().encode('Hello, World!');\n * const seed = new Uint8Array(await crypto.subtle.digest('SHA-256', message));\n *\n * const derivedSigner = await createKeyPairSignerFromPrivateKeyBytes(seed);\n * ```\n *\n * @see {@link createKeyPairSignerFromBytes} if you have the 64-bytes secret key instead (private key and public key).\n */\nexport async function createKeyPairSignerFromPrivateKeyBytes(\n bytes: ReadonlyUint8Array,\n extractable?: boolean,\n): Promise {\n return await createSignerFromKeyPair(await createKeyPairFromPrivateKeyBytes(bytes, extractable));\n}\n","import { Address, isAddress } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SolanaError } from '@solana/errors';\n\nimport { SignableMessage } from './signable-message';\nimport { BaseSignerConfig } from './types';\n\n/**\n * The configuration to optionally provide when calling the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} method.\n *\n * @see {@link BaseSignerConfig}\n */\nexport type MessageModifyingSignerConfig = BaseSignerConfig;\n\n/**\n * A signer interface that _potentially_ modifies the content\n * of the provided {@link SignableMessage | SignableMessages} before signing them.\n *\n * For instance, this enables wallets to prefix or suffix nonces to the messages they sign.\n * For each message, instead of returning a {@link SignatureDictionary}, the\n * {@link MessageModifyingSigner#modifyAndSignMessages | modifyAndSignMessages} function\n * returns an updated {@link SignableMessage} with a potentially modified content and signature dictionary.\n *\n * @typeParam TAddress - Supply a string literal to define a signer having a particular address.\n *\n * @example\n * ```ts\n * const signer: MessageModifyingSigner<'1234..5678'> = {\n * address: address('1234..5678'),\n * modifyAndSignMessages: async (\n * messages: SignableMessage[]\n * ): Promise => {\n * // My custom signing logic.\n * },\n * };\n * ```\n *\n * @remarks\n * Here are the main characteristics of this signer interface:\n *\n * - **Sequential**. Contrary to partial signers, these cannot be executed in\n * parallel as each call can modify the content of the message.\n * - **First signers**. For a given message, a modifying signer must always be used\n * before a partial signer as the former will likely modify the message and\n * thus impact the outcome of the latter.\n * - **Potential conflicts**. If more than one modifying signer is provided, the second\n * signer may invalidate the signature of the first one. However, modifying signers\n * may decide not to modify a message based on the existence of signatures for that message.\n *\n * @see {@link SignableMessage}\n * @see {@link createSignableMessage}\n * @see {@link isMessageModifyingSigner}\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport type MessageModifyingSigner = Readonly<{\n address: Address;\n modifyAndSignMessages(\n messages: readonly SignableMessage[],\n config?: MessageModifyingSignerConfig,\n ): Promise;\n}>;\n\n/**\n * Checks whether the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageModifyingSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageModifyingSigner}\n */\nexport function isMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageModifyingSigner {\n return (\n isAddress(value.address) &&\n 'modifyAndSignMessages' in value &&\n typeof value.modifyAndSignMessages === 'function'\n );\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageModifyingSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageModifyingSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageModifyingSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageModifyingSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageModifyingSigner}\n */\nexport function assertIsMessageModifyingSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageModifyingSigner {\n if (!isMessageModifyingSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\nimport { SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SolanaError } from '@solana/errors';\n\nimport { isMessageModifyingSigner, MessageModifyingSigner } from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner } from './message-partial-signer';\n\n/**\n * Defines a signer capable of signing messages.\n *\n * @see {@link MessageModifyingSigner} For signers that can modify messages before signing them.\n * @see {@link MessagePartialSigner} For signers that can be used in parallel.\n * @see {@link isMessageSigner}\n * @see {@link assertIsMessageSigner}\n */\nexport type MessageSigner =\n | MessageModifyingSigner\n | MessagePartialSigner;\n\n/**\n * Checks whether the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { isMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * isMessageSigner({ address, signMessages: async () => {} }); // true\n * isMessageSigner({ address, modifyAndSignMessages: async () => {} }); // true\n * isMessageSigner({ address }); // false\n * ```\n *\n * @see {@link assertIsMessageSigner}\n */\nexport function isMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): value is MessageSigner {\n return isMessagePartialSigner(value) || isMessageModifyingSigner(value);\n}\n\n/**\n * Asserts that the provided value implements the {@link MessageSigner} interface.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { Address } from '@solana/addresses';\n * import { assertIsMessageSigner } from '@solana/signers';\n *\n * const address = '1234..5678' as Address<'1234..5678'>;\n * assertIsMessageSigner({ address, signMessages: async () => {} }); // void\n * assertIsMessageSigner({ address, modifyAndSignMessages: async () => {} }); // void\n * assertIsMessageSigner({ address }); // Throws an error.\n * ```\n *\n * @see {@link isMessageSigner}\n */\nexport function assertIsMessageSigner(value: {\n [key: string]: unknown;\n address: Address;\n}): asserts value is MessageSigner {\n if (!isMessageSigner(value)) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, {\n address: value.address,\n });\n }\n}\n","import { Address } from '@solana/addresses';\n\nimport { MessagePartialSigner } from './message-partial-signer';\nimport { TransactionPartialSigner } from './transaction-partial-signer';\n\n/**\n * Defines a Noop (No-Operation) signer that pretends to partially sign messages and transactions.\n *\n * For a given {@link Address}, a Noop Signer can be created to offer an implementation of both\n * the {@link MessagePartialSigner} and {@link TransactionPartialSigner} interfaces such that\n * they do not sign anything. Namely, signing a transaction or a message with a `NoopSigner`\n * will return an empty `SignatureDictionary`.\n *\n * @typeParam TAddress - Supply a string literal to define a Noop signer having a particular address.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * const [messageSignatures] = await signer.signMessages([message]);\n * const [transactionSignatures] = await signer.signTransactions([transaction]);\n * // ^ Both messageSignatures and transactionSignatures are empty.\n * ```\n *\n * @remarks\n * This signer may be useful:\n *\n * - For testing purposes.\n * - For indicating that a given account is a signer and taking the responsibility to provide\n * the signature for that account ourselves. For instance, if we need to send the transaction\n * to a server that will sign it and send it for us.\n *\n * @see {@link createNoopSigner}\n */\nexport type NoopSigner = MessagePartialSigner &\n TransactionPartialSigner;\n\n/**\n * Creates a {@link NoopSigner} from the provided {@link Address}.\n *\n * @typeParam TAddress - The inferred type of the address provided.\n *\n * @example\n * ```ts\n * import { address } from '@solana/addresses';\n * import { createNoopSigner } from '@solana/signers';\n *\n * const signer = createNoopSigner(address('1234..5678'));\n * ```\n */\nexport function createNoopSigner(address: Address): NoopSigner {\n const out: NoopSigner = {\n address,\n signMessages: messages => Promise.resolve(messages.map(() => Object.freeze({}))),\n signTransactions: transactions => Promise.resolve(transactions.map(() => Object.freeze({}))),\n };\n\n return Object.freeze(out);\n}\n","import { OffchainMessageWithRequiredSignatories } from '@solana/offchain-messages';\n\nimport { deduplicateSigners } from './deduplicate-signers';\nimport { isMessageSigner, MessageSigner } from './message-signer';\n\n/**\n * Represents a {@link Signer} that is required to sign an offchain message for it to be valid.\n */\nexport type OffchainMessageSignatorySigner = MessageSigner;\n\n/**\n * Extracts and deduplicates all {@link MessageSigner | MessageSigners} stored inside a given\n * {@link OffchainMessageWithSigners | offchain message}.\n *\n * Any extracted signers that share the same {@link Address} will be de-duplicated.\n *\n * @typeParam TAddress - Supply a string literal to define an account having a particular address.\n * @typeParam TSigner - Optionally provide a narrower type for {@link MessageSigner | MessageSigners}.\n * @typeParam TOffchainMessage - The inferred type of the offchain message provided.\n *\n * @example\n * ```ts\n * import { OffchainMessageWithSigners, getSignersFromOffchainMessage } from '@solana/signers';\n *\n * const signerA = { address: address('1111..1111'), signMessages: async () => {} };\n * const signerB = { address: address('2222..2222'), modifyAndSignMessages: async () => {} };\n * const OffchainMessage: OffchainMessageWithSigners = {\n * /* ... *\\/\n * requiredSignatories: [signerA, signerB],\n * };\n *\n * const messageSigners = getSignersFromOffchainMessage(offchainMessage);\n * // ^ [signerA, signerB]\n * ```\n */\nexport function getSignersFromOffchainMessage({\n requiredSignatories,\n}: OffchainMessageWithRequiredSignatories): readonly MessageSigner[] {\n const messageSigners = requiredSignatories.filter(isMessageSigner);\n return deduplicateSigners(messageSigners);\n}\n","import {\n assertIsFullySignedOffchainMessageEnvelope,\n compileOffchainMessageEnvelope,\n FullySignedOffchainMessageEnvelope,\n OffchainMessage,\n OffchainMessageEnvelope,\n OffchainMessageSignatory,\n OffchainMessageWithRequiredSignatories,\n} from '@solana/offchain-messages';\n\nimport {\n isMessageModifyingSigner,\n MessageModifyingSigner,\n MessageModifyingSignerConfig,\n} from './message-modifying-signer';\nimport { isMessagePartialSigner, MessagePartialSigner, MessagePartialSignerConfig } from './message-partial-signer';\nimport { MessageSigner } from './message-signer';\nimport { getSignersFromOffchainMessage, OffchainMessageSignatorySigner } from './offchain-message-signer';\nimport { SignableMessage } from './signable-message';\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope.\n *\n * It first uses all {@link MessageModifyingSigner | MessageModifyingSigners} sequentially before\n * using all {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link MessageModifyingSigner} if no other signer implements that interface. Otherwise, it will\n * be used as a {@link MessagePartialSigner}.\n *\n * @example\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @see {@link signOffchainMessageWithSigners}\n */\nexport async function partiallySignOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeMessageSigners(\n getSignersFromOffchainMessage(offchainMessage),\n );\n return await signModifyingAndPartialMessageSigners(offchainMessage, modifyingSigners, partialSigners, config);\n}\n\n/**\n * Extracts all {@link MessageSigner | MessageSigners} inside the provided offchain message and uses\n * them to return a signed offchain message envelope before asserting that all signatures required\n * by the message are present.\n *\n * This function delegates to the {@link partiallySignOffchainMessageWithSigners} function\n * in order to extract signers from the offchain message and sign it.\n *\n * @example\n * ```ts\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage);\n *\n * // With additional config.\n * const mySignedOffchainMessageEnvelope = await signOffchainMessageWithSigners(myOffchainMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the offchain message is fully signed.\n * mySignedOffchainMessageEnvelope satisfies FullySignedOffchainMessageEnvelope;\n * ```\n *\n * @see {@link partiallySignOffchainMessageWithSigners}\n */\nexport async function signOffchainMessageWithSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n config?: MessagePartialSignerConfig,\n): Promise {\n const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, config);\n assertIsFullySignedOffchainMessageEnvelope(signedOffchainMessageEnvelope);\n return signedOffchainMessageEnvelope;\n}\n\n/**\n * Identifies each provided {@link MessageSigner} and categorizes them into their respective types.\n * When a signer implements multiple interfaces, it will try to used to most powerful interface but\n * fall back to the least powerful interface when necessary.\n *\n * For instance, if a signer implements {@link MessageSigner} and {@link MessageModifyingSigner},\n * it will be categorized as a `MessageModifyingSigner`.\n */\nfunction categorizeMessageSigners(signers: readonly MessageSigner[]): Readonly<{\n modifyingSigners: readonly MessageModifyingSigner[];\n partialSigners: readonly MessagePartialSigner[];\n}> {\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyMessageModifyingSigners(signers);\n\n // Use any remaining signers as partial signers.\n const partialSigners = signers\n .filter(isMessagePartialSigner)\n .filter(signer => !(modifyingSigners as typeof signers).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners });\n}\n\n/** Identifies the best signers to use as MessageModifyingSigners, if any */\nfunction identifyMessageModifyingSigners(\n signers: readonly (MessageModifyingSigner | MessagePartialSigner)[],\n): readonly MessageModifyingSigner[] {\n // Ensure there are any MessageModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isMessageModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isMessagePartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs an offchain message using the provided\n * {@link MessageModifyingSigner | MessageModifyingSigners} sequentially followed by the\n * {@link MessagePartialSigner | MessagePartialSigners} in parallel.\n */\nasync function signModifyingAndPartialMessageSigners(\n offchainMessage: OffchainMessageWithRequiredSignatories &\n Omit,\n modifyingSigners: readonly MessageModifyingSigner[] = [],\n partialSigners: readonly MessagePartialSigner[] = [],\n config?: MessageModifyingSignerConfig,\n): Promise {\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n const offchainMessageEnvelope: SignableMessage = compileOffchainMessageEnvelope(offchainMessage);\n\n // Handle modifying signers sequentially.\n const modifiedOffchainMessage = await modifyingSigners.reduce(async (offchainMessageEnvelope, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [message] = await modifyingSigner.modifyAndSignMessages([await offchainMessageEnvelope], config);\n return Object.freeze(message);\n }, Promise.resolve(offchainMessageEnvelope));\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signMessages([modifiedOffchainMessage], config);\n return signatures;\n }),\n );\n\n // @ts-expect-error SignableMessage should probably specify `ReadonlyUint8Array` here.\n return Object.freeze({\n ...modifiedOffchainMessage,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedOffchainMessage.signatures ?? {}),\n ),\n } as OffchainMessageEnvelope);\n}\n","import {\n SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,\n SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { Brand } from '@solana/nominal-types';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { isTransactionModifyingSigner } from './transaction-modifying-signer';\nimport { isTransactionPartialSigner } from './transaction-partial-signer';\nimport { isTransactionSendingSigner } from './transaction-sending-signer';\n\n/**\n * Defines a transaction message with exactly one {@link TransactionSendingSigner}.\n *\n * This type is used to narrow the type of transaction messages that have been\n * checked to have exactly one sending signer.\n *\n * @example\n * ```ts\n * import { assertIsTransactionMessageWithSingleSendingSigner } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * transactionMessage satisfies TransactionMessageWithSingleSendingSigner;\n * ```\n *\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport type TransactionMessageWithSingleSendingSigner = Brand<\n TransactionMessageWithSigners,\n 'TransactionMessageWithSingleSendingSigner'\n>;\n\n/**\n * Checks whether the provided transaction has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using {@link signAndSendTransactionMessageWithSigners} to provide\n * a fallback strategy in case the transaction message cannot be send using this function.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * isTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners,\n * signTransactionMessageWithSigners,\n * } from '@solana/signers';\n * import { getBase64EncodedWireTransaction } from '@solana/transactions';\n *\n * let transactionSignature: SignatureBytes;\n * if (isTransactionMessageWithSingleSendingSigner(transactionMessage)) {\n * transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * } else {\n * const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);\n * const encodedTransaction = getBase64EncodedWireTransaction(signedTransaction);\n * transactionSignature = await rpc.sendTransaction(encodedTransaction).send();\n * }\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n */\nexport function isTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(transaction: TTransactionMessage): transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n try {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Asserts that the provided transaction message has exactly one {@link TransactionSendingSigner}.\n *\n * This can be useful when using the {@link signAndSendTransactionMessageWithSigners} function\n * to ensure it will be able to select the correct signer to send the transaction.\n *\n * @typeParam TTransactionMessage - The inferred type of the transaction message provided.\n *\n * @example\n * ```ts\n * import {\n * assertIsTransactionMessageWithSingleSendingSigner,\n * signAndSendTransactionMessageWithSigners\n * } from '@solana/signers';\n *\n * assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * @see {@link signAndSendTransactionMessageWithSigners}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n */\nexport function assertIsTransactionMessageWithSingleSendingSigner<\n TTransactionMessage extends BaseTransactionMessage & TransactionMessageWithFeePayer,\n>(\n transaction: TTransactionMessage,\n): asserts transaction is TransactionMessageWithSingleSendingSigner & TTransactionMessage {\n const signers = getSignersFromTransactionMessage(transaction);\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n\n if (sendingSigners.length === 0) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n // When identifying if there are multiple sending signers, we only need to check for\n // sending signers that do not implement other transaction signer interfaces as\n // they will be used as these other signer interfaces in case of a conflict.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer),\n );\n\n if (sendingOnlySigners.length > 1) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS);\n }\n}\n","import { SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SolanaError } from '@solana/errors';\nimport { SignatureBytes } from '@solana/keys';\nimport { BaseTransactionMessage, TransactionMessageWithFeePayer } from '@solana/transaction-messages';\nimport {\n assertIsFullySignedTransaction,\n compileTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithinSizeLimit,\n TransactionWithLifetime,\n} from '@solana/transactions';\n\nimport { getSignersFromTransactionMessage, TransactionMessageWithSigners } from './account-signer-meta';\nimport { deduplicateSigners } from './deduplicate-signers';\nimport {\n isTransactionModifyingSigner,\n TransactionModifyingSigner,\n TransactionModifyingSignerConfig,\n} from './transaction-modifying-signer';\nimport {\n isTransactionPartialSigner,\n TransactionPartialSigner,\n TransactionPartialSignerConfig,\n} from './transaction-partial-signer';\nimport {\n isTransactionSendingSigner,\n TransactionSendingSigner,\n TransactionSendingSignerConfig,\n} from './transaction-sending-signer';\nimport { isTransactionSigner, TransactionSigner } from './transaction-signer';\nimport { assertIsTransactionMessageWithSingleSendingSigner } from './transaction-with-single-sending-signer';\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction.\n *\n * It first uses all {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before\n * using all {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n *\n * If a composite signer implements both interfaces, it will be used as a\n * {@link TransactionModifyingSigner} if no other signer implements that interface.\n * Otherwise, it will be used as a {@link TransactionPartialSigner}.\n *\n * @example\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage);\n * ```\n *\n * It also accepts an optional {@link AbortSignal} that will be propagated to all signers.\n *\n * ```ts\n * const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Finally, note that this function ignores {@link TransactionSendingSigner | TransactionSendingSigners}\n * as it does not send the transaction. Check out the {@link signAndSendTransactionMessageWithSigners}\n * function for more details on how to use sending signers.\n *\n * @see {@link signTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function partiallySignTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const { partialSigners, modifyingSigners } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transactionMessage).filter(isTransactionSigner)),\n { identifySendingSigner: false },\n );\n\n return await signModifyingAndPartialTransactionSigners(\n transactionMessage,\n modifyingSigners,\n partialSigners,\n config,\n );\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to return a signed transaction before asserting\n * that all signatures required by the transaction are present.\n *\n * This function delegates to the {@link partiallySignTransactionMessageWithSigners} function\n * in order to extract signers from the transaction message and sign the transaction.\n *\n * @example\n * ```ts\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage);\n *\n * // With additional config.\n * const mySignedTransaction = await signTransactionMessageWithSigners(myTransactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n *\n * // We now know the transaction is fully signed.\n * mySignedTransaction satisfies FullySignedTransaction;\n * ```\n *\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signAndSendTransactionMessageWithSigners}\n */\nexport async function signTransactionMessageWithSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionPartialSignerConfig,\n): Promise {\n const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, config);\n assertIsFullySignedTransaction(signedTransaction);\n return signedTransaction;\n}\n\n/**\n * Extracts all {@link TransactionSigner | TransactionSigners} inside the provided\n * transaction message and uses them to sign it before sending it immediately to the blockchain.\n *\n * It returns the signature of the sent transaction (i.e. its identifier) as bytes.\n *\n * @example\n * ```ts\n * import { signAndSendTransactionMessageWithSigners } from '@solana/signers';\n *\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage);\n *\n * // With additional config.\n * const transactionSignature = await signAndSendTransactionMessageWithSigners(transactionMessage, {\n * abortSignal: myAbortController.signal,\n * });\n * ```\n *\n * @remarks\n * Similarly to the {@link partiallySignTransactionMessageWithSigners} function, it first uses all\n * {@link TransactionModifyingSigner | TransactionModifyingSigners} sequentially before using all\n * {@link TransactionPartialSigner | TransactionPartialSigners} in parallel.\n * It then sends the transaction using the {@link TransactionSendingSigner} it identified.\n *\n * Composite transaction signers are treated such that at least one sending signer is used if any.\n * When a {@link TransactionSigner} implements more than one interface, we use it as a:\n *\n * - {@link TransactionSendingSigner}, if no other {@link TransactionSendingSigner} exists.\n * - {@link TransactionModifyingSigner}, if no other {@link TransactionModifyingSigner} exists.\n * - {@link TransactionPartialSigner}, otherwise.\n *\n * The provided transaction must contain exactly one {@link TransactionSendingSigner} inside its account metas.\n * If more than one composite signers implement the {@link TransactionSendingSigner} interface,\n * one of them will be selected as the sending signer. Otherwise, if multiple\n * {@link TransactionSendingSigner | TransactionSendingSigners} must be selected, the function will throw an error.\n *\n * If you'd like to assert that a transaction makes use of exactly one {@link TransactionSendingSigner}\n * _before_ calling this function, you may use the {@link assertIsTransactionMessageWithSingleSendingSigner} function.\n *\n * Alternatively, you may use the {@link isTransactionMessageWithSingleSendingSigner} function to provide a\n * fallback in case the transaction does not contain any sending signer.\n *\n * @see {@link assertIsTransactionMessageWithSingleSendingSigner}\n * @see {@link isTransactionMessageWithSingleSendingSigner}\n * @see {@link partiallySignTransactionMessageWithSigners}\n * @see {@link signTransactionMessageWithSigners}\n *\n */\nexport async function signAndSendTransactionMessageWithSigners(\n transaction: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n config?: TransactionSendingSignerConfig,\n): Promise {\n assertIsTransactionMessageWithSingleSendingSigner(transaction);\n\n const abortSignal = config?.abortSignal;\n const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(\n deduplicateSigners(getSignersFromTransactionMessage(transaction).filter(isTransactionSigner)),\n );\n\n abortSignal?.throwIfAborted();\n const signedTransaction = await signModifyingAndPartialTransactionSigners(\n transaction,\n modifyingSigners,\n partialSigners,\n config,\n );\n\n if (!sendingSigner) {\n throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);\n }\n\n abortSignal?.throwIfAborted();\n const [signature] = await sendingSigner.signAndSendTransactions([signedTransaction], config);\n abortSignal?.throwIfAborted();\n\n return signature;\n}\n\n/**\n * Identifies each provided TransactionSigner and categorizes them into their respective types.\n * When a signer implements multiple interface, it will try to used to most powerful interface\n * but fallback to the least powerful interface when necessary.\n * For instance, if a signer implements TransactionSendingSigner and TransactionModifyingSigner,\n * it will be categorized as a TransactionSendingSigner if and only if no other signers implement\n * the TransactionSendingSigner interface.\n */\nfunction categorizeTransactionSigners(\n signers: readonly TransactionSigner[],\n config: { identifySendingSigner?: boolean } = {},\n): Readonly<{\n modifyingSigners: readonly TransactionModifyingSigner[];\n partialSigners: readonly TransactionPartialSigner[];\n sendingSigner: TransactionSendingSigner | null;\n}> {\n // Identify the unique sending signer that should be used.\n const identifySendingSigner = config.identifySendingSigner ?? true;\n const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;\n\n // Now, focus on the other signers.\n // I.e. the modifying or partial signers that are not the identified sending signer.\n // Note that any other sending only signers will be discarded.\n const otherSigners = signers.filter(\n (signer): signer is TransactionModifyingSigner | TransactionPartialSigner =>\n signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer)),\n );\n\n // Identify the modifying signers from the other signers.\n const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);\n\n // Use any remaining signers as partial signers.\n const partialSigners = otherSigners\n .filter(isTransactionPartialSigner)\n .filter(signer => !(modifyingSigners as typeof otherSigners).includes(signer));\n\n return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });\n}\n\n/** Identifies the best signer to use as a TransactionSendingSigner, if any */\nfunction identifyTransactionSendingSigner(signers: readonly TransactionSigner[]): TransactionSendingSigner | null {\n // Ensure there are any TransactionSendingSigners in the first place.\n const sendingSigners = signers.filter(isTransactionSendingSigner);\n if (sendingSigners.length === 0) return null;\n\n // Prefer sending signers that do not offer other interfaces.\n const sendingOnlySigners = sendingSigners.filter(\n signer => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer),\n );\n if (sendingOnlySigners.length > 0) {\n return sendingOnlySigners[0];\n }\n\n // Otherwise, choose any sending signer.\n return sendingSigners[0];\n}\n\n/** Identifies the best signers to use as TransactionModifyingSigners, if any */\nfunction identifyTransactionModifyingSigners(\n signers: readonly (TransactionModifyingSigner | TransactionPartialSigner)[],\n): readonly TransactionModifyingSigner[] {\n // Ensure there are any TransactionModifyingSigner in the first place.\n const modifyingSigners = signers.filter(isTransactionModifyingSigner);\n if (modifyingSigners.length === 0) return [];\n\n // Prefer modifying signers that do not offer partial signing.\n const nonPartialSigners = modifyingSigners.filter(signer => !isTransactionPartialSigner(signer));\n if (nonPartialSigners.length > 0) return nonPartialSigners;\n\n // Otherwise, choose only one modifying signer (whichever).\n return [modifyingSigners[0]];\n}\n\n/**\n * Signs a transaction using the provided TransactionModifyingSigners\n * sequentially followed by the TransactionPartialSigners in parallel.\n */\nasync function signModifyingAndPartialTransactionSigners(\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer & TransactionMessageWithSigners,\n modifyingSigners: readonly TransactionModifyingSigner[] = [],\n partialSigners: readonly TransactionPartialSigner[] = [],\n config?: TransactionModifyingSignerConfig,\n): Promise {\n // serialize the transaction\n const transaction = compileTransaction(transactionMessage);\n\n // Handle modifying signers sequentially.\n const modifiedTransaction = (await modifyingSigners.reduce(\n async (transaction, modifyingSigner) => {\n config?.abortSignal?.throwIfAborted();\n const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction], config);\n return Object.freeze(tx);\n },\n Promise.resolve(transaction) as Promise>,\n )) as Transaction & TransactionWithinSizeLimit & TransactionWithLifetime;\n\n // Handle partial signers in parallel.\n config?.abortSignal?.throwIfAborted();\n const signatureDictionaries = await Promise.all(\n partialSigners.map(async partialSigner => {\n const [signatures] = await partialSigner.signTransactions([modifiedTransaction], config);\n return signatures;\n }),\n );\n\n return Object.freeze({\n ...modifiedTransaction,\n signatures: Object.freeze(\n signatureDictionaries.reduce((signatures, signatureDictionary) => {\n return { ...signatures, ...signatureDictionary };\n }, modifiedTransaction.signatures ?? {}),\n ),\n });\n}\n","export const TextDecoder = globalThis.TextDecoder;\nexport const TextEncoder = globalThis.TextEncoder;\n","import { TextEncoder } from '@solana/text-encoding-impl';\n\nimport { SignatureDictionary } from './types';\n\n/**\n * Defines a message that needs signing and its current set of signatures if any.\n *\n * This interface allows {@link MessageModifyingSigner | MessageModifyingSigners}\n * to decide on whether or not they should modify the provided message depending\n * on whether or not signatures already exist for such message.\n *\n * It also helps create a more consistent API by providing a structure analogous\n * to transactions which also keep track of their {@link SignatureDictionary}.\n *\n * @example\n * ```ts\n * import { createSignableMessage } from '@solana/signers';\n *\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * message.content; // The content of the message as bytes.\n * message.signatures; // The current set of signatures for this message.\n * ```\n *\n * @see {@link createSignableMessage}\n */\nexport type SignableMessage = Readonly<{\n content: Uint8Array;\n signatures: SignatureDictionary;\n}>;\n\n/**\n * Creates a {@link SignableMessage} from a `Uint8Array` or a UTF-8 string.\n *\n * It optionally accepts a signature dictionary if the message already contains signatures.\n *\n * @example\n * ```ts\n * const message = createSignableMessage(new Uint8Array([1, 2, 3]));\n * const messageFromText = createSignableMessage('Hello world!');\n * const messageWithSignatures = createSignableMessage('Hello world!', {\n * [address('1234..5678')]: new Uint8Array([1, 2, 3]) as SignatureBytes,\n * });\n * ```\n */\nexport function createSignableMessage(\n content: Uint8Array | string,\n signatures: SignatureDictionary = {},\n): SignableMessage {\n return Object.freeze({\n content: typeof content === 'string' ? new TextEncoder().encode(content) : content,\n signatures: Object.freeze({ ...signatures }),\n });\n}\n","import { setMaxListeners } from 'node:events';\n\nexport const AbortController = class extends globalThis.AbortController {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);\n }\n};\n\nexport const EventTarget = class extends globalThis.EventTarget {\n constructor(...args: ConstructorParameters) {\n super(...args);\n setMaxListeners(Number.MAX_SAFE_INTEGER, this);\n }\n};\n","import { SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { GetEpochInfoApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport type { Commitment } from '@solana/rpc-types';\n\ntype GetBlockHeightExceedencePromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the block height as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /** The block height after which to reject the promise */\n lastValidBlockHeight: bigint;\n}) => Promise;\n\ntype CreateBlockHeightExceedencePromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that throws when the network progresses past the block height after which the\n * supplied blockhash is considered expired for use as a transaction lifetime specifier.\n *\n * When a transaction's lifetime is tied to a blockhash, that transaction can be landed on the\n * network until that blockhash expires. All blockhashes have a block height after which they are\n * considered to have expired.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createBlockHeightExceedencePromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getBlockHeightExceedencePromise({ lastValidBlockHeight });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error(\n * `The block height of the network has exceeded ${e.context.lastValidBlockHeight}. ` +\n * `It is now ${e.context.currentBlockHeight}`,\n * );\n * // Re-sign and retry the transaction.\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'devnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'testnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig<'mainnet'>): GetBlockHeightExceedencePromiseFn;\nexport function createBlockHeightExceedencePromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateBlockHeightExceedencePromiseFactoryConfig): GetBlockHeightExceedencePromiseFn {\n return async function getBlockHeightExceedencePromise({\n abortSignal: callerAbortSignal,\n commitment,\n lastValidBlockHeight,\n }): Promise {\n callerAbortSignal.throwIfAborted();\n const abortController = new AbortController();\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {\n const { absoluteSlot, blockHeight } = await rpc\n .getEpochInfo({ commitment })\n .send({ abortSignal: abortController.signal });\n return {\n blockHeight,\n differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight,\n };\n }\n try {\n const [slotNotifications, { blockHeight: initialBlockHeight, differenceBetweenSlotHeightAndBlockHeight }] =\n await Promise.all([\n rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),\n getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight(),\n ]);\n callerAbortSignal.throwIfAborted();\n let currentBlockHeight = initialBlockHeight;\n if (currentBlockHeight <= lastValidBlockHeight) {\n let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;\n for await (const slotNotification of slotNotifications) {\n const { slot } = slotNotification;\n if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {\n // Before making a final decision, recheck the actual block height.\n const {\n blockHeight: recheckedBlockHeight,\n differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight,\n } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();\n currentBlockHeight = recheckedBlockHeight;\n if (currentBlockHeight > lastValidBlockHeight) {\n // Verified; the block height has been exceeded.\n break;\n } else {\n // The block height has not been exceeded, which implies that the\n // difference between the slot height and the block height has grown\n // (ie. some blocks have been skipped since we started). Recalibrate the\n // difference and keep waiting.\n lastKnownDifferenceBetweenSlotHeightAndBlockHeight =\n currentDifferenceBetweenSlotHeightAndBlockHeight;\n }\n }\n }\n }\n callerAbortSignal.throwIfAborted();\n throw new SolanaError(SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, {\n currentBlockHeight,\n lastValidBlockHeight,\n });\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Decoder, getBase64Encoder } from '@solana/codecs-strings';\nimport { SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport { safeRace } from '@solana/promises';\nimport type { GetAccountInfoApi, Rpc } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions } from '@solana/rpc-subscriptions';\nimport type { Base64EncodedDataResponse, Commitment } from '@solana/rpc-types';\nimport { Nonce } from '@solana/transaction-messages';\n\ntype GetNonceInvalidationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * Fetch the nonce account details as of the highest slot that has reached this level of\n * commitment.\n */\n commitment: Commitment;\n /**\n * The value of the nonce that we would expect to see in the nonce account in order for any\n * transaction with that nonce-based lifetime to be considered valid.\n */\n currentNonceValue: Nonce;\n /** The address of the account in which the currently-valid nonce value is stored */\n nonceAccountAddress: Address;\n}) => Promise;\n\ntype CreateNonceInvalidationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\nconst NONCE_VALUE_OFFSET =\n 4 + // version(u32)\n 4 + // state(u32)\n 32; // nonce authority(pubkey)\n// Then comes the nonce value.\n\n/**\n * Creates a promise that throws when the value stored in a nonce account is not the expected one.\n *\n * When a transaction's lifetime is tied to the value stored in a nonce account, that transaction\n * can be landed on the network until the nonce is advanced to a new value.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, SolanaError } from '@solana/errors';\n * import { createNonceInvalidationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getNonceInvalidationPromise({\n * currentNonceValue,\n * nonceAccountAddress,\n * });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_INVALID)) {\n * console.error(`The nonce has advanced to ${e.context.actualNonceValue}`);\n * // Re-sign and retry the transaction.\n * return;\n * } else if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(`No nonce account was found at ${nonceAccountAddress}`);\n * }\n * throw e;\n * }\n * ```\n */\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'devnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'testnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig<'mainnet'>): GetNonceInvalidationPromiseFn;\nexport function createNonceInvalidationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateNonceInvalidationPromiseFactoryConfig): GetNonceInvalidationPromiseFn {\n return async function getNonceInvalidationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n currentNonceValue: expectedNonceValue,\n nonceAccountAddress,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for nonce account changes.\n */\n const accountNotifications = await rpcSubscriptions\n .accountNotifications(nonceAccountAddress, { commitment, encoding: 'base64' })\n .subscribe({ abortSignal: abortController.signal });\n const base58Decoder = getBase58Decoder();\n const base64Encoder = getBase64Encoder();\n function getNonceFromAccountData([base64EncodedBytes]: Base64EncodedDataResponse): Nonce {\n const data = base64Encoder.encode(base64EncodedBytes);\n const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);\n return base58Decoder.decode(nonceValueBytes) as Nonce;\n }\n const nonceAccountDidAdvancePromise = (async () => {\n for await (const accountNotification of accountNotifications) {\n const nonceValue = getNonceFromAccountData(accountNotification.value.data);\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current nonce\n * value to check if it has already been advanced.\n */\n const nonceIsAlreadyInvalidPromise = (async () => {\n const { value: nonceAccount } = await rpc\n .getAccountInfo(nonceAccountAddress, {\n commitment,\n dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },\n encoding: 'base58',\n })\n .send({ abortSignal: abortController.signal });\n if (!nonceAccount) {\n throw new SolanaError(SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, {\n nonceAccountAddress,\n });\n }\n const nonceValue =\n // This works because we asked for the exact slice of data representing the nonce\n // value, and furthermore asked for it in `base58` encoding.\n nonceAccount.data[0] as unknown as Nonce;\n if (nonceValue !== expectedNonceValue) {\n throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {\n actualNonceValue: nonceValue,\n expectedNonceValue,\n });\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import { getSolanaErrorFromTransactionError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { GetSignatureStatusesApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { type Commitment, commitmentComparator } from '@solana/rpc-types';\n\ntype GetRecentSignatureConfirmationPromiseFn = (config: {\n abortSignal: AbortSignal;\n /**\n * The level of commitment the transaction must have achieved in order for the promise to\n * resolve.\n */\n commitment: Commitment;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}) => Promise;\n\ntype CreateRecentSignatureConfirmationPromiseFactoryConfig = {\n rpc: Rpc & { '~cluster'?: TCluster };\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Creates a promise that resolves when a recently-landed transaction achieves the target\n * confirmation commitment, and throws when the transaction fails with an error.\n *\n * The status of recently-landed transactions is available in the network's status cache. This\n * confirmation strategy will only yield a result if the signature is still in the status cache. To\n * fetch the status of transactions older than those available in the status cache, use the\n * {@link GetSignatureStatusesApi.getSignatureStatuses} method setting the\n * `searchTransactionHistory` configuration param to `true`.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { createRecentSignatureConfirmationPromiseFactory } from '@solana/transaction-confirmation';\n *\n * const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n * rpc,\n * rpcSubscriptions,\n * });\n * try {\n * await getRecentSignatureConfirmationPromise({\n * commitment,\n * signature,\n * });\n * console.log(`The transaction with signature \\`${signature}\\` has achieved a commitment level of \\`${commitment}\\``);\n * } catch (e) {\n * console.error(`The transaction with signature \\`${signature}\\` failed`, e.cause);\n * throw e;\n * }\n * ```\n */\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'devnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'testnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig<'mainnet'>): GetRecentSignatureConfirmationPromiseFn;\nexport function createRecentSignatureConfirmationPromiseFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: CreateRecentSignatureConfirmationPromiseFactoryConfig): GetRecentSignatureConfirmationPromiseFn {\n return async function getRecentSignatureConfirmationPromise({\n abortSignal: callerAbortSignal,\n commitment,\n signature,\n }) {\n const abortController = new AbortController();\n function handleAbort() {\n abortController.abort();\n }\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n /**\n * STEP 1: Set up a subscription for status changes to a signature.\n */\n const signatureStatusNotifications = await rpcSubscriptions\n .signatureNotifications(signature, { commitment })\n .subscribe({ abortSignal: abortController.signal });\n const signatureDidCommitPromise = (async () => {\n for await (const signatureStatusNotification of signatureStatusNotifications) {\n if (signatureStatusNotification.value.err) {\n throw getSolanaErrorFromTransactionError(signatureStatusNotification.value.err);\n } else {\n return;\n }\n }\n })();\n /**\n * STEP 2: Having subscribed for updates, make a one-shot request for the current status.\n * This will only yield a result if the signature is still in the status cache.\n */\n const signatureStatusLookupPromise = (async () => {\n const { value: signatureStatusResults } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: abortController.signal });\n const signatureStatus = signatureStatusResults[0];\n if (signatureStatus?.err) {\n throw getSolanaErrorFromTransactionError(signatureStatus.err);\n } else if (\n signatureStatus?.confirmationStatus &&\n commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0\n ) {\n return;\n } else {\n await new Promise(() => {\n /* never resolve */\n });\n }\n })();\n try {\n return await safeRace([signatureDidCommitPromise, signatureStatusLookupPromise]);\n } finally {\n abortController.abort();\n }\n };\n}\n","import type { Commitment } from '@solana/rpc-types';\n\ntype Config = Readonly<{\n abortSignal: AbortSignal;\n /**\n * The timeout promise will throw after 30 seconds when the commitment is `processed`, and 60\n * seconds otherwise.\n */\n commitment: Commitment;\n}>;\n\n/**\n * When no other heuristic exists to infer that a transaction has expired, you can use this promise\n * factory with a commitment level. It throws after 30 seconds when the commitment is `processed`,\n * and 60 seconds otherwise. You would typically race this with another confirmation strategy.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { safeRace } from '@solana/promises';\n * import { getTimeoutPromise } from '@solana/transaction-confirmation';\n *\n * try {\n * await safeRace([getCustomTransactionConfirmationPromise(/* ... *\\/), getTimeoutPromise({ commitment })]);\n * } catch (e) {\n * if (e instanceof DOMException && e.name === 'TimeoutError') {\n * console.log('Could not confirm transaction after a timeout');\n * }\n * throw e;\n * }\n * ```\n */\nexport async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }: Config) {\n return await new Promise((_, reject) => {\n const handleAbort = (e: AbortSignalEventMap['abort']) => {\n clearTimeout(timeoutId);\n const abortError = new DOMException((e.target as AbortSignal).reason, 'AbortError');\n reject(abortError);\n };\n callerAbortSignal.addEventListener('abort', handleAbort);\n const timeoutMs = commitment === 'processed' ? 30_000 : 60_000;\n const startMs = performance.now();\n const timeoutId =\n // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure\n // elapsed time instead of active time.\n // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static\n setTimeout(() => {\n const elapsedMs = performance.now() - startMs;\n reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, 'TimeoutError'));\n }, timeoutMs);\n });\n}\n","import { AbortController } from '@solana/event-target-impl';\nimport type { Signature } from '@solana/keys';\nimport { safeRace } from '@solana/promises';\nimport type { Commitment } from '@solana/rpc-types';\n\nimport { createRecentSignatureConfirmationPromiseFactory } from './confirmation-strategy-recent-signature';\n\nexport interface BaseTransactionConfirmationStrategyConfig {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n getRecentSignatureConfirmationPromise: ReturnType;\n}\n\ntype WithNonNullableAbortSignal = Omit & Readonly<{ abortSignal: AbortSignal }>;\n\nexport async function raceStrategies(\n signature: Signature,\n config: TConfig,\n getSpecificStrategiesForRace: (config: WithNonNullableAbortSignal) => readonly Promise[],\n) {\n const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;\n callerAbortSignal?.throwIfAborted();\n const abortController = new AbortController();\n if (callerAbortSignal) {\n const handleAbort = () => {\n abortController.abort();\n };\n callerAbortSignal.addEventListener('abort', handleAbort, { signal: abortController.signal });\n }\n try {\n const specificStrategies = getSpecificStrategiesForRace({\n ...config,\n abortSignal: abortController.signal,\n });\n return await safeRace([\n getRecentSignatureConfirmationPromise({\n abortSignal: abortController.signal,\n commitment,\n signature,\n }),\n ...specificStrategies,\n ]);\n } finally {\n abortController.abort();\n }\n}\n","import { Signature } from '@solana/keys';\nimport {\n getSignatureFromTransaction,\n Transaction,\n TransactionWithBlockhashLifetime,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { createBlockHeightExceedencePromiseFactory } from './confirmation-strategy-blockheight';\nimport { createNonceInvalidationPromiseFactory } from './confirmation-strategy-nonce';\nimport { BaseTransactionConfirmationStrategyConfig, raceStrategies } from './confirmation-strategy-racer';\nimport { getTimeoutPromise } from './confirmation-strategy-timeout';\n\nexport type TransactionWithLastValidBlockHeight = Omit & {\n lifetimeConstraint: Omit;\n};\n\ninterface WaitForDurableNonceTransactionConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getNonceInvalidationPromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getBlockHeightExceedencePromise: ReturnType;\n transaction: Readonly;\n}\n\ninterface WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig extends BaseTransactionConfirmationStrategyConfig {\n getTimeoutPromise: typeof getTimeoutPromise;\n /**\n * A 64 byte Ed25519 signature, encoded as a base-58 string, that uniquely identifies a\n * transaction by virtue of being the first or only signature in its list of signatures.\n */\n signature: Signature;\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom nonce\n * transaction confirmation strategy.\n *\n * @example\n * ```ts\n * import { waitForDurableNonceTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForDurableNonceTransactionConfirmation({\n * getNonceInvalidationPromise({ abortSignal, commitment, currentNonceValue, nonceAccountAddress }) {\n * // Return a promise that rejects when a nonce becomes invalid.\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForDurableNonceTransactionConfirmation(\n config: WaitForDurableNonceTransactionConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {\n return [\n getNonceInvalidationPromise({\n abortSignal,\n commitment,\n currentNonceValue: transaction.lifetimeConstraint.nonce,\n nonceAccountAddress: transaction.lifetimeConstraint.nonceAccountAddress,\n }),\n ];\n },\n );\n}\n\n/**\n * Supply your own confirmation implementations to this function to create a custom confirmation\n * strategy for recently-landed transactions.\n *\n * @example\n * ```ts\n * import { waitForRecentTransactionConfirmation } from '@solana/transaction-confirmation';\n *\n * try {\n * await waitForRecentTransactionConfirmation({\n * getBlockHeightExceedencePromise({ abortSignal, commitment, lastValidBlockHeight }) {\n * // Return a promise that rejects when the blockhash's block height has been exceeded\n * },\n * getRecentSignatureConfirmationPromise({ abortSignal, commitment, signature }) {\n * // Return a promise that resolves when a transaction achieves confirmation\n * },\n * });\n * } catch (e) {\n * // Handle errors.\n * }\n * ```\n */\nexport async function waitForRecentTransactionConfirmation(\n config: WaitForRecentTransactionWithBlockhashLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n getSignatureFromTransaction(config.transaction),\n config,\n function getSpecificStrategiesForRace({\n abortSignal,\n commitment,\n getBlockHeightExceedencePromise,\n transaction,\n }) {\n return [\n getBlockHeightExceedencePromise({\n abortSignal,\n commitment,\n lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight,\n }),\n ];\n },\n );\n}\n\n/** @deprecated */\nexport async function waitForRecentTransactionConfirmationUntilTimeout(\n config: WaitForRecentTransactionWithTimeBasedLifetimeConfirmationConfig,\n): Promise {\n await raceStrategies(\n config.signature,\n config,\n function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise }) {\n return [\n getTimeoutPromise({\n abortSignal,\n commitment,\n }),\n ];\n },\n );\n}\n","import type { Address } from '@solana/addresses';\nimport type { Signature } from '@solana/keys';\nimport type { RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { Commitment, Lamports } from '@solana/rpc-types';\nimport { waitForRecentTransactionConfirmationUntilTimeout } from '@solana/transaction-confirmation';\n\ntype RequestAndConfirmAirdropConfig = Readonly<{\n abortSignal?: AbortSignal;\n commitment: Commitment;\n confirmSignatureOnlyTransaction: (\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) => Promise;\n lamports: Lamports;\n recipientAddress: Address;\n rpc: Rpc;\n}>;\n\nexport async function requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmSignatureOnlyTransaction,\n lamports,\n recipientAddress,\n rpc,\n}: RequestAndConfirmAirdropConfig): Promise {\n const airdropTransactionSignature = await rpc\n .requestAirdrop(recipientAddress, lamports, { commitment })\n .send({ abortSignal });\n await confirmSignatureOnlyTransaction({\n abortSignal,\n commitment,\n signature: airdropTransactionSignature,\n });\n return airdropTransactionSignature;\n}\n","import type { Signature } from '@solana/keys';\nimport type { GetSignatureStatusesApi, RequestAirdropApi, Rpc } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createRecentSignatureConfirmationPromiseFactory,\n getTimeoutPromise,\n waitForRecentTransactionConfirmationUntilTimeout,\n} from '@solana/transaction-confirmation';\n\nimport { requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT } from './airdrop-internal';\n\ntype AirdropFunction = (\n config: Omit<\n Parameters[0],\n 'confirmSignatureOnlyTransaction' | 'rpc'\n >,\n) => Promise;\n\ntype AirdropFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link RequestAirdropApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to airdrop a certain amount of {@link Lamports} to a Solana\n * address.\n *\n * > [!NOTE] This only works on test clusters.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { address, airdropFactory, createSolanaRpc, createSolanaRpcSubscriptions, devnet, lamports } from '@solana/kit';\n *\n * const rpc = createSolanaRpc(devnet('http://127.0.0.1:8899'));\n * const rpcSubscriptions = createSolanaRpcSubscriptions(devnet('ws://127.0.0.1:8900'));\n *\n * const airdrop = airdropFactory({ rpc, rpcSubscriptions });\n *\n * await airdrop({\n * commitment: 'confirmed',\n * recipientAddress: address('FnHyam9w4NZoWR6mKN1CuGBritdsEWZQa4Z4oawLZGxa'),\n * lamports: lamports(10_000_000n),\n * });\n * ```\n */\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'devnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'mainnet'>): AirdropFunction;\nexport function airdropFactory({ rpc, rpcSubscriptions }: AirdropFactoryConfig<'testnet'>): AirdropFunction;\nexport function airdropFactory({\n rpc,\n rpcSubscriptions,\n}: AirdropFactoryConfig): AirdropFunction {\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmSignatureOnlyTransaction(\n config: Omit<\n Parameters[0],\n 'getRecentSignatureConfirmationPromise' | 'getTimeoutPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmationUntilTimeout({\n ...config,\n getRecentSignatureConfirmationPromise,\n getTimeoutPromise,\n });\n }\n return async function airdrop(config) {\n return await requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmSignatureOnlyTransaction,\n rpc,\n });\n };\n}\n","import {\n assertAccountsDecoded,\n assertAccountsExist,\n type FetchAccountsConfig,\n fetchJsonParsedAccounts,\n} from '@solana/accounts';\nimport type { Address } from '@solana/addresses';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport { type AddressesByLookupTableAddress } from '@solana/transaction-messages';\n\ntype FetchedAddressLookup = {\n addresses: Address[];\n};\n\n/**\n * Given a list of addresses belonging to address lookup tables, returns a map of lookup table\n * addresses to an ordered array of the addresses they contain.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function fetchAddressesForLookupTables(\n lookupTableAddresses: Address[],\n rpc: Rpc,\n config?: FetchAccountsConfig,\n): Promise {\n if (lookupTableAddresses.length === 0) {\n return {};\n }\n\n const fetchedLookupTables = await fetchJsonParsedAccounts(\n rpc,\n lookupTableAddresses,\n config,\n );\n\n assertAccountsDecoded(fetchedLookupTables);\n assertAccountsExist(fetchedLookupTables);\n\n return fetchedLookupTables.reduce((acc, lookup) => {\n return {\n ...acc,\n [lookup.address]: lookup.data.addresses,\n };\n }, {});\n}\n","import { type FetchAccountsConfig } from '@solana/accounts';\nimport type { GetMultipleAccountsApi, Rpc } from '@solana/rpc';\nimport {\n CompiledTransactionMessage,\n CompiledTransactionMessageWithLifetime,\n decompileTransactionMessage,\n TransactionMessage,\n TransactionMessageWithFeePayer,\n TransactionMessageWithLifetime,\n} from '@solana/transaction-messages';\n\nimport { fetchAddressesForLookupTables } from './fetch-lookup-tables';\n\ntype DecompileTransactionMessageFetchingLookupTablesConfig = FetchAccountsConfig & {\n lastValidBlockHeight?: bigint;\n};\n\n/**\n * Returns a {@link TransactionMessage} from a {@link CompiledTransactionMessage}. If any of the\n * accounts in the compiled message require an address lookup table to find their address, this\n * function will use the supplied RPC instance to fetch the contents of the address lookup table\n * from the network.\n *\n * @param rpc An object that supports the {@link GetMultipleAccountsApi} of the Solana RPC API\n * @param config\n */\nexport async function decompileTransactionMessageFetchingLookupTables(\n compiledTransactionMessage: CompiledTransactionMessage & CompiledTransactionMessageWithLifetime,\n rpc: Rpc,\n config?: DecompileTransactionMessageFetchingLookupTablesConfig,\n): Promise {\n const lookupTables =\n 'addressTableLookups' in compiledTransactionMessage &&\n compiledTransactionMessage.addressTableLookups !== undefined &&\n compiledTransactionMessage.addressTableLookups.length > 0\n ? compiledTransactionMessage.addressTableLookups\n : [];\n const lookupTableAddresses = lookupTables.map(l => l.lookupTableAddress);\n\n const { lastValidBlockHeight, ...fetchAccountsConfig } = config ?? {};\n const addressesByLookupTableAddress =\n lookupTableAddresses.length > 0\n ? await fetchAddressesForLookupTables(lookupTableAddresses, rpc, fetchAccountsConfig)\n : {};\n\n return decompileTransactionMessage(compiledTransactionMessage, {\n addressesByLookupTableAddress,\n lastValidBlockHeight,\n });\n}\n","import type { Lamports } from '@solana/rpc-types';\n\n/**\n * Calculates the minimum {@link Lamports | lamports} required to make an account rent exempt for a\n * given data size, without performing an RPC call.\n *\n * Values are sourced from the on-chain rent parameters in the Solana runtime:\n * https://github.com/anza-xyz/solana-sdk/blob/c07f692e41d757057c8700211a9300cdcd6d33b1/rent/src/lib.rs#L93-L97\n *\n * Note that this logic may change, or be incorrect depending on the cluster you are connected to.\n * You can always use the RPC method `getMinimumBalanceForRentExemption` to get the current value.\n *\n * @param space The number of bytes of account data.\n */\nexport function getMinimumBalanceForRentExemption(space: bigint): Lamports {\n const RENT = {\n ACCOUNT_STORAGE_OVERHEAD: 128n,\n DEFAULT_EXEMPTION_THRESHOLD: 2n,\n DEFAULT_LAMPORTS_PER_BYTE_YEAR: 3_480n,\n } as const;\n const requiredLamports =\n (RENT.ACCOUNT_STORAGE_OVERHEAD + space) *\n RENT.DEFAULT_LAMPORTS_PER_BYTE_YEAR *\n RENT.DEFAULT_EXEMPTION_THRESHOLD;\n return requiredLamports as Lamports;\n}\n","import type { Signature } from '@solana/keys';\nimport type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { Commitment, commitmentComparator } from '@solana/rpc-types';\nimport {\n TransactionWithLastValidBlockHeight,\n waitForDurableNonceTransactionConfirmation,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getBase64EncodedWireTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\ninterface SendAndConfirmDurableNonceTransactionConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmDurableNonceTransaction: (\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime;\n}\n\ninterface SendAndConfirmTransactionWithBlockhashLifetimeConfig\n extends SendTransactionBaseConfig, SendTransactionConfigWithoutEncoding {\n confirmRecentTransaction: (\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) => Promise;\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight;\n}\n\ninterface SendTransactionBaseConfig extends SendTransactionConfigWithoutEncoding {\n abortSignal?: AbortSignal;\n commitment: Commitment;\n rpc: Rpc;\n transaction: SendableTransaction & Transaction;\n}\n\ntype SendTransactionConfigWithoutEncoding = Omit<\n NonNullable[1]>,\n 'encoding'\n>;\n\nfunction getSendTransactionConfigWithAdjustedPreflightCommitment(\n commitment: Commitment,\n config?: SendTransactionConfigWithoutEncoding,\n): SendTransactionConfigWithoutEncoding | void {\n if (\n // The developer has supplied no value for `preflightCommitment`.\n !config?.preflightCommitment &&\n // The value of `commitment` is lower than the server default of `preflightCommitment`.\n commitmentComparator(commitment, 'finalized' /* default value of `preflightCommitment` */) < 0\n ) {\n return {\n ...config,\n // In the common case, it is unlikely that you want to simulate a transaction at\n // `finalized` commitment when your standard of commitment for confirming the\n // transaction is lower. Cap the simulation commitment level to the level of the\n // confirmation commitment.\n preflightCommitment: commitment,\n };\n }\n // The commitment at which the developer wishes to confirm the transaction is at least as\n // high as the commitment at which they want to simulate it. Honour the config as-is.\n return config;\n}\n\nexport async function sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendTransactionBaseConfig): Promise {\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);\n return await rpc\n .sendTransaction(base64EncodedWireTransaction, {\n ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),\n encoding: 'base64',\n })\n .send({ abortSignal });\n}\n\nexport async function sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmDurableNonceTransactionConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmDurableNonceTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n\nexport async function sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n abortSignal,\n commitment,\n confirmRecentTransaction,\n rpc,\n transaction,\n ...sendTransactionConfig\n}: SendAndConfirmTransactionWithBlockhashLifetimeConfig): Promise {\n const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...sendTransactionConfig,\n abortSignal,\n commitment,\n rpc,\n transaction,\n });\n await confirmRecentTransaction({\n abortSignal,\n commitment,\n transaction,\n });\n return transactionSignature;\n}\n","import { getSolanaErrorFromTransactionError, isSolanaError, SOLANA_ERROR__INVALID_NONCE } from '@solana/errors';\nimport { Signature } from '@solana/keys';\nimport type { GetAccountInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { AccountNotificationsApi, RpcSubscriptions, SignatureNotificationsApi } from '@solana/rpc-subscriptions';\nimport { commitmentComparator } from '@solana/rpc-types';\nimport {\n createNonceInvalidationPromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n waitForDurableNonceTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport {\n getSignatureFromTransaction,\n SendableTransaction,\n Transaction,\n TransactionWithDurableNonceLifetime,\n} from '@solana/transactions';\n\nimport { sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmDurableNonceTransactionFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithDurableNonceLifetime,\n config: Omit<\n Parameters[0],\n 'confirmDurableNonceTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmDurableNonceTransactionFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link AccountNotificationsApi} and the {@link SignatureNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a nonce-based transaction to the network and to wait\n * until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * isSolanaError,\n * sendAndConfirmDurableNonceTransactionFactory,\n * SOLANA_ERROR__INVALID_NONCE,\n * SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,\n * } from '@solana/kit';\n *\n * const sendAndConfirmNonceTransaction = sendAndConfirmDurableNonceTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmNonceTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND)) {\n * console.error(\n * 'The lifetime specified by this transaction refers to a nonce account ' +\n * `\\`${e.context.nonceAccountAddress}\\` that does not exist`,\n * );\n * } else if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n * console.error('This transaction depends on a nonce that is no longer valid');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'devnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'testnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig<'mainnet'>): SendAndConfirmDurableNonceTransactionFunction;\nexport function sendAndConfirmDurableNonceTransactionFactory<\n TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void,\n>({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmDurableNonceTransactionFactoryConfig): SendAndConfirmDurableNonceTransactionFunction {\n const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions } as Parameters<\n typeof createNonceInvalidationPromiseFactory\n >[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n\n /**\n * Creates a wrapped version of getNonceInvalidationPromise that handles the race condition\n * where the nonce account update notification arrives before the signature confirmation.\n *\n * When the nonce changes, we check if our transaction actually landed on-chain.\n * If it did, we don't throw - letting the signature confirmation promise continue.\n */\n function createNonceInvalidationPromiseHandlingRaceCondition(\n signature: Signature,\n ): typeof getNonceInvalidationPromise {\n return async function wrappedGetNonceInvalidationPromise(config) {\n try {\n return await getNonceInvalidationPromise(config);\n } catch (e) {\n // If nonce became invalid, check if our transaction actually landed\n if (isSolanaError(e, SOLANA_ERROR__INVALID_NONCE)) {\n let status;\n try {\n const { value: statuses } = await rpc\n .getSignatureStatuses([signature])\n .send({ abortSignal: config.abortSignal });\n status = statuses[0];\n } catch {\n // RPC failed - propagate the original nonce error\n throw e;\n }\n\n if (status === null || status === undefined) {\n // Transaction doesn't exist - nonce was truly invalid\n throw e;\n }\n\n // Check if status meets required commitment\n if (\n status.confirmationStatus !== null &&\n commitmentComparator(status.confirmationStatus, config.commitment) >= 0\n ) {\n // Transaction failed on-chain, throw the error from the transaction\n if (status.err !== null) {\n throw getSolanaErrorFromTransactionError(status.err);\n }\n // Transaction succeeded, resolve the promise successfully\n return;\n }\n\n // Commitment not met yet - return a never-resolving promise\n // This lets the signature confirmation promise continue\n return await new Promise(() => {});\n }\n throw e;\n }\n };\n }\n\n async function confirmDurableNonceTransaction(\n config: Omit<\n Parameters[0],\n 'getNonceInvalidationPromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n const wrappedGetNonceInvalidationPromise = createNonceInvalidationPromiseHandlingRaceCondition(\n getSignatureFromTransaction(config.transaction),\n );\n\n await waitForDurableNonceTransactionConfirmation({\n ...config,\n getNonceInvalidationPromise: wrappedGetNonceInvalidationPromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmDurableNonceTransaction(transaction, config) {\n await sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmDurableNonceTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { GetEpochInfoApi, GetSignatureStatusesApi, Rpc, SendTransactionApi } from '@solana/rpc';\nimport type { RpcSubscriptions, SignatureNotificationsApi, SlotNotificationsApi } from '@solana/rpc-subscriptions';\nimport {\n createBlockHeightExceedencePromiseFactory,\n createRecentSignatureConfirmationPromiseFactory,\n TransactionWithLastValidBlockHeight,\n waitForRecentTransactionConfirmation,\n} from '@solana/transaction-confirmation';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFunction = (\n transaction: SendableTransaction & Transaction & TransactionWithLastValidBlockHeight,\n config: Omit<\n Parameters[0],\n 'confirmRecentTransaction' | 'rpc' | 'transaction'\n >,\n) => Promise;\n\ntype SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig = {\n /** An object that supports the {@link GetSignatureStatusesApi} and the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc & { '~cluster'?: TCluster };\n /** An object that supports the {@link SignatureNotificationsApi} and the {@link SlotNotificationsApi} of the Solana RPC Subscriptions API */\n rpcSubscriptions: RpcSubscriptions & { '~cluster'?: TCluster };\n};\n\n/**\n * Returns a function that you can call to send a blockhash-based transaction to the network and to\n * wait until it has been confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { isSolanaError, sendAndConfirmTransactionFactory, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED } from '@solana/kit';\n *\n * const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });\n *\n * try {\n * await sendAndConfirmTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {\n * console.error('This transaction depends on a blockhash that has expired');\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'devnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'testnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig<'mainnet'>): SendAndConfirmTransactionWithBlockhashLifetimeFunction;\nexport function sendAndConfirmTransactionFactory({\n rpc,\n rpcSubscriptions,\n}: SendAndConfirmTransactionWithBlockhashLifetimeFactoryConfig): SendAndConfirmTransactionWithBlockhashLifetimeFunction {\n const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({\n rpc,\n rpcSubscriptions,\n } as Parameters[0]);\n async function confirmRecentTransaction(\n config: Omit<\n Parameters[0],\n 'getBlockHeightExceedencePromise' | 'getRecentSignatureConfirmationPromise'\n >,\n ) {\n await waitForRecentTransactionConfirmation({\n ...config,\n getBlockHeightExceedencePromise,\n getRecentSignatureConfirmationPromise,\n });\n }\n return async function sendAndConfirmTransaction(transaction, config) {\n await sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n confirmRecentTransaction,\n rpc,\n transaction,\n });\n };\n}\n","import type { Rpc, SendTransactionApi } from '@solana/rpc';\nimport { SendableTransaction, Transaction } from '@solana/transactions';\n\nimport { sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT } from './send-transaction-internal';\n\ntype SendTransactionWithoutConfirmingFunction = (\n transaction: SendableTransaction & Transaction,\n config: Omit[0], 'rpc' | 'transaction'>,\n) => Promise;\n\ninterface SendTransactionWithoutConfirmingFactoryConfig {\n /** An object that supports the {@link SendTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}\n\n/**\n * Returns a function that you can call to send a transaction with any kind of lifetime to the\n * network without waiting for it to be confirmed.\n *\n * @param config\n *\n * @example\n * ```ts\n * import {\n * sendTransactionWithoutConfirmingFactory,\n * SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,\n * } from '@solana/kit';\n *\n * const sendTransaction = sendTransactionWithoutConfirmingFactory({ rpc });\n *\n * try {\n * await sendTransaction(transaction, { commitment: 'confirmed' });\n * } catch (e) {\n * if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE)) {\n * console.error('The transaction failed in simulation', e.cause);\n * } else {\n * throw e;\n * }\n * }\n * ```\n */\nexport function sendTransactionWithoutConfirmingFactory({\n rpc,\n}: SendTransactionWithoutConfirmingFactoryConfig): SendTransactionWithoutConfirmingFunction {\n return async function sendTransactionWithoutConfirming(transaction, config) {\n await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({\n ...config,\n rpc,\n transaction,\n });\n };\n}\n","/**\n * Wallet Key Derivation\n *\n * BIP-39 mnemonic generation + BIP-44 HD key derivation for EVM and Solana.\n * Absorbed from @blockrun/clawwallet. No file I/O here - auth.ts handles persistence.\n *\n * Solana uses SLIP-10 Ed25519 derivation (Phantom/Solflare/Backpack compatible).\n * EVM uses standard BIP-32 secp256k1 derivation.\n */\n\nimport { HDKey } from \"@scure/bip32\";\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from \"@scure/bip39\";\nimport { wordlist as english } from \"@scure/bip39/wordlists/english\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha512 } from \"@noble/hashes/sha512\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst ETH_DERIVATION_PATH = \"m/44'/60'/0'/0/0\";\nconst SOLANA_HARDENED_INDICES = [44 + 0x80000000, 501 + 0x80000000, 0 + 0x80000000, 0 + 0x80000000]; // m/44'/501'/0'/0'\n\nexport interface DerivedKeys {\n mnemonic: string;\n evmPrivateKey: `0x${string}`;\n evmAddress: string;\n solanaPrivateKeyBytes: Uint8Array; // 32 bytes\n}\n\n/**\n * Generate a 24-word BIP-39 mnemonic.\n */\nexport function generateWalletMnemonic(): string {\n return generateMnemonic(english, 256);\n}\n\n/**\n * Validate a BIP-39 mnemonic.\n */\nexport function isValidMnemonic(mnemonic: string): boolean {\n return validateMnemonic(mnemonic, english);\n}\n\n/**\n * Derive EVM private key and address from a BIP-39 mnemonic.\n * Path: m/44'/60'/0'/0/0 (standard Ethereum derivation)\n */\nexport function deriveEvmKey(mnemonic: string): { privateKey: `0x${string}`; address: string } {\n const seed = mnemonicToSeedSync(mnemonic);\n const hdKey = HDKey.fromMasterSeed(seed);\n const derived = hdKey.derive(ETH_DERIVATION_PATH);\n if (!derived.privateKey) throw new Error(\"Failed to derive EVM private key\");\n const hex = `0x${Buffer.from(derived.privateKey).toString(\"hex\")}` as `0x${string}`;\n const account = privateKeyToAccount(hex);\n return { privateKey: hex, address: account.address };\n}\n\n/**\n * Derive 32-byte Solana private key using SLIP-10 Ed25519 derivation.\n * Path: m/44'/501'/0'/0' (Phantom / Solflare / Backpack compatible)\n *\n * Algorithm (SLIP-0010 for Ed25519):\n * 1. Master: HMAC-SHA512(key=\"ed25519 seed\", data=bip39_seed) → IL=key, IR=chainCode\n * 2. For each hardened child index:\n * HMAC-SHA512(key=chainCode, data=0x00 || key || ser32(index)) → split again\n * 3. Final IL (32 bytes) = Ed25519 private key seed\n */\nexport function deriveSolanaKeyBytes(mnemonic: string): Uint8Array {\n const seed = mnemonicToSeedSync(mnemonic);\n\n // Master key from SLIP-10\n let I = hmac(sha512, \"ed25519 seed\", seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n // Derive each hardened child: m/44'/501'/0'/0'\n for (const index of SOLANA_HARDENED_INDICES) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n // ser32 big-endian\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n return new Uint8Array(key);\n}\n\n/**\n * Derive both EVM and Solana keys from a single mnemonic.\n */\nexport function deriveAllKeys(mnemonic: string): DerivedKeys {\n const { privateKey: evmPrivateKey, address: evmAddress } = deriveEvmKey(mnemonic);\n const solanaPrivateKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return { mnemonic, evmPrivateKey, evmAddress, solanaPrivateKeyBytes };\n}\n\n/**\n * Get the Solana address from 32-byte private key bytes.\n * Uses @solana/kit's createKeyPairSignerFromPrivateKeyBytes (dynamic import).\n */\nexport async function getSolanaAddress(privateKeyBytes: Uint8Array): Promise {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(privateKeyBytes);\n return signer.address;\n}\n","/**\n * Solana USDC Balance Monitor\n *\n * Checks USDC balance on Solana mainnet with caching.\n * Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).\n */\n\nimport { address as solAddress, createSolanaRpc } from \"@solana/kit\";\n\nconst SOLANA_USDC_MINT = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nconst SOLANA_DEFAULT_RPC = \"https://api.mainnet-beta.solana.com\";\nconst BALANCE_TIMEOUT_MS = 10_000;\nconst CACHE_TTL_MS = 30_000;\n\nexport type SolanaBalanceInfo = {\n balance: bigint;\n balanceUSD: string;\n assetSymbol: string;\n isLow: boolean;\n isEmpty: boolean;\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SolanaSufficiencyResult = {\n sufficient: boolean;\n info: SolanaBalanceInfo;\n shortfall?: string;\n};\n\nexport class SolanaBalanceMonitor {\n private readonly rpc: ReturnType;\n private readonly walletAddress: string;\n private cachedBalance: bigint | null = null;\n private cachedAt = 0;\n\n constructor(walletAddress: string, rpcUrl?: string) {\n this.walletAddress = walletAddress;\n const url = rpcUrl || process[\"env\"].CLAWROUTER_SOLANA_RPC_URL || SOLANA_DEFAULT_RPC;\n this.rpc = createSolanaRpc(url);\n }\n\n async checkBalance(): Promise {\n const now = Date.now();\n if (\n this.cachedBalance !== null &&\n this.cachedBalance > 0n &&\n now - this.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(this.cachedBalance);\n }\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n const balance = await this.fetchBalance();\n if (balance > 0n) {\n this.cachedBalance = balance;\n this.cachedAt = now;\n }\n return this.buildInfo(balance);\n }\n\n deductEstimated(amountMicros: bigint): void {\n if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {\n this.cachedBalance -= amountMicros;\n }\n }\n\n invalidate(): void {\n this.cachedBalance = null;\n this.cachedAt = 0;\n }\n\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSDC(shortfall),\n };\n }\n\n /**\n * Format USDC amount (in micros) as \"$X.XX\".\n */\n formatUSDC(amountMicros: bigint): string {\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n getAssetSymbol(): string {\n return \"USDC\";\n }\n\n /**\n * Check native SOL balance (in lamports). Useful for detecting users who\n * funded with SOL instead of USDC.\n */\n async checkSolBalance(): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n try {\n const owner = solAddress(this.walletAddress);\n const response = await this.rpc.getBalance(owner).send({ abortSignal: controller.signal });\n return BigInt(response.value);\n } catch {\n return 0n;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async fetchBalance(): Promise {\n const owner = solAddress(this.walletAddress);\n const mint = solAddress(SOLANA_USDC_MINT);\n\n // The public Solana RPC frequently returns empty token account lists even\n // for funded wallets. Retry once on empty before accepting $0 as truth.\n for (let attempt = 0; attempt < 2; attempt++) {\n const result = await this.fetchBalanceOnce(owner, mint);\n if (result > 0n || attempt === 1) return result;\n await new Promise((r) => setTimeout(r, 1_000));\n }\n return 0n;\n }\n\n private async fetchBalanceOnce(\n owner: ReturnType,\n mint: ReturnType,\n ): Promise {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);\n\n try {\n const response = await this.rpc\n .getTokenAccountsByOwner(owner, { mint }, { encoding: \"jsonParsed\" })\n .send({ abortSignal: controller.signal });\n\n if (response.value.length === 0) return 0n;\n\n let total = 0n;\n for (const account of response.value) {\n const parsed = account.account.data as {\n parsed: { info: { tokenAmount: { amount: string } } };\n };\n total += BigInt(parsed.parsed.info.tokenAmount.amount);\n }\n return total;\n } catch (err) {\n throw new Error(\n `Failed to fetch Solana USDC balance: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n private buildInfo(balance: bigint): SolanaBalanceInfo {\n const dollars = Number(balance) / 1_000_000;\n return {\n balance,\n balanceUSD: `$${dollars.toFixed(2)}`,\n assetSymbol: \"USDC\",\n isLow: balance < 1_000_000n,\n isEmpty: balance < 100n,\n walletAddress: this.walletAddress,\n };\n }\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n};\n\nexport function getMintEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getMintCodec(): FixedSizeCodec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n\nexport function getMintSize(): number {\n return 82;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getTokenEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getTokenCodec(): FixedSizeCodec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n\nexport function getTokenSize(): number {\n return 165;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n} from '../instructions';\n\nexport const TOKEN_PROGRAM_ADDRESS =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n\nexport enum TokenAccount {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyTokenAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenAccount {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return TokenAccount.Mint;\n }\n if (data.length === 165) {\n return TokenAccount.Token;\n }\n if (data.length === 355) {\n return TokenAccount.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token account.'\n );\n}\n\nexport enum TokenInstruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n}\n\nexport function identifyTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): TokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return TokenInstruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return TokenInstruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return TokenInstruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return TokenInstruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return TokenInstruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return TokenInstruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return TokenInstruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return TokenInstruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return TokenInstruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return TokenInstruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return TokenInstruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return TokenInstruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return TokenInstruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return TokenInstruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return TokenInstruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return TokenInstruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return TokenInstruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return TokenInstruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return TokenInstruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return TokenInstruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return TokenInstruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return TokenInstruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return TokenInstruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return TokenInstruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return TokenInstruction.UiAmountToAmount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token instruction.'\n );\n}\n\nexport type ParsedTokenInstruction<\n TProgram extends string = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n> =\n | ({\n instructionType: TokenInstruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: TokenInstruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: TokenInstruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: TokenInstruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: TokenInstruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: TokenInstruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: TokenInstruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: TokenInstruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: TokenInstruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: TokenInstruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: TokenInstruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: TokenInstruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: TokenInstruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: TokenInstruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: TokenInstruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: TokenInstruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: TokenInstruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: TokenInstruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: TokenInstruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: TokenInstruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type TokenError =\n | typeof TOKEN_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_ERROR__ALREADY_IN_USE\n | typeof TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__FIXED_SUPPLY\n | typeof TOKEN_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_ERROR__INVALID_MINT\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_ERROR__INVALID_STATE\n | typeof TOKEN_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_ERROR__MINT_MISMATCH\n | typeof TOKEN_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_ERROR__OVERFLOW\n | typeof TOKEN_ERROR__OWNER_MISMATCH\n | typeof TOKEN_ERROR__UNINITIALIZED_STATE;\n\nlet tokenErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n tokenErrorMessages = {\n [TOKEN_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getTokenErrorMessage(code: TokenError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (tokenErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isTokenError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU32Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAdvanceNonceAccountInstruction,\n type ParsedAllocateInstruction,\n type ParsedAllocateWithSeedInstruction,\n type ParsedAssignInstruction,\n type ParsedAssignWithSeedInstruction,\n type ParsedAuthorizeNonceAccountInstruction,\n type ParsedCreateAccountInstruction,\n type ParsedCreateAccountWithSeedInstruction,\n type ParsedInitializeNonceAccountInstruction,\n type ParsedTransferSolInstruction,\n type ParsedTransferSolWithSeedInstruction,\n type ParsedUpgradeNonceAccountInstruction,\n type ParsedWithdrawNonceAccountInstruction,\n} from '../instructions';\n\nexport const SYSTEM_PROGRAM_ADDRESS =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n\nexport enum SystemAccount {\n Nonce,\n}\n\nexport enum SystemInstruction {\n CreateAccount,\n Assign,\n TransferSol,\n CreateAccountWithSeed,\n AdvanceNonceAccount,\n WithdrawNonceAccount,\n InitializeNonceAccount,\n AuthorizeNonceAccount,\n Allocate,\n AllocateWithSeed,\n AssignWithSeed,\n TransferSolWithSeed,\n UpgradeNonceAccount,\n}\n\nexport function identifySystemInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): SystemInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU32Encoder().encode(0), 0)) {\n return SystemInstruction.CreateAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(1), 0)) {\n return SystemInstruction.Assign;\n }\n if (containsBytes(data, getU32Encoder().encode(2), 0)) {\n return SystemInstruction.TransferSol;\n }\n if (containsBytes(data, getU32Encoder().encode(3), 0)) {\n return SystemInstruction.CreateAccountWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(4), 0)) {\n return SystemInstruction.AdvanceNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(5), 0)) {\n return SystemInstruction.WithdrawNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(6), 0)) {\n return SystemInstruction.InitializeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(7), 0)) {\n return SystemInstruction.AuthorizeNonceAccount;\n }\n if (containsBytes(data, getU32Encoder().encode(8), 0)) {\n return SystemInstruction.Allocate;\n }\n if (containsBytes(data, getU32Encoder().encode(9), 0)) {\n return SystemInstruction.AllocateWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(10), 0)) {\n return SystemInstruction.AssignWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(11), 0)) {\n return SystemInstruction.TransferSolWithSeed;\n }\n if (containsBytes(data, getU32Encoder().encode(12), 0)) {\n return SystemInstruction.UpgradeNonceAccount;\n }\n throw new Error(\n 'The provided instruction could not be identified as a system instruction.'\n );\n}\n\nexport type ParsedSystemInstruction<\n TProgram extends string = '11111111111111111111111111111111',\n> =\n | ({\n instructionType: SystemInstruction.CreateAccount;\n } & ParsedCreateAccountInstruction)\n | ({\n instructionType: SystemInstruction.Assign;\n } & ParsedAssignInstruction)\n | ({\n instructionType: SystemInstruction.TransferSol;\n } & ParsedTransferSolInstruction)\n | ({\n instructionType: SystemInstruction.CreateAccountWithSeed;\n } & ParsedCreateAccountWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AdvanceNonceAccount;\n } & ParsedAdvanceNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.WithdrawNonceAccount;\n } & ParsedWithdrawNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.InitializeNonceAccount;\n } & ParsedInitializeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.AuthorizeNonceAccount;\n } & ParsedAuthorizeNonceAccountInstruction)\n | ({\n instructionType: SystemInstruction.Allocate;\n } & ParsedAllocateInstruction)\n | ({\n instructionType: SystemInstruction.AllocateWithSeed;\n } & ParsedAllocateWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.AssignWithSeed;\n } & ParsedAssignWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.TransferSolWithSeed;\n } & ParsedTransferSolWithSeedInstruction)\n | ({\n instructionType: SystemInstruction.UpgradeNonceAccount;\n } & ParsedUpgradeNonceAccountInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\n\n/** AccountAlreadyInUse: an account with the same address already exists */\nexport const SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE = 0x0; // 0\n/** ResultWithNegativeLamports: account does not have enough SOL to perform the operation */\nexport const SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS = 0x1; // 1\n/** InvalidProgramId: cannot assign account to this program id */\nexport const SYSTEM_ERROR__INVALID_PROGRAM_ID = 0x2; // 2\n/** InvalidAccountDataLength: cannot allocate account data of this length */\nexport const SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH = 0x3; // 3\n/** MaxSeedLengthExceeded: length of requested seed is too long */\nexport const SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED = 0x4; // 4\n/** AddressWithSeedMismatch: provided address does not match addressed derived from seed */\nexport const SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH = 0x5; // 5\n/** NonceNoRecentBlockhashes: advancing stored nonce requires a populated RecentBlockhashes sysvar */\nexport const SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES = 0x6; // 6\n/** NonceBlockhashNotExpired: stored nonce is still in recent_blockhashes */\nexport const SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED = 0x7; // 7\n/** NonceUnexpectedBlockhashValue: specified nonce does not match stored nonce */\nexport const SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE = 0x8; // 8\n\nexport type SystemError =\n | typeof SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE\n | typeof SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH\n | typeof SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH\n | typeof SYSTEM_ERROR__INVALID_PROGRAM_ID\n | typeof SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED\n | typeof SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED\n | typeof SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES\n | typeof SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE\n | typeof SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS;\n\nlet systemErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n systemErrorMessages = {\n [SYSTEM_ERROR__ACCOUNT_ALREADY_IN_USE]: `an account with the same address already exists`,\n [SYSTEM_ERROR__ADDRESS_WITH_SEED_MISMATCH]: `provided address does not match addressed derived from seed`,\n [SYSTEM_ERROR__INVALID_ACCOUNT_DATA_LENGTH]: `cannot allocate account data of this length`,\n [SYSTEM_ERROR__INVALID_PROGRAM_ID]: `cannot assign account to this program id`,\n [SYSTEM_ERROR__MAX_SEED_LENGTH_EXCEEDED]: `length of requested seed is too long`,\n [SYSTEM_ERROR__NONCE_BLOCKHASH_NOT_EXPIRED]: `stored nonce is still in recent_blockhashes`,\n [SYSTEM_ERROR__NONCE_NO_RECENT_BLOCKHASHES]: `advancing stored nonce requires a populated RecentBlockhashes sysvar`,\n [SYSTEM_ERROR__NONCE_UNEXPECTED_BLOCKHASH_VALUE]: `specified nonce does not match stored nonce`,\n [SYSTEM_ERROR__RESULT_WITH_NEGATIVE_LAMPORTS]: `account does not have enough SOL to perform the operation`,\n };\n}\n\nexport function getSystemErrorMessage(code: SystemError): string {\n if (process.env.NODE_ENV !== 'production') {\n return (systemErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isSystemError(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n SYSTEM_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n BASE_ACCOUNT_SIZE,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { SYSTEM_PROGRAM_ADDRESS } from '../programs';\nimport {\n getAccountMetaFactory,\n type InstructionWithByteDelta,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ACCOUNT_DISCRIMINATOR = 0;\n\nexport function getCreateAccountDiscriminatorBytes() {\n return getU32Encoder().encode(CREATE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNewAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNewAccount extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountNewAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAccountInstructionData = {\n discriminator: number;\n lamports: bigint;\n space: bigint;\n programAddress: Address;\n};\n\nexport type CreateAccountInstructionDataArgs = {\n lamports: number | bigint;\n space: number | bigint;\n programAddress: Address;\n};\n\nexport function getCreateAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU32Encoder()],\n ['lamports', getU64Encoder()],\n ['space', getU64Encoder()],\n ['programAddress', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: CREATE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU32Decoder()],\n ['lamports', getU64Decoder()],\n ['space', getU64Decoder()],\n ['programAddress', getAddressDecoder()],\n ]);\n}\n\nexport function getCreateAccountInstructionDataCodec(): FixedSizeCodec<\n CreateAccountInstructionDataArgs,\n CreateAccountInstructionData\n> {\n return combineCodec(\n getCreateAccountInstructionDataEncoder(),\n getCreateAccountInstructionDataDecoder()\n );\n}\n\nexport type CreateAccountInput<\n TAccountPayer extends string = string,\n TAccountNewAccount extends string = string,\n> = {\n payer: TransactionSigner;\n newAccount: TransactionSigner;\n lamports: CreateAccountInstructionDataArgs['lamports'];\n space: CreateAccountInstructionDataArgs['space'];\n programAddress: CreateAccountInstructionDataArgs['programAddress'];\n};\n\nexport function getCreateAccountInstruction<\n TAccountPayer extends string,\n TAccountNewAccount extends string,\n TProgramAddress extends Address = typeof SYSTEM_PROGRAM_ADDRESS,\n>(\n input: CreateAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n> &\n InstructionWithByteDelta {\n // Program address.\n const programAddress = config?.programAddress ?? SYSTEM_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n newAccount: { value: input.newAccount ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Bytes created or reallocated by the instruction.\n const byteDelta: number = [Number(args.space) + BASE_ACCOUNT_SIZE].reduce(\n (a, b) => a + b,\n 0\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'omitted');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.newAccount),\n ],\n byteDelta,\n data: getCreateAccountInstructionDataEncoder().encode(\n args as CreateAccountInstructionDataArgs\n ),\n programAddress,\n } as CreateAccountInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNewAccount\n > &\n InstructionWithByteDelta);\n}\n\nexport type ParsedCreateAccountInstruction<\n TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n payer: TAccountMetas[0];\n newAccount: TAccountMetas[1];\n };\n data: CreateAccountInstructionData;\n};\n\nexport function parseCreateAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAccountInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { payer: getNextAccount(), newAccount: getNextAccount() },\n data: getCreateAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import { getCreateAccountInstruction } from '@solana-program/system';\nimport {\n Address,\n InstructionPlan,\n OptionOrNullable,\n sequentialInstructionPlan,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n getInitializeMint2Instruction,\n getMintSize,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\n// RPC `getMinimumBalanceForRentExemption` for 82 bytes, which is token mint size\n// Hardcoded to avoid requiring an RPC request each time\nconst MINIMUM_BALANCE_FOR_MINT = 1461600;\n\nexport type CreateMintInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** New mint account to create. */\n newMint: TransactionSigner;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n /**\n * Optional override for the amount of Lamports to fund the mint account with.\n * @default 1461600\n * */\n mintAccountLamports?: number;\n};\n\ntype CreateMintInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n};\n\nexport function getCreateMintInstructionPlan(\n input: CreateMintInstructionPlanInput,\n config?: CreateMintInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAccountInstruction(\n {\n payer: input.payer,\n newAccount: input.newMint,\n lamports: input.mintAccountLamports ?? MINIMUM_BALANCE_FOR_MINT,\n space: getMintSize(),\n programAddress: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n },\n {\n programAddress: config?.systemProgram,\n }\n ),\n getInitializeMint2Instruction(\n {\n mint: input.newMint.address,\n decimals: input.decimals,\n mintAuthority: input.mintAuthority,\n freezeAuthority: input.freezeAuthority,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getMintToCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype MintToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to mint to.\n * Will be created if it does not already exist.\n * Note: Use {@link getMintToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n ata: Address;\n /** Wallet address for the associated token account. */\n owner: Address;\n /** The token mint for the associated token account. */\n mint: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: Address | TransactionSigner;\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype MintToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getMintToATAInstructionPlan(\n input: MintToATAInstructionPlanInput,\n config?: MintToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.ata,\n owner: input.owner,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n // mint to this token account\n getMintToCheckedInstruction(\n {\n mint: input.mint,\n token: input.ata,\n mintAuthority: input.mintAuthority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype MintToATAInstructionPlanAsyncInput = Omit<\n MintToATAInstructionPlanInput,\n 'ata'\n>;\n\nexport async function getMintToATAInstructionPlanAsync(\n input: MintToATAInstructionPlanAsyncInput,\n config?: MintToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.owner,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getMintToATAInstructionPlan(\n {\n ...input,\n ata: ataAddress,\n },\n config\n );\n}\n","import {\n InstructionPlan,\n sequentialInstructionPlan,\n Address,\n TransactionSigner,\n} from '@solana/kit';\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getTransferCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from './generated';\n\ntype TransferToATAInstructionPlanInput = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** The token mint to transfer. */\n mint: Address;\n /** The source account for the transfer. */\n source: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n /** Associated token account address to transfer to.\n * Will be created if it does not already exist.\n * Note: Use {@link getTransferToATAInstructionPlanAsync} instead to derive this automatically.\n * Note: Use {@link findAssociatedTokenPda} to derive the associated token account address.\n */\n destination: Address;\n /** Wallet address for the destination. */\n recipient: Address;\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n multiSigners?: Array;\n};\n\ntype TransferToATAInstructionPlanConfig = {\n systemProgram?: Address;\n tokenProgram?: Address;\n associatedTokenProgram?: Address;\n};\n\nexport function getTransferToATAInstructionPlan(\n input: TransferToATAInstructionPlanInput,\n config?: TransferToATAInstructionPlanConfig\n): InstructionPlan {\n return sequentialInstructionPlan([\n getCreateAssociatedTokenIdempotentInstruction(\n {\n payer: input.payer,\n ata: input.destination,\n owner: input.recipient,\n mint: input.mint,\n systemProgram: config?.systemProgram,\n tokenProgram: config?.tokenProgram,\n },\n {\n programAddress: config?.associatedTokenProgram,\n }\n ),\n getTransferCheckedInstruction(\n {\n source: input.source,\n mint: input.mint,\n destination: input.destination,\n authority: input.authority,\n amount: input.amount,\n decimals: input.decimals,\n multiSigners: input.multiSigners,\n },\n {\n programAddress: config?.tokenProgram,\n }\n ),\n ]);\n}\n\ntype TransferToATAInstructionPlanAsyncInput = Omit<\n TransferToATAInstructionPlanInput,\n 'destination'\n>;\n\nexport async function getTransferToATAInstructionPlanAsync(\n input: TransferToATAInstructionPlanAsyncInput,\n config?: TransferToATAInstructionPlanConfig\n): Promise {\n const [ataAddress] = await findAssociatedTokenPda({\n owner: input.recipient,\n tokenProgram: config?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS,\n mint: input.mint,\n });\n return getTransferToATAInstructionPlan(\n {\n ...input,\n destination: ataAddress,\n },\n config\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AccountState {\n Uninitialized,\n Initialized,\n Frozen,\n}\n\nexport type AccountStateArgs = AccountState;\n\nexport function getAccountStateEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AccountState);\n}\n\nexport function getAccountStateDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AccountState);\n}\n\nexport function getAccountStateCodec(): FixedSizeCodec<\n AccountStateArgs,\n AccountState\n> {\n return combineCodec(getAccountStateEncoder(), getAccountStateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport enum AuthorityType {\n MintTokens,\n FreezeAccount,\n AccountOwner,\n CloseAccount,\n TransferFeeConfig,\n WithheldWithdraw,\n CloseMint,\n InterestRate,\n PermanentDelegate,\n ConfidentialTransferMint,\n TransferHookProgramId,\n ConfidentialTransferFeeConfig,\n MetadataPointer,\n GroupPointer,\n GroupMemberPointer,\n ScaledUiAmount,\n Pause,\n}\n\nexport type AuthorityTypeArgs = AuthorityType;\n\nexport function getAuthorityTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(AuthorityType);\n}\n\nexport function getAuthorityTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(AuthorityType);\n}\n\nexport function getAuthorityTypeCodec(): FixedSizeCodec<\n AuthorityTypeArgs,\n AuthorityType\n> {\n return combineCodec(getAuthorityTypeEncoder(), getAuthorityTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** Authenticated encryption containing an account balance. */\nexport type DecryptableBalance = ReadonlyUint8Array;\n\nexport type DecryptableBalanceArgs = DecryptableBalance;\n\nexport function getDecryptableBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 36);\n}\n\nexport function getDecryptableBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 36);\n}\n\nexport function getDecryptableBalanceCodec(): FixedSizeCodec<\n DecryptableBalanceArgs,\n DecryptableBalance\n> {\n return combineCodec(\n getDecryptableBalanceEncoder(),\n getDecryptableBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\n/** ElGamal ciphertext containing an account balance. */\nexport type EncryptedBalance = ReadonlyUint8Array;\n\nexport type EncryptedBalanceArgs = EncryptedBalance;\n\nexport function getEncryptedBalanceEncoder(): FixedSizeEncoder {\n return fixEncoderSize(getBytesEncoder(), 64);\n}\n\nexport function getEncryptedBalanceDecoder(): FixedSizeDecoder {\n return fixDecoderSize(getBytesDecoder(), 64);\n}\n\nexport function getEncryptedBalanceCodec(): FixedSizeCodec<\n EncryptedBalanceArgs,\n EncryptedBalance\n> {\n return combineCodec(\n getEncryptedBalanceEncoder(),\n getEncryptedBalanceDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getF64Decoder,\n getF64Encoder,\n getI16Decoder,\n getI16Encoder,\n getMapDecoder,\n getMapEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n getEncryptedBalanceDecoder,\n getEncryptedBalanceEncoder,\n getTransferFeeDecoder,\n getTransferFeeEncoder,\n type AccountState,\n type AccountStateArgs,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n type EncryptedBalance,\n type EncryptedBalanceArgs,\n type TransferFee,\n type TransferFeeArgs,\n} from '.';\n\nexport type Extension =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFee;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFee;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: Option
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalance;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalance;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalance;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalance;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountState }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: Option
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalance;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: Option
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: Option
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: Option
;\n /** Optional account address that holds the group. */\n groupAddress: Option
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: Option
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: bigint;\n /** The maximum number of group members. */\n maxSize: bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: Option
;\n /** Optional account address that holds the member. */\n memberAddress: Option
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: bigint;\n newMultiplier: number;\n }\n | { __kind: 'PausableConfig'; authority: Option
; paused: boolean }\n | { __kind: 'PausableAccount' };\n\nexport type ExtensionArgs =\n | { __kind: 'Uninitialized' }\n | {\n __kind: 'TransferFeeConfig';\n /** Optional authority to set the fee. */\n transferFeeConfigAuthority: Address;\n /** Withdraw from mint instructions must be signed by this key. */\n withdrawWithheldAuthority: Address;\n /** Withheld transfer fee tokens that have been moved to the mint for withdrawal. */\n withheldAmount: number | bigint;\n /** Older transfer fee, used if the current epoch < newerTransferFee.epoch. */\n olderTransferFee: TransferFeeArgs;\n /** Newer transfer fee, used if the current epoch >= newerTransferFee.epoch. */\n newerTransferFee: TransferFeeArgs;\n }\n | {\n __kind: 'TransferFeeAmount';\n /** Withheld transfer fee tokens that can be claimed by the fee authority. */\n withheldAmount: number | bigint;\n }\n | { __kind: 'MintCloseAuthority'; closeAuthority: Address }\n | {\n __kind: 'ConfidentialTransferMint';\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts (if `auto_approve_new_accounts` is true).\n *\n * The legacy Token Multisig account is not supported as the authority.\n */\n authority: OptionOrNullable
;\n /**\n * Indicate if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n *\n * * If `true`, no approval is required and new accounts may be used immediately.\n * * If `false`, the authority must approve newly configured accounts (see\n * `ConfidentialTransferInstruction::ConfigureAccount`).\n */\n autoApproveNewAccounts: boolean;\n /** Authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n }\n | {\n __kind: 'ConfidentialTransferAccount';\n /**\n * `true` if this account has been approved for use. All confidential\n * transfer operations for the account will fail until approval is granted.\n */\n approved: boolean;\n /** The public key associated with ElGamal encryption. */\n elgamalPubkey: Address;\n /** The low 16 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceLow: EncryptedBalanceArgs;\n /** The high 32 bits of the pending balance (encrypted by `elgamal_pubkey`). */\n pendingBalanceHigh: EncryptedBalanceArgs;\n /** The available balance (encrypted by `encrypiton_pubkey`). */\n availableBalance: EncryptedBalanceArgs;\n /** The decryptable available balance. */\n decryptableAvailableBalance: DecryptableBalanceArgs;\n /** If `false`, the extended account rejects any incoming confidential transfers. */\n allowConfidentialCredits: boolean;\n /** If `false`, the base account rejects any incoming transfers. */\n allowNonConfidentialCredits: boolean;\n /** The total number of `Deposit` and `Transfer` instructions that have credited `pending_balance`. */\n pendingBalanceCreditCounter: number | bigint;\n /**\n * The maximum number of `Deposit` and `Transfer` instructions that can\n * credit `pending_balance` before the `ApplyPendingBalance`\n * instruction is executed.\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * The `expected_pending_balance_credit_counter` value that was included in\n * the last `ApplyPendingBalance` instruction.\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The actual `pending_balance_credit_counter` when the last\n * `ApplyPendingBalance` instruction was executed.\n */\n actualPendingBalanceCreditCounter: number | bigint;\n }\n | { __kind: 'DefaultAccountState'; state: AccountStateArgs }\n | { __kind: 'ImmutableOwner' }\n | {\n __kind: 'MemoTransfer';\n /** Require transfers into this account to be accompanied by a memo. */\n requireIncomingTransferMemos: boolean;\n }\n | { __kind: 'NonTransferable' }\n | {\n __kind: 'InterestBearingConfig';\n rateAuthority: Address;\n initializationTimestamp: number | bigint;\n preUpdateAverageRate: number;\n lastUpdateTimestamp: number | bigint;\n currentRate: number;\n }\n | {\n __kind: 'CpiGuard';\n /** Lock certain token operations from taking place within CPI for this account. */\n lockCpi: boolean;\n }\n | { __kind: 'PermanentDelegate'; delegate: Address }\n | { __kind: 'NonTransferableAccount' }\n | {\n __kind: 'TransferHook';\n /** The transfer hook update authority. */\n authority: Address;\n /** The transfer hook program account. */\n programId: Address;\n }\n | {\n __kind: 'TransferHookAccount';\n /**\n * Whether or not this account is currently transferring tokens\n * True during the transfer hook cpi, otherwise false.\n */\n transferring: boolean;\n }\n | {\n __kind: 'ConfidentialTransferFee';\n /** Optional authority to set the withdraw withheld authority ElGamal key. */\n authority: OptionOrNullable
;\n /**\n * Withheld fees from accounts must be encrypted with this ElGamal key.\n *\n * Note that whoever holds the ElGamal private key for this ElGamal public\n * key has the ability to decode any withheld fee amount that are\n * associated with accounts. When combined with the fee parameters, the\n * withheld fee amounts can reveal information about transfer amounts.\n */\n elgamalPubkey: Address;\n /** If `false`, the harvest of withheld tokens to mint is rejected. */\n harvestToMintEnabled: boolean;\n /**\n * Withheld confidential transfer fee tokens that have been moved to the\n * mint for withdrawal.\n */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'ConfidentialTransferFeeAmount';\n /** Amount withheld during confidential transfers, to be harvest to the mint. */\n withheldAmount: EncryptedBalanceArgs;\n }\n | {\n __kind: 'MetadataPointer';\n /** Optional authority that can set the metadata address. */\n authority: OptionOrNullable
;\n /** Optional Account Address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenMetadata';\n /** The authority that can sign to update the metadata. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that metadata belongs to a particular mint. */\n mint: Address;\n /** The longer name of the token. */\n name: string;\n /** The shortened symbol for the token. */\n symbol: string;\n /** The URI pointing to richer metadata. */\n uri: string;\n /** Any additional metadata about the token as key-value pairs. */\n additionalMetadata: Map;\n }\n | {\n __kind: 'GroupPointer';\n /** Optional authority that can set the group address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the group. */\n groupAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroup';\n /** The authority that can sign to update the group. */\n updateAuthority: OptionOrNullable
;\n /** The associated mint, used to counter spoofing to be sure that group belongs to a particular mint. */\n mint: Address;\n /** The current number of group members. */\n size: number | bigint;\n /** The maximum number of group members. */\n maxSize: number | bigint;\n }\n | {\n __kind: 'GroupMemberPointer';\n /** Optional authority that can set the member address. */\n authority: OptionOrNullable
;\n /** Optional account address that holds the member. */\n memberAddress: OptionOrNullable
;\n }\n | {\n __kind: 'TokenGroupMember';\n /** The associated mint, used to counter spoofing to be sure that member belongs to a particular mint. */\n mint: Address;\n /** The pubkey of the `TokenGroup`. */\n group: Address;\n /** The member number. */\n memberNumber: number | bigint;\n }\n | { __kind: 'ConfidentialMintBurn' }\n | {\n __kind: 'ScaledUiAmountConfig';\n authority: Address;\n multiplier: number;\n newMultiplierEffectiveTimestamp: number | bigint;\n newMultiplier: number;\n }\n | {\n __kind: 'PausableConfig';\n authority: OptionOrNullable
;\n paused: boolean;\n }\n | { __kind: 'PausableAccount' };\n\nexport function getExtensionEncoder(): Encoder {\n return getDiscriminatedUnionEncoder(\n [\n ['Uninitialized', getUnitEncoder()],\n [\n 'TransferFeeConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['transferFeeConfigAuthority', getAddressEncoder()],\n ['withdrawWithheldAuthority', getAddressEncoder()],\n ['withheldAmount', getU64Encoder()],\n ['olderTransferFee', getTransferFeeEncoder()],\n ['newerTransferFee', getTransferFeeEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getU64Encoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addEncoderSizePrefix(\n getStructEncoder([['closeAuthority', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addEncoderSizePrefix(\n getStructEncoder([\n ['approved', getBooleanEncoder()],\n ['elgamalPubkey', getAddressEncoder()],\n ['pendingBalanceLow', getEncryptedBalanceEncoder()],\n ['pendingBalanceHigh', getEncryptedBalanceEncoder()],\n ['availableBalance', getEncryptedBalanceEncoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['allowConfidentialCredits', getBooleanEncoder()],\n ['allowNonConfidentialCredits', getBooleanEncoder()],\n ['pendingBalanceCreditCounter', getU64Encoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['actualPendingBalanceCreditCounter', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addEncoderSizePrefix(\n getStructEncoder([['state', getAccountStateEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'MemoTransfer',\n addEncoderSizePrefix(\n getStructEncoder([\n ['requireIncomingTransferMemos', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferable',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'InterestBearingConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['rateAuthority', getAddressEncoder()],\n ['initializationTimestamp', getU64Encoder()],\n ['preUpdateAverageRate', getI16Encoder()],\n ['lastUpdateTimestamp', getU64Encoder()],\n ['currentRate', getI16Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'CpiGuard',\n addEncoderSizePrefix(\n getStructEncoder([['lockCpi', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addEncoderSizePrefix(\n getStructEncoder([['delegate', getAddressEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addEncoderSizePrefix(getStructEncoder([]), getU16Encoder()),\n ],\n [\n 'TransferHook',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['programId', getAddressEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addEncoderSizePrefix(\n getStructEncoder([['transferring', getBooleanEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressEncoder()],\n ['harvestToMintEnabled', getBooleanEncoder()],\n ['withheldAmount', getEncryptedBalanceEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addEncoderSizePrefix(\n getStructEncoder([['withheldAmount', getEncryptedBalanceEncoder()]]),\n getU16Encoder()\n ),\n ],\n [\n 'MetadataPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenMetadata',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n [\n 'additionalMetadata',\n getMapEncoder(\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())\n ),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroup',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressEncoder()],\n ['size', getU64Encoder()],\n ['maxSize', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addEncoderSizePrefix(\n getStructEncoder([\n ['mint', getAddressEncoder()],\n ['group', getAddressEncoder()],\n ['memberNumber', getU64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitEncoder()],\n [\n 'ScaledUiAmountConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n ['authority', getAddressEncoder()],\n ['multiplier', getF64Encoder()],\n ['newMultiplierEffectiveTimestamp', getU64Encoder()],\n ['newMultiplier', getF64Encoder()],\n ]),\n getU16Encoder()\n ),\n ],\n [\n 'PausableConfig',\n addEncoderSizePrefix(\n getStructEncoder([\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanEncoder()],\n ]),\n getU16Encoder()\n ),\n ],\n ['PausableAccount', getUnitEncoder()],\n ],\n { size: getU16Encoder() }\n );\n}\n\nexport function getExtensionDecoder(): Decoder {\n return getDiscriminatedUnionDecoder(\n [\n ['Uninitialized', getUnitDecoder()],\n [\n 'TransferFeeConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['transferFeeConfigAuthority', getAddressDecoder()],\n ['withdrawWithheldAuthority', getAddressDecoder()],\n ['withheldAmount', getU64Decoder()],\n ['olderTransferFee', getTransferFeeDecoder()],\n ['newerTransferFee', getTransferFeeDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getU64Decoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MintCloseAuthority',\n addDecoderSizePrefix(\n getStructDecoder([['closeAuthority', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferMint',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferAccount',\n addDecoderSizePrefix(\n getStructDecoder([\n ['approved', getBooleanDecoder()],\n ['elgamalPubkey', getAddressDecoder()],\n ['pendingBalanceLow', getEncryptedBalanceDecoder()],\n ['pendingBalanceHigh', getEncryptedBalanceDecoder()],\n ['availableBalance', getEncryptedBalanceDecoder()],\n ['decryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['allowConfidentialCredits', getBooleanDecoder()],\n ['allowNonConfidentialCredits', getBooleanDecoder()],\n ['pendingBalanceCreditCounter', getU64Decoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['actualPendingBalanceCreditCounter', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'DefaultAccountState',\n addDecoderSizePrefix(\n getStructDecoder([['state', getAccountStateDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ImmutableOwner',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'MemoTransfer',\n addDecoderSizePrefix(\n getStructDecoder([\n ['requireIncomingTransferMemos', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferable',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'InterestBearingConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['rateAuthority', getAddressDecoder()],\n ['initializationTimestamp', getU64Decoder()],\n ['preUpdateAverageRate', getI16Decoder()],\n ['lastUpdateTimestamp', getU64Decoder()],\n ['currentRate', getI16Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'CpiGuard',\n addDecoderSizePrefix(\n getStructDecoder([['lockCpi', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'PermanentDelegate',\n addDecoderSizePrefix(\n getStructDecoder([['delegate', getAddressDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'NonTransferableAccount',\n addDecoderSizePrefix(getStructDecoder([]), getU16Decoder()),\n ],\n [\n 'TransferHook',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['programId', getAddressDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TransferHookAccount',\n addDecoderSizePrefix(\n getStructDecoder([['transferring', getBooleanDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFee',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['elgamalPubkey', getAddressDecoder()],\n ['harvestToMintEnabled', getBooleanDecoder()],\n ['withheldAmount', getEncryptedBalanceDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'ConfidentialTransferFeeAmount',\n addDecoderSizePrefix(\n getStructDecoder([['withheldAmount', getEncryptedBalanceDecoder()]]),\n getU16Decoder()\n ),\n ],\n [\n 'MetadataPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenMetadata',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n [\n 'additionalMetadata',\n getMapDecoder(\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())\n ),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroup',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['mint', getAddressDecoder()],\n ['size', getU64Decoder()],\n ['maxSize', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'GroupMemberPointer',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'TokenGroupMember',\n addDecoderSizePrefix(\n getStructDecoder([\n ['mint', getAddressDecoder()],\n ['group', getAddressDecoder()],\n ['memberNumber', getU64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['ConfidentialMintBurn', getUnitDecoder()],\n [\n 'ScaledUiAmountConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n ['authority', getAddressDecoder()],\n ['multiplier', getF64Decoder()],\n ['newMultiplierEffectiveTimestamp', getU64Decoder()],\n ['newMultiplier', getF64Decoder()],\n ]),\n getU16Decoder()\n ),\n ],\n [\n 'PausableConfig',\n addDecoderSizePrefix(\n getStructDecoder([\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['paused', getBooleanDecoder()],\n ]),\n getU16Decoder()\n ),\n ],\n ['PausableAccount', getUnitDecoder()],\n ],\n { size: getU16Decoder() }\n );\n}\n\nexport function getExtensionCodec(): Codec {\n return combineCodec(getExtensionEncoder(), getExtensionDecoder());\n}\n\n// Data Enum Helpers.\nexport function extension(\n kind: 'Uninitialized'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MintCloseAuthority',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MintCloseAuthority'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferMint',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferMint'\n>;\nexport function extension(\n kind: 'ConfidentialTransferAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferAccount'\n>;\nexport function extension(\n kind: 'DefaultAccountState',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'DefaultAccountState'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ImmutableOwner',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ImmutableOwner'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'MemoTransfer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MemoTransfer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferable',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferable'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'InterestBearingConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'InterestBearingConfig'\n>;\nexport function extension(\n kind: 'CpiGuard',\n data: GetDiscriminatedUnionVariantContent\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PermanentDelegate',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PermanentDelegate'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'NonTransferableAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'NonTransferableAccount'\n>;\nexport function extension(\n kind: 'TransferHook',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHook'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TransferHookAccount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TransferHookAccount'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialTransferFee',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFee'\n>;\nexport function extension(\n kind: 'ConfidentialTransferFeeAmount',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialTransferFeeAmount'\n>;\nexport function extension(\n kind: 'MetadataPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'MetadataPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenMetadata',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenMetadata'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroup',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroup'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'GroupMemberPointer',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'GroupMemberPointer'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'TokenGroupMember',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'TokenGroupMember'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'ConfidentialMintBurn'\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ConfidentialMintBurn'\n>;\nexport function extension(\n kind: 'ScaledUiAmountConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n >\n): GetDiscriminatedUnionVariant<\n ExtensionArgs,\n '__kind',\n 'ScaledUiAmountConfig'\n>;\nexport function extension(\n kind: 'PausableConfig',\n data: GetDiscriminatedUnionVariantContent<\n ExtensionArgs,\n '__kind',\n 'PausableConfig'\n >\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: 'PausableAccount'\n): GetDiscriminatedUnionVariant;\nexport function extension(\n kind: K,\n data?: Data\n) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isExtension(\n kind: K,\n value: Extension\n): value is Extension & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n getU16Decoder,\n getU16Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\n/**\n * Extensions that can be applied to mints or accounts. Mint extensions must\n * only be applied to mint accounts, and account extensions must only be\n * applied to token holding accounts.\n */\nexport enum ExtensionType {\n Uninitialized,\n TransferFeeConfig,\n TransferFeeAmount,\n MintCloseAuthority,\n ConfidentialTransferMint,\n ConfidentialTransferAccount,\n DefaultAccountState,\n ImmutableOwner,\n MemoTransfer,\n NonTransferable,\n InterestBearingConfig,\n CpiGuard,\n PermanentDelegate,\n NonTransferableAccount,\n TransferHook,\n TransferHookAccount,\n ConfidentialTransferFee,\n ConfidentialTransferFeeAmount,\n ScaledUiAmountConfig,\n PausableConfig,\n PausableAccount,\n MetadataPointer,\n TokenMetadata,\n GroupPointer,\n TokenGroup,\n GroupMemberPointer,\n TokenGroupMember,\n}\n\nexport type ExtensionTypeArgs = ExtensionType;\n\nexport function getExtensionTypeEncoder(): FixedSizeEncoder {\n return getEnumEncoder(ExtensionType, { size: getU16Encoder() });\n}\n\nexport function getExtensionTypeDecoder(): FixedSizeDecoder {\n return getEnumDecoder(ExtensionType, { size: getU16Decoder() });\n}\n\nexport function getExtensionTypeCodec(): FixedSizeCodec<\n ExtensionTypeArgs,\n ExtensionType\n> {\n return combineCodec(getExtensionTypeEncoder(), getExtensionTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getDiscriminatedUnionDecoder,\n getDiscriminatedUnionEncoder,\n getStructDecoder,\n getStructEncoder,\n getTupleDecoder,\n getTupleEncoder,\n getU32Decoder,\n getU32Encoder,\n getUnitDecoder,\n getUnitEncoder,\n getUtf8Decoder,\n getUtf8Encoder,\n type Codec,\n type Decoder,\n type Encoder,\n type GetDiscriminatedUnionVariant,\n type GetDiscriminatedUnionVariantContent,\n} from '@solana/kit';\n\n/** Fields in the metadata account, used for updating. */\nexport type TokenMetadataField =\n | { __kind: 'Name' }\n | { __kind: 'Symbol' }\n | { __kind: 'Uri' }\n | { __kind: 'Key'; fields: readonly [string] };\n\nexport type TokenMetadataFieldArgs = TokenMetadataField;\n\nexport function getTokenMetadataFieldEncoder(): Encoder {\n return getDiscriminatedUnionEncoder([\n ['Name', getUnitEncoder()],\n ['Symbol', getUnitEncoder()],\n ['Uri', getUnitEncoder()],\n [\n 'Key',\n getStructEncoder([\n [\n 'fields',\n getTupleEncoder([\n addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldDecoder(): Decoder {\n return getDiscriminatedUnionDecoder([\n ['Name', getUnitDecoder()],\n ['Symbol', getUnitDecoder()],\n ['Uri', getUnitDecoder()],\n [\n 'Key',\n getStructDecoder([\n [\n 'fields',\n getTupleDecoder([\n addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),\n ]),\n ],\n ]),\n ],\n ]);\n}\n\nexport function getTokenMetadataFieldCodec(): Codec<\n TokenMetadataFieldArgs,\n TokenMetadataField\n> {\n return combineCodec(\n getTokenMetadataFieldEncoder(),\n getTokenMetadataFieldDecoder()\n );\n}\n\n// Data Enum Helpers.\nexport function tokenMetadataField(\n kind: 'Name'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Symbol'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Uri'\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField(\n kind: 'Key',\n data: GetDiscriminatedUnionVariantContent<\n TokenMetadataFieldArgs,\n '__kind',\n 'Key'\n >['fields']\n): GetDiscriminatedUnionVariant;\nexport function tokenMetadataField<\n K extends TokenMetadataFieldArgs['__kind'],\n Data,\n>(kind: K, data?: Data) {\n return Array.isArray(data)\n ? { __kind: kind, fields: data }\n : { __kind: kind, ...(data ?? {}) };\n}\n\nexport function isTokenMetadataField(\n kind: K,\n value: TokenMetadataField\n): value is TokenMetadataField & { __kind: K } {\n return value.__kind === kind;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from '@solana/kit';\n\nexport type TransferFee = {\n /** First epoch where the transfer fee takes effect. */\n epoch: bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport type TransferFeeArgs = {\n /** First epoch where the transfer fee takes effect. */\n epoch: number | bigint;\n /** Maximum fee assessed on transfers, expressed as an amount of tokens. */\n maximumFee: number | bigint;\n /**\n * Amount of transfer collected as fees, expressed as basis points of the\n * transfer amount, ie. increments of 0.01%.\n */\n transferFeeBasisPoints: number;\n};\n\nexport function getTransferFeeEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['epoch', getU64Encoder()],\n ['maximumFee', getU64Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ]);\n}\n\nexport function getTransferFeeDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['epoch', getU64Decoder()],\n ['maximumFee', getU64Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ]);\n}\n\nexport function getTransferFeeCodec(): FixedSizeCodec<\n TransferFeeArgs,\n TransferFee\n> {\n return combineCodec(getTransferFeeEncoder(), getTransferFeeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n padLeftEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getExtensionDecoder,\n getExtensionEncoder,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Mint = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: Option
;\n /** Total supply of tokens. */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: Option
;\n /** The extensions activated on the mint account. */\n extensions: Option>;\n};\n\nexport type MintArgs = {\n /**\n * Optional authority used to mint new tokens. The mint authority may only\n * be provided during mint creation. If no mint authority is present\n * then the mint has a fixed supply and no further tokens may be minted.\n */\n mintAuthority: OptionOrNullable
;\n /** Total supply of tokens. */\n supply: number | bigint;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts. */\n freezeAuthority: OptionOrNullable
;\n /** The extensions activated on the mint account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getMintEncoder(): Encoder {\n return getStructEncoder([\n [\n 'mintAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n [\n 'freezeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintDecoder(): Decoder {\n return getStructDecoder([\n [\n 'mintAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['supply', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n [\n 'freezeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getMintCodec(): Codec {\n return combineCodec(getMintEncoder(), getMintDecoder());\n}\n\nexport function decodeMint(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMint(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMint(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMintDecoder()\n );\n}\n\nexport async function fetchMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMint(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMint(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMint(maybeAccount);\n}\n\nexport async function fetchAllMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMint(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMint(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMint(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nexport type Multisig = {\n /** Number of signers required. */\n m: number;\n /** Number of valid signers. */\n n: number;\n /** Is `true` if this structure has been initialized. */\n isInitialized: boolean;\n /** Signer public keys. */\n signers: Array
;\n};\n\nexport type MultisigArgs = Multisig;\n\nexport function getMultisigEncoder(): FixedSizeEncoder {\n return getStructEncoder([\n ['m', getU8Encoder()],\n ['n', getU8Encoder()],\n ['isInitialized', getBooleanEncoder()],\n ['signers', getArrayEncoder(getAddressEncoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['m', getU8Decoder()],\n ['n', getU8Decoder()],\n ['isInitialized', getBooleanDecoder()],\n ['signers', getArrayDecoder(getAddressDecoder(), { size: 11 })],\n ]);\n}\n\nexport function getMultisigCodec(): FixedSizeCodec {\n return combineCodec(getMultisigEncoder(), getMultisigDecoder());\n}\n\nexport function decodeMultisig(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeMultisig(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeMultisig(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getMultisigDecoder()\n );\n}\n\nexport async function fetchMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeMultisig(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeMultisig(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeMultisig(maybeAccount);\n}\n\nexport async function fetchAllMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeMultisig(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeMultisig(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeMultisig(maybeAccount));\n}\n\nexport function getMultisigSize(): number {\n return 355;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getConstantDecoder,\n getConstantEncoder,\n getHiddenPrefixDecoder,\n getHiddenPrefixEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Encoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n} from '@solana/kit';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n getExtensionDecoder,\n getExtensionEncoder,\n type AccountState,\n type AccountStateArgs,\n type Extension,\n type ExtensionArgs,\n} from '../types';\n\nexport type Token = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: Option
;\n /** The account's state. */\n state: AccountState;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: Option;\n /** The amount delegated. */\n delegatedAmount: bigint;\n /** Optional authority to close the account. */\n closeAuthority: Option
;\n /** The extensions activated on the token account. */\n extensions: Option>;\n};\n\nexport type TokenArgs = {\n /** The mint associated with this account. */\n mint: Address;\n /** The owner of this account. */\n owner: Address;\n /** The amount of tokens this account holds. */\n amount: number | bigint;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents\n * the amount authorized by the delegate.\n */\n delegate: OptionOrNullable
;\n /** The account's state. */\n state: AccountStateArgs;\n /**\n * If is_native.is_some, this is a native token, and the value logs the\n * rent-exempt reserve. An Account is required to be rent-exempt, so\n * the value is used by the Processor to ensure that wrapped SOL\n * accounts do not drop below this threshold.\n */\n isNative: OptionOrNullable;\n /** The amount delegated. */\n delegatedAmount: number | bigint;\n /** Optional authority to close the account. */\n closeAuthority: OptionOrNullable
;\n /** The extensions activated on the token account. */\n extensions: OptionOrNullable>;\n};\n\nexport function getTokenEncoder(): Encoder {\n return getStructEncoder([\n ['mint', getAddressEncoder()],\n ['owner', getAddressEncoder()],\n ['amount', getU64Encoder()],\n [\n 'delegate',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateEncoder()],\n [\n 'isNative',\n getOptionEncoder(getU64Encoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Encoder()],\n [\n 'closeAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: getU32Encoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionEncoder(\n getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenDecoder(): Decoder {\n return getStructDecoder([\n ['mint', getAddressDecoder()],\n ['owner', getAddressDecoder()],\n ['amount', getU64Decoder()],\n [\n 'delegate',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['state', getAccountStateDecoder()],\n [\n 'isNative',\n getOptionDecoder(getU64Decoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n ['delegatedAmount', getU64Decoder()],\n [\n 'closeAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: getU32Decoder(),\n noneValue: 'zeroes',\n }),\n ],\n [\n 'extensions',\n getOptionDecoder(\n getHiddenPrefixDecoder(\n getArrayDecoder(getExtensionDecoder(), { size: 'remainder' }),\n [getConstantDecoder(getU8Encoder().encode(2))]\n ),\n { prefix: null }\n ),\n ],\n ]);\n}\n\nexport function getTokenCodec(): Codec {\n return combineCodec(getTokenEncoder(), getTokenDecoder());\n}\n\nexport function decodeToken(\n encodedAccount: EncodedAccount\n): Account;\nexport function decodeToken(\n encodedAccount: MaybeEncodedAccount\n): MaybeAccount;\nexport function decodeToken(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): Account | MaybeAccount {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount,\n getTokenDecoder()\n );\n}\n\nexport async function fetchToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchMaybeToken(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeToken(\n rpc: Parameters[0],\n address: Address,\n config?: FetchAccountConfig\n): Promise> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeToken(maybeAccount);\n}\n\nexport async function fetchAllToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchAllMaybeToken(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeToken(\n rpc: Parameters[0],\n addresses: Array
,\n config?: FetchAccountsConfig\n): Promise[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeToken(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedCreateAssociatedTokenIdempotentInstruction,\n type ParsedCreateAssociatedTokenInstruction,\n type ParsedRecoverNestedAssociatedTokenInstruction,\n} from '../instructions';\n\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>;\n\nexport enum AssociatedTokenInstruction {\n CreateAssociatedToken,\n CreateAssociatedTokenIdempotent,\n RecoverNestedAssociatedToken,\n}\n\nexport function identifyAssociatedTokenInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): AssociatedTokenInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedToken;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n }\n throw new Error(\n 'The provided instruction could not be identified as a associatedToken instruction.'\n );\n}\n\nexport type ParsedAssociatedTokenInstruction<\n TProgram extends string = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',\n> =\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedToken;\n } & ParsedCreateAssociatedTokenInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.CreateAssociatedTokenIdempotent;\n } & ParsedCreateAssociatedTokenIdempotentInstruction)\n | ({\n instructionType: AssociatedTokenInstruction.RecoverNestedAssociatedToken;\n } & ParsedRecoverNestedAssociatedTokenInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedAmountToUiAmountInstruction,\n type ParsedApplyConfidentialPendingBalanceInstruction,\n type ParsedApproveCheckedInstruction,\n type ParsedApproveConfidentialTransferAccountInstruction,\n type ParsedApproveInstruction,\n type ParsedBurnCheckedInstruction,\n type ParsedBurnInstruction,\n type ParsedCloseAccountInstruction,\n type ParsedConfidentialDepositInstruction,\n type ParsedConfidentialTransferInstruction,\n type ParsedConfidentialTransferWithFeeInstruction,\n type ParsedConfidentialWithdrawInstruction,\n type ParsedConfigureConfidentialTransferAccountInstruction,\n type ParsedCreateNativeMintInstruction,\n type ParsedDisableConfidentialCreditsInstruction,\n type ParsedDisableCpiGuardInstruction,\n type ParsedDisableHarvestToMintInstruction,\n type ParsedDisableMemoTransfersInstruction,\n type ParsedDisableNonConfidentialCreditsInstruction,\n type ParsedEmitTokenMetadataInstruction,\n type ParsedEmptyConfidentialTransferAccountInstruction,\n type ParsedEnableConfidentialCreditsInstruction,\n type ParsedEnableCpiGuardInstruction,\n type ParsedEnableHarvestToMintInstruction,\n type ParsedEnableMemoTransfersInstruction,\n type ParsedEnableNonConfidentialCreditsInstruction,\n type ParsedFreezeAccountInstruction,\n type ParsedGetAccountDataSizeInstruction,\n type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction,\n type ParsedHarvestWithheldTokensToMintInstruction,\n type ParsedInitializeAccount2Instruction,\n type ParsedInitializeAccount3Instruction,\n type ParsedInitializeAccountInstruction,\n type ParsedInitializeConfidentialTransferFeeInstruction,\n type ParsedInitializeConfidentialTransferMintInstruction,\n type ParsedInitializeDefaultAccountStateInstruction,\n type ParsedInitializeGroupMemberPointerInstruction,\n type ParsedInitializeGroupPointerInstruction,\n type ParsedInitializeImmutableOwnerInstruction,\n type ParsedInitializeInterestBearingMintInstruction,\n type ParsedInitializeMetadataPointerInstruction,\n type ParsedInitializeMint2Instruction,\n type ParsedInitializeMintCloseAuthorityInstruction,\n type ParsedInitializeMintInstruction,\n type ParsedInitializeMultisig2Instruction,\n type ParsedInitializeMultisigInstruction,\n type ParsedInitializeNonTransferableMintInstruction,\n type ParsedInitializePausableConfigInstruction,\n type ParsedInitializePermanentDelegateInstruction,\n type ParsedInitializeScaledUiAmountMintInstruction,\n type ParsedInitializeTokenGroupInstruction,\n type ParsedInitializeTokenGroupMemberInstruction,\n type ParsedInitializeTokenMetadataInstruction,\n type ParsedInitializeTransferFeeConfigInstruction,\n type ParsedInitializeTransferHookInstruction,\n type ParsedMintToCheckedInstruction,\n type ParsedMintToInstruction,\n type ParsedPauseInstruction,\n type ParsedReallocateInstruction,\n type ParsedRemoveTokenMetadataKeyInstruction,\n type ParsedResumeInstruction,\n type ParsedRevokeInstruction,\n type ParsedSetAuthorityInstruction,\n type ParsedSetTransferFeeInstruction,\n type ParsedSyncNativeInstruction,\n type ParsedThawAccountInstruction,\n type ParsedTransferCheckedInstruction,\n type ParsedTransferCheckedWithFeeInstruction,\n type ParsedTransferInstruction,\n type ParsedUiAmountToAmountInstruction,\n type ParsedUpdateConfidentialTransferMintInstruction,\n type ParsedUpdateDefaultAccountStateInstruction,\n type ParsedUpdateGroupMemberPointerInstruction,\n type ParsedUpdateGroupPointerInstruction,\n type ParsedUpdateMetadataPointerInstruction,\n type ParsedUpdateMultiplierScaledUiMintInstruction,\n type ParsedUpdateRateInterestBearingMintInstruction,\n type ParsedUpdateTokenGroupMaxSizeInstruction,\n type ParsedUpdateTokenGroupUpdateAuthorityInstruction,\n type ParsedUpdateTokenMetadataFieldInstruction,\n type ParsedUpdateTokenMetadataUpdateAuthorityInstruction,\n type ParsedUpdateTransferHookInstruction,\n type ParsedWithdrawExcessLamportsInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromAccountsInstruction,\n type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction,\n type ParsedWithdrawWithheldTokensFromMintInstruction,\n} from '../instructions';\n\nexport const TOKEN_2022_PROGRAM_ADDRESS =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n\nexport enum Token2022Account {\n Mint,\n Token,\n Multisig,\n}\n\nexport function identifyToken2022Account(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Account {\n const data = 'data' in account ? account.data : account;\n if (data.length === 82) {\n return Token2022Account.Mint;\n }\n if (data.length === 165) {\n return Token2022Account.Token;\n }\n if (data.length === 355) {\n return Token2022Account.Multisig;\n }\n throw new Error(\n 'The provided account could not be identified as a token-2022 account.'\n );\n}\n\nexport enum Token2022Instruction {\n InitializeMint,\n InitializeAccount,\n InitializeMultisig,\n Transfer,\n Approve,\n Revoke,\n SetAuthority,\n MintTo,\n Burn,\n CloseAccount,\n FreezeAccount,\n ThawAccount,\n TransferChecked,\n ApproveChecked,\n MintToChecked,\n BurnChecked,\n InitializeAccount2,\n SyncNative,\n InitializeAccount3,\n InitializeMultisig2,\n InitializeMint2,\n GetAccountDataSize,\n InitializeImmutableOwner,\n AmountToUiAmount,\n UiAmountToAmount,\n InitializeMintCloseAuthority,\n InitializeTransferFeeConfig,\n TransferCheckedWithFee,\n WithdrawWithheldTokensFromMint,\n WithdrawWithheldTokensFromAccounts,\n HarvestWithheldTokensToMint,\n SetTransferFee,\n InitializeConfidentialTransferMint,\n UpdateConfidentialTransferMint,\n ConfigureConfidentialTransferAccount,\n ApproveConfidentialTransferAccount,\n EmptyConfidentialTransferAccount,\n ConfidentialDeposit,\n ConfidentialWithdraw,\n ConfidentialTransfer,\n ApplyConfidentialPendingBalance,\n EnableConfidentialCredits,\n DisableConfidentialCredits,\n EnableNonConfidentialCredits,\n DisableNonConfidentialCredits,\n ConfidentialTransferWithFee,\n InitializeDefaultAccountState,\n UpdateDefaultAccountState,\n Reallocate,\n EnableMemoTransfers,\n DisableMemoTransfers,\n CreateNativeMint,\n InitializeNonTransferableMint,\n InitializeInterestBearingMint,\n UpdateRateInterestBearingMint,\n EnableCpiGuard,\n DisableCpiGuard,\n InitializePermanentDelegate,\n InitializeTransferHook,\n UpdateTransferHook,\n InitializeConfidentialTransferFee,\n WithdrawWithheldTokensFromMintForConfidentialTransferFee,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFee,\n HarvestWithheldTokensToMintForConfidentialTransferFee,\n EnableHarvestToMint,\n DisableHarvestToMint,\n WithdrawExcessLamports,\n InitializeMetadataPointer,\n UpdateMetadataPointer,\n InitializeGroupPointer,\n UpdateGroupPointer,\n InitializeGroupMemberPointer,\n UpdateGroupMemberPointer,\n InitializeScaledUiAmountMint,\n UpdateMultiplierScaledUiMint,\n InitializePausableConfig,\n Pause,\n Resume,\n InitializeTokenMetadata,\n UpdateTokenMetadataField,\n RemoveTokenMetadataKey,\n UpdateTokenMetadataUpdateAuthority,\n EmitTokenMetadata,\n InitializeTokenGroup,\n UpdateTokenGroupMaxSize,\n UpdateTokenGroupUpdateAuthority,\n InitializeTokenGroupMember,\n}\n\nexport function identifyToken2022Instruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): Token2022Instruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return Token2022Instruction.InitializeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return Token2022Instruction.InitializeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return Token2022Instruction.InitializeMultisig;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return Token2022Instruction.Transfer;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return Token2022Instruction.Approve;\n }\n if (containsBytes(data, getU8Encoder().encode(5), 0)) {\n return Token2022Instruction.Revoke;\n }\n if (containsBytes(data, getU8Encoder().encode(6), 0)) {\n return Token2022Instruction.SetAuthority;\n }\n if (containsBytes(data, getU8Encoder().encode(7), 0)) {\n return Token2022Instruction.MintTo;\n }\n if (containsBytes(data, getU8Encoder().encode(8), 0)) {\n return Token2022Instruction.Burn;\n }\n if (containsBytes(data, getU8Encoder().encode(9), 0)) {\n return Token2022Instruction.CloseAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(10), 0)) {\n return Token2022Instruction.FreezeAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(11), 0)) {\n return Token2022Instruction.ThawAccount;\n }\n if (containsBytes(data, getU8Encoder().encode(12), 0)) {\n return Token2022Instruction.TransferChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(13), 0)) {\n return Token2022Instruction.ApproveChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(14), 0)) {\n return Token2022Instruction.MintToChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(15), 0)) {\n return Token2022Instruction.BurnChecked;\n }\n if (containsBytes(data, getU8Encoder().encode(16), 0)) {\n return Token2022Instruction.InitializeAccount2;\n }\n if (containsBytes(data, getU8Encoder().encode(17), 0)) {\n return Token2022Instruction.SyncNative;\n }\n if (containsBytes(data, getU8Encoder().encode(18), 0)) {\n return Token2022Instruction.InitializeAccount3;\n }\n if (containsBytes(data, getU8Encoder().encode(19), 0)) {\n return Token2022Instruction.InitializeMultisig2;\n }\n if (containsBytes(data, getU8Encoder().encode(20), 0)) {\n return Token2022Instruction.InitializeMint2;\n }\n if (containsBytes(data, getU8Encoder().encode(21), 0)) {\n return Token2022Instruction.GetAccountDataSize;\n }\n if (containsBytes(data, getU8Encoder().encode(22), 0)) {\n return Token2022Instruction.InitializeImmutableOwner;\n }\n if (containsBytes(data, getU8Encoder().encode(23), 0)) {\n return Token2022Instruction.AmountToUiAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(24), 0)) {\n return Token2022Instruction.UiAmountToAmount;\n }\n if (containsBytes(data, getU8Encoder().encode(25), 0)) {\n return Token2022Instruction.InitializeMintCloseAuthority;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferFeeConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.TransferCheckedWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(26), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.SetTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateConfidentialTransferMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.ConfigureConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.ApproveConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EmptyConfidentialTransferAccount;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.ConfidentialDeposit;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(6), 1)\n ) {\n return Token2022Instruction.ConfidentialWithdraw;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(7), 1)\n ) {\n return Token2022Instruction.ConfidentialTransfer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(8), 1)\n ) {\n return Token2022Instruction.ApplyConfidentialPendingBalance;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(9), 1)\n ) {\n return Token2022Instruction.EnableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(10), 1)\n ) {\n return Token2022Instruction.DisableConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(11), 1)\n ) {\n return Token2022Instruction.EnableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(12), 1)\n ) {\n return Token2022Instruction.DisableNonConfidentialCredits;\n }\n if (\n containsBytes(data, getU8Encoder().encode(27), 0) &&\n containsBytes(data, getU8Encoder().encode(13), 1)\n ) {\n return Token2022Instruction.ConfidentialTransferWithFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeDefaultAccountState;\n }\n if (\n containsBytes(data, getU8Encoder().encode(28), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateDefaultAccountState;\n }\n if (containsBytes(data, getU8Encoder().encode(29), 0)) {\n return Token2022Instruction.Reallocate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableMemoTransfers;\n }\n if (\n containsBytes(data, getU8Encoder().encode(30), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableMemoTransfers;\n }\n if (containsBytes(data, getU8Encoder().encode(31), 0)) {\n return Token2022Instruction.CreateNativeMint;\n }\n if (containsBytes(data, getU8Encoder().encode(32), 0)) {\n return Token2022Instruction.InitializeNonTransferableMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(33), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateRateInterestBearingMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.EnableCpiGuard;\n }\n if (\n containsBytes(data, getU8Encoder().encode(34), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.DisableCpiGuard;\n }\n if (containsBytes(data, getU8Encoder().encode(35), 0)) {\n return Token2022Instruction.InitializePermanentDelegate;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(36), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateTransferHook;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(3), 1)\n ) {\n return Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(4), 1)\n ) {\n return Token2022Instruction.EnableHarvestToMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(37), 0) &&\n containsBytes(data, getU8Encoder().encode(5), 1)\n ) {\n return Token2022Instruction.DisableHarvestToMint;\n }\n if (containsBytes(data, getU8Encoder().encode(38), 0)) {\n return Token2022Instruction.WithdrawExcessLamports;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(39), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMetadataPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(40), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(41), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateGroupMemberPointer;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializeScaledUiAmountMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(43), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.UpdateMultiplierScaledUiMint;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(0), 1)\n ) {\n return Token2022Instruction.InitializePausableConfig;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(1), 1)\n ) {\n return Token2022Instruction.Pause;\n }\n if (\n containsBytes(data, getU8Encoder().encode(44), 0) &&\n containsBytes(data, getU8Encoder().encode(2), 1)\n ) {\n return Token2022Instruction.Resume;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([210, 225, 30, 162, 88, 184, 77, 141]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenMetadata;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([221, 233, 49, 45, 181, 202, 220, 200]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataField;\n }\n if (\n containsBytes(data, new Uint8Array([234, 18, 32, 56, 89, 141, 37, 181]), 0)\n ) {\n return Token2022Instruction.RemoveTokenMetadataKey;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([250, 166, 180, 250, 13, 12, 184, 70]),\n 0\n )\n ) {\n return Token2022Instruction.EmitTokenMetadata;\n }\n if (\n containsBytes(data, new Uint8Array([121, 113, 108, 39, 54, 51, 0, 4]), 0)\n ) {\n return Token2022Instruction.InitializeTokenGroup;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([108, 37, 171, 143, 248, 30, 18, 110]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupMaxSize;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([161, 105, 88, 1, 237, 221, 216, 203]),\n 0\n )\n ) {\n return Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n }\n if (\n containsBytes(\n data,\n new Uint8Array([152, 32, 222, 176, 223, 237, 116, 134]),\n 0\n )\n ) {\n return Token2022Instruction.InitializeTokenGroupMember;\n }\n throw new Error(\n 'The provided instruction could not be identified as a token-2022 instruction.'\n );\n}\n\nexport type ParsedToken2022Instruction<\n TProgram extends string = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n> =\n | ({\n instructionType: Token2022Instruction.InitializeMint;\n } & ParsedInitializeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount;\n } & ParsedInitializeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig;\n } & ParsedInitializeMultisigInstruction)\n | ({\n instructionType: Token2022Instruction.Transfer;\n } & ParsedTransferInstruction)\n | ({\n instructionType: Token2022Instruction.Approve;\n } & ParsedApproveInstruction)\n | ({\n instructionType: Token2022Instruction.Revoke;\n } & ParsedRevokeInstruction)\n | ({\n instructionType: Token2022Instruction.SetAuthority;\n } & ParsedSetAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.MintTo;\n } & ParsedMintToInstruction)\n | ({\n instructionType: Token2022Instruction.Burn;\n } & ParsedBurnInstruction)\n | ({\n instructionType: Token2022Instruction.CloseAccount;\n } & ParsedCloseAccountInstruction)\n | ({\n instructionType: Token2022Instruction.FreezeAccount;\n } & ParsedFreezeAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ThawAccount;\n } & ParsedThawAccountInstruction)\n | ({\n instructionType: Token2022Instruction.TransferChecked;\n } & ParsedTransferCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveChecked;\n } & ParsedApproveCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.MintToChecked;\n } & ParsedMintToCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.BurnChecked;\n } & ParsedBurnCheckedInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount2;\n } & ParsedInitializeAccount2Instruction)\n | ({\n instructionType: Token2022Instruction.SyncNative;\n } & ParsedSyncNativeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeAccount3;\n } & ParsedInitializeAccount3Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMultisig2;\n } & ParsedInitializeMultisig2Instruction)\n | ({\n instructionType: Token2022Instruction.InitializeMint2;\n } & ParsedInitializeMint2Instruction)\n | ({\n instructionType: Token2022Instruction.GetAccountDataSize;\n } & ParsedGetAccountDataSizeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeImmutableOwner;\n } & ParsedInitializeImmutableOwnerInstruction)\n | ({\n instructionType: Token2022Instruction.AmountToUiAmount;\n } & ParsedAmountToUiAmountInstruction)\n | ({\n instructionType: Token2022Instruction.UiAmountToAmount;\n } & ParsedUiAmountToAmountInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMintCloseAuthority;\n } & ParsedInitializeMintCloseAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferFeeConfig;\n } & ParsedInitializeTransferFeeConfigInstruction)\n | ({\n instructionType: Token2022Instruction.TransferCheckedWithFee;\n } & ParsedTransferCheckedWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMint;\n } & ParsedWithdrawWithheldTokensFromMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccounts;\n } & ParsedWithdrawWithheldTokensFromAccountsInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMint;\n } & ParsedHarvestWithheldTokensToMintInstruction)\n | ({\n instructionType: Token2022Instruction.SetTransferFee;\n } & ParsedSetTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferMint;\n } & ParsedInitializeConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateConfidentialTransferMint;\n } & ParsedUpdateConfidentialTransferMintInstruction)\n | ({\n instructionType: Token2022Instruction.ConfigureConfidentialTransferAccount;\n } & ParsedConfigureConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ApproveConfidentialTransferAccount;\n } & ParsedApproveConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.EmptyConfidentialTransferAccount;\n } & ParsedEmptyConfidentialTransferAccountInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialDeposit;\n } & ParsedConfidentialDepositInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialWithdraw;\n } & ParsedConfidentialWithdrawInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransfer;\n } & ParsedConfidentialTransferInstruction)\n | ({\n instructionType: Token2022Instruction.ApplyConfidentialPendingBalance;\n } & ParsedApplyConfidentialPendingBalanceInstruction)\n | ({\n instructionType: Token2022Instruction.EnableConfidentialCredits;\n } & ParsedEnableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableConfidentialCredits;\n } & ParsedDisableConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.EnableNonConfidentialCredits;\n } & ParsedEnableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.DisableNonConfidentialCredits;\n } & ParsedDisableNonConfidentialCreditsInstruction)\n | ({\n instructionType: Token2022Instruction.ConfidentialTransferWithFee;\n } & ParsedConfidentialTransferWithFeeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeDefaultAccountState;\n } & ParsedInitializeDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateDefaultAccountState;\n } & ParsedUpdateDefaultAccountStateInstruction)\n | ({\n instructionType: Token2022Instruction.Reallocate;\n } & ParsedReallocateInstruction)\n | ({\n instructionType: Token2022Instruction.EnableMemoTransfers;\n } & ParsedEnableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.DisableMemoTransfers;\n } & ParsedDisableMemoTransfersInstruction)\n | ({\n instructionType: Token2022Instruction.CreateNativeMint;\n } & ParsedCreateNativeMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeNonTransferableMint;\n } & ParsedInitializeNonTransferableMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeInterestBearingMint;\n } & ParsedInitializeInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateRateInterestBearingMint;\n } & ParsedUpdateRateInterestBearingMintInstruction)\n | ({\n instructionType: Token2022Instruction.EnableCpiGuard;\n } & ParsedEnableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.DisableCpiGuard;\n } & ParsedDisableCpiGuardInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePermanentDelegate;\n } & ParsedInitializePermanentDelegateInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTransferHook;\n } & ParsedInitializeTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTransferHook;\n } & ParsedUpdateTransferHookInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeConfidentialTransferFee;\n } & ParsedInitializeConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromMintForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawWithheldTokensFromAccountsForConfidentialTransferFee;\n } & ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.HarvestWithheldTokensToMintForConfidentialTransferFee;\n } & ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction)\n | ({\n instructionType: Token2022Instruction.EnableHarvestToMint;\n } & ParsedEnableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.DisableHarvestToMint;\n } & ParsedDisableHarvestToMintInstruction)\n | ({\n instructionType: Token2022Instruction.WithdrawExcessLamports;\n } & ParsedWithdrawExcessLamportsInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeMetadataPointer;\n } & ParsedInitializeMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMetadataPointer;\n } & ParsedUpdateMetadataPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupPointer;\n } & ParsedInitializeGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupPointer;\n } & ParsedUpdateGroupPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeGroupMemberPointer;\n } & ParsedInitializeGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateGroupMemberPointer;\n } & ParsedUpdateGroupMemberPointerInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeScaledUiAmountMint;\n } & ParsedInitializeScaledUiAmountMintInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateMultiplierScaledUiMint;\n } & ParsedUpdateMultiplierScaledUiMintInstruction)\n | ({\n instructionType: Token2022Instruction.InitializePausableConfig;\n } & ParsedInitializePausableConfigInstruction)\n | ({\n instructionType: Token2022Instruction.Pause;\n } & ParsedPauseInstruction)\n | ({\n instructionType: Token2022Instruction.Resume;\n } & ParsedResumeInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenMetadata;\n } & ParsedInitializeTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataField;\n } & ParsedUpdateTokenMetadataFieldInstruction)\n | ({\n instructionType: Token2022Instruction.RemoveTokenMetadataKey;\n } & ParsedRemoveTokenMetadataKeyInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenMetadataUpdateAuthority;\n } & ParsedUpdateTokenMetadataUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.EmitTokenMetadata;\n } & ParsedEmitTokenMetadataInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroup;\n } & ParsedInitializeTokenGroupInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupMaxSize;\n } & ParsedUpdateTokenGroupMaxSizeInstruction)\n | ({\n instructionType: Token2022Instruction.UpdateTokenGroupUpdateAuthority;\n } & ParsedUpdateTokenGroupUpdateAuthorityInstruction)\n | ({\n instructionType: Token2022Instruction.InitializeTokenGroupMember;\n } & ParsedInitializeTokenGroupMemberInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\n\n/** InvalidOwner: Associated token account owner does not match address derivation */\nexport const ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0x0; // 0\n\nexport type AssociatedTokenError = typeof ASSOCIATED_TOKEN_ERROR__INVALID_OWNER;\n\nlet associatedTokenErrorMessages:\n | Record\n | undefined;\nif (process.env.NODE_ENV !== 'production') {\n associatedTokenErrorMessages = {\n [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`,\n };\n}\n\nexport function getAssociatedTokenErrorMessage(\n code: AssociatedTokenError\n): string {\n if (process.env.NODE_ENV !== 'production') {\n return (\n associatedTokenErrorMessages as Record\n )[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isAssociatedTokenError<\n TProgramErrorCode extends AssociatedTokenError,\n>(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n isProgramError,\n type Address,\n type SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,\n type SolanaError,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\n\n/** NotRentExempt: Lamport balance below rent-exempt threshold */\nexport const TOKEN_2022_ERROR__NOT_RENT_EXEMPT = 0x0; // 0\n/** InsufficientFunds: Insufficient funds */\nexport const TOKEN_2022_ERROR__INSUFFICIENT_FUNDS = 0x1; // 1\n/** InvalidMint: Invalid Mint */\nexport const TOKEN_2022_ERROR__INVALID_MINT = 0x2; // 2\n/** MintMismatch: Account not associated with this Mint */\nexport const TOKEN_2022_ERROR__MINT_MISMATCH = 0x3; // 3\n/** OwnerMismatch: Owner does not match */\nexport const TOKEN_2022_ERROR__OWNER_MISMATCH = 0x4; // 4\n/** FixedSupply: Fixed supply */\nexport const TOKEN_2022_ERROR__FIXED_SUPPLY = 0x5; // 5\n/** AlreadyInUse: Already in use */\nexport const TOKEN_2022_ERROR__ALREADY_IN_USE = 0x6; // 6\n/** InvalidNumberOfProvidedSigners: Invalid number of provided signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 0x7; // 7\n/** InvalidNumberOfRequiredSigners: Invalid number of required signers */\nexport const TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 0x8; // 8\n/** UninitializedState: State is unititialized */\nexport const TOKEN_2022_ERROR__UNINITIALIZED_STATE = 0x9; // 9\n/** NativeNotSupported: Instruction does not support native tokens */\nexport const TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED = 0xa; // 10\n/** NonNativeHasBalance: Non-native account can only be closed if its balance is zero */\nexport const TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE = 0xb; // 11\n/** InvalidInstruction: Invalid instruction */\nexport const TOKEN_2022_ERROR__INVALID_INSTRUCTION = 0xc; // 12\n/** InvalidState: State is invalid for requested operation */\nexport const TOKEN_2022_ERROR__INVALID_STATE = 0xd; // 13\n/** Overflow: Operation overflowed */\nexport const TOKEN_2022_ERROR__OVERFLOW = 0xe; // 14\n/** AuthorityTypeNotSupported: Account does not support specified authority type */\nexport const TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 0xf; // 15\n/** MintCannotFreeze: This token mint cannot freeze accounts */\nexport const TOKEN_2022_ERROR__MINT_CANNOT_FREEZE = 0x10; // 16\n/** AccountFrozen: Account is frozen */\nexport const TOKEN_2022_ERROR__ACCOUNT_FROZEN = 0x11; // 17\n/** MintDecimalsMismatch: The provided decimals value different from the Mint decimals */\nexport const TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH = 0x12; // 18\n/** NonNativeNotSupported: Instruction does not support non-native tokens */\nexport const TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED = 0x13; // 19\n\nexport type Token2022Error =\n | typeof TOKEN_2022_ERROR__ACCOUNT_FROZEN\n | typeof TOKEN_2022_ERROR__ALREADY_IN_USE\n | typeof TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__FIXED_SUPPLY\n | typeof TOKEN_2022_ERROR__INSUFFICIENT_FUNDS\n | typeof TOKEN_2022_ERROR__INVALID_INSTRUCTION\n | typeof TOKEN_2022_ERROR__INVALID_MINT\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS\n | typeof TOKEN_2022_ERROR__INVALID_STATE\n | typeof TOKEN_2022_ERROR__MINT_CANNOT_FREEZE\n | typeof TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH\n | typeof TOKEN_2022_ERROR__MINT_MISMATCH\n | typeof TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE\n | typeof TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED\n | typeof TOKEN_2022_ERROR__NOT_RENT_EXEMPT\n | typeof TOKEN_2022_ERROR__OVERFLOW\n | typeof TOKEN_2022_ERROR__OWNER_MISMATCH\n | typeof TOKEN_2022_ERROR__UNINITIALIZED_STATE;\n\nlet token2022ErrorMessages: Record | undefined;\nif (process.env.NODE_ENV !== 'production') {\n token2022ErrorMessages = {\n [TOKEN_2022_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,\n [TOKEN_2022_ERROR__ALREADY_IN_USE]: `Already in use`,\n [TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,\n [TOKEN_2022_ERROR__FIXED_SUPPLY]: `Fixed supply`,\n [TOKEN_2022_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,\n [TOKEN_2022_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,\n [TOKEN_2022_ERROR__INVALID_MINT]: `Invalid Mint`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,\n [TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,\n [TOKEN_2022_ERROR__INVALID_STATE]: `State is invalid for requested operation`,\n [TOKEN_2022_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,\n [TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,\n [TOKEN_2022_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,\n [TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,\n [TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,\n [TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,\n [TOKEN_2022_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,\n [TOKEN_2022_ERROR__OVERFLOW]: `Operation overflowed`,\n [TOKEN_2022_ERROR__OWNER_MISMATCH]: `Owner does not match`,\n [TOKEN_2022_ERROR__UNINITIALIZED_STATE]: `State is unititialized`,\n };\n}\n\nexport function getToken2022ErrorMessage(code: Token2022Error): string {\n if (process.env.NODE_ENV !== 'production') {\n return (token2022ErrorMessages as Record)[code];\n }\n\n return 'Error message not available in production bundles.';\n}\n\nexport function isToken2022Error(\n error: unknown,\n transactionMessage: {\n instructions: Record;\n },\n code?: TProgramErrorCode\n): error is SolanaError &\n Readonly<{ context: Readonly<{ code: TProgramErrorCode }> }> {\n return isProgramError(\n error,\n transactionMessage,\n TOKEN_2022_PROGRAM_ADDRESS,\n code\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n isProgramDerivedAddress,\n isTransactionSigner as kitIsTransactionSigner,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type ProgramDerivedAddress,\n type TransactionSigner,\n upgradeRoleToSigner,\n} from '@solana/kit';\n\n/**\n * Asserts that the given value is not null or undefined.\n * @internal\n */\nexport function expectSome(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error('Expected a value but received null or undefined.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a PublicKey.\n * @internal\n */\nexport function expectAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): Address {\n if (!value) {\n throw new Error('Expected a Address.');\n }\n if (typeof value === 'object' && 'address' in value) {\n return value.address;\n }\n if (Array.isArray(value)) {\n return value[0] as Address;\n }\n return value as Address;\n}\n\n/**\n * Asserts that the given value is a PDA.\n * @internal\n */\nexport function expectProgramDerivedAddress(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): ProgramDerivedAddress {\n if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) {\n throw new Error('Expected a ProgramDerivedAddress.');\n }\n return value;\n}\n\n/**\n * Asserts that the given value is a TransactionSigner.\n * @internal\n */\nexport function expectTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null\n | undefined\n): TransactionSigner {\n if (!value || !isTransactionSigner(value)) {\n throw new Error('Expected a TransactionSigner.');\n }\n return value;\n}\n\n/**\n * Defines an instruction account to resolve.\n * @internal\n */\nexport type ResolvedAccount<\n T extends string = string,\n U extends\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null =\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n | null,\n> = {\n isWritable: boolean;\n value: U;\n};\n\n/**\n * Defines an instruction that stores additional bytes on-chain.\n * @internal\n */\nexport type InstructionWithByteDelta = {\n byteDelta: number;\n};\n\n/**\n * Get account metas and signers from resolved accounts.\n * @internal\n */\nexport function getAccountMetaFactory(\n programAddress: Address,\n optionalAccountStrategy: 'omitted' | 'programId'\n) {\n return (\n account: ResolvedAccount\n ): AccountMeta | AccountSignerMeta | undefined => {\n if (!account.value) {\n if (optionalAccountStrategy === 'omitted') return;\n return Object.freeze({\n address: programAddress,\n role: AccountRole.READONLY,\n });\n }\n\n const writableRole = account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return Object.freeze({\n address: expectAddress(account.value),\n role: isTransactionSigner(account.value)\n ? upgradeRoleToSigner(writableRole)\n : writableRole,\n ...(isTransactionSigner(account.value) ? { signer: account.value } : {}),\n });\n };\n}\n\nexport function isTransactionSigner(\n value:\n | Address\n | ProgramDerivedAddress\n | TransactionSigner\n): value is TransactionSigner {\n return (\n !!value &&\n typeof value === 'object' &&\n 'address' in value &&\n kitIsTransactionSigner(value)\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR = 23;\n\nexport function getAmountToUiAmountDiscriminatorBytes() {\n return getU8Encoder().encode(AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR);\n}\n\nexport type AmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type AmountToUiAmountInstructionData = {\n discriminator: number;\n /** The amount of tokens to reformat. */\n amount: bigint;\n};\n\nexport type AmountToUiAmountInstructionDataArgs = {\n /** The amount of tokens to reformat. */\n amount: number | bigint;\n};\n\nexport function getAmountToUiAmountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AMOUNT_TO_UI_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getAmountToUiAmountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getAmountToUiAmountInstructionDataCodec(): FixedSizeCodec<\n AmountToUiAmountInstructionDataArgs,\n AmountToUiAmountInstructionData\n> {\n return combineCodec(\n getAmountToUiAmountInstructionDataEncoder(),\n getAmountToUiAmountInstructionDataDecoder()\n );\n}\n\nexport type AmountToUiAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n amount: AmountToUiAmountInstructionDataArgs['amount'];\n};\n\nexport function getAmountToUiAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: AmountToUiAmountInput,\n config?: { programAddress?: TProgramAddress }\n): AmountToUiAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getAmountToUiAmountInstructionDataEncoder().encode(\n args as AmountToUiAmountInstructionDataArgs\n ),\n programAddress,\n } as AmountToUiAmountInstruction);\n}\n\nexport type ParsedAmountToUiAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: AmountToUiAmountInstructionData;\n};\n\nexport function parseAmountToUiAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedAmountToUiAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getAmountToUiAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR = 27;\n\nexport function getApplyConfidentialPendingBalanceDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR\n );\n}\n\nexport const APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 8;\n\nexport function getApplyConfidentialPendingBalanceConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApplyConfidentialPendingBalanceInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalance;\n};\n\nexport type ApplyConfidentialPendingBalanceInstructionDataArgs = {\n /**\n * The expected number of pending balance credits since the last successful\n * `ApplyPendingBalance` instruction\n */\n expectedPendingBalanceCreditCounter: number | bigint;\n /**\n * The new decryptable balance if the pending balance is applied\n * successfully\n */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n};\n\nexport function getApplyConfidentialPendingBalanceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['expectedPendingBalanceCreditCounter', getU64Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPLY_CONFIDENTIAL_PENDING_BALANCE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPLY_CONFIDENTIAL_PENDING_BALANCE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['expectedPendingBalanceCreditCounter', getU64Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getApplyConfidentialPendingBalanceInstructionDataCodec(): FixedSizeCodec<\n ApplyConfidentialPendingBalanceInstructionDataArgs,\n ApplyConfidentialPendingBalanceInstructionData\n> {\n return combineCodec(\n getApplyConfidentialPendingBalanceInstructionDataEncoder(),\n getApplyConfidentialPendingBalanceInstructionDataDecoder()\n );\n}\n\nexport type ApplyConfidentialPendingBalanceInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n expectedPendingBalanceCreditCounter: ApplyConfidentialPendingBalanceInstructionDataArgs['expectedPendingBalanceCreditCounter'];\n newDecryptableAvailableBalance: ApplyConfidentialPendingBalanceInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getApplyConfidentialPendingBalanceInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApplyConfidentialPendingBalanceInput,\n config?: { programAddress?: TProgramAddress }\n): ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getApplyConfidentialPendingBalanceInstructionDataEncoder().encode(\n args as ApplyConfidentialPendingBalanceInstructionDataArgs\n ),\n programAddress,\n } as ApplyConfidentialPendingBalanceInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedApplyConfidentialPendingBalanceInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: ApplyConfidentialPendingBalanceInstructionData;\n};\n\nexport function parseApplyConfidentialPendingBalanceInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApplyConfidentialPendingBalanceInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getApplyConfidentialPendingBalanceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_DISCRIMINATOR = 4;\n\nexport function getApproveDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_DISCRIMINATOR);\n}\n\nexport type ApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n};\n\nexport type ApproveInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n};\n\nexport function getApproveInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_DISCRIMINATOR })\n );\n}\n\nexport function getApproveInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getApproveInstructionDataCodec(): FixedSizeCodec<\n ApproveInstructionDataArgs,\n ApproveInstructionData\n> {\n return combineCodec(\n getApproveInstructionDataEncoder(),\n getApproveInstructionDataDecoder()\n );\n}\n\nexport type ApproveInput<\n TAccountSource extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getApproveInstruction<\n TAccountSource extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveInput,\n config?: { programAddress?: TProgramAddress }\n): ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveInstructionDataEncoder().encode(\n args as ApproveInstructionDataArgs\n ),\n programAddress,\n } as ApproveInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The delegate. */\n delegate: TAccountMetas[1];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ApproveInstructionData;\n};\n\nexport function parseApproveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CHECKED_DISCRIMINATOR = 13;\n\nexport function getApproveCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(APPROVE_CHECKED_DISCRIMINATOR);\n}\n\nexport type ApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDelegate extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDelegate extends string\n ? ReadonlyAccount\n : TAccountDelegate,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens the delegate is approved for. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ApproveCheckedInstructionDataArgs = {\n /** The amount of tokens the delegate is approved for. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getApproveCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: APPROVE_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getApproveCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getApproveCheckedInstructionDataCodec(): FixedSizeCodec<\n ApproveCheckedInstructionDataArgs,\n ApproveCheckedInstructionData\n> {\n return combineCodec(\n getApproveCheckedInstructionDataEncoder(),\n getApproveCheckedInstructionDataDecoder()\n );\n}\n\nexport type ApproveCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDelegate extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The delegate. */\n delegate: Address;\n /** The source account owner or its multisignature account. */\n owner: Address | TransactionSigner;\n amount: ApproveCheckedInstructionDataArgs['amount'];\n decimals: ApproveCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getApproveCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDelegate extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n delegate: { value: input.delegate ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.delegate),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getApproveCheckedInstructionDataEncoder().encode(\n args as ApproveCheckedInstructionDataArgs\n ),\n programAddress,\n } as ApproveCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDelegate,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedApproveCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The delegate. */\n delegate: TAccountMetas[2];\n /** The source account owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ApproveCheckedInstructionData;\n};\n\nexport function parseApproveCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n delegate: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getApproveCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getApproveConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 3;\n\nexport function getApproveConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ApproveConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type ApproveConfidentialTransferAccountInstructionDataArgs = {};\n\nexport function getApproveConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n APPROVE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getApproveConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ApproveConfidentialTransferAccountInstructionDataArgs,\n ApproveConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getApproveConfidentialTransferAccountInstructionDataEncoder(),\n getApproveConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ApproveConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account to approve. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n};\n\nexport function getApproveConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ApproveConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getApproveConfidentialTransferAccountInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as ApproveConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedApproveConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account to approve. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[2];\n };\n data: ApproveConfidentialTransferAccountInstructionData;\n};\n\nexport function parseApproveConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedApproveConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getApproveConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_DISCRIMINATOR = 8;\n\nexport function getBurnDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_DISCRIMINATOR);\n}\n\nexport type BurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnInstructionData = {\n /** The amount of tokens to burn. */\n discriminator: number;\n amount: bigint;\n};\n\nexport type BurnInstructionDataArgs = { amount: number | bigint };\n\nexport function getBurnInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_DISCRIMINATOR })\n );\n}\n\nexport function getBurnInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getBurnInstructionDataCodec(): FixedSizeCodec<\n BurnInstructionDataArgs,\n BurnInstructionData\n> {\n return combineCodec(\n getBurnInstructionDataEncoder(),\n getBurnInstructionDataDecoder()\n );\n}\n\nexport type BurnInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getBurnInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnInput,\n config?: { programAddress?: TProgramAddress }\n): BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnInstructionDataEncoder().encode(\n args as BurnInstructionDataArgs\n ),\n programAddress,\n } as BurnInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnInstructionData;\n};\n\nexport function parseBurnInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const BURN_CHECKED_DISCRIMINATOR = 15;\n\nexport function getBurnCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(BURN_CHECKED_DISCRIMINATOR);\n}\n\nexport type BurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type BurnCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to burn. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type BurnCheckedInstructionDataArgs = {\n /** The amount of tokens to burn. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getBurnCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: BURN_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getBurnCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getBurnCheckedInstructionDataCodec(): FixedSizeCodec<\n BurnCheckedInstructionDataArgs,\n BurnCheckedInstructionData\n> {\n return combineCodec(\n getBurnCheckedInstructionDataEncoder(),\n getBurnCheckedInstructionDataDecoder()\n );\n}\n\nexport type BurnCheckedInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The account to burn from. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: BurnCheckedInstructionDataArgs['amount'];\n decimals: BurnCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getBurnCheckedInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: BurnCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getBurnCheckedInstructionDataEncoder().encode(\n args as BurnCheckedInstructionDataArgs\n ),\n programAddress,\n } as BurnCheckedInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedBurnCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to burn from. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: BurnCheckedInstructionData;\n};\n\nexport function parseBurnCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedBurnCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getBurnCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CLOSE_ACCOUNT_DISCRIMINATOR = 9;\n\nexport function getCloseAccountDiscriminatorBytes() {\n return getU8Encoder().encode(CLOSE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type CloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CloseAccountInstructionData = { discriminator: number };\n\nexport type CloseAccountInstructionDataArgs = {};\n\nexport function getCloseAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CLOSE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getCloseAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCloseAccountInstructionDataCodec(): FixedSizeCodec<\n CloseAccountInstructionDataArgs,\n CloseAccountInstructionData\n> {\n return combineCodec(\n getCloseAccountInstructionDataEncoder(),\n getCloseAccountInstructionDataDecoder()\n );\n}\n\nexport type CloseAccountInput<\n TAccountAccount extends string = string,\n TAccountDestination extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to close. */\n account: Address;\n /** The destination account. */\n destination: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getCloseAccountInstruction<\n TAccountAccount extends string,\n TAccountDestination extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CloseAccountInput,\n config?: { programAddress?: TProgramAddress }\n): CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getCloseAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as CloseAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountDestination,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedCloseAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to close. */\n account: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: CloseAccountInstructionData;\n};\n\nexport function parseCloseAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCloseAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n destination: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getCloseAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CONFIDENTIAL_DEPOSIT_DISCRIMINATOR = 27;\n\nexport function getConfidentialDepositDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_DEPOSIT_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 5;\n\nexport function getConfidentialDepositConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialDepositInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to deposit. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type ConfidentialDepositInstructionDataArgs = {\n /** The amount of tokens to deposit. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getConfidentialDepositInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_DEPOSIT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_DEPOSIT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialDepositInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getConfidentialDepositInstructionDataCodec(): FixedSizeCodec<\n ConfidentialDepositInstructionDataArgs,\n ConfidentialDepositInstructionData\n> {\n return combineCodec(\n getConfidentialDepositInstructionDataEncoder(),\n getConfidentialDepositInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialDepositInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialDepositInstructionDataArgs['amount'];\n decimals: ConfidentialDepositInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialDepositInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialDepositInput<\n TAccountToken,\n TAccountMint,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialDepositInstructionDataEncoder().encode(\n args as ConfidentialDepositInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialDepositInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialDepositInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: ConfidentialDepositInstructionData;\n};\n\nexport function parseConfidentialDepositInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialDepositInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialDepositInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 7;\n\nexport function getConfidentialTransferConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Transfer` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n ciphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU128Data`\n * instruction to the `Transfer` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['ciphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferInstructionDataArgs,\n ConfidentialTransferInstructionData\n> {\n return combineCodec(\n getConfidentialTransferInstructionDataEncoder(),\n getConfidentialTransferInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['equalityProofInstructionOffset'];\n ciphertextValidityProofInstructionOffset: ConfidentialTransferInstructionDataArgs['ciphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n ciphertextValidityRecord: {\n value: input.ciphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.ciphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferInstructionDataEncoder().encode(\n args as ConfidentialTransferInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /** (Optional) Ciphertext validity proof record account or context state account. */\n ciphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[6] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[7];\n };\n data: ConfidentialTransferInstructionData;\n};\n\nexport function parseConfidentialTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferInstruction {\n if (instruction.accounts.length < 8) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n ciphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR = 27;\n\nexport function getConfidentialTransferWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 13;\n\nexport function getConfidentialTransferWithFeeConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestinationToken extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountTransferAmountCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountFeeSigmaRecord extends string | AccountMeta = string,\n TAccountFeeCiphertextValidityRecord extends\n | string\n | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceToken extends string\n ? WritableAccount\n : TAccountSourceToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestinationToken extends string\n ? WritableAccount\n : TAccountDestinationToken,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord extends string\n ? ReadonlyAccount\n : TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord extends string\n ? ReadonlyAccount\n : TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialTransferWithFeeInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialTransferWithFeeInstructionDataArgs = {\n /** The new source decryptable balance if the transfer succeeds. */\n newSourceDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `TransferWithFee` instruction in the transaction. If the offset\n * is `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext3HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n transferAmountCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::VerifyPercentageWithFee`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeSigmaProofInstructionOffset: number;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyBatchedGroupedCiphertext2HandlesValidity`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n feeCiphertextValidityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU256Data`\n * instruction to the `TransferWithFee` instruction in the transaction.\n * If the offset is `0`, then use a context state account for the\n * proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialTransferWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n [\n 'transferAmountCiphertextValidityProofInstructionOffset',\n getI8Encoder(),\n ],\n ['feeSigmaProofInstructionOffset', getI8Encoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_TRANSFER_WITH_FEE_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_TRANSFER_WITH_FEE_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['newSourceDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['transferAmountCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['feeSigmaProofInstructionOffset', getI8Decoder()],\n ['feeCiphertextValidityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialTransferWithFeeInstructionDataCodec(): FixedSizeCodec<\n ConfidentialTransferWithFeeInstructionDataArgs,\n ConfidentialTransferWithFeeInstructionData\n> {\n return combineCodec(\n getConfidentialTransferWithFeeInstructionDataEncoder(),\n getConfidentialTransferWithFeeInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialTransferWithFeeInput<\n TAccountSourceToken extends string = string,\n TAccountMint extends string = string,\n TAccountDestinationToken extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountTransferAmountCiphertextValidityRecord extends string = string,\n TAccountFeeSigmaRecord extends string = string,\n TAccountFeeCiphertextValidityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source SPL Token account. */\n sourceToken: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /** The destination SPL Token account. */\n destinationToken: Address;\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: Address;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: Address;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n newSourceDecryptableAvailableBalance: ConfidentialTransferWithFeeInstructionDataArgs['newSourceDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['equalityProofInstructionOffset'];\n transferAmountCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['transferAmountCiphertextValidityProofInstructionOffset'];\n feeSigmaProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeSigmaProofInstructionOffset'];\n feeCiphertextValidityProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['feeCiphertextValidityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialTransferWithFeeInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialTransferWithFeeInstruction<\n TAccountSourceToken extends string,\n TAccountMint extends string,\n TAccountDestinationToken extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountTransferAmountCiphertextValidityRecord extends string,\n TAccountFeeSigmaRecord extends string,\n TAccountFeeCiphertextValidityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialTransferWithFeeInput<\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceToken: { value: input.sourceToken ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destinationToken: {\n value: input.destinationToken ?? null,\n isWritable: true,\n },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n transferAmountCiphertextValidityRecord: {\n value: input.transferAmountCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n feeSigmaRecord: { value: input.feeSigmaRecord ?? null, isWritable: false },\n feeCiphertextValidityRecord: {\n value: input.feeCiphertextValidityRecord ?? null,\n isWritable: false,\n },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceToken),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destinationToken),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.transferAmountCiphertextValidityRecord),\n getAccountMeta(accounts.feeSigmaRecord),\n getAccountMeta(accounts.feeCiphertextValidityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialTransferWithFeeInstructionDataEncoder().encode(\n args as ConfidentialTransferWithFeeInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialTransferWithFeeInstruction<\n TProgramAddress,\n TAccountSourceToken,\n TAccountMint,\n TAccountDestinationToken,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountTransferAmountCiphertextValidityRecord,\n TAccountFeeSigmaRecord,\n TAccountFeeCiphertextValidityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialTransferWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source SPL Token account. */\n sourceToken: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /** The destination SPL Token account. */\n destinationToken: TAccountMetas[2];\n /**\n * (Optional) Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[3] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[4] | undefined;\n /**\n * (Optional) Transfer amount ciphertext validity proof record\n * account or context state account.\n */\n transferAmountCiphertextValidityRecord?: TAccountMetas[5] | undefined;\n /** (Optional) Fee sigma proof record account or context state account. */\n feeSigmaRecord?: TAccountMetas[6] | undefined;\n /** (Optional) Fee ciphertext validity proof record account or context state account. */\n feeCiphertextValidityRecord?: TAccountMetas[7] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[8] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[9];\n };\n data: ConfidentialTransferWithFeeInstructionData;\n};\n\nexport function parseConfidentialTransferWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialTransferWithFeeInstruction {\n if (instruction.accounts.length < 10) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceToken: getNextAccount(),\n mint: getNextAccount(),\n destinationToken: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n transferAmountCiphertextValidityRecord: getNextOptionalAccount(),\n feeSigmaRecord: getNextOptionalAccount(),\n feeCiphertextValidityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialTransferWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIDENTIAL_WITHDRAW_DISCRIMINATOR = 27;\n\nexport function getConfidentialWithdrawDiscriminatorBytes() {\n return getU8Encoder().encode(CONFIDENTIAL_WITHDRAW_DISCRIMINATOR);\n}\n\nexport const CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 6;\n\nexport function getConfidentialWithdrawConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvar extends string | AccountMeta = string,\n TAccountEqualityRecord extends string | AccountMeta = string,\n TAccountRangeRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvar extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvar,\n TAccountEqualityRecord extends string\n ? ReadonlyAccount\n : TAccountEqualityRecord,\n TAccountRangeRecord extends string\n ? ReadonlyAccount\n : TAccountRangeRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfidentialWithdrawInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The amount of tokens to withdraw. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalance;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport type ConfidentialWithdrawInstructionDataArgs = {\n /** The amount of tokens to withdraw. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The new decryptable balance if the withdrawal succeeds. */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n /**\n * Relative location of the\n * `ProofInstruction::VerifyCiphertextCommitmentEquality` instruction\n * to the `Withdraw` instruction in the transaction. If the offset is\n * `0`, then use a context state account for the proof.\n */\n equalityProofInstructionOffset: number;\n /**\n * Relative location of the `ProofInstruction::BatchedRangeProofU64`\n * instruction to the `Withdraw` instruction in the transaction. If the\n * offset is `0`, then use a context state account for the proof.\n */\n rangeProofInstructionOffset: number;\n};\n\nexport function getConfidentialWithdrawInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ['equalityProofInstructionOffset', getI8Encoder()],\n ['rangeProofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIDENTIAL_WITHDRAW_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIDENTIAL_WITHDRAW_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfidentialWithdrawInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ['equalityProofInstructionOffset', getI8Decoder()],\n ['rangeProofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfidentialWithdrawInstructionDataCodec(): FixedSizeCodec<\n ConfidentialWithdrawInstructionDataArgs,\n ConfidentialWithdrawInstructionData\n> {\n return combineCodec(\n getConfidentialWithdrawInstructionDataEncoder(),\n getConfidentialWithdrawInstructionDataDecoder()\n );\n}\n\nexport type ConfidentialWithdrawInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvar extends string = string,\n TAccountEqualityRecord extends string = string,\n TAccountRangeRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: Address;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: Address;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: ConfidentialWithdrawInstructionDataArgs['amount'];\n decimals: ConfidentialWithdrawInstructionDataArgs['decimals'];\n newDecryptableAvailableBalance: ConfidentialWithdrawInstructionDataArgs['newDecryptableAvailableBalance'];\n equalityProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['equalityProofInstructionOffset'];\n rangeProofInstructionOffset: ConfidentialWithdrawInstructionDataArgs['rangeProofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfidentialWithdrawInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvar extends string,\n TAccountEqualityRecord extends string,\n TAccountRangeRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfidentialWithdrawInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvar: {\n value: input.instructionsSysvar ?? null,\n isWritable: false,\n },\n equalityRecord: { value: input.equalityRecord ?? null, isWritable: false },\n rangeRecord: { value: input.rangeRecord ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvar),\n getAccountMeta(accounts.equalityRecord),\n getAccountMeta(accounts.rangeRecord),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfidentialWithdrawInstructionDataEncoder().encode(\n args as ConfidentialWithdrawInstructionDataArgs\n ),\n programAddress,\n } as ConfidentialWithdrawInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvar,\n TAccountEqualityRecord,\n TAccountRangeRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfidentialWithdrawInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if at least one of the\n * `zk_elgamal_proof` instructions are included in the same\n * transaction.\n */\n instructionsSysvar?: TAccountMetas[2] | undefined;\n /** (Optional) Equality proof record account or context state account. */\n equalityRecord?: TAccountMetas[3] | undefined;\n /** (Optional) Range proof record account or context state account. */\n rangeRecord?: TAccountMetas[4] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[5];\n };\n data: ConfidentialWithdrawInstructionData;\n};\n\nexport function parseConfidentialWithdrawInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfidentialWithdrawInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvar: getNextOptionalAccount(),\n equalityRecord: getNextOptionalAccount(),\n rangeRecord: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfidentialWithdrawInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getConfigureConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 2;\n\nexport function getConfigureConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ConfigureConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalance;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type ConfigureConfidentialTransferAccountInstructionDataArgs = {\n /** The decryptable balance (always 0) once the configure account succeeds. */\n decryptableZeroBalance: DecryptableBalanceArgs;\n /**\n * The maximum number of despots and transfers that an account can receiver\n * before the `ApplyPendingBalance` is executed\n */\n maximumPendingBalanceCreditCounter: number | bigint;\n /**\n * Relative location of the `ProofInstruction::ZeroCiphertextProof`\n * instruction to the `ConfigureAccount` instruction in the\n * transaction. If the offset is `0`, then use a context state account\n * for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getConfigureConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['decryptableZeroBalance', getDecryptableBalanceEncoder()],\n ['maximumPendingBalanceCreditCounter', getU64Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n CONFIGURE_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['decryptableZeroBalance', getDecryptableBalanceDecoder()],\n ['maximumPendingBalanceCreditCounter', getU64Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getConfigureConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n ConfigureConfidentialTransferAccountInstructionDataArgs,\n ConfigureConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getConfigureConfidentialTransferAccountInstructionDataEncoder(),\n getConfigureConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type ConfigureConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountMint extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The corresponding SPL Token mint. */\n mint: Address;\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n decryptableZeroBalance: ConfigureConfidentialTransferAccountInstructionDataArgs['decryptableZeroBalance'];\n maximumPendingBalanceCreditCounter: ConfigureConfidentialTransferAccountInstructionDataArgs['maximumPendingBalanceCreditCounter'];\n proofInstructionOffset: ConfigureConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getConfigureConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountMint extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ConfigureConfidentialTransferAccountInput<\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getConfigureConfidentialTransferAccountInstructionDataEncoder().encode(\n args as ConfigureConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as ConfigureConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountMint,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The corresponding SPL Token mint. */\n mint: TAccountMetas[1];\n /**\n * Instructions sysvar if `VerifyPubkeyValidity` is included in\n * the same transaction or context state account if\n * `VerifyPubkeyValidity` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[3] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[4];\n };\n data: ConfigureConfidentialTransferAccountInstructionData;\n};\n\nexport function parseConfigureConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedConfigureConfidentialTransferAccountInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n mint: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getConfigureConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nexport type AssociatedTokenSeeds = {\n /** The wallet address of the associated token account. */\n owner: Address;\n /** The address of the token program to use. */\n tokenProgram: Address;\n /** The mint address of the associated token account. */\n mint: Address;\n};\n\nexport async function findAssociatedTokenPda(\n seeds: AssociatedTokenSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise {\n const {\n programAddress = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getAddressEncoder().encode(seeds.owner),\n getAddressEncoder().encode(seeds.tokenProgram),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR = 0;\n\nexport function getCreateAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type CreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenInstructionData = { discriminator: number };\n\nexport type CreateAssociatedTokenInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenInstructionDataArgs,\n CreateAssociatedTokenInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenInstructionDataEncoder(),\n getCreateAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenInstructionData;\n};\n\nexport function parseCreateAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR = 1;\n\nexport function getCreateAssociatedTokenIdempotentDiscriminatorBytes() {\n return getU8Encoder().encode(\n CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR\n );\n}\n\nexport type CreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountAta extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountAta extends string ? WritableAccount : TAccountAta,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateAssociatedTokenIdempotentInstructionData = {\n discriminator: number;\n};\n\nexport type CreateAssociatedTokenIdempotentInstructionDataArgs = {};\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: CREATE_ASSOCIATED_TOKEN_IDEMPOTENT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateAssociatedTokenIdempotentInstructionDataCodec(): FixedSizeCodec<\n CreateAssociatedTokenIdempotentInstructionDataArgs,\n CreateAssociatedTokenIdempotentInstructionData\n> {\n return combineCodec(\n getCreateAssociatedTokenIdempotentInstructionDataEncoder(),\n getCreateAssociatedTokenIdempotentInstructionDataDecoder()\n );\n}\n\nexport type CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata?: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getCreateAssociatedTokenIdempotentInstructionAsync<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentAsyncInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ata.value) {\n accounts.ata.value = await findAssociatedTokenPda({\n owner: expectAddress(accounts.owner.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.mint.value),\n });\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type CreateAssociatedTokenIdempotentInput<\n TAccountPayer extends string = string,\n TAccountAta extends string = string,\n TAccountOwner extends string = string,\n TAccountMint extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Funding account (must be a system account). */\n payer: TransactionSigner;\n /** Associated token account address to be created. */\n ata: Address;\n /** Wallet address for the new associated token account. */\n owner: Address;\n /** The token mint for the new associated token account. */\n mint: Address;\n /** System program. */\n systemProgram?: Address;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getCreateAssociatedTokenIdempotentInstruction<\n TAccountPayer extends string,\n TAccountAta extends string,\n TAccountOwner extends string,\n TAccountMint extends string,\n TAccountSystemProgram extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: CreateAssociatedTokenIdempotentInput<\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n ata: { value: input.ata ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n mint: { value: input.mint ?? null, isWritable: false },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.ata),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getCreateAssociatedTokenIdempotentInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateAssociatedTokenIdempotentInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountAta,\n TAccountOwner,\n TAccountMint,\n TAccountSystemProgram,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account). */\n payer: TAccountMetas[0];\n /** Associated token account address to be created. */\n ata: TAccountMetas[1];\n /** Wallet address for the new associated token account. */\n owner: TAccountMetas[2];\n /** The token mint for the new associated token account. */\n mint: TAccountMetas[3];\n /** System program. */\n systemProgram: TAccountMetas[4];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[5];\n };\n data: CreateAssociatedTokenIdempotentInstructionData;\n};\n\nexport function parseCreateAssociatedTokenIdempotentInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateAssociatedTokenIdempotentInstruction {\n if (instruction.accounts.length < 6) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n ata: getNextAccount(),\n owner: getNextAccount(),\n mint: getNextAccount(),\n systemProgram: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getCreateAssociatedTokenIdempotentInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const CREATE_NATIVE_MINT_DISCRIMINATOR = 31;\n\nexport function getCreateNativeMintDiscriminatorBytes() {\n return getU8Encoder().encode(CREATE_NATIVE_MINT_DISCRIMINATOR);\n}\n\nexport type CreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountPayer extends string | AccountMeta = string,\n TAccountNativeMint extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountNativeMint extends string\n ? WritableAccount\n : TAccountNativeMint,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type CreateNativeMintInstructionData = { discriminator: number };\n\nexport type CreateNativeMintInstructionDataArgs = {};\n\nexport function getCreateNativeMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: CREATE_NATIVE_MINT_DISCRIMINATOR })\n );\n}\n\nexport function getCreateNativeMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getCreateNativeMintInstructionDataCodec(): FixedSizeCodec<\n CreateNativeMintInstructionDataArgs,\n CreateNativeMintInstructionData\n> {\n return combineCodec(\n getCreateNativeMintInstructionDataEncoder(),\n getCreateNativeMintInstructionDataDecoder()\n );\n}\n\nexport type CreateNativeMintInput<\n TAccountPayer extends string = string,\n TAccountNativeMint extends string = string,\n TAccountSystemProgram extends string = string,\n> = {\n /** Funding account (must be a system account) */\n payer: TransactionSigner;\n /** The native mint address */\n nativeMint: Address;\n /** System program for mint account funding */\n systemProgram?: Address;\n};\n\nexport function getCreateNativeMintInstruction<\n TAccountPayer extends string,\n TAccountNativeMint extends string,\n TAccountSystemProgram extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: CreateNativeMintInput<\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n payer: { value: input.payer ?? null, isWritable: true },\n nativeMint: { value: input.nativeMint ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.nativeMint),\n getAccountMeta(accounts.systemProgram),\n ],\n data: getCreateNativeMintInstructionDataEncoder().encode({}),\n programAddress,\n } as CreateNativeMintInstruction<\n TProgramAddress,\n TAccountPayer,\n TAccountNativeMint,\n TAccountSystemProgram\n >);\n}\n\nexport type ParsedCreateNativeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Funding account (must be a system account) */\n payer: TAccountMetas[0];\n /** The native mint address */\n nativeMint: TAccountMetas[1];\n /** System program for mint account funding */\n systemProgram: TAccountMetas[2];\n };\n data: CreateNativeMintInstructionData;\n};\n\nexport function parseCreateNativeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedCreateNativeMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n payer: getNextAccount(),\n nativeMint: getNextAccount(),\n systemProgram: getNextAccount(),\n },\n data: getCreateNativeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 10;\n\nexport function getDisableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableConfidentialCreditsInstructionDataArgs,\n DisableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableConfidentialCreditsInstructionDataEncoder(),\n getDisableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getDisableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 1;\n\nexport function getDisableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type DisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type DisableCpiGuardInstructionDataArgs = {};\n\nexport function getDisableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: DISABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n DisableCpiGuardInstructionDataArgs,\n DisableCpiGuardInstructionData\n> {\n return combineCodec(\n getDisableCpiGuardInstructionDataEncoder(),\n getDisableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type DisableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableCpiGuardInstructionData;\n};\n\nexport function parseDisableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getDisableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getDisableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type DisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type DisableHarvestToMintInstructionDataArgs = {};\n\nexport function getDisableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n DISABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n DisableHarvestToMintInstructionDataArgs,\n DisableHarvestToMintInstructionData\n> {\n return combineCodec(\n getDisableHarvestToMintInstructionDataEncoder(),\n getDisableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type DisableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: DisableHarvestToMintInstructionData;\n};\n\nexport function parseDisableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getDisableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getDisableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 1;\n\nexport function getDisableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type DisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type DisableMemoTransfersInstructionDataArgs = {};\n\nexport function getDisableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n DISABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n DisableMemoTransfersInstructionDataArgs,\n DisableMemoTransfersInstructionData\n> {\n return combineCodec(\n getDisableMemoTransfersInstructionDataEncoder(),\n getDisableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type DisableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getDisableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedDisableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: DisableMemoTransfersInstructionData;\n};\n\nexport function parseDisableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getDisableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getDisableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 12;\n\nexport function getDisableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type DisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type DisableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type DisableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getDisableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: DISABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n DISABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getDisableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n DisableNonConfidentialCreditsInstructionDataArgs,\n DisableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getDisableNonConfidentialCreditsInstructionDataEncoder(),\n getDisableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type DisableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getDisableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: DisableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getDisableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as DisableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedDisableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: DisableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseDisableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedDisableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getDisableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMIT_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 250, 166, 180, 250, 13, 12, 184, 70,\n]);\n\nexport function getEmitTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(EMIT_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type EmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? ReadonlyAccount\n : TAccountMetadata,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmitTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Start of range of data to emit */\n start: Option;\n /** End of range of data to emit */\n end: Option;\n};\n\nexport type EmitTokenMetadataInstructionDataArgs = {\n /** Start of range of data to emit */\n start?: OptionOrNullable;\n /** End of range of data to emit */\n end?: OptionOrNullable;\n};\n\nexport function getEmitTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['start', getOptionEncoder(getU64Encoder())],\n ['end', getOptionEncoder(getU64Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: EMIT_TOKEN_METADATA_DISCRIMINATOR,\n start: value.start ?? none(),\n end: value.end ?? none(),\n })\n );\n}\n\nexport function getEmitTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['start', getOptionDecoder(getU64Decoder())],\n ['end', getOptionDecoder(getU64Decoder())],\n ]);\n}\n\nexport function getEmitTokenMetadataInstructionDataCodec(): Codec<\n EmitTokenMetadataInstructionDataArgs,\n EmitTokenMetadataInstructionData\n> {\n return combineCodec(\n getEmitTokenMetadataInstructionDataEncoder(),\n getEmitTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type EmitTokenMetadataInput = {\n metadata: Address;\n start?: EmitTokenMetadataInstructionDataArgs['start'];\n end?: EmitTokenMetadataInstructionDataArgs['end'];\n};\n\nexport function getEmitTokenMetadataInstruction<\n TAccountMetadata extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmitTokenMetadataInput,\n config?: { programAddress?: TProgramAddress }\n): EmitTokenMetadataInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.metadata)],\n data: getEmitTokenMetadataInstructionDataEncoder().encode(\n args as EmitTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as EmitTokenMetadataInstruction);\n}\n\nexport type ParsedEmitTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n };\n data: EmitTokenMetadataInstructionData;\n};\n\nexport function parseEmitTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmitTokenMetadataInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount() },\n data: getEmitTokenMetadataInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR = 27;\n\nexport function getEmptyConfidentialTransferAccountDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR\n );\n}\n\nexport const EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 4;\n\nexport function getEmptyConfidentialTransferAccountConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = 'Sysvar1nstructions1111111111111111111111111',\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EmptyConfidentialTransferAccountInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport type EmptyConfidentialTransferAccountInstructionDataArgs = {\n /**\n * Relative location of the `ProofInstruction::VerifyCloseAccount`\n * instruction to the `EmptyAccount` instruction in the transaction. If\n * the offset is `0`, then use a context state account for the proof.\n */\n proofInstructionOffset: number;\n};\n\nexport function getEmptyConfidentialTransferAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n EMPTY_CONFIDENTIAL_TRANSFER_ACCOUNT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ]);\n}\n\nexport function getEmptyConfidentialTransferAccountInstructionDataCodec(): FixedSizeCodec<\n EmptyConfidentialTransferAccountInstructionDataArgs,\n EmptyConfidentialTransferAccountInstructionData\n> {\n return combineCodec(\n getEmptyConfidentialTransferAccountInstructionDataEncoder(),\n getEmptyConfidentialTransferAccountInstructionDataDecoder()\n );\n}\n\nexport type EmptyConfidentialTransferAccountInput<\n TAccountToken extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState?: Address;\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n proofInstructionOffset: EmptyConfidentialTransferAccountInstructionDataArgs['proofInstructionOffset'];\n multiSigners?: Array;\n};\n\nexport function getEmptyConfidentialTransferAccountInstruction<\n TAccountToken extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EmptyConfidentialTransferAccountInput<\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.instructionsSysvarOrContextState.value) {\n accounts.instructionsSysvarOrContextState.value =\n 'Sysvar1nstructions1111111111111111111111111' as Address<'Sysvar1nstructions1111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEmptyConfidentialTransferAccountInstructionDataEncoder().encode(\n args as EmptyConfidentialTransferAccountInstructionDataArgs\n ),\n programAddress,\n } as EmptyConfidentialTransferAccountInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEmptyConfidentialTransferAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /**\n * Instructions sysvar if `VerifyZeroCiphertext` is included in\n * the same transaction or context state account if\n * `VerifyZeroCiphertext` is pre-verified into a context state\n * account.\n */\n instructionsSysvarOrContextState: TAccountMetas[1];\n /** (Optional) Record account if the accompanying proof is to be read from a record account. */\n record?: TAccountMetas[2] | undefined;\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: EmptyConfidentialTransferAccountInstructionData;\n};\n\nexport function parseEmptyConfidentialTransferAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEmptyConfidentialTransferAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getEmptyConfidentialTransferAccountInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 9;\n\nexport function getEnableConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableConfidentialCreditsInstructionDataArgs,\n EnableConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableConfidentialCreditsInstructionDataEncoder(),\n getEnableConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_CPI_GUARD_DISCRIMINATOR = 34;\n\nexport function getEnableCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport const ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR = 0;\n\nexport function getEnableCpiGuardCpiGuardDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR);\n}\n\nexport type EnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableCpiGuardInstructionData = {\n discriminator: number;\n cpiGuardDiscriminator: number;\n};\n\nexport type EnableCpiGuardInstructionDataArgs = {};\n\nexport function getEnableCpiGuardInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['cpiGuardDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_CPI_GUARD_DISCRIMINATOR,\n cpiGuardDiscriminator: ENABLE_CPI_GUARD_CPI_GUARD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableCpiGuardInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['cpiGuardDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableCpiGuardInstructionDataCodec(): FixedSizeCodec<\n EnableCpiGuardInstructionDataArgs,\n EnableCpiGuardInstructionData\n> {\n return combineCodec(\n getEnableCpiGuardInstructionDataEncoder(),\n getEnableCpiGuardInstructionDataDecoder()\n );\n}\n\nexport type EnableCpiGuardInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner/delegate or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableCpiGuardInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableCpiGuardInput,\n config?: { programAddress?: TProgramAddress }\n): EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableCpiGuardInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableCpiGuardInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableCpiGuardInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner/delegate or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableCpiGuardInstructionData;\n};\n\nexport function parseEnableCpiGuardInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableCpiGuardInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableCpiGuardInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_HARVEST_TO_MINT_DISCRIMINATOR = 37;\n\nexport function getEnableHarvestToMintDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_HARVEST_TO_MINT_DISCRIMINATOR);\n}\n\nexport const ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getEnableHarvestToMintConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type EnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableHarvestToMintInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n};\n\nexport type EnableHarvestToMintInstructionDataArgs = {};\n\nexport function getEnableHarvestToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_HARVEST_TO_MINT_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n ENABLE_HARVEST_TO_MINT_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableHarvestToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableHarvestToMintInstructionDataCodec(): FixedSizeCodec<\n EnableHarvestToMintInstructionDataArgs,\n EnableHarvestToMintInstructionData\n> {\n return combineCodec(\n getEnableHarvestToMintInstructionDataEncoder(),\n getEnableHarvestToMintInstructionDataDecoder()\n );\n}\n\nexport type EnableHarvestToMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The confidential transfer fee authority */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableHarvestToMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableHarvestToMintInput,\n config?: { programAddress?: TProgramAddress }\n): EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableHarvestToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableHarvestToMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableHarvestToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The confidential transfer fee authority */\n authority: TAccountMetas[1];\n };\n data: EnableHarvestToMintInstructionData;\n};\n\nexport function parseEnableHarvestToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableHarvestToMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getEnableHarvestToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_MEMO_TRANSFERS_DISCRIMINATOR = 30;\n\nexport function getEnableMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_MEMO_TRANSFERS_DISCRIMINATOR);\n}\n\nexport const ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR = 0;\n\nexport function getEnableMemoTransfersMemoTransfersDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR\n );\n}\n\nexport type EnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableMemoTransfersInstructionData = {\n discriminator: number;\n memoTransfersDiscriminator: number;\n};\n\nexport type EnableMemoTransfersInstructionDataArgs = {};\n\nexport function getEnableMemoTransfersInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['memoTransfersDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_MEMO_TRANSFERS_DISCRIMINATOR,\n memoTransfersDiscriminator:\n ENABLE_MEMO_TRANSFERS_MEMO_TRANSFERS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableMemoTransfersInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['memoTransfersDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableMemoTransfersInstructionDataCodec(): FixedSizeCodec<\n EnableMemoTransfersInstructionDataArgs,\n EnableMemoTransfersInstructionData\n> {\n return combineCodec(\n getEnableMemoTransfersInstructionDataEncoder(),\n getEnableMemoTransfersInstructionDataDecoder()\n );\n}\n\nexport type EnableMemoTransfersInput<\n TAccountToken extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to update. */\n token: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableMemoTransfersInstruction<\n TAccountToken extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableMemoTransfersInput,\n config?: { programAddress?: TProgramAddress }\n): EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getEnableMemoTransfersInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableMemoTransfersInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedEnableMemoTransfersInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to update. */\n token: TAccountMetas[0];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[1];\n };\n data: EnableMemoTransfersInstructionData;\n};\n\nexport function parseEnableMemoTransfersInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableMemoTransfersInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), owner: getNextAccount() },\n data: getEnableMemoTransfersInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR = 27;\n\nexport function getEnableNonConfidentialCreditsDiscriminatorBytes() {\n return getU8Encoder().encode(ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR);\n}\n\nexport const ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 11;\n\nexport function getEnableNonConfidentialCreditsConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type EnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type EnableNonConfidentialCreditsInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n};\n\nexport type EnableNonConfidentialCreditsInstructionDataArgs = {};\n\nexport function getEnableNonConfidentialCreditsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: ENABLE_NON_CONFIDENTIAL_CREDITS_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n ENABLE_NON_CONFIDENTIAL_CREDITS_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getEnableNonConfidentialCreditsInstructionDataCodec(): FixedSizeCodec<\n EnableNonConfidentialCreditsInstructionDataArgs,\n EnableNonConfidentialCreditsInstructionData\n> {\n return combineCodec(\n getEnableNonConfidentialCreditsInstructionDataEncoder(),\n getEnableNonConfidentialCreditsInstructionDataDecoder()\n );\n}\n\nexport type EnableNonConfidentialCreditsInput<\n TAccountToken extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token account. */\n token: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getEnableNonConfidentialCreditsInstruction<\n TAccountToken extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: EnableNonConfidentialCreditsInput,\n config?: { programAddress?: TProgramAddress }\n): EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getEnableNonConfidentialCreditsInstructionDataEncoder().encode({}),\n programAddress,\n } as EnableNonConfidentialCreditsInstruction<\n TProgramAddress,\n TAccountToken,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedEnableNonConfidentialCreditsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token account. */\n token: TAccountMetas[0];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[1];\n };\n data: EnableNonConfidentialCreditsInstructionData;\n};\n\nexport function parseEnableNonConfidentialCreditsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedEnableNonConfidentialCreditsInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { token: getNextAccount(), authority: getNextAccount() },\n data: getEnableNonConfidentialCreditsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const FREEZE_ACCOUNT_DISCRIMINATOR = 10;\n\nexport function getFreezeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(FREEZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type FreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type FreezeAccountInstructionData = { discriminator: number };\n\nexport type FreezeAccountInstructionDataArgs = {};\n\nexport function getFreezeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: FREEZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getFreezeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getFreezeAccountInstructionDataCodec(): FixedSizeCodec<\n FreezeAccountInstructionDataArgs,\n FreezeAccountInstructionData\n> {\n return combineCodec(\n getFreezeAccountInstructionDataEncoder(),\n getFreezeAccountInstructionDataDecoder()\n );\n}\n\nexport type FreezeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to freeze. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getFreezeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: FreezeAccountInput,\n config?: { programAddress?: TProgramAddress }\n): FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getFreezeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as FreezeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedFreezeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to freeze. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: FreezeAccountInstructionData;\n};\n\nexport function parseFreezeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedFreezeAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getFreezeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR = 21;\n\nexport function getGetAccountDataSizeDiscriminatorBytes() {\n return getU8Encoder().encode(GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR);\n}\n\nexport type GetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type GetAccountDataSizeInstructionData = { discriminator: number };\n\nexport type GetAccountDataSizeInstructionDataArgs = {};\n\nexport function getGetAccountDataSizeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: GET_ACCOUNT_DATA_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getGetAccountDataSizeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getGetAccountDataSizeInstructionDataCodec(): FixedSizeCodec<\n GetAccountDataSizeInstructionDataArgs,\n GetAccountDataSizeInstructionData\n> {\n return combineCodec(\n getGetAccountDataSizeInstructionDataEncoder(),\n getGetAccountDataSizeInstructionDataDecoder()\n );\n}\n\nexport type GetAccountDataSizeInput = {\n /** The mint to calculate for. */\n mint: Address;\n};\n\nexport function getGetAccountDataSizeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: GetAccountDataSizeInput,\n config?: { programAddress?: TProgramAddress }\n): GetAccountDataSizeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getGetAccountDataSizeInstructionDataEncoder().encode({}),\n programAddress,\n } as GetAccountDataSizeInstruction);\n}\n\nexport type ParsedGetAccountDataSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: GetAccountDataSizeInstructionData;\n};\n\nexport function parseGetAccountDataSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedGetAccountDataSizeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getGetAccountDataSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR = 26;\n\nexport function getHarvestWithheldTokensToMintDiscriminatorBytes() {\n return getU8Encoder().encode(HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR);\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR = 4;\n\nexport function getHarvestWithheldTokensToMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type HarvestWithheldTokensToMintInstructionDataArgs = {};\n\nexport function getHarvestWithheldTokensToMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: HARVEST_WITHHELD_TOKENS_TO_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintInstructionDataArgs,\n HarvestWithheldTokensToMintInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintInstructionDataEncoder(),\n getHarvestWithheldTokensToMintInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintInput<\n TAccountMint extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n sources: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.sources.map((address) => ({\n address,\n role: AccountRole.WRITABLE,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintInstructionDataEncoder().encode({}),\n programAddress,\n } as HarvestWithheldTokensToMintInstruction);\n}\n\nexport type ParsedHarvestWithheldTokensToMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData =\n { discriminator: number; confidentialTransferFeeDiscriminator: number };\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs =\n {};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n HARVEST_WITHHELD_TOKENS_TO_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataArgs,\n HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder(),\n getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type HarvestWithheldTokensToMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n sources?: Array
;\n};\n\nexport function getHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: HarvestWithheldTokensToMintForConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.sources ?? []).map(\n (address) => ({ address, role: AccountRole.WRITABLE })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), ...remainingAccounts],\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n {}\n ),\n programAddress,\n } as HarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: HarvestWithheldTokensToMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedHarvestWithheldTokensToMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getHarvestWithheldTokensToMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;\n\nexport function getInitializeAccountDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type InitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccountInstructionData = { discriminator: number };\n\nexport type InitializeAccountInstructionDataArgs = {};\n\nexport function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<\n InitializeAccountInstructionDataArgs,\n InitializeAccountInstructionData\n> {\n return combineCodec(\n getInitializeAccountInstructionDataEncoder(),\n getInitializeAccountInstructionDataDecoder()\n );\n}\n\nexport type InitializeAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** The new account's owner/multisignature. */\n owner: Address;\n /** Rent sysvar. */\n rent?: Address;\n};\n\nexport function getInitializeAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccountInput<\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountOwner,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** The new account's owner/multisignature. */\n owner: TAccountMetas[2];\n /** Rent sysvar. */\n rent: TAccountMetas[3];\n };\n data: InitializeAccountInstructionData;\n};\n\nexport function parseInitializeAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccountInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT2_DISCRIMINATOR = 16;\n\nexport function getInitializeAccount2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT2_DISCRIMINATOR);\n}\n\nexport type InitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount2InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount2InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount2InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount2InstructionDataArgs,\n InitializeAccount2InstructionData\n> {\n return combineCodec(\n getInitializeAccount2InstructionDataEncoder(),\n getInitializeAccount2InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount2Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n owner: InitializeAccount2InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount2Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rent),\n ],\n data: getInitializeAccount2InstructionDataEncoder().encode(\n args as InitializeAccount2InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount2Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeAccount2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n /** Rent sysvar. */\n rent: TAccountMetas[2];\n };\n data: InitializeAccount2InstructionData;\n};\n\nexport function parseInitializeAccount2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount2Instruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n rent: getNextAccount(),\n },\n data: getInitializeAccount2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_ACCOUNT3_DISCRIMINATOR = 18;\n\nexport function getInitializeAccount3DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_ACCOUNT3_DISCRIMINATOR);\n}\n\nexport type InitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeAccount3InstructionData = {\n discriminator: number;\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport type InitializeAccount3InstructionDataArgs = {\n /** The new account's owner/multisignature. */\n owner: Address;\n};\n\nexport function getInitializeAccount3InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['owner', getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT3_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeAccount3InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['owner', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializeAccount3InstructionDataCodec(): FixedSizeCodec<\n InitializeAccount3InstructionDataArgs,\n InitializeAccount3InstructionData\n> {\n return combineCodec(\n getInitializeAccount3InstructionDataEncoder(),\n getInitializeAccount3InstructionDataDecoder()\n );\n}\n\nexport type InitializeAccount3Input<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n /** The mint this account will be associated with. */\n mint: Address;\n owner: InitializeAccount3InstructionDataArgs['owner'];\n};\n\nexport function getInitializeAccount3Instruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeAccount3Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account), getAccountMeta(accounts.mint)],\n data: getInitializeAccount3InstructionDataEncoder().encode(\n args as InitializeAccount3InstructionDataArgs\n ),\n programAddress,\n } as InitializeAccount3Instruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeAccount3Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n /** The mint this account will be associated with. */\n mint: TAccountMetas[1];\n };\n data: InitializeAccount3InstructionData;\n};\n\nexport function parseInitializeAccount3Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeAccount3Instruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount(), mint: getNextAccount() },\n data: getInitializeAccount3InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getInitializeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferFeeInstructionData = {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: Option
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferFeeInstructionDataArgs = {\n /** Optional authority to set the withdraw withheld authority ElGamal key */\n authority: OptionOrNullable
;\n /** Withheld fees from accounts must be encrypted with this ElGamal key */\n withdrawWithheldAuthorityElGamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'withdrawWithheldAuthorityElGamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferFeeInstructionDataArgs,\n InitializeConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferFeeInstructionDataEncoder(),\n getInitializeConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferFeeInstructionDataArgs['authority'];\n withdrawWithheldAuthorityElGamalPubkey: InitializeConfidentialTransferFeeInstructionDataArgs['withdrawWithheldAuthorityElGamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferFeeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferFeeInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferFeeInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferFeeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getInitializeConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR\n );\n}\n\nexport const INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 0;\n\nexport function getInitializeConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type InitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: Option
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type InitializeConfidentialTransferMintInstructionDataArgs = {\n /**\n * Authority to modify the `ConfidentialTransferMint` configuration and to\n * approve new accounts.\n */\n authority: OptionOrNullable
;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getInitializeConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n INITIALIZE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n InitializeConfidentialTransferMintInstructionDataArgs,\n InitializeConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getInitializeConfidentialTransferMintInstructionDataEncoder(),\n getInitializeConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeConfidentialTransferMintInput<\n TAccountMint extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n authority: InitializeConfidentialTransferMintInstructionDataArgs['authority'];\n autoApproveNewAccounts: InitializeConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: InitializeConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getInitializeConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeConfidentialTransferMintInstructionDataEncoder().encode(\n args as InitializeConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint\n >);\n}\n\nexport type ParsedInitializeConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeConfidentialTransferMintInstructionData;\n};\n\nexport function parseInitializeConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeConfidentialTransferMintInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getInitializeDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 0;\n\nexport function getInitializeDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type InitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type InitializeDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getInitializeDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n INITIALIZE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getInitializeDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n InitializeDefaultAccountStateInstructionDataArgs,\n InitializeDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getInitializeDefaultAccountStateInstructionDataEncoder(),\n getInitializeDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type InitializeDefaultAccountStateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n state: InitializeDefaultAccountStateInstructionDataArgs['state'];\n};\n\nexport function getInitializeDefaultAccountStateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeDefaultAccountStateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeDefaultAccountStateInstructionDataEncoder().encode(\n args as InitializeDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as InitializeDefaultAccountStateInstruction);\n}\n\nexport type ParsedInitializeDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializeDefaultAccountStateInstructionData;\n};\n\nexport function parseInitializeDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeDefaultAccountStateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getInitializeGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The public key for the account that can update the group member address. */\n authority: Option
;\n /** The account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type InitializeGroupMemberPointerInstructionDataArgs = {\n /** The public key for the account that can update the group member address. */\n authority: OptionOrNullable
;\n /** The account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n INITIALIZE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupMemberPointerInstructionDataArgs,\n InitializeGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupMemberPointerInstructionDataEncoder(),\n getInitializeGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupMemberPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupMemberPointerInstructionDataArgs['authority'];\n memberAddress: InitializeGroupMemberPointerInstructionDataArgs['memberAddress'];\n};\n\nexport function getInitializeGroupMemberPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupMemberPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupMemberPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupMemberPointerInstructionDataEncoder().encode(\n args as InitializeGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupMemberPointerInstruction);\n}\n\nexport type ParsedInitializeGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupMemberPointerInstructionData;\n};\n\nexport function parseInitializeGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupMemberPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getInitializeGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The public key for the account that can update the group address. */\n authority: Option
;\n /** The account address that holds the group. */\n groupAddress: Option
;\n};\n\nexport type InitializeGroupPointerInstructionDataArgs = {\n /** The public key for the account that can update the group address. */\n authority: OptionOrNullable
;\n /** The account address that holds the group. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getInitializeGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n INITIALIZE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeGroupPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeGroupPointerInstructionDataArgs,\n InitializeGroupPointerInstructionData\n> {\n return combineCodec(\n getInitializeGroupPointerInstructionDataEncoder(),\n getInitializeGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeGroupPointerInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeGroupPointerInstructionDataArgs['authority'];\n groupAddress: InitializeGroupPointerInstructionDataArgs['groupAddress'];\n };\n\nexport function getInitializeGroupPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeGroupPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeGroupPointerInstructionDataEncoder().encode(\n args as InitializeGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeGroupPointerInstruction);\n}\n\nexport type ParsedInitializeGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeGroupPointerInstructionData;\n};\n\nexport function parseInitializeGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeGroupPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR = 22;\n\nexport function getInitializeImmutableOwnerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR);\n}\n\nexport type InitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeImmutableOwnerInstructionData = { discriminator: number };\n\nexport type InitializeImmutableOwnerInstructionDataArgs = {};\n\nexport function getInitializeImmutableOwnerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_IMMUTABLE_OWNER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeImmutableOwnerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeImmutableOwnerInstructionDataCodec(): FixedSizeCodec<\n InitializeImmutableOwnerInstructionDataArgs,\n InitializeImmutableOwnerInstructionData\n> {\n return combineCodec(\n getInitializeImmutableOwnerInstructionDataEncoder(),\n getInitializeImmutableOwnerInstructionDataDecoder()\n );\n}\n\nexport type InitializeImmutableOwnerInput<\n TAccountAccount extends string = string,\n> = {\n /** The account to initialize. */\n account: Address;\n};\n\nexport function getInitializeImmutableOwnerInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeImmutableOwnerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeImmutableOwnerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getInitializeImmutableOwnerInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeImmutableOwnerInstruction);\n}\n\nexport type ParsedInitializeImmutableOwnerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to initialize. */\n account: TAccountMetas[0];\n };\n data: InitializeImmutableOwnerInstructionData;\n};\n\nexport function parseInitializeImmutableOwnerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeImmutableOwnerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getInitializeImmutableOwnerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getI16Decoder,\n getI16Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getInitializeInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The public key for the account that can update the rate */\n rateAuthority: Option
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport type InitializeInterestBearingMintInstructionDataArgs = {\n /** The public key for the account that can update the rate */\n rateAuthority: OptionOrNullable
;\n /** The initial interest rate */\n rate: number;\n};\n\nexport function getInitializeInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n [\n 'rateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n INITIALIZE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n [\n 'rateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getInitializeInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n InitializeInterestBearingMintInstructionDataArgs,\n InitializeInterestBearingMintInstructionData\n> {\n return combineCodec(\n getInitializeInterestBearingMintInstructionDataEncoder(),\n getInitializeInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeInterestBearingMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n rateAuthority: InitializeInterestBearingMintInstructionDataArgs['rateAuthority'];\n rate: InitializeInterestBearingMintInstructionDataArgs['rate'];\n};\n\nexport function getInitializeInterestBearingMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeInterestBearingMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeInterestBearingMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeInterestBearingMintInstructionDataEncoder().encode(\n args as InitializeInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeInterestBearingMintInstruction);\n}\n\nexport type ParsedInitializeInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeInterestBearingMintInstructionData;\n};\n\nexport function parseInitializeInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeInterestBearingMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getInitializeMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 0;\n\nexport function getInitializeMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type InitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The public key for the account that can update the metadata address. */\n authority: Option
;\n /** The account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type InitializeMetadataPointerInstructionDataArgs = {\n /** The public key for the account that can update the metadata address. */\n authority: OptionOrNullable
;\n /** The account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getInitializeMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n INITIALIZE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n InitializeMetadataPointerInstructionDataArgs,\n InitializeMetadataPointerInstructionData\n> {\n return combineCodec(\n getInitializeMetadataPointerInstructionDataEncoder(),\n getInitializeMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type InitializeMetadataPointerInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeMetadataPointerInstructionDataArgs['authority'];\n metadataAddress: InitializeMetadataPointerInstructionDataArgs['metadataAddress'];\n};\n\nexport function getInitializeMetadataPointerInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMetadataPointerInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMetadataPointerInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMetadataPointerInstructionDataEncoder().encode(\n args as InitializeMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as InitializeMetadataPointerInstruction);\n}\n\nexport type ParsedInitializeMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMetadataPointerInstructionData;\n};\n\nexport function parseInitializeMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMetadataPointerInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintInstructionData = {\n discriminator: number;\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMintInstructionDataArgs = {\n /** Number of decimals in token account amounts. */\n decimals: number;\n /** Minting authority. */\n mintAuthority: Address;\n /** Optional authority that can freeze token accounts. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMintInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMintInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintInstructionDataCodec(): Codec<\n InitializeMintInstructionDataArgs,\n InitializeMintInstructionData\n> {\n return combineCodec(\n getInitializeMintInstructionDataEncoder(),\n getInitializeMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintInput<\n TAccountMint extends string = string,\n TAccountRent extends string = string,\n> = {\n /** Token mint account. */\n mint: Address;\n /** Rent sysvar. */\n rent?: Address;\n decimals: InitializeMintInstructionDataArgs['decimals'];\n mintAuthority: InitializeMintInstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMintInstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMintInstruction<\n TAccountMint extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint), getAccountMeta(accounts.rent)],\n data: getInitializeMintInstructionDataEncoder().encode(\n args as InitializeMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintInstruction);\n}\n\nexport type ParsedInitializeMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Token mint account. */\n mint: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMintInstructionData;\n};\n\nexport function parseInitializeMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMintInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n none,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT2_DISCRIMINATOR = 20;\n\nexport function getInitializeMint2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT2_DISCRIMINATOR);\n}\n\nexport type InitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMint2InstructionData = {\n discriminator: number;\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority: Option
;\n};\n\nexport type InitializeMint2InstructionDataArgs = {\n /** Number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /** The authority/multisignature to mint tokens. */\n mintAuthority: Address;\n /** The optional freeze authority/multisignature of the mint. */\n freezeAuthority?: OptionOrNullable
;\n};\n\nexport function getInitializeMint2InstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['decimals', getU8Encoder()],\n ['mintAuthority', getAddressEncoder()],\n ['freezeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT2_DISCRIMINATOR,\n freezeAuthority: value.freezeAuthority ?? none(),\n })\n );\n}\n\nexport function getInitializeMint2InstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['decimals', getU8Decoder()],\n ['mintAuthority', getAddressDecoder()],\n ['freezeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMint2InstructionDataCodec(): Codec<\n InitializeMint2InstructionDataArgs,\n InitializeMint2InstructionData\n> {\n return combineCodec(\n getInitializeMint2InstructionDataEncoder(),\n getInitializeMint2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMint2Input = {\n /** The mint to initialize. */\n mint: Address;\n decimals: InitializeMint2InstructionDataArgs['decimals'];\n mintAuthority: InitializeMint2InstructionDataArgs['mintAuthority'];\n freezeAuthority?: InitializeMint2InstructionDataArgs['freezeAuthority'];\n};\n\nexport function getInitializeMint2Instruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMint2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMint2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMint2InstructionDataEncoder().encode(\n args as InitializeMint2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMint2Instruction);\n}\n\nexport type ParsedInitializeMint2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMint2InstructionData;\n};\n\nexport function parseInitializeMint2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMint2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMint2InstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR = 25;\n\nexport function getInitializeMintCloseAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type InitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMintCloseAuthorityInstructionData = {\n discriminator: number;\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: Option
;\n};\n\nexport type InitializeMintCloseAuthorityInstructionDataArgs = {\n /** Authority that must sign the `CloseAccount` instruction on a mint. */\n closeAuthority: OptionOrNullable
;\n};\n\nexport function getInitializeMintCloseAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['closeAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_MINT_CLOSE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['closeAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getInitializeMintCloseAuthorityInstructionDataCodec(): Codec<\n InitializeMintCloseAuthorityInstructionDataArgs,\n InitializeMintCloseAuthorityInstructionData\n> {\n return combineCodec(\n getInitializeMintCloseAuthorityInstructionDataEncoder(),\n getInitializeMintCloseAuthorityInstructionDataDecoder()\n );\n}\n\nexport type InitializeMintCloseAuthorityInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n closeAuthority: InitializeMintCloseAuthorityInstructionDataArgs['closeAuthority'];\n};\n\nexport function getInitializeMintCloseAuthorityInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMintCloseAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMintCloseAuthorityInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeMintCloseAuthorityInstructionDataEncoder().encode(\n args as InitializeMintCloseAuthorityInstructionDataArgs\n ),\n programAddress,\n } as InitializeMintCloseAuthorityInstruction);\n}\n\nexport type ParsedInitializeMintCloseAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeMintCloseAuthorityInstructionData;\n};\n\nexport function parseInitializeMintCloseAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMintCloseAuthorityInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeMintCloseAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG_DISCRIMINATOR = 2;\n\nexport function getInitializeMultisigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG_DISCRIMINATOR);\n}\n\nexport type InitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TAccountRent extends\n | string\n | AccountMeta = 'SysvarRent111111111111111111111111111111111',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n TAccountRent extends string\n ? ReadonlyAccount\n : TAccountRent,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisigInstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisigInstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisigInstructionDataCodec(): FixedSizeCodec<\n InitializeMultisigInstructionDataArgs,\n InitializeMultisigInstructionData\n> {\n return combineCodec(\n getInitializeMultisigInstructionDataEncoder(),\n getInitializeMultisigInstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisigInput<\n TAccountMultisig extends string = string,\n TAccountRent extends string = string,\n> = {\n /** The multisignature account to initialize. */\n multisig: Address;\n /** Rent sysvar. */\n rent?: Address;\n m: InitializeMultisigInstructionDataArgs['m'];\n signers: Array
;\n};\n\nexport function getInitializeMultisigInstruction<\n TAccountMultisig extends string,\n TAccountRent extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n rent: { value: input.rent ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.rent.value) {\n accounts.rent.value =\n 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.multisig),\n getAccountMeta(accounts.rent),\n ...remainingAccounts,\n ],\n data: getInitializeMultisigInstructionDataEncoder().encode(\n args as InitializeMultisigInstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisigInstruction<\n TProgramAddress,\n TAccountMultisig,\n TAccountRent\n >);\n}\n\nexport type ParsedInitializeMultisigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n /** Rent sysvar. */\n rent: TAccountMetas[1];\n };\n data: InitializeMultisigInstructionData;\n};\n\nexport function parseInitializeMultisigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisigInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount(), rent: getNextAccount() },\n data: getInitializeMultisigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_MULTISIG2_DISCRIMINATOR = 19;\n\nexport function getInitializeMultisig2DiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_MULTISIG2_DISCRIMINATOR);\n}\n\nexport type InitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMultisig extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMultisig extends string\n ? WritableAccount\n : TAccountMultisig,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeMultisig2InstructionData = {\n discriminator: number;\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport type InitializeMultisig2InstructionDataArgs = {\n /** The number of signers (M) required to validate this multisignature account. */\n m: number;\n};\n\nexport function getInitializeMultisig2InstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['m', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: INITIALIZE_MULTISIG2_DISCRIMINATOR })\n );\n}\n\nexport function getInitializeMultisig2InstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['m', getU8Decoder()],\n ]);\n}\n\nexport function getInitializeMultisig2InstructionDataCodec(): FixedSizeCodec<\n InitializeMultisig2InstructionDataArgs,\n InitializeMultisig2InstructionData\n> {\n return combineCodec(\n getInitializeMultisig2InstructionDataEncoder(),\n getInitializeMultisig2InstructionDataDecoder()\n );\n}\n\nexport type InitializeMultisig2Input =\n {\n /** The multisignature account to initialize. */\n multisig: Address;\n m: InitializeMultisig2InstructionDataArgs['m'];\n signers: Array
;\n };\n\nexport function getInitializeMultisig2Instruction<\n TAccountMultisig extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeMultisig2Input,\n config?: { programAddress?: TProgramAddress }\n): InitializeMultisig2Instruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n multisig: { value: input.multisig ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = args.signers.map((address) => ({\n address,\n role: AccountRole.READONLY,\n }));\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.multisig), ...remainingAccounts],\n data: getInitializeMultisig2InstructionDataEncoder().encode(\n args as InitializeMultisig2InstructionDataArgs\n ),\n programAddress,\n } as InitializeMultisig2Instruction);\n}\n\nexport type ParsedInitializeMultisig2Instruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The multisignature account to initialize. */\n multisig: TAccountMetas[0];\n };\n data: InitializeMultisig2InstructionData;\n};\n\nexport function parseInitializeMultisig2Instruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeMultisig2Instruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { multisig: getNextAccount() },\n data: getInitializeMultisig2InstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR = 32;\n\nexport function getInitializeNonTransferableMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR);\n}\n\nexport type InitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeNonTransferableMintInstructionData = {\n discriminator: number;\n};\n\nexport type InitializeNonTransferableMintInstructionDataArgs = {};\n\nexport function getInitializeNonTransferableMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_NON_TRANSFERABLE_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeNonTransferableMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getInitializeNonTransferableMintInstructionDataCodec(): FixedSizeCodec<\n InitializeNonTransferableMintInstructionDataArgs,\n InitializeNonTransferableMintInstructionData\n> {\n return combineCodec(\n getInitializeNonTransferableMintInstructionDataEncoder(),\n getInitializeNonTransferableMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeNonTransferableMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint account to initialize. */\n mint: Address;\n};\n\nexport function getInitializeNonTransferableMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeNonTransferableMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeNonTransferableMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeNonTransferableMintInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeNonTransferableMintInstruction);\n}\n\nexport type ParsedInitializeNonTransferableMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeNonTransferableMintInstructionData;\n};\n\nexport function parseInitializeNonTransferableMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeNonTransferableMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeNonTransferableMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR = 44;\n\nexport function getInitializePausableConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR = 0;\n\nexport function getInitializePausableConfigPausableDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR\n );\n}\n\nexport type InitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePausableConfigInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n /** The authority that can pause and resume the mint. */\n authority: Option
;\n};\n\nexport type InitializePausableConfigInstructionDataArgs = {\n /** The authority that can pause and resume the mint. */\n authority: OptionOrNullable
;\n};\n\nexport function getInitializePausableConfigInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PAUSABLE_CONFIG_DISCRIMINATOR,\n pausableDiscriminator: INITIALIZE_PAUSABLE_CONFIG_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePausableConfigInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializePausableConfigInstructionDataCodec(): FixedSizeCodec<\n InitializePausableConfigInstructionDataArgs,\n InitializePausableConfigInstructionData\n> {\n return combineCodec(\n getInitializePausableConfigInstructionDataEncoder(),\n getInitializePausableConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializePausableConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n authority: InitializePausableConfigInstructionDataArgs['authority'];\n};\n\nexport function getInitializePausableConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePausableConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePausableConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePausableConfigInstructionDataEncoder().encode(\n args as InitializePausableConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializePausableConfigInstruction);\n}\n\nexport type ParsedInitializePausableConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n };\n data: InitializePausableConfigInstructionData;\n};\n\nexport function parseInitializePausableConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePausableConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePausableConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR = 35;\n\nexport function getInitializePermanentDelegateDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR);\n}\n\nexport type InitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializePermanentDelegateInstructionData = {\n discriminator: number;\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport type InitializePermanentDelegateInstructionDataArgs = {\n /** Authority that may sign for `Transfer`s and `Burn`s on any account */\n delegate: Address;\n};\n\nexport function getInitializePermanentDelegateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['delegate', getAddressEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_PERMANENT_DELEGATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializePermanentDelegateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['delegate', getAddressDecoder()],\n ]);\n}\n\nexport function getInitializePermanentDelegateInstructionDataCodec(): FixedSizeCodec<\n InitializePermanentDelegateInstructionDataArgs,\n InitializePermanentDelegateInstructionData\n> {\n return combineCodec(\n getInitializePermanentDelegateInstructionDataEncoder(),\n getInitializePermanentDelegateInstructionDataDecoder()\n );\n}\n\nexport type InitializePermanentDelegateInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n delegate: InitializePermanentDelegateInstructionDataArgs['delegate'];\n};\n\nexport function getInitializePermanentDelegateInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializePermanentDelegateInput,\n config?: { programAddress?: TProgramAddress }\n): InitializePermanentDelegateInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializePermanentDelegateInstructionDataEncoder().encode(\n args as InitializePermanentDelegateInstructionDataArgs\n ),\n programAddress,\n } as InitializePermanentDelegateInstruction);\n}\n\nexport type ParsedInitializePermanentDelegateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializePermanentDelegateInstructionData;\n};\n\nexport function parseInitializePermanentDelegateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializePermanentDelegateInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializePermanentDelegateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getF64Decoder,\n getF64Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 43;\n\nexport function getInitializeScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 0;\n\nexport function getInitializeScaledUiAmountMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type InitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeScaledUiAmountMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The authority that can update the multiplier */\n authority: Option
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport type InitializeScaledUiAmountMintInstructionDataArgs = {\n /** The authority that can update the multiplier */\n authority: OptionOrNullable
;\n /** The initial multiplier for the scaled UI extension */\n multiplier: number;\n};\n\nexport function getInitializeScaledUiAmountMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n INITIALIZE_SCALED_UI_AMOUNT_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['multiplier', getF64Decoder()],\n ]);\n}\n\nexport function getInitializeScaledUiAmountMintInstructionDataCodec(): FixedSizeCodec<\n InitializeScaledUiAmountMintInstructionDataArgs,\n InitializeScaledUiAmountMintInstructionData\n> {\n return combineCodec(\n getInitializeScaledUiAmountMintInstructionDataEncoder(),\n getInitializeScaledUiAmountMintInstructionDataDecoder()\n );\n}\n\nexport type InitializeScaledUiAmountMintInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeScaledUiAmountMintInstructionDataArgs['authority'];\n multiplier: InitializeScaledUiAmountMintInstructionDataArgs['multiplier'];\n};\n\nexport function getInitializeScaledUiAmountMintInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeScaledUiAmountMintInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeScaledUiAmountMintInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeScaledUiAmountMintInstructionDataEncoder().encode(\n args as InitializeScaledUiAmountMintInstructionDataArgs\n ),\n programAddress,\n } as InitializeScaledUiAmountMintInstruction);\n}\n\nexport type ParsedInitializeScaledUiAmountMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeScaledUiAmountMintInstructionData;\n};\n\nexport function parseInitializeScaledUiAmountMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeScaledUiAmountMintInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeScaledUiAmountMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_DISCRIMINATOR = new Uint8Array([\n 121, 113, 108, 39, 54, 51, 0, 4,\n]);\n\nexport function getInitializeTokenGroupDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Update authority for the group */\n updateAuthority: Option
;\n /** The maximum number of group members */\n maxSize: bigint;\n};\n\nexport type InitializeTokenGroupInstructionDataArgs = {\n /** Update authority for the group */\n updateAuthority: OptionOrNullable
;\n /** The maximum number of group members */\n maxSize: number | bigint;\n};\n\nexport function getInitializeTokenGroupInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'updateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'updateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTokenGroupInstructionDataCodec(): Codec<\n InitializeTokenGroupInstructionDataArgs,\n InitializeTokenGroupInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupInstructionDataEncoder(),\n getInitializeTokenGroupInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupInput<\n TAccountGroup extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n group: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n updateAuthority: InitializeTokenGroupInstructionDataArgs['updateAuthority'];\n maxSize: InitializeTokenGroupInstructionDataArgs['maxSize'];\n};\n\nexport function getInitializeTokenGroupInstruction<\n TAccountGroup extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupInput<\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenGroupInstructionDataEncoder().encode(\n args as InitializeTokenGroupInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenGroupInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n mint: TAccountMetas[1];\n mintAuthority: TAccountMetas[2];\n };\n data: InitializeTokenGroupInstructionData;\n};\n\nexport function parseInitializeTokenGroupInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n group: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR = new Uint8Array([\n 152, 32, 222, 176, 223, 237, 116, 134,\n]);\n\nexport function getInitializeTokenGroupMemberDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR);\n}\n\nexport type InitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMember extends string | AccountMeta = string,\n TAccountMemberMint extends string | AccountMeta = string,\n TAccountMemberMintAuthority extends string | AccountMeta = string,\n TAccountGroup extends string | AccountMeta = string,\n TAccountGroupUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMember extends string\n ? WritableAccount\n : TAccountMember,\n TAccountMemberMint extends string\n ? ReadonlyAccount\n : TAccountMemberMint,\n TAccountMemberMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMemberMintAuthority,\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountGroupUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenGroupMemberInstructionData = {\n discriminator: ReadonlyUint8Array;\n};\n\nexport type InitializeTokenGroupMemberInstructionDataArgs = {};\n\nexport function getInitializeTokenGroupMemberInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getBytesEncoder()]]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataDecoder(): Decoder {\n return getStructDecoder([['discriminator', getBytesDecoder()]]);\n}\n\nexport function getInitializeTokenGroupMemberInstructionDataCodec(): Codec<\n InitializeTokenGroupMemberInstructionDataArgs,\n InitializeTokenGroupMemberInstructionData\n> {\n return combineCodec(\n getInitializeTokenGroupMemberInstructionDataEncoder(),\n getInitializeTokenGroupMemberInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenGroupMemberInput<\n TAccountMember extends string = string,\n TAccountMemberMint extends string = string,\n TAccountMemberMintAuthority extends string = string,\n TAccountGroup extends string = string,\n TAccountGroupUpdateAuthority extends string = string,\n> = {\n member: Address;\n memberMint: Address;\n memberMintAuthority: TransactionSigner;\n group: Address;\n groupUpdateAuthority: TransactionSigner;\n};\n\nexport function getInitializeTokenGroupMemberInstruction<\n TAccountMember extends string,\n TAccountMemberMint extends string,\n TAccountMemberMintAuthority extends string,\n TAccountGroup extends string,\n TAccountGroupUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenGroupMemberInput<\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n member: { value: input.member ?? null, isWritable: true },\n memberMint: { value: input.memberMint ?? null, isWritable: false },\n memberMintAuthority: {\n value: input.memberMintAuthority ?? null,\n isWritable: false,\n },\n group: { value: input.group ?? null, isWritable: true },\n groupUpdateAuthority: {\n value: input.groupUpdateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.member),\n getAccountMeta(accounts.memberMint),\n getAccountMeta(accounts.memberMintAuthority),\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.groupUpdateAuthority),\n ],\n data: getInitializeTokenGroupMemberInstructionDataEncoder().encode({}),\n programAddress,\n } as InitializeTokenGroupMemberInstruction<\n TProgramAddress,\n TAccountMember,\n TAccountMemberMint,\n TAccountMemberMintAuthority,\n TAccountGroup,\n TAccountGroupUpdateAuthority\n >);\n}\n\nexport type ParsedInitializeTokenGroupMemberInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n member: TAccountMetas[0];\n memberMint: TAccountMetas[1];\n memberMintAuthority: TAccountMetas[2];\n group: TAccountMetas[3];\n groupUpdateAuthority: TAccountMetas[4];\n };\n data: InitializeTokenGroupMemberInstructionData;\n};\n\nexport function parseInitializeTokenGroupMemberInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenGroupMemberInstruction {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n member: getNextAccount(),\n memberMint: getNextAccount(),\n memberMintAuthority: getNextAccount(),\n group: getNextAccount(),\n groupUpdateAuthority: getNextAccount(),\n },\n data: getInitializeTokenGroupMemberInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([\n 210, 225, 30, 162, 88, 184, 77, 141,\n]);\n\nexport function getInitializeTokenMetadataDiscriminatorBytes() {\n return getBytesEncoder().encode(INITIALIZE_TOKEN_METADATA_DISCRIMINATOR);\n}\n\nexport type InitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlyAccount\n : TAccountUpdateAuthority,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountMintAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTokenMetadataInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport type InitializeTokenMetadataInstructionDataArgs = {\n /** Longer name of the token. */\n name: string;\n /** Shortened symbol of the token. */\n symbol: string;\n /** URI pointing to more metadata (image, video, etc.). */\n uri: string;\n};\n\nexport function getInitializeTokenMetadataInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['symbol', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['uri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TOKEN_METADATA_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTokenMetadataInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['symbol', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['uri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getInitializeTokenMetadataInstructionDataCodec(): Codec<\n InitializeTokenMetadataInstructionDataArgs,\n InitializeTokenMetadataInstructionData\n> {\n return combineCodec(\n getInitializeTokenMetadataInstructionDataEncoder(),\n getInitializeTokenMetadataInstructionDataDecoder()\n );\n}\n\nexport type InitializeTokenMetadataInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n TAccountMint extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: Address;\n mint: Address;\n mintAuthority: TransactionSigner;\n name: InitializeTokenMetadataInstructionDataArgs['name'];\n symbol: InitializeTokenMetadataInstructionDataArgs['symbol'];\n uri: InitializeTokenMetadataInstructionDataArgs['uri'];\n};\n\nexport function getInitializeTokenMetadataInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TAccountMint extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTokenMetadataInput<\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n mint: { value: input.mint ?? null, isWritable: false },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.mintAuthority),\n ],\n data: getInitializeTokenMetadataInstructionDataEncoder().encode(\n args as InitializeTokenMetadataInstructionDataArgs\n ),\n programAddress,\n } as InitializeTokenMetadataInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority,\n TAccountMint,\n TAccountMintAuthority\n >);\n}\n\nexport type ParsedInitializeTokenMetadataInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n mint: TAccountMetas[2];\n mintAuthority: TAccountMetas[3];\n };\n data: InitializeTokenMetadataInstructionData;\n};\n\nexport function parseInitializeTokenMetadataInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTokenMetadataInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n metadata: getNextAccount(),\n updateAuthority: getNextAccount(),\n mint: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getInitializeTokenMetadataInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR = 26;\n\nexport function getInitializeTransferFeeConfigDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferFeeConfigTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferFeeConfigInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: Option
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: Option
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type InitializeTransferFeeConfigInstructionDataArgs = {\n /** Pubkey that may update the fees. */\n transferFeeConfigAuthority: OptionOrNullable
;\n /** Withdraw instructions must be signed by this key. */\n withdrawWithheldAuthority: OptionOrNullable
;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getInitializeTransferFeeConfigInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeConfigAuthority', getOptionEncoder(getAddressEncoder())],\n ['withdrawWithheldAuthority', getOptionEncoder(getAddressEncoder())],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_FEE_CONFIG_DISCRIMINATOR,\n transferFeeDiscriminator:\n INITIALIZE_TRANSFER_FEE_CONFIG_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeConfigAuthority', getOptionDecoder(getAddressDecoder())],\n ['withdrawWithheldAuthority', getOptionDecoder(getAddressDecoder())],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getInitializeTransferFeeConfigInstructionDataCodec(): Codec<\n InitializeTransferFeeConfigInstructionDataArgs,\n InitializeTransferFeeConfigInstructionData\n> {\n return combineCodec(\n getInitializeTransferFeeConfigInstructionDataEncoder(),\n getInitializeTransferFeeConfigInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferFeeConfigInput<\n TAccountMint extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n transferFeeConfigAuthority: InitializeTransferFeeConfigInstructionDataArgs['transferFeeConfigAuthority'];\n withdrawWithheldAuthority: InitializeTransferFeeConfigInstructionDataArgs['withdrawWithheldAuthority'];\n transferFeeBasisPoints: InitializeTransferFeeConfigInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: InitializeTransferFeeConfigInstructionDataArgs['maximumFee'];\n};\n\nexport function getInitializeTransferFeeConfigInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferFeeConfigInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferFeeConfigInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferFeeConfigInstructionDataEncoder().encode(\n args as InitializeTransferFeeConfigInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferFeeConfigInstruction);\n}\n\nexport type ParsedInitializeTransferFeeConfigInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferFeeConfigInstructionData;\n};\n\nexport function parseInitializeTransferFeeConfigInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferFeeConfigInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferFeeConfigInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getInitializeTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 0;\n\nexport function getInitializeTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type InitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type InitializeTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The public key for the account that can update the program id */\n authority: Option
;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type InitializeTransferHookInstructionDataArgs = {\n /** The public key for the account that can update the program id */\n authority: OptionOrNullable
;\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getInitializeTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'authority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: INITIALIZE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n INITIALIZE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getInitializeTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'authority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getInitializeTransferHookInstructionDataCodec(): FixedSizeCodec<\n InitializeTransferHookInstructionDataArgs,\n InitializeTransferHookInstructionData\n> {\n return combineCodec(\n getInitializeTransferHookInstructionDataEncoder(),\n getInitializeTransferHookInstructionDataDecoder()\n );\n}\n\nexport type InitializeTransferHookInput =\n {\n /** The mint to initialize. */\n mint: Address;\n authority: InitializeTransferHookInstructionDataArgs['authority'];\n programId: InitializeTransferHookInstructionDataArgs['programId'];\n };\n\nexport function getInitializeTransferHookInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: InitializeTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): InitializeTransferHookInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getInitializeTransferHookInstructionDataEncoder().encode(\n args as InitializeTransferHookInstructionDataArgs\n ),\n programAddress,\n } as InitializeTransferHookInstruction);\n}\n\nexport type ParsedInitializeTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n };\n data: InitializeTransferHookInstructionData;\n};\n\nexport function parseInitializeTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedInitializeTransferHookInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getInitializeTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_DISCRIMINATOR = 7;\n\nexport function getMintToDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_DISCRIMINATOR);\n}\n\nexport type MintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n};\n\nexport type MintToInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n};\n\nexport function getMintToInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_DISCRIMINATOR })\n );\n}\n\nexport function getMintToInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getMintToInstructionDataCodec(): FixedSizeCodec<\n MintToInstructionDataArgs,\n MintToInstructionData\n> {\n return combineCodec(\n getMintToInstructionDataEncoder(),\n getMintToInstructionDataDecoder()\n );\n}\n\nexport type MintToInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint account. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getMintToInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToInput,\n config?: { programAddress?: TProgramAddress }\n): MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToInstructionDataEncoder().encode(\n args as MintToInstructionDataArgs\n ),\n programAddress,\n } as MintToInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint account. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToInstructionData;\n};\n\nexport function parseMintToInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const MINT_TO_CHECKED_DISCRIMINATOR = 14;\n\nexport function getMintToCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(MINT_TO_CHECKED_DISCRIMINATOR);\n}\n\nexport type MintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountToken extends string | AccountMeta = string,\n TAccountMintAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountMintAuthority extends string\n ? ReadonlyAccount\n : TAccountMintAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type MintToCheckedInstructionData = {\n discriminator: number;\n /** The amount of new tokens to mint. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type MintToCheckedInstructionDataArgs = {\n /** The amount of new tokens to mint. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getMintToCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: MINT_TO_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getMintToCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getMintToCheckedInstructionDataCodec(): FixedSizeCodec<\n MintToCheckedInstructionDataArgs,\n MintToCheckedInstructionData\n> {\n return combineCodec(\n getMintToCheckedInstructionDataEncoder(),\n getMintToCheckedInstructionDataDecoder()\n );\n}\n\nexport type MintToCheckedInput<\n TAccountMint extends string = string,\n TAccountToken extends string = string,\n TAccountMintAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The account to mint tokens to. */\n token: Address;\n /** The mint's minting authority or its multisignature account. */\n mintAuthority:\n | Address\n | TransactionSigner;\n amount: MintToCheckedInstructionDataArgs['amount'];\n decimals: MintToCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getMintToCheckedInstruction<\n TAccountMint extends string,\n TAccountToken extends string,\n TAccountMintAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: MintToCheckedInput,\n config?: { programAddress?: TProgramAddress }\n): MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n token: { value: input.token ?? null, isWritable: true },\n mintAuthority: { value: input.mintAuthority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.mintAuthority),\n ...remainingAccounts,\n ],\n data: getMintToCheckedInstructionDataEncoder().encode(\n args as MintToCheckedInstructionDataArgs\n ),\n programAddress,\n } as MintToCheckedInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountToken,\n (typeof input)['mintAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMintAuthority\n >);\n}\n\nexport type ParsedMintToCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The account to mint tokens to. */\n token: TAccountMetas[1];\n /** The mint's minting authority or its multisignature account. */\n mintAuthority: TAccountMetas[2];\n };\n data: MintToCheckedInstructionData;\n};\n\nexport function parseMintToCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedMintToCheckedInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n token: getNextAccount(),\n mintAuthority: getNextAccount(),\n },\n data: getMintToCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const PAUSE_DISCRIMINATOR = 44;\n\nexport function getPauseDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_DISCRIMINATOR);\n}\n\nexport const PAUSE_PAUSABLE_DISCRIMINATOR = 1;\n\nexport function getPausePausableDiscriminatorBytes() {\n return getU8Encoder().encode(PAUSE_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type PauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type PauseInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type PauseInstructionDataArgs = {};\n\nexport function getPauseInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: PAUSE_DISCRIMINATOR,\n pausableDiscriminator: PAUSE_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getPauseInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getPauseInstructionDataCodec(): FixedSizeCodec<\n PauseInstructionDataArgs,\n PauseInstructionData\n> {\n return combineCodec(\n getPauseInstructionDataEncoder(),\n getPauseInstructionDataDecoder()\n );\n}\n\nexport type PauseInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can pause the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getPauseInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: PauseInput,\n config?: { programAddress?: TProgramAddress }\n): PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getPauseInstructionDataEncoder().encode({}),\n programAddress,\n } as PauseInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedPauseInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can pause the mint. */\n authority: TAccountMetas[1];\n };\n data: PauseInstructionData;\n};\n\nexport function parsePauseInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedPauseInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getPauseInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getExtensionTypeDecoder,\n getExtensionTypeEncoder,\n type ExtensionType,\n type ExtensionTypeArgs,\n} from '../types';\n\nexport const REALLOCATE_DISCRIMINATOR = 29;\n\nexport function getReallocateDiscriminatorBytes() {\n return getU8Encoder().encode(REALLOCATE_DISCRIMINATOR);\n}\n\nexport type ReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountToken extends string | AccountMeta = string,\n TAccountPayer extends string | AccountMeta = string,\n TAccountSystemProgram extends\n | string\n | AccountMeta = '11111111111111111111111111111111',\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountToken extends string\n ? WritableAccount\n : TAccountToken,\n TAccountPayer extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountPayer,\n TAccountSystemProgram extends string\n ? ReadonlyAccount\n : TAccountSystemProgram,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ReallocateInstructionData = {\n discriminator: number;\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport type ReallocateInstructionDataArgs = {\n /** New extension types to include in the reallocated account. */\n newExtensionTypes: Array;\n};\n\nexport function getReallocateInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n [\n 'newExtensionTypes',\n getArrayEncoder(getExtensionTypeEncoder(), { size: 'remainder' }),\n ],\n ]),\n (value) => ({ ...value, discriminator: REALLOCATE_DISCRIMINATOR })\n );\n}\n\nexport function getReallocateInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n [\n 'newExtensionTypes',\n getArrayDecoder(getExtensionTypeDecoder(), { size: 'remainder' }),\n ],\n ]);\n}\n\nexport function getReallocateInstructionDataCodec(): Codec<\n ReallocateInstructionDataArgs,\n ReallocateInstructionData\n> {\n return combineCodec(\n getReallocateInstructionDataEncoder(),\n getReallocateInstructionDataDecoder()\n );\n}\n\nexport type ReallocateInput<\n TAccountToken extends string = string,\n TAccountPayer extends string = string,\n TAccountSystemProgram extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The token account to reallocate. */\n token: Address;\n /** The payer account to fund reallocation. */\n payer: TransactionSigner;\n /** System program for reallocation funding. */\n systemProgram?: Address;\n /** The account's owner or its multisignature account. */\n owner: Address | TransactionSigner;\n newExtensionTypes: ReallocateInstructionDataArgs['newExtensionTypes'];\n multiSigners?: Array;\n};\n\nexport function getReallocateInstruction<\n TAccountToken extends string,\n TAccountPayer extends string,\n TAccountSystemProgram extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ReallocateInput<\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n TAccountOwner\n >,\n config?: { programAddress?: TProgramAddress }\n): ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n token: { value: input.token ?? null, isWritable: true },\n payer: { value: input.payer ?? null, isWritable: true },\n systemProgram: { value: input.systemProgram ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Resolve default values.\n if (!accounts.systemProgram.value) {\n accounts.systemProgram.value =\n '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>;\n }\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.token),\n getAccountMeta(accounts.payer),\n getAccountMeta(accounts.systemProgram),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getReallocateInstructionDataEncoder().encode(\n args as ReallocateInstructionDataArgs\n ),\n programAddress,\n } as ReallocateInstruction<\n TProgramAddress,\n TAccountToken,\n TAccountPayer,\n TAccountSystemProgram,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedReallocateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token account to reallocate. */\n token: TAccountMetas[0];\n /** The payer account to fund reallocation. */\n payer: TAccountMetas[1];\n /** System program for reallocation funding. */\n systemProgram: TAccountMetas[2];\n /** The account's owner or its multisignature account. */\n owner: TAccountMetas[3];\n };\n data: ReallocateInstructionData;\n};\n\nexport function parseReallocateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedReallocateInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n token: getNextAccount(),\n payer: getNextAccount(),\n systemProgram: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getReallocateInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { findAssociatedTokenPda } from '../pdas';\nimport { ASSOCIATED_TOKEN_PROGRAM_ADDRESS } from '../programs';\nimport {\n expectAddress,\n getAccountMetaFactory,\n type ResolvedAccount,\n} from '../shared';\n\nexport const RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR = 2;\n\nexport function getRecoverNestedAssociatedTokenDiscriminatorBytes() {\n return getU8Encoder().encode(RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR);\n}\n\nexport type RecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountNestedAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountNestedTokenMintAddress extends string | AccountMeta = string,\n TAccountDestinationAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerAssociatedAccountAddress extends\n | string\n | AccountMeta = string,\n TAccountOwnerTokenMintAddress extends string | AccountMeta = string,\n TAccountWalletAddress extends string | AccountMeta = string,\n TAccountTokenProgram extends\n | string\n | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountNestedAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress extends string\n ? WritableAccount\n : TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress extends string\n ? ReadonlyAccount\n : TAccountOwnerTokenMintAddress,\n TAccountWalletAddress extends string\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountWalletAddress,\n TAccountTokenProgram extends string\n ? ReadonlyAccount\n : TAccountTokenProgram,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RecoverNestedAssociatedTokenInstructionData = {\n discriminator: number;\n};\n\nexport type RecoverNestedAssociatedTokenInstructionDataArgs = {};\n\nexport function getRecoverNestedAssociatedTokenInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: RECOVER_NESTED_ASSOCIATED_TOKEN_DISCRIMINATOR,\n })\n );\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRecoverNestedAssociatedTokenInstructionDataCodec(): FixedSizeCodec<\n RecoverNestedAssociatedTokenInstructionDataArgs,\n RecoverNestedAssociatedTokenInstructionData\n> {\n return combineCodec(\n getRecoverNestedAssociatedTokenInstructionDataEncoder(),\n getRecoverNestedAssociatedTokenInstructionDataDecoder()\n );\n}\n\nexport type RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress?: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress?: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress?: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport async function getRecoverNestedAssociatedTokenInstructionAsync<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenAsyncInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): Promise<\n RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n if (!accounts.ownerAssociatedAccountAddress.value) {\n accounts.ownerAssociatedAccountAddress.value = await findAssociatedTokenPda(\n {\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.ownerTokenMintAddress.value),\n }\n );\n }\n if (!accounts.nestedAssociatedAccountAddress.value) {\n accounts.nestedAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.ownerAssociatedAccountAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n if (!accounts.destinationAssociatedAccountAddress.value) {\n accounts.destinationAssociatedAccountAddress.value =\n await findAssociatedTokenPda({\n owner: expectAddress(accounts.walletAddress.value),\n tokenProgram: expectAddress(accounts.tokenProgram.value),\n mint: expectAddress(accounts.nestedTokenMintAddress.value),\n });\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress extends string = string,\n TAccountNestedTokenMintAddress extends string = string,\n TAccountDestinationAssociatedAccountAddress extends string = string,\n TAccountOwnerAssociatedAccountAddress extends string = string,\n TAccountOwnerTokenMintAddress extends string = string,\n TAccountWalletAddress extends string = string,\n TAccountTokenProgram extends string = string,\n> = {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: Address;\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: Address;\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: Address;\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: Address;\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: Address;\n /** Wallet address for the owner associated token account. */\n walletAddress: TransactionSigner;\n /** SPL Token program. */\n tokenProgram?: Address;\n};\n\nexport function getRecoverNestedAssociatedTokenInstruction<\n TAccountNestedAssociatedAccountAddress extends string,\n TAccountNestedTokenMintAddress extends string,\n TAccountDestinationAssociatedAccountAddress extends string,\n TAccountOwnerAssociatedAccountAddress extends string,\n TAccountOwnerTokenMintAddress extends string,\n TAccountWalletAddress extends string,\n TAccountTokenProgram extends string,\n TProgramAddress extends Address = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n>(\n input: RecoverNestedAssociatedTokenInput<\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >,\n config?: { programAddress?: TProgramAddress }\n): RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n> {\n // Program address.\n const programAddress =\n config?.programAddress ?? ASSOCIATED_TOKEN_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n nestedAssociatedAccountAddress: {\n value: input.nestedAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n nestedTokenMintAddress: {\n value: input.nestedTokenMintAddress ?? null,\n isWritable: false,\n },\n destinationAssociatedAccountAddress: {\n value: input.destinationAssociatedAccountAddress ?? null,\n isWritable: true,\n },\n ownerAssociatedAccountAddress: {\n value: input.ownerAssociatedAccountAddress ?? null,\n isWritable: false,\n },\n ownerTokenMintAddress: {\n value: input.ownerTokenMintAddress ?? null,\n isWritable: false,\n },\n walletAddress: { value: input.walletAddress ?? null, isWritable: true },\n tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Resolve default values.\n if (!accounts.tokenProgram.value) {\n accounts.tokenProgram.value =\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>;\n }\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.nestedAssociatedAccountAddress),\n getAccountMeta(accounts.nestedTokenMintAddress),\n getAccountMeta(accounts.destinationAssociatedAccountAddress),\n getAccountMeta(accounts.ownerAssociatedAccountAddress),\n getAccountMeta(accounts.ownerTokenMintAddress),\n getAccountMeta(accounts.walletAddress),\n getAccountMeta(accounts.tokenProgram),\n ],\n data: getRecoverNestedAssociatedTokenInstructionDataEncoder().encode({}),\n programAddress,\n } as RecoverNestedAssociatedTokenInstruction<\n TProgramAddress,\n TAccountNestedAssociatedAccountAddress,\n TAccountNestedTokenMintAddress,\n TAccountDestinationAssociatedAccountAddress,\n TAccountOwnerAssociatedAccountAddress,\n TAccountOwnerTokenMintAddress,\n TAccountWalletAddress,\n TAccountTokenProgram\n >);\n}\n\nexport type ParsedRecoverNestedAssociatedTokenInstruction<\n TProgram extends string = typeof ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Nested associated token account, must be owned by `ownerAssociatedAccountAddress`. */\n nestedAssociatedAccountAddress: TAccountMetas[0];\n /** Token mint for the nested associated token account. */\n nestedTokenMintAddress: TAccountMetas[1];\n /** Wallet's associated token account. */\n destinationAssociatedAccountAddress: TAccountMetas[2];\n /** Owner associated token account address, must be owned by `walletAddress`. */\n ownerAssociatedAccountAddress: TAccountMetas[3];\n /** Token mint for the owner associated token account. */\n ownerTokenMintAddress: TAccountMetas[4];\n /** Wallet address for the owner associated token account. */\n walletAddress: TAccountMetas[5];\n /** SPL Token program. */\n tokenProgram: TAccountMetas[6];\n };\n data: RecoverNestedAssociatedTokenInstructionData;\n};\n\nexport function parseRecoverNestedAssociatedTokenInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRecoverNestedAssociatedTokenInstruction {\n if (instruction.accounts.length < 7) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n nestedAssociatedAccountAddress: getNextAccount(),\n nestedTokenMintAddress: getNextAccount(),\n destinationAssociatedAccountAddress: getNextAccount(),\n ownerAssociatedAccountAddress: getNextAccount(),\n ownerTokenMintAddress: getNextAccount(),\n walletAddress: getNextAccount(),\n tokenProgram: getNextAccount(),\n },\n data: getRecoverNestedAssociatedTokenInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR = new Uint8Array([\n 234, 18, 32, 56, 89, 141, 37, 181,\n]);\n\nexport function getRemoveTokenMetadataKeyDiscriminatorBytes() {\n return getBytesEncoder().encode(REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR);\n}\n\nexport type RemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RemoveTokenMetadataKeyInstructionData = {\n discriminator: ReadonlyUint8Array;\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport type RemoveTokenMetadataKeyInstructionDataArgs = {\n /**\n * If the idempotent flag is set to true, then the instruction will not\n * error if the key does not exist\n */\n idempotent?: boolean;\n /** Key to remove in the additional metadata portion. */\n key: string;\n};\n\nexport function getRemoveTokenMetadataKeyInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['idempotent', getBooleanEncoder()],\n ['key', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR,\n idempotent: value.idempotent ?? false,\n })\n );\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['idempotent', getBooleanDecoder()],\n ['key', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getRemoveTokenMetadataKeyInstructionDataCodec(): Codec<\n RemoveTokenMetadataKeyInstructionDataArgs,\n RemoveTokenMetadataKeyInstructionData\n> {\n return combineCodec(\n getRemoveTokenMetadataKeyInstructionDataEncoder(),\n getRemoveTokenMetadataKeyInstructionDataDecoder()\n );\n}\n\nexport type RemoveTokenMetadataKeyInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n idempotent?: RemoveTokenMetadataKeyInstructionDataArgs['idempotent'];\n key: RemoveTokenMetadataKeyInstructionDataArgs['key'];\n};\n\nexport function getRemoveTokenMetadataKeyInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RemoveTokenMetadataKeyInput,\n config?: { programAddress?: TProgramAddress }\n): RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getRemoveTokenMetadataKeyInstructionDataEncoder().encode(\n args as RemoveTokenMetadataKeyInstructionDataArgs\n ),\n programAddress,\n } as RemoveTokenMetadataKeyInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedRemoveTokenMetadataKeyInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: RemoveTokenMetadataKeyInstructionData;\n};\n\nexport function parseRemoveTokenMetadataKeyInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRemoveTokenMetadataKeyInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getRemoveTokenMetadataKeyInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const RESUME_DISCRIMINATOR = 44;\n\nexport function getResumeDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_DISCRIMINATOR);\n}\n\nexport const RESUME_PAUSABLE_DISCRIMINATOR = 2;\n\nexport function getResumePausableDiscriminatorBytes() {\n return getU8Encoder().encode(RESUME_PAUSABLE_DISCRIMINATOR);\n}\n\nexport type ResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ResumeInstructionData = {\n discriminator: number;\n pausableDiscriminator: number;\n};\n\nexport type ResumeInstructionDataArgs = {};\n\nexport function getResumeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['pausableDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: RESUME_DISCRIMINATOR,\n pausableDiscriminator: RESUME_PAUSABLE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getResumeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['pausableDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getResumeInstructionDataCodec(): FixedSizeCodec<\n ResumeInstructionDataArgs,\n ResumeInstructionData\n> {\n return combineCodec(\n getResumeInstructionDataEncoder(),\n getResumeInstructionDataDecoder()\n );\n}\n\nexport type ResumeInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The pausable authority that can resume the mint. */\n authority: Address | TransactionSigner;\n};\n\nexport function getResumeInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ResumeInput,\n config?: { programAddress?: TProgramAddress }\n): ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getResumeInstructionDataEncoder().encode({}),\n programAddress,\n } as ResumeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedResumeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The pausable authority that can resume the mint. */\n authority: TAccountMetas[1];\n };\n data: ResumeInstructionData;\n};\n\nexport function parseResumeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedResumeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getResumeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const REVOKE_DISCRIMINATOR = 5;\n\nexport function getRevokeDiscriminatorBytes() {\n return getU8Encoder().encode(REVOKE_DISCRIMINATOR);\n}\n\nexport type RevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RevokeInstructionData = { discriminator: number };\n\nexport type RevokeInstructionDataArgs = {};\n\nexport function getRevokeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })\n );\n}\n\nexport function getRevokeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getRevokeInstructionDataCodec(): FixedSizeCodec<\n RevokeInstructionDataArgs,\n RevokeInstructionData\n> {\n return combineCodec(\n getRevokeInstructionDataEncoder(),\n getRevokeInstructionDataDecoder()\n );\n}\n\nexport type RevokeInput<\n TAccountSource extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The source account owner or its multisignature. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getRevokeInstruction<\n TAccountSource extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: RevokeInput,\n config?: { programAddress?: TProgramAddress }\n): RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getRevokeInstructionDataEncoder().encode({}),\n programAddress,\n } as RevokeInstruction<\n TProgramAddress,\n TAccountSource,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedRevokeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The source account owner or its multisignature. */\n owner: TAccountMetas[1];\n };\n data: RevokeInstructionData;\n};\n\nexport function parseRevokeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedRevokeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { source: getNextAccount(), owner: getNextAccount() },\n data: getRevokeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAuthorityTypeDecoder,\n getAuthorityTypeEncoder,\n type AuthorityType,\n type AuthorityTypeArgs,\n} from '../types';\n\nexport const SET_AUTHORITY_DISCRIMINATOR = 6;\n\nexport function getSetAuthorityDiscriminatorBytes() {\n return getU8Encoder().encode(SET_AUTHORITY_DISCRIMINATOR);\n}\n\nexport type SetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountOwned extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountOwned extends string\n ? WritableAccount\n : TAccountOwned,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetAuthorityInstructionData = {\n discriminator: number;\n /** The type of authority to update. */\n authorityType: AuthorityType;\n /** The new authority */\n newAuthority: Option
;\n};\n\nexport type SetAuthorityInstructionDataArgs = {\n /** The type of authority to update. */\n authorityType: AuthorityTypeArgs;\n /** The new authority */\n newAuthority: OptionOrNullable
;\n};\n\nexport function getSetAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['authorityType', getAuthorityTypeEncoder()],\n ['newAuthority', getOptionEncoder(getAddressEncoder())],\n ]),\n (value) => ({ ...value, discriminator: SET_AUTHORITY_DISCRIMINATOR })\n );\n}\n\nexport function getSetAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['authorityType', getAuthorityTypeDecoder()],\n ['newAuthority', getOptionDecoder(getAddressDecoder())],\n ]);\n}\n\nexport function getSetAuthorityInstructionDataCodec(): Codec<\n SetAuthorityInstructionDataArgs,\n SetAuthorityInstructionData\n> {\n return combineCodec(\n getSetAuthorityInstructionDataEncoder(),\n getSetAuthorityInstructionDataDecoder()\n );\n}\n\nexport type SetAuthorityInput<\n TAccountOwned extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The mint or account to change the authority of. */\n owned: Address;\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: Address | TransactionSigner;\n authorityType: SetAuthorityInstructionDataArgs['authorityType'];\n newAuthority: SetAuthorityInstructionDataArgs['newAuthority'];\n multiSigners?: Array;\n};\n\nexport function getSetAuthorityInstruction<\n TAccountOwned extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetAuthorityInput,\n config?: { programAddress?: TProgramAddress }\n): SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n owned: { value: input.owned ?? null, isWritable: true },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.owned),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getSetAuthorityInstructionDataEncoder().encode(\n args as SetAuthorityInstructionDataArgs\n ),\n programAddress,\n } as SetAuthorityInstruction<\n TProgramAddress,\n TAccountOwned,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedSetAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint or account to change the authority of. */\n owned: TAccountMetas[0];\n /** The current authority or the multisignature account of the mint or account to update. */\n owner: TAccountMetas[1];\n };\n data: SetAuthorityInstructionData;\n};\n\nexport function parseSetAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { owned: getNextAccount(), owner: getNextAccount() },\n data: getSetAuthorityInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SET_TRANSFER_FEE_DISCRIMINATOR = 26;\n\nexport function getSetTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport const SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR = 5;\n\nexport function getSetTransferFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR);\n}\n\nexport type SetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountTransferFeeConfigAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountTransferFeeConfigAuthority extends string\n ? ReadonlyAccount\n : TAccountTransferFeeConfigAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SetTransferFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: bigint;\n};\n\nexport type SetTransferFeeInstructionDataArgs = {\n /** Amount of transfer collected as fees, expressed as basis points of the transfer amount. */\n transferFeeBasisPoints: number;\n /** Maximum fee assessed on transfers. */\n maximumFee: number | bigint;\n};\n\nexport function getSetTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['transferFeeBasisPoints', getU16Encoder()],\n ['maximumFee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_TRANSFER_FEE_DISCRIMINATOR,\n transferFeeDiscriminator: SET_TRANSFER_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['transferFeeBasisPoints', getU16Decoder()],\n ['maximumFee', getU64Decoder()],\n ]);\n}\n\nexport function getSetTransferFeeInstructionDataCodec(): FixedSizeCodec<\n SetTransferFeeInstructionDataArgs,\n SetTransferFeeInstructionData\n> {\n return combineCodec(\n getSetTransferFeeInstructionDataEncoder(),\n getSetTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type SetTransferFeeInput<\n TAccountMint extends string = string,\n TAccountTransferFeeConfigAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority:\n | Address\n | TransactionSigner;\n transferFeeBasisPoints: SetTransferFeeInstructionDataArgs['transferFeeBasisPoints'];\n maximumFee: SetTransferFeeInstructionDataArgs['maximumFee'];\n multiSigners?: Array;\n};\n\nexport function getSetTransferFeeInstruction<\n TAccountMint extends string,\n TAccountTransferFeeConfigAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SetTransferFeeInput,\n config?: { programAddress?: TProgramAddress }\n): SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n transferFeeConfigAuthority: {\n value: input.transferFeeConfigAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.transferFeeConfigAuthority),\n ...remainingAccounts,\n ],\n data: getSetTransferFeeInstructionDataEncoder().encode(\n args as SetTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as SetTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['transferFeeConfigAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountTransferFeeConfigAuthority\n >);\n}\n\nexport type ParsedSetTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint's fee account owner or its multisignature account. */\n transferFeeConfigAuthority: TAccountMetas[1];\n };\n data: SetTransferFeeInstructionData;\n};\n\nexport function parseSetTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSetTransferFeeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n transferFeeConfigAuthority: getNextAccount(),\n },\n data: getSetTransferFeeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const SYNC_NATIVE_DISCRIMINATOR = 17;\n\nexport function getSyncNativeDiscriminatorBytes() {\n return getU8Encoder().encode(SYNC_NATIVE_DISCRIMINATOR);\n}\n\nexport type SyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type SyncNativeInstructionData = { discriminator: number };\n\nexport type SyncNativeInstructionDataArgs = {};\n\nexport function getSyncNativeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: SYNC_NATIVE_DISCRIMINATOR })\n );\n}\n\nexport function getSyncNativeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getSyncNativeInstructionDataCodec(): FixedSizeCodec<\n SyncNativeInstructionDataArgs,\n SyncNativeInstructionData\n> {\n return combineCodec(\n getSyncNativeInstructionDataEncoder(),\n getSyncNativeInstructionDataDecoder()\n );\n}\n\nexport type SyncNativeInput = {\n /** The native token account to sync with its underlying lamports. */\n account: Address;\n};\n\nexport function getSyncNativeInstruction<\n TAccountAccount extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: SyncNativeInput,\n config?: { programAddress?: TProgramAddress }\n): SyncNativeInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.account)],\n data: getSyncNativeInstructionDataEncoder().encode({}),\n programAddress,\n } as SyncNativeInstruction);\n}\n\nexport type ParsedSyncNativeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The native token account to sync with its underlying lamports. */\n account: TAccountMetas[0];\n };\n data: SyncNativeInstructionData;\n};\n\nexport function parseSyncNativeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedSyncNativeInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { account: getNextAccount() },\n data: getSyncNativeInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const THAW_ACCOUNT_DISCRIMINATOR = 11;\n\nexport function getThawAccountDiscriminatorBytes() {\n return getU8Encoder().encode(THAW_ACCOUNT_DISCRIMINATOR);\n}\n\nexport type ThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountAccount extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountOwner extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountAccount extends string\n ? WritableAccount\n : TAccountAccount,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountOwner extends string\n ? ReadonlyAccount\n : TAccountOwner,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type ThawAccountInstructionData = { discriminator: number };\n\nexport type ThawAccountInstructionDataArgs = {};\n\nexport function getThawAccountInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({ ...value, discriminator: THAW_ACCOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getThawAccountInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getThawAccountInstructionDataCodec(): FixedSizeCodec<\n ThawAccountInstructionDataArgs,\n ThawAccountInstructionData\n> {\n return combineCodec(\n getThawAccountInstructionDataEncoder(),\n getThawAccountInstructionDataDecoder()\n );\n}\n\nexport type ThawAccountInput<\n TAccountAccount extends string = string,\n TAccountMint extends string = string,\n TAccountOwner extends string = string,\n> = {\n /** The account to thaw. */\n account: Address;\n /** The token mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n owner: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getThawAccountInstruction<\n TAccountAccount extends string,\n TAccountMint extends string,\n TAccountOwner extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: ThawAccountInput,\n config?: { programAddress?: TProgramAddress }\n): ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n account: { value: input.account ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n owner: { value: input.owner ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.account),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.owner),\n ...remainingAccounts,\n ],\n data: getThawAccountInstructionDataEncoder().encode({}),\n programAddress,\n } as ThawAccountInstruction<\n TProgramAddress,\n TAccountAccount,\n TAccountMint,\n (typeof input)['owner'] extends TransactionSigner\n ? ReadonlySignerAccount & AccountSignerMeta\n : TAccountOwner\n >);\n}\n\nexport type ParsedThawAccountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The account to thaw. */\n account: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The mint freeze authority or its multisignature account. */\n owner: TAccountMetas[2];\n };\n data: ThawAccountInstructionData;\n};\n\nexport function parseThawAccountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedThawAccountInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n account: getNextAccount(),\n mint: getNextAccount(),\n owner: getNextAccount(),\n },\n data: getThawAccountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_DISCRIMINATOR = 3;\n\nexport function getTransferDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_DISCRIMINATOR);\n}\n\nexport type TransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n};\n\nexport type TransferInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n};\n\nexport function getTransferInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_DISCRIMINATOR })\n );\n}\n\nexport function getTransferInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ]);\n}\n\nexport function getTransferInstructionDataCodec(): FixedSizeCodec<\n TransferInstructionDataArgs,\n TransferInstructionData\n> {\n return combineCodec(\n getTransferInstructionDataEncoder(),\n getTransferInstructionDataDecoder()\n );\n}\n\nexport type TransferInput<\n TAccountSource extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferInstructionDataArgs['amount'];\n multiSigners?: Array;\n};\n\nexport function getTransferInstruction<\n TAccountSource extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferInput,\n config?: { programAddress?: TProgramAddress }\n): TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferInstructionDataEncoder().encode(\n args as TransferInstructionDataArgs\n ),\n programAddress,\n } as TransferInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The destination account. */\n destination: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: TransferInstructionData;\n};\n\nexport function parseTransferInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nexport function getTransferCheckedDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);\n}\n\nexport type TransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedInstructionData = {\n discriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport type TransferCheckedInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n};\n\nexport function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })\n );\n}\n\nexport function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ]);\n}\n\nexport function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedInstructionDataArgs,\n TransferCheckedInstructionData\n> {\n return combineCodec(\n getTransferCheckedInstructionDataEncoder(),\n getTransferCheckedInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. */\n source: Address;\n /** The token mint. */\n mint: Address;\n /** The destination account. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedInstructionDataArgs['amount'];\n decimals: TransferCheckedInstructionDataArgs['decimals'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedInstructionDataEncoder().encode(\n args as TransferCheckedInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. */\n source: TAccountMetas[0];\n /** The token mint. */\n mint: TAccountMetas[1];\n /** The destination account. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedInstructionData;\n};\n\nexport function parseTransferCheckedInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR = 26;\n\nexport function getTransferCheckedWithFeeDiscriminatorBytes() {\n return getU8Encoder().encode(TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR);\n}\n\nexport const TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getTransferCheckedWithFeeTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type TransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSource extends string | AccountMeta = string,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSource extends string\n ? WritableAccount\n : TAccountSource,\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type TransferCheckedWithFeeInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** The amount of tokens to transfer. */\n amount: bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: bigint;\n};\n\nexport type TransferCheckedWithFeeInstructionDataArgs = {\n /** The amount of tokens to transfer. */\n amount: number | bigint;\n /** Expected number of base 10 digits to the right of the decimal place. */\n decimals: number;\n /**\n * Expected fee assessed on this transfer, calculated off-chain based\n * on the transfer_fee_basis_points and maximum_fee of the mint. May\n * be 0 for a mint without a configured transfer fee.\n */\n fee: number | bigint;\n};\n\nexport function getTransferCheckedWithFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['amount', getU64Encoder()],\n ['decimals', getU8Encoder()],\n ['fee', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: TRANSFER_CHECKED_WITH_FEE_DISCRIMINATOR,\n transferFeeDiscriminator:\n TRANSFER_CHECKED_WITH_FEE_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getTransferCheckedWithFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['amount', getU64Decoder()],\n ['decimals', getU8Decoder()],\n ['fee', getU64Decoder()],\n ]);\n}\n\nexport function getTransferCheckedWithFeeInstructionDataCodec(): FixedSizeCodec<\n TransferCheckedWithFeeInstructionDataArgs,\n TransferCheckedWithFeeInstructionData\n> {\n return combineCodec(\n getTransferCheckedWithFeeInstructionDataEncoder(),\n getTransferCheckedWithFeeInstructionDataDecoder()\n );\n}\n\nexport type TransferCheckedWithFeeInput<\n TAccountSource extends string = string,\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: Address;\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: Address;\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n amount: TransferCheckedWithFeeInstructionDataArgs['amount'];\n decimals: TransferCheckedWithFeeInstructionDataArgs['decimals'];\n fee: TransferCheckedWithFeeInstructionDataArgs['fee'];\n multiSigners?: Array;\n};\n\nexport function getTransferCheckedWithFeeInstruction<\n TAccountSource extends string,\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: TransferCheckedWithFeeInput<\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n source: { value: input.source ?? null, isWritable: true },\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.source),\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getTransferCheckedWithFeeInstructionDataEncoder().encode(\n args as TransferCheckedWithFeeInstructionDataArgs\n ),\n programAddress,\n } as TransferCheckedWithFeeInstruction<\n TProgramAddress,\n TAccountSource,\n TAccountMint,\n TAccountDestination,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedTransferCheckedWithFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The source account. May include the `TransferFeeAmount` extension. */\n source: TAccountMetas[0];\n /** The token mint. May include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[1];\n /** The destination account. May include the `TransferFeeAmount` extension. */\n destination: TAccountMetas[2];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[3];\n };\n data: TransferCheckedWithFeeInstructionData;\n};\n\nexport function parseTransferCheckedWithFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedTransferCheckedWithFeeInstruction {\n if (instruction.accounts.length < 4) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n source: getNextAccount(),\n mint: getNextAccount(),\n destination: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getTransferCheckedWithFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR = 24;\n\nexport function getUiAmountToAmountDiscriminatorBytes() {\n return getU8Encoder().encode(UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR);\n}\n\nexport type UiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UiAmountToAmountInstructionData = {\n discriminator: number;\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport type UiAmountToAmountInstructionDataArgs = {\n /** The ui_amount of tokens to reformat. */\n uiAmount: string;\n};\n\nexport function getUiAmountToAmountInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['uiAmount', getUtf8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: UI_AMOUNT_TO_AMOUNT_DISCRIMINATOR })\n );\n}\n\nexport function getUiAmountToAmountInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['uiAmount', getUtf8Decoder()],\n ]);\n}\n\nexport function getUiAmountToAmountInstructionDataCodec(): Codec<\n UiAmountToAmountInstructionDataArgs,\n UiAmountToAmountInstructionData\n> {\n return combineCodec(\n getUiAmountToAmountInstructionDataEncoder(),\n getUiAmountToAmountInstructionDataDecoder()\n );\n}\n\nexport type UiAmountToAmountInput = {\n /** The mint to calculate for. */\n mint: Address;\n uiAmount: UiAmountToAmountInstructionDataArgs['uiAmount'];\n};\n\nexport function getUiAmountToAmountInstruction<\n TAccountMint extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UiAmountToAmountInput,\n config?: { programAddress?: TProgramAddress }\n): UiAmountToAmountInstruction {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [getAccountMeta(accounts.mint)],\n data: getUiAmountToAmountInstructionDataEncoder().encode(\n args as UiAmountToAmountInstructionDataArgs\n ),\n programAddress,\n } as UiAmountToAmountInstruction);\n}\n\nexport type ParsedUiAmountToAmountInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to calculate for. */\n mint: TAccountMetas[0];\n };\n data: UiAmountToAmountInstructionData;\n};\n\nexport function parseUiAmountToAmountInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUiAmountToAmountInstruction {\n if (instruction.accounts.length < 1) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount() },\n data: getUiAmountToAmountInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR = 27;\n\nexport function getUpdateConfidentialTransferMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR = 1;\n\nexport function getUpdateConfidentialTransferMintConfidentialTransferDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR\n );\n}\n\nexport type UpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateConfidentialTransferMintInstructionData = {\n discriminator: number;\n confidentialTransferDiscriminator: number;\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: Option
;\n};\n\nexport type UpdateConfidentialTransferMintInstructionDataArgs = {\n /**\n * Determines if newly configured accounts must be approved by the\n * `authority` before they may be used by the user.\n */\n autoApproveNewAccounts: boolean;\n /** New authority to decode any transfer amount in a confidential transfer. */\n auditorElgamalPubkey: OptionOrNullable
;\n};\n\nexport function getUpdateConfidentialTransferMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferDiscriminator', getU8Encoder()],\n ['autoApproveNewAccounts', getBooleanEncoder()],\n [\n 'auditorElgamalPubkey',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_CONFIDENTIAL_TRANSFER_MINT_DISCRIMINATOR,\n confidentialTransferDiscriminator:\n UPDATE_CONFIDENTIAL_TRANSFER_MINT_CONFIDENTIAL_TRANSFER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferDiscriminator', getU8Decoder()],\n ['autoApproveNewAccounts', getBooleanDecoder()],\n [\n 'auditorElgamalPubkey',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateConfidentialTransferMintInstructionDataCodec(): FixedSizeCodec<\n UpdateConfidentialTransferMintInstructionDataArgs,\n UpdateConfidentialTransferMintInstructionData\n> {\n return combineCodec(\n getUpdateConfidentialTransferMintInstructionDataEncoder(),\n getUpdateConfidentialTransferMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateConfidentialTransferMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The SPL Token mint. */\n mint: Address;\n /** Confidential transfer mint authority. */\n authority: TransactionSigner;\n autoApproveNewAccounts: UpdateConfidentialTransferMintInstructionDataArgs['autoApproveNewAccounts'];\n auditorElgamalPubkey: UpdateConfidentialTransferMintInstructionDataArgs['auditorElgamalPubkey'];\n};\n\nexport function getUpdateConfidentialTransferMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateConfidentialTransferMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ],\n data: getUpdateConfidentialTransferMintInstructionDataEncoder().encode(\n args as UpdateConfidentialTransferMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateConfidentialTransferMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateConfidentialTransferMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The SPL Token mint. */\n mint: TAccountMetas[0];\n /** Confidential transfer mint authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateConfidentialTransferMintInstructionData;\n};\n\nexport function parseUpdateConfidentialTransferMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateConfidentialTransferMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateConfidentialTransferMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getAccountStateDecoder,\n getAccountStateEncoder,\n type AccountState,\n type AccountStateArgs,\n} from '../types';\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 28;\n\nexport function getUpdateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR);\n}\n\nexport const UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR = 1;\n\nexport function getUpdateDefaultAccountStateDefaultAccountStateDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR\n );\n}\n\nexport type UpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFreezeAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFreezeAuthority extends string\n ? ReadonlyAccount\n : TAccountFreezeAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateDefaultAccountStateInstructionData = {\n discriminator: number;\n defaultAccountStateDiscriminator: number;\n /** The state each new token account should start with. */\n state: AccountState;\n};\n\nexport type UpdateDefaultAccountStateInstructionDataArgs = {\n /** The state each new token account should start with. */\n state: AccountStateArgs;\n};\n\nexport function getUpdateDefaultAccountStateInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['defaultAccountStateDiscriminator', getU8Encoder()],\n ['state', getAccountStateEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n defaultAccountStateDiscriminator:\n UPDATE_DEFAULT_ACCOUNT_STATE_DEFAULT_ACCOUNT_STATE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['defaultAccountStateDiscriminator', getU8Decoder()],\n ['state', getAccountStateDecoder()],\n ]);\n}\n\nexport function getUpdateDefaultAccountStateInstructionDataCodec(): FixedSizeCodec<\n UpdateDefaultAccountStateInstructionDataArgs,\n UpdateDefaultAccountStateInstructionData\n> {\n return combineCodec(\n getUpdateDefaultAccountStateInstructionDataEncoder(),\n getUpdateDefaultAccountStateInstructionDataDecoder()\n );\n}\n\nexport type UpdateDefaultAccountStateInput<\n TAccountMint extends string = string,\n TAccountFreezeAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority:\n | Address\n | TransactionSigner;\n state: UpdateDefaultAccountStateInstructionDataArgs['state'];\n multiSigners?: Array;\n};\n\nexport function getUpdateDefaultAccountStateInstruction<\n TAccountMint extends string,\n TAccountFreezeAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateDefaultAccountStateInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n freezeAuthority: {\n value: input.freezeAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.freezeAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateDefaultAccountStateInstructionDataEncoder().encode(\n args as UpdateDefaultAccountStateInstructionDataArgs\n ),\n programAddress,\n } as UpdateDefaultAccountStateInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['freezeAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountFreezeAuthority\n >);\n}\n\nexport type ParsedUpdateDefaultAccountStateInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint freeze authority or its multisignature account. */\n freezeAuthority: TAccountMetas[1];\n };\n data: UpdateDefaultAccountStateInstructionData;\n};\n\nexport function parseUpdateDefaultAccountStateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateDefaultAccountStateInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), freezeAuthority: getNextAccount() },\n data: getUpdateDefaultAccountStateInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR = 41;\n\nexport function getUpdateGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupMemberPointerGroupMemberPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupMemberPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupMemberPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupMemberPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupMemberPointerInstructionData = {\n discriminator: number;\n groupMemberPointerDiscriminator: number;\n /** The new account address that holds the member. */\n memberAddress: Option
;\n};\n\nexport type UpdateGroupMemberPointerInstructionDataArgs = {\n /** The new account address that holds the member. */\n memberAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupMemberPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupMemberPointerDiscriminator', getU8Encoder()],\n [\n 'memberAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n groupMemberPointerDiscriminator:\n UPDATE_GROUP_MEMBER_POINTER_GROUP_MEMBER_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupMemberPointerDiscriminator', getU8Decoder()],\n [\n 'memberAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupMemberPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupMemberPointerInstructionDataArgs,\n UpdateGroupMemberPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupMemberPointerInstructionDataEncoder(),\n getUpdateGroupMemberPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupMemberPointerInput<\n TAccountMint extends string = string,\n TAccountGroupMemberPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority:\n | Address\n | TransactionSigner;\n memberAddress: UpdateGroupMemberPointerInstructionDataArgs['memberAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupMemberPointerInstruction<\n TAccountMint extends string,\n TAccountGroupMemberPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupMemberPointerInput<\n TAccountMint,\n TAccountGroupMemberPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupMemberPointerAuthority: {\n value: input.groupMemberPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupMemberPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupMemberPointerInstructionDataEncoder().encode(\n args as UpdateGroupMemberPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupMemberPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupMemberPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupMemberPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupMemberPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group member pointer authority or its multisignature account. */\n groupMemberPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupMemberPointerInstructionData;\n};\n\nexport function parseUpdateGroupMemberPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupMemberPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupMemberPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupMemberPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_GROUP_POINTER_DISCRIMINATOR = 40;\n\nexport function getUpdateGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_GROUP_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateGroupPointerGroupPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountGroupPointerAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountGroupPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountGroupPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateGroupPointerInstructionData = {\n discriminator: number;\n groupPointerDiscriminator: number;\n /** The new account address that holds the group configurations. */\n groupAddress: Option
;\n};\n\nexport type UpdateGroupPointerInstructionDataArgs = {\n /** The new account address that holds the group configurations. */\n groupAddress: OptionOrNullable
;\n};\n\nexport function getUpdateGroupPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['groupPointerDiscriminator', getU8Encoder()],\n [\n 'groupAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_GROUP_POINTER_DISCRIMINATOR,\n groupPointerDiscriminator:\n UPDATE_GROUP_POINTER_GROUP_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateGroupPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['groupPointerDiscriminator', getU8Decoder()],\n [\n 'groupAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateGroupPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateGroupPointerInstructionDataArgs,\n UpdateGroupPointerInstructionData\n> {\n return combineCodec(\n getUpdateGroupPointerInstructionDataEncoder(),\n getUpdateGroupPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateGroupPointerInput<\n TAccountMint extends string = string,\n TAccountGroupPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority:\n | Address\n | TransactionSigner;\n groupAddress: UpdateGroupPointerInstructionDataArgs['groupAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateGroupPointerInstruction<\n TAccountMint extends string,\n TAccountGroupPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateGroupPointerInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n groupPointerAuthority: {\n value: input.groupPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.groupPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateGroupPointerInstructionDataEncoder().encode(\n args as UpdateGroupPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateGroupPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['groupPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountGroupPointerAuthority\n >);\n}\n\nexport type ParsedUpdateGroupPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The group pointer authority or its multisignature account. */\n groupPointerAuthority: TAccountMetas[1];\n };\n data: UpdateGroupPointerInstructionData;\n};\n\nexport function parseUpdateGroupPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateGroupPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n groupPointerAuthority: getNextAccount(),\n },\n data: getUpdateGroupPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_METADATA_POINTER_DISCRIMINATOR = 39;\n\nexport function getUpdateMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_METADATA_POINTER_DISCRIMINATOR);\n}\n\nexport const UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR = 1;\n\nexport function getUpdateMetadataPointerMetadataPointerDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR\n );\n}\n\nexport type UpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountMetadataPointerAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountMetadataPointerAuthority extends string\n ? ReadonlyAccount\n : TAccountMetadataPointerAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMetadataPointerInstructionData = {\n discriminator: number;\n metadataPointerDiscriminator: number;\n /** The new account address that holds the metadata. */\n metadataAddress: Option
;\n};\n\nexport type UpdateMetadataPointerInstructionDataArgs = {\n /** The new account address that holds the metadata. */\n metadataAddress: OptionOrNullable
;\n};\n\nexport function getUpdateMetadataPointerInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['metadataPointerDiscriminator', getU8Encoder()],\n [\n 'metadataAddress',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_METADATA_POINTER_DISCRIMINATOR,\n metadataPointerDiscriminator:\n UPDATE_METADATA_POINTER_METADATA_POINTER_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMetadataPointerInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['metadataPointerDiscriminator', getU8Decoder()],\n [\n 'metadataAddress',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateMetadataPointerInstructionDataCodec(): FixedSizeCodec<\n UpdateMetadataPointerInstructionDataArgs,\n UpdateMetadataPointerInstructionData\n> {\n return combineCodec(\n getUpdateMetadataPointerInstructionDataEncoder(),\n getUpdateMetadataPointerInstructionDataDecoder()\n );\n}\n\nexport type UpdateMetadataPointerInput<\n TAccountMint extends string = string,\n TAccountMetadataPointerAuthority extends string = string,\n> = {\n /** The mint to initialize. */\n mint: Address;\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority:\n | Address\n | TransactionSigner;\n metadataAddress: UpdateMetadataPointerInstructionDataArgs['metadataAddress'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMetadataPointerInstruction<\n TAccountMint extends string,\n TAccountMetadataPointerAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMetadataPointerInput<\n TAccountMint,\n TAccountMetadataPointerAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n metadataPointerAuthority: {\n value: input.metadataPointerAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.metadataPointerAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateMetadataPointerInstructionDataEncoder().encode(\n args as UpdateMetadataPointerInstructionDataArgs\n ),\n programAddress,\n } as UpdateMetadataPointerInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['metadataPointerAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountMetadataPointerAuthority\n >);\n}\n\nexport type ParsedUpdateMetadataPointerInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint to initialize. */\n mint: TAccountMetas[0];\n /** The metadata pointer authority or its multisignature account. */\n metadataPointerAuthority: TAccountMetas[1];\n };\n data: UpdateMetadataPointerInstructionData;\n};\n\nexport function parseUpdateMetadataPointerInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMetadataPointerInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n metadataPointerAuthority: getNextAccount(),\n },\n data: getUpdateMetadataPointerInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getF64Decoder,\n getF64Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR = 43;\n\nexport function getUpdateMultiplierScaledUiMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateMultiplierScaledUiMintScaledUiAmountMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? WritableAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateMultiplierScaledUiMintInstructionData = {\n discriminator: number;\n scaledUiAmountMintDiscriminator: number;\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: bigint;\n};\n\nexport type UpdateMultiplierScaledUiMintInstructionDataArgs = {\n /** The new multiplier for the scaled UI extension */\n multiplier: number;\n /** The timestamp at which the new multiplier will take effect */\n effectiveTimestamp: number | bigint;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['scaledUiAmountMintDiscriminator', getU8Encoder()],\n ['multiplier', getF64Encoder()],\n ['effectiveTimestamp', getI64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_MULTIPLIER_SCALED_UI_MINT_DISCRIMINATOR,\n scaledUiAmountMintDiscriminator:\n UPDATE_MULTIPLIER_SCALED_UI_MINT_SCALED_UI_AMOUNT_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['scaledUiAmountMintDiscriminator', getU8Decoder()],\n ['multiplier', getF64Decoder()],\n ['effectiveTimestamp', getI64Decoder()],\n ]);\n}\n\nexport function getUpdateMultiplierScaledUiMintInstructionDataCodec(): FixedSizeCodec<\n UpdateMultiplierScaledUiMintInstructionDataArgs,\n UpdateMultiplierScaledUiMintInstructionData\n> {\n return combineCodec(\n getUpdateMultiplierScaledUiMintInstructionDataEncoder(),\n getUpdateMultiplierScaledUiMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateMultiplierScaledUiMintInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The multiplier authority. */\n authority: Address | TransactionSigner;\n multiplier: UpdateMultiplierScaledUiMintInstructionDataArgs['multiplier'];\n effectiveTimestamp: UpdateMultiplierScaledUiMintInstructionDataArgs['effectiveTimestamp'];\n multiSigners?: Array;\n};\n\nexport function getUpdateMultiplierScaledUiMintInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateMultiplierScaledUiMintInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateMultiplierScaledUiMintInstructionDataEncoder().encode(\n args as UpdateMultiplierScaledUiMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateMultiplierScaledUiMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The multiplier authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateMultiplierScaledUiMintInstructionData;\n};\n\nexport function parseUpdateMultiplierScaledUiMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateMultiplierScaledUiMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateMultiplierScaledUiMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI16Decoder,\n getI16Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n type WritableSignerAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR = 33;\n\nexport function getUpdateRateInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR);\n}\n\nexport const UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR = 1;\n\nexport function getUpdateRateInterestBearingMintInterestBearingMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR\n );\n}\n\nexport type UpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountRateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountRateAuthority extends string\n ? WritableAccount\n : TAccountRateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateRateInterestBearingMintInstructionData = {\n discriminator: number;\n interestBearingMintDiscriminator: number;\n /** The interest rate to update. */\n rate: number;\n};\n\nexport type UpdateRateInterestBearingMintInstructionDataArgs = {\n /** The interest rate to update. */\n rate: number;\n};\n\nexport function getUpdateRateInterestBearingMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['interestBearingMintDiscriminator', getU8Encoder()],\n ['rate', getI16Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_RATE_INTEREST_BEARING_MINT_DISCRIMINATOR,\n interestBearingMintDiscriminator:\n UPDATE_RATE_INTEREST_BEARING_MINT_INTEREST_BEARING_MINT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['interestBearingMintDiscriminator', getU8Decoder()],\n ['rate', getI16Decoder()],\n ]);\n}\n\nexport function getUpdateRateInterestBearingMintInstructionDataCodec(): FixedSizeCodec<\n UpdateRateInterestBearingMintInstructionDataArgs,\n UpdateRateInterestBearingMintInstructionData\n> {\n return combineCodec(\n getUpdateRateInterestBearingMintInstructionDataEncoder(),\n getUpdateRateInterestBearingMintInstructionDataDecoder()\n );\n}\n\nexport type UpdateRateInterestBearingMintInput<\n TAccountMint extends string = string,\n TAccountRateAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The mint rate authority. */\n rateAuthority:\n | Address\n | TransactionSigner;\n rate: UpdateRateInterestBearingMintInstructionDataArgs['rate'];\n multiSigners?: Array;\n};\n\nexport function getUpdateRateInterestBearingMintInstruction<\n TAccountMint extends string,\n TAccountRateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateRateInterestBearingMintInput<\n TAccountMint,\n TAccountRateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n rateAuthority: { value: input.rateAuthority ?? null, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.rateAuthority),\n ...remainingAccounts,\n ],\n data: getUpdateRateInterestBearingMintInstructionDataEncoder().encode(\n args as UpdateRateInterestBearingMintInstructionDataArgs\n ),\n programAddress,\n } as UpdateRateInterestBearingMintInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['rateAuthority'] extends TransactionSigner\n ? WritableSignerAccount &\n AccountSignerMeta\n : TAccountRateAuthority\n >);\n}\n\nexport type ParsedUpdateRateInterestBearingMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The mint rate authority. */\n rateAuthority: TAccountMetas[1];\n };\n data: UpdateRateInterestBearingMintInstructionData;\n};\n\nexport function parseUpdateRateInterestBearingMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateRateInterestBearingMintInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), rateAuthority: getNextAccount() },\n data: getUpdateRateInterestBearingMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR = new Uint8Array([\n 108, 37, 171, 143, 248, 30, 18, 110,\n]);\n\nexport function getUpdateTokenGroupMaxSizeDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR);\n}\n\nexport type UpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupMaxSizeInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New max size for the group */\n maxSize: bigint;\n};\n\nexport type UpdateTokenGroupMaxSizeInstructionDataArgs = {\n /** New max size for the group */\n maxSize: number | bigint;\n};\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['maxSize', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['maxSize', getU64Decoder()],\n ]);\n}\n\nexport function getUpdateTokenGroupMaxSizeInstructionDataCodec(): Codec<\n UpdateTokenGroupMaxSizeInstructionDataArgs,\n UpdateTokenGroupMaxSizeInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupMaxSizeInstructionDataEncoder(),\n getUpdateTokenGroupMaxSizeInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupMaxSizeInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n updateAuthority: TransactionSigner;\n maxSize: UpdateTokenGroupMaxSizeInstructionDataArgs['maxSize'];\n};\n\nexport function getUpdateTokenGroupMaxSizeInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupMaxSizeInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupMaxSizeInstructionDataEncoder().encode(\n args as UpdateTokenGroupMaxSizeInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupMaxSizeInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupMaxSizeInstructionData;\n};\n\nexport function parseUpdateTokenGroupMaxSizeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupMaxSizeInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupMaxSizeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR = new Uint8Array(\n [161, 105, 88, 1, 237, 221, 216, 203]\n);\n\nexport function getUpdateTokenGroupUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountGroup extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountGroup extends string\n ? WritableAccount\n : TAccountGroup,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenGroupUpdateAuthorityInstructionDataArgs = {\n /** New authority for the group, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenGroupUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenGroupUpdateAuthorityInstructionDataArgs,\n UpdateTokenGroupUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n group: Address;\n /** Current update authority */\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenGroupUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenGroupUpdateAuthorityInstruction<\n TAccountGroup extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenGroupUpdateAuthorityInput<\n TAccountGroup,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n group: { value: input.group ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.group),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenGroupUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenGroupUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountGroup,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n group: TAccountMetas[0];\n /** Current update authority */\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenGroupUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenGroupUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenGroupUpdateAuthorityInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { group: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenGroupUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n combineCodec,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getTokenMetadataFieldDecoder,\n getTokenMetadataFieldEncoder,\n type TokenMetadataField,\n type TokenMetadataFieldArgs,\n} from '../types';\n\nexport const UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR = new Uint8Array([\n 221, 233, 49, 45, 181, 202, 220, 200,\n]);\n\nexport function getUpdateTokenMetadataFieldDiscriminatorBytes() {\n return getBytesEncoder().encode(UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR);\n}\n\nexport type UpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataFieldInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** Field to update in the metadata. */\n field: TokenMetadataField;\n /** Value to write for the field. */\n value: string;\n};\n\nexport type UpdateTokenMetadataFieldInstructionDataArgs = {\n /** Field to update in the metadata. */\n field: TokenMetadataFieldArgs;\n /** Value to write for the field. */\n value: string;\n};\n\nexport function getUpdateTokenMetadataFieldInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n ['field', getTokenMetadataFieldEncoder()],\n ['value', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n ['field', getTokenMetadataFieldDecoder()],\n ['value', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ]);\n}\n\nexport function getUpdateTokenMetadataFieldInstructionDataCodec(): Codec<\n UpdateTokenMetadataFieldInstructionDataArgs,\n UpdateTokenMetadataFieldInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataFieldInstructionDataEncoder(),\n getUpdateTokenMetadataFieldInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataFieldInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n field: UpdateTokenMetadataFieldInstructionDataArgs['field'];\n value: UpdateTokenMetadataFieldInstructionDataArgs['value'];\n};\n\nexport function getUpdateTokenMetadataFieldInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataFieldInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataFieldInstructionDataEncoder().encode(\n args as UpdateTokenMetadataFieldInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataFieldInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataFieldInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataFieldInstructionData;\n};\n\nexport function parseUpdateTokenMetadataFieldInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataFieldInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataFieldInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type Codec,\n type Decoder,\n type Encoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR =\n new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]);\n\nexport function getUpdateTokenMetadataUpdateAuthorityDiscriminatorBytes() {\n return getBytesEncoder().encode(\n UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetadata extends string | AccountMeta = string,\n TAccountUpdateAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMetadata extends string\n ? WritableAccount\n : TAccountMetadata,\n TAccountUpdateAuthority extends string\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountUpdateAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionData = {\n discriminator: ReadonlyUint8Array;\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: Option
;\n};\n\nexport type UpdateTokenMetadataUpdateAuthorityInstructionDataArgs = {\n /** New authority for the token metadata, or unset if `None` */\n newUpdateAuthority: OptionOrNullable
;\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(): Encoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getBytesEncoder()],\n [\n 'newUpdateAuthority',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder(): Decoder {\n return getStructDecoder([\n ['discriminator', getBytesDecoder()],\n [\n 'newUpdateAuthority',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstructionDataCodec(): Codec<\n UpdateTokenMetadataUpdateAuthorityInstructionDataArgs,\n UpdateTokenMetadataUpdateAuthorityInstructionData\n> {\n return combineCodec(\n getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder(),\n getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder()\n );\n}\n\nexport type UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata extends string = string,\n TAccountUpdateAuthority extends string = string,\n> = {\n metadata: Address;\n updateAuthority: TransactionSigner;\n newUpdateAuthority: UpdateTokenMetadataUpdateAuthorityInstructionDataArgs['newUpdateAuthority'];\n};\n\nexport function getUpdateTokenMetadataUpdateAuthorityInstruction<\n TAccountMetadata extends string,\n TAccountUpdateAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTokenMetadataUpdateAuthorityInput<\n TAccountMetadata,\n TAccountUpdateAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n metadata: { value: input.metadata ?? null, isWritable: true },\n updateAuthority: {\n value: input.updateAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.metadata),\n getAccountMeta(accounts.updateAuthority),\n ],\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataEncoder().encode(\n args as UpdateTokenMetadataUpdateAuthorityInstructionDataArgs\n ),\n programAddress,\n } as UpdateTokenMetadataUpdateAuthorityInstruction<\n TProgramAddress,\n TAccountMetadata,\n TAccountUpdateAuthority\n >);\n}\n\nexport type ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n metadata: TAccountMetas[0];\n updateAuthority: TAccountMetas[1];\n };\n data: UpdateTokenMetadataUpdateAuthorityInstructionData;\n};\n\nexport function parseUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTokenMetadataUpdateAuthorityInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { metadata: getNextAccount(), updateAuthority: getNextAccount() },\n data: getUpdateTokenMetadataUpdateAuthorityInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type Option,\n type OptionOrNullable,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const UPDATE_TRANSFER_HOOK_DISCRIMINATOR = 36;\n\nexport function getUpdateTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(UPDATE_TRANSFER_HOOK_DISCRIMINATOR);\n}\n\nexport const UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR = 1;\n\nexport function getUpdateTransferHookTransferHookDiscriminatorBytes() {\n return getU8Encoder().encode(\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR\n );\n}\n\nexport type UpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateTransferHookInstructionData = {\n discriminator: number;\n transferHookDiscriminator: number;\n /** The program id that performs logic during transfers */\n programId: Option
;\n};\n\nexport type UpdateTransferHookInstructionDataArgs = {\n /** The program id that performs logic during transfers */\n programId: OptionOrNullable
;\n};\n\nexport function getUpdateTransferHookInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferHookDiscriminator', getU8Encoder()],\n [\n 'programId',\n getOptionEncoder(getAddressEncoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]),\n (value) => ({\n ...value,\n discriminator: UPDATE_TRANSFER_HOOK_DISCRIMINATOR,\n transferHookDiscriminator:\n UPDATE_TRANSFER_HOOK_TRANSFER_HOOK_DISCRIMINATOR,\n })\n );\n}\n\nexport function getUpdateTransferHookInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferHookDiscriminator', getU8Decoder()],\n [\n 'programId',\n getOptionDecoder(getAddressDecoder(), {\n prefix: null,\n noneValue: 'zeroes',\n }),\n ],\n ]);\n}\n\nexport function getUpdateTransferHookInstructionDataCodec(): FixedSizeCodec<\n UpdateTransferHookInstructionDataArgs,\n UpdateTransferHookInstructionData\n> {\n return combineCodec(\n getUpdateTransferHookInstructionDataEncoder(),\n getUpdateTransferHookInstructionDataDecoder()\n );\n}\n\nexport type UpdateTransferHookInput<\n TAccountMint extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The mint. */\n mint: Address;\n /** The transfer hook authority. */\n authority: Address | TransactionSigner;\n programId: UpdateTransferHookInstructionDataArgs['programId'];\n multiSigners?: Array;\n};\n\nexport function getUpdateTransferHookInstruction<\n TAccountMint extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: UpdateTransferHookInput,\n config?: { programAddress?: TProgramAddress }\n): UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getUpdateTransferHookInstructionDataEncoder().encode(\n args as UpdateTransferHookInstructionDataArgs\n ),\n programAddress,\n } as UpdateTransferHookInstruction<\n TProgramAddress,\n TAccountMint,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedUpdateTransferHookInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The mint. */\n mint: TAccountMetas[0];\n /** The transfer hook authority. */\n authority: TAccountMetas[1];\n };\n data: UpdateTransferHookInstructionData;\n};\n\nexport function parseUpdateTransferHookInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedUpdateTransferHookInstruction {\n if (instruction.accounts.length < 2) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { mint: getNextAccount(), authority: getNextAccount() },\n data: getUpdateTransferHookInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR = 38;\n\nexport function getWithdrawExcessLamportsDiscriminatorBytes() {\n return getU8Encoder().encode(WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR);\n}\n\nexport type WithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountSourceAccount extends string | AccountMeta = string,\n TAccountDestinationAccount extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountSourceAccount extends string\n ? WritableAccount\n : TAccountSourceAccount,\n TAccountDestinationAccount extends string\n ? WritableAccount\n : TAccountDestinationAccount,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawExcessLamportsInstructionData = { discriminator: number };\n\nexport type WithdrawExcessLamportsInstructionDataArgs = {};\n\nexport function getWithdrawExcessLamportsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([['discriminator', getU8Encoder()]]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_EXCESS_LAMPORTS_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawExcessLamportsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([['discriminator', getU8Decoder()]]);\n}\n\nexport function getWithdrawExcessLamportsInstructionDataCodec(): FixedSizeCodec<\n WithdrawExcessLamportsInstructionDataArgs,\n WithdrawExcessLamportsInstructionData\n> {\n return combineCodec(\n getWithdrawExcessLamportsInstructionDataEncoder(),\n getWithdrawExcessLamportsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawExcessLamportsInput<\n TAccountSourceAccount extends string = string,\n TAccountDestinationAccount extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** Account holding excess lamports. */\n sourceAccount: Address;\n /** Destination account for withdrawn lamports. */\n destinationAccount: Address;\n /** The source account's owner/delegate or its multisignature account. */\n authority: Address | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawExcessLamportsInstruction<\n TAccountSourceAccount extends string,\n TAccountDestinationAccount extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawExcessLamportsInput<\n TAccountSourceAccount,\n TAccountDestinationAccount,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n sourceAccount: { value: input.sourceAccount ?? null, isWritable: true },\n destinationAccount: {\n value: input.destinationAccount ?? null,\n isWritable: true,\n },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.sourceAccount),\n getAccountMeta(accounts.destinationAccount),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawExcessLamportsInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawExcessLamportsInstruction<\n TProgramAddress,\n TAccountSourceAccount,\n TAccountDestinationAccount,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawExcessLamportsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** Account holding excess lamports. */\n sourceAccount: TAccountMetas[0];\n /** Destination account for withdrawn lamports. */\n destinationAccount: TAccountMetas[1];\n /** The source account's owner/delegate or its multisignature account. */\n authority: TAccountMetas[2];\n };\n data: WithdrawExcessLamportsInstructionData;\n};\n\nexport function parseWithdrawExcessLamportsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawExcessLamportsInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n sourceAccount: getNextAccount(),\n destinationAccount: getNextAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawExcessLamportsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromAccountsDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR = 3;\n\nexport function getWithdrawWithheldTokensFromAccountsTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport type WithdrawWithheldTokensFromAccountsInstructionDataArgs = {\n /** Number of token accounts harvested. */\n numTokenAccounts: number;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsInstructionDataArgs['numTokenAccounts'];\n multiSigners?: Array;\n sources: Array
;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = [\n ...(args.multiSigners ?? []).map((signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })),\n ...args.sources.map((address) => ({ address, role: AccountRole.WRITABLE })),\n ];\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromAccountsInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? ReadonlyAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Number of token accounts harvested */\n numTokenAccounts: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['numTokenAccounts', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_ACCOUNTS_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['numTokenAccounts', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n numTokenAccounts: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['numTokenAccounts'];\n proofInstructionOffset: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: false },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromAccountsForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR = 26;\n\nexport function getWithdrawWithheldTokensFromMintDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR = 2;\n\nexport function getWithdrawWithheldTokensFromMintTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountFeeReceiver extends string | AccountMeta = string,\n TAccountWithdrawWithheldAuthority extends\n | string\n | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountFeeReceiver extends string\n ? WritableAccount\n : TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority extends string\n ? ReadonlyAccount\n : TAccountWithdrawWithheldAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintInstructionData = {\n discriminator: number;\n transferFeeDiscriminator: number;\n};\n\nexport type WithdrawWithheldTokensFromMintInstructionDataArgs = {};\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['transferFeeDiscriminator', getU8Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: WITHDRAW_WITHHELD_TOKENS_FROM_MINT_DISCRIMINATOR,\n transferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['transferFeeDiscriminator', getU8Decoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintInstructionDataArgs,\n WithdrawWithheldTokensFromMintInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintInput<\n TAccountMint extends string = string,\n TAccountFeeReceiver extends string = string,\n TAccountWithdrawWithheldAuthority extends string = string,\n> = {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: Address;\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: Address;\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority:\n | Address\n | TransactionSigner;\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintInstruction<\n TAccountMint extends string,\n TAccountFeeReceiver extends string,\n TAccountWithdrawWithheldAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintInput<\n TAccountMint,\n TAccountFeeReceiver,\n TAccountWithdrawWithheldAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n feeReceiver: { value: input.feeReceiver ?? null, isWritable: true },\n withdrawWithheldAuthority: {\n value: input.withdrawWithheldAuthority ?? null,\n isWritable: false,\n },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.feeReceiver),\n getAccountMeta(accounts.withdrawWithheldAuthority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintInstructionDataEncoder().encode({}),\n programAddress,\n } as WithdrawWithheldTokensFromMintInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountFeeReceiver,\n (typeof input)['withdrawWithheldAuthority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountWithdrawWithheldAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. Must include the `TransferFeeConfig` extension. */\n mint: TAccountMetas[0];\n /**\n * The fee receiver account. Must include the `TransferFeeAmount`\n * extension associated with the provided mint.\n */\n feeReceiver: TAccountMetas[1];\n /** The mint's `withdraw_withheld_authority` or its multisignature account. */\n withdrawWithheldAuthority: TAccountMetas[2];\n };\n data: WithdrawWithheldTokensFromMintInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintInstruction {\n if (instruction.accounts.length < 3) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n feeReceiver: getNextAccount(),\n withdrawWithheldAuthority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n AccountRole,\n combineCodec,\n getI8Decoder,\n getI8Encoder,\n getStructDecoder,\n getStructEncoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type AccountSignerMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlySignerAccount,\n type ReadonlyUint8Array,\n type TransactionSigner,\n type WritableAccount,\n} from '@solana/kit';\nimport { TOKEN_2022_PROGRAM_ADDRESS } from '../programs';\nimport { getAccountMetaFactory, type ResolvedAccount } from '../shared';\nimport {\n getDecryptableBalanceDecoder,\n getDecryptableBalanceEncoder,\n type DecryptableBalance,\n type DecryptableBalanceArgs,\n} from '../types';\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 37;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport const WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR = 1;\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeConfidentialTransferFeeDiscriminatorBytes() {\n return getU8Encoder().encode(\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMint extends string | AccountMeta = string,\n TAccountDestination extends string | AccountMeta = string,\n TAccountInstructionsSysvarOrContextState extends\n | string\n | AccountMeta = string,\n TAccountRecord extends string | AccountMeta = string,\n TAccountAuthority extends string | AccountMeta = string,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts<\n [\n TAccountMint extends string\n ? WritableAccount\n : TAccountMint,\n TAccountDestination extends string\n ? WritableAccount\n : TAccountDestination,\n TAccountInstructionsSysvarOrContextState extends string\n ? ReadonlyAccount\n : TAccountInstructionsSysvarOrContextState,\n TAccountRecord extends string\n ? ReadonlyAccount\n : TAccountRecord,\n TAccountAuthority extends string\n ? ReadonlyAccount\n : TAccountAuthority,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData =\n {\n discriminator: number;\n confidentialTransferFeeDiscriminator: number;\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalance;\n };\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs =\n {\n /** Proof instruction offset */\n proofInstructionOffset: number;\n /** The new decryptable balance in the destination token account */\n newDecryptableAvailableBalance: DecryptableBalanceArgs;\n };\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['confidentialTransferFeeDiscriminator', getU8Encoder()],\n ['proofInstructionOffset', getI8Encoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceEncoder()],\n ]),\n (value) => ({\n ...value,\n discriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n confidentialTransferFeeDiscriminator:\n WITHDRAW_WITHHELD_TOKENS_FROM_MINT_FOR_CONFIDENTIAL_TRANSFER_FEE_CONFIDENTIAL_TRANSFER_FEE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['confidentialTransferFeeDiscriminator', getU8Decoder()],\n ['proofInstructionOffset', getI8Decoder()],\n ['newDecryptableAvailableBalance', getDecryptableBalanceDecoder()],\n ]);\n}\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataCodec(): FixedSizeCodec<\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs,\n WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData\n> {\n return combineCodec(\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder(),\n getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder()\n );\n}\n\nexport type WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint extends string = string,\n TAccountDestination extends string = string,\n TAccountInstructionsSysvarOrContextState extends string = string,\n TAccountRecord extends string = string,\n TAccountAuthority extends string = string,\n> = {\n /** The token mint. */\n mint: Address;\n /** The fee receiver account. */\n destination: Address;\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: Address;\n /** Optional record account if proof is read from record */\n record?: Address;\n /** The mint's withdraw_withheld_authority */\n authority: Address | TransactionSigner;\n proofInstructionOffset: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['proofInstructionOffset'];\n newDecryptableAvailableBalance: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs['newDecryptableAvailableBalance'];\n multiSigners?: Array;\n};\n\nexport function getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TAccountMint extends string,\n TAccountDestination extends string,\n TAccountInstructionsSysvarOrContextState extends string,\n TAccountRecord extends string,\n TAccountAuthority extends string,\n TProgramAddress extends Address = typeof TOKEN_2022_PROGRAM_ADDRESS,\n>(\n input: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInput<\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n TAccountAuthority\n >,\n config?: { programAddress?: TProgramAddress }\n): WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n> {\n // Program address.\n const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;\n\n // Original accounts.\n const originalAccounts = {\n mint: { value: input.mint ?? null, isWritable: true },\n destination: { value: input.destination ?? null, isWritable: true },\n instructionsSysvarOrContextState: {\n value: input.instructionsSysvarOrContextState ?? null,\n isWritable: false,\n },\n record: { value: input.record ?? null, isWritable: false },\n authority: { value: input.authority ?? null, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedAccount\n >;\n\n // Original args.\n const args = { ...input };\n\n // Remaining accounts.\n const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(\n (signer) => ({\n address: signer.address,\n role: AccountRole.READONLY_SIGNER,\n signer,\n })\n );\n\n const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');\n return Object.freeze({\n accounts: [\n getAccountMeta(accounts.mint),\n getAccountMeta(accounts.destination),\n getAccountMeta(accounts.instructionsSysvarOrContextState),\n getAccountMeta(accounts.record),\n getAccountMeta(accounts.authority),\n ...remainingAccounts,\n ],\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataEncoder().encode(\n args as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataArgs\n ),\n programAddress,\n } as WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgramAddress,\n TAccountMint,\n TAccountDestination,\n TAccountInstructionsSysvarOrContextState,\n TAccountRecord,\n (typeof input)['authority'] extends TransactionSigner\n ? ReadonlySignerAccount &\n AccountSignerMeta\n : TAccountAuthority\n >);\n}\n\nexport type ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string = typeof TOKEN_2022_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address;\n accounts: {\n /** The token mint. */\n mint: TAccountMetas[0];\n /** The fee receiver account. */\n destination: TAccountMetas[1];\n /** Instructions sysvar or context state account */\n instructionsSysvarOrContextState: TAccountMetas[2];\n /** Optional record account if proof is read from record */\n record?: TAccountMetas[3] | undefined;\n /** The mint's withdraw_withheld_authority */\n authority: TAccountMetas[4];\n };\n data: WithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionData;\n};\n\nexport function parseWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction &\n InstructionWithAccounts &\n InstructionWithData\n): ParsedWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstruction<\n TProgram,\n TAccountMetas\n> {\n if (instruction.accounts.length < 5) {\n // TODO: Coded error.\n throw new Error('Not enough accounts');\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === TOKEN_2022_PROGRAM_ADDRESS\n ? undefined\n : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n mint: getNextAccount(),\n destination: getNextAccount(),\n instructionsSysvarOrContextState: getNextAccount(),\n record: getNextOptionalAccount(),\n authority: getNextAccount(),\n },\n data: getWithdrawWithheldTokensFromMintForConfidentialTransferFeeInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","import {\n type GetAccountInfoApi,\n type Rpc,\n Address,\n UnixTimestamp,\n unwrapOption,\n} from '@solana/kit';\nimport { fetchSysvarClock } from '@solana/sysvars';\nimport { fetchMint } from './generated';\n\n// Constants\nconst ONE_IN_BASIS_POINTS = 10000;\nconst SECONDS_PER_YEAR = 60 * 60 * 24 * 365.24;\n\n/**\n * Calculates the exponent for the interest rate formula.\n * @param t1 - The start time in seconds.\n * @param t2 - The end time in seconds.\n * @param r - The interest rate in basis points.\n *\n * @returns The calculated exponent.\n */\nfunction calculateExponentForTimesAndRate(t1: number, t2: number, r: number) {\n const timespan = t2 - t1;\n if (timespan < 0) {\n throw new Error('Invalid timespan: end time before start time');\n }\n\n const numerator = r * timespan;\n const exponent = numerator / (SECONDS_PER_YEAR * ONE_IN_BASIS_POINTS);\n return Math.exp(exponent);\n}\n\n/**\n * Calculates the total scale factor for an interest bearing token by combining two exponential functions:\n * One for the period between initialization and last update using the pre-update average rate,\n * and another for the period between last update and current time using the current rate.\n *\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points before last update\n * @param currentRate Current interest rate in basis points\n *\n * @returns The total scale factor as a product of the two exponential functions\n */\nfunction calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n}: {\n currentTimestamp: number;\n lastUpdateTimestamp: number;\n initializationTimestamp: number;\n preUpdateAverageRate: number;\n currentRate: number;\n}): number {\n // Calculate pre-update exponent\n const preUpdateExp = calculateExponentForTimesAndRate(\n initializationTimestamp,\n lastUpdateTimestamp,\n preUpdateAverageRate\n );\n\n // Calculate post-update exponent\n const postUpdateExp = calculateExponentForTimesAndRate(\n lastUpdateTimestamp,\n currentTimestamp,\n currentRate\n );\n\n return preUpdateExp * postUpdateExp;\n}\n\n/**\n * Calculates the decimal factor for a given number of decimals\n * @param decimals - Number of decimals\n * @returns The decimal factor (e.g., 100 for 2 decimals)\n */\nfunction getDecimalFactor(decimals: number): number {\n return Math.pow(10, decimals);\n}\n\n/**\n * Retrieves the current timestamp from the Solana clock sysvar.\n * @param rpc - The Solana rpc object.\n * @returns A promise that resolves to the current timestamp in seconds.\n * @throws An error if the sysvar clock cannot be fetched or parsed.\n */\nasync function getSysvarClockTimestamp(\n rpc: Rpc\n): Promise {\n const info = await fetchSysvarClock(rpc);\n if (!info) {\n throw new Error('Failed to fetch sysvar clock');\n }\n return info.unixTimestamp;\n}\n\n// ========== INTEREST BEARING MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with interest bearing extension without simulating a transaction\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n * In general to calculate compounding interest over a period of time, the formula is:\n * A = P * e^(r * t) where\n * A = final amount after interest\n * P = principal amount (initial investment)\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n * e = mathematical constant (~2.718)\n *\n * In this case, we are calculating the total scale factor for the interest bearing extension which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 and r2 are the interest rates before and after the last update, and t1 and t2 are the times in years between\n * the initialization timestamp and the last update timestamp, and between the last update timestamp and the current timestamp.\n *\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (1 basis point = 0.01%) before last update\n * @param currentRate Current interest rate in basis points\n *\n * @return Amount scaled by accrued interest as a string with appropriate decimal places\n */\nexport function amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): string {\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Scale the amount by the total interest factor\n const scaledAmount = Number(amount) * totalScale;\n const decimalFactor = getDecimalFactor(decimals);\n\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert an amount with interest back to the original amount without interest\n * This implements the same logic as the CPI instruction available in /token/program-2022/src/extension/interest_bearing_mint/mod.rs\n *\n * @param uiAmount UI Amount (principal plus continuously compounding interest) to be converted back to original principal\n * @param decimals Number of decimals for the mint\n * @param currentTimestamp Current timestamp in seconds\n * @param lastUpdateTimestamp Last time the interest rate was updated in seconds\n * @param initializationTimestamp Time the interest bearing extension was initialized in seconds\n * @param preUpdateAverageRate Interest rate in basis points (hundredths of a percent) before the last update\n * @param currentRate Current interest rate in basis points\n *\n * In general to calculate the principal from the UI amount, the formula is:\n * P = A / (e^(r * t)) where\n * P = principal\n * A = UI amount\n * r = annual interest rate (as a decimal, e.g., 5% = 0.05)\n * t = time in years\n *\n * In this case, we are calculating the principal by dividing the UI amount by the total scale factor which is the product of two exponential functions:\n * totalScale = e^(r1 * t1) * e^(r2 * t2)\n * where r1 is the pre-update average rate, r2 is the current rate, t1 is the time in years between the initialization timestamp and the last update timestamp,\n * and t2 is the time in years between the last update timestamp and the current timestamp.\n * then to calculate the principal, we divide the UI amount by the total scale factor:\n * P = A / totalScale\n *\n * @return Original amount (principal) without interest\n */\nexport function uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n currentTimestamp: number,\n lastUpdateTimestamp: number,\n initializationTimestamp: number,\n preUpdateAverageRate: number,\n currentRate: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n\n const totalScale = calculateTotalScale({\n currentTimestamp,\n lastUpdateTimestamp,\n initializationTimestamp,\n preUpdateAverageRate,\n currentRate,\n });\n\n // Calculate original principal by dividing the UI amount by the total scale\n const originalPrincipal = uiAmountScaled / totalScale;\n return BigInt(Math.trunc(originalPrincipal));\n}\n\n// ========== SCALED UI AMOUNT MINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint with scaled UI amount extension\n * @param amount Amount of tokens to be converted\n * @param decimals Number of decimals of the mint\n * @param multiplier Multiplier to scale the amount\n * @return Scaled UI amount as a string\n */\nexport function amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount: bigint,\n decimals: number,\n multiplier: number\n): string {\n const scaledAmount = Number(amount) * multiplier;\n const decimalFactor = getDecimalFactor(decimals);\n return (Math.trunc(scaledAmount) / decimalFactor).toString();\n}\n\n/**\n * Convert a UI amount back to the raw amount for a mint with a scaled UI amount extension\n * @param uiAmount UI Amount to be converted back to raw amount\n * @param decimals Number of decimals for the mint\n * @param multiplier Multiplier for the scaled UI amount\n *\n * @return Raw amount\n */\nexport function uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount: string,\n decimals: number,\n multiplier: number\n): bigint {\n const uiAmountNumber = parseFloat(uiAmount);\n const decimalsFactor = getDecimalFactor(decimals);\n const uiAmountScaled = uiAmountNumber * decimalsFactor;\n const rawAmount = uiAmountScaled / multiplier;\n return BigInt(Math.trunc(rawAmount));\n}\n\n// ========== MAIN ENTRY POINT FUNCTIONS ==========\n\n/**\n * Convert amount to UiAmount for a mint without simulating a transaction\n * This implements the same logic as `process_amount_to_ui_amount` in\n * solana-labs/solana-program-library/token/program-2022/src/processor.rs\n * and `process_amount_to_ui_amount` in solana-labs/solana-program-library/token/program/src/processor.rs\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param amount Amount of tokens to be converted to Ui Amount\n *\n * @return Ui Amount generated\n */\nexport async function amountToUiAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n amount: bigint\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const amountNumber = Number(amount);\n const decimalsFactor = getDecimalFactor(accountInfo.data.decimals);\n return (amountNumber / decimalsFactor).toString();\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return amountToUiAmountForInterestBearingMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return amountToUiAmountForScaledUiAmountMintWithoutSimulation(\n amount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n\n/**\n * Convert a UI amount back to the raw amount\n *\n * @param rpc Rpc to use\n * @param mint Mint to use for calculations\n * @param uiAmount UI Amount to be converted back to raw amount\n *\n * @return Raw amount\n */\nexport async function uiAmountToAmountForMintWithoutSimulation(\n rpc: Rpc,\n mint: Address,\n uiAmount: string\n): Promise {\n const accountInfo = await fetchMint(rpc, mint);\n const extensions = unwrapOption(accountInfo.data.extensions);\n\n // Check for interest bearing mint extension\n const interestBearingMintConfigState = extensions?.find(\n (ext) => ext.__kind === 'InterestBearingConfig'\n );\n\n // Check for scaled UI amount extension\n const scaledUiAmountConfig = extensions?.find(\n (ext) => ext.__kind === 'ScaledUiAmountConfig'\n );\n\n // If no special extension, do standard conversion\n if (!interestBearingMintConfigState && !scaledUiAmountConfig) {\n const uiAmountScaled =\n parseFloat(uiAmount) * getDecimalFactor(accountInfo.data.decimals);\n return BigInt(Math.trunc(uiAmountScaled));\n }\n\n // Get timestamp if needed for special mint types\n const timestamp = await getSysvarClockTimestamp(rpc);\n\n // Handle interest bearing mint\n if (interestBearingMintConfigState) {\n return uiAmountToAmountForInterestBearingMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n Number(timestamp),\n Number(interestBearingMintConfigState.lastUpdateTimestamp),\n Number(interestBearingMintConfigState.initializationTimestamp),\n interestBearingMintConfigState.preUpdateAverageRate,\n interestBearingMintConfigState.currentRate\n );\n }\n\n // At this point, we know it must be a scaled UI amount mint\n if (scaledUiAmountConfig) {\n let multiplier = scaledUiAmountConfig.multiplier;\n // Use new multiplier if it's effective\n if (timestamp >= scaledUiAmountConfig.newMultiplierEffectiveTimestamp) {\n multiplier = scaledUiAmountConfig.newMultiplier;\n }\n return uiAmountToAmountForScaledUiAmountMintWithoutSimulation(\n uiAmount,\n accountInfo.data.decimals,\n multiplier\n );\n }\n\n // This should never happen due to the conditions above\n throw new Error('Unknown mint extension type');\n}\n","import {\n Address,\n Instruction,\n isNone,\n isOption,\n TransactionSigner,\n wrapNullable,\n} from '@solana/kit';\nimport {\n ExtensionArgs,\n getDisableMemoTransfersInstruction,\n getEnableMemoTransfersInstruction,\n getEnableCpiGuardInstruction,\n getDisableCpiGuardInstruction,\n getInitializeConfidentialTransferMintInstruction,\n getInitializeDefaultAccountStateInstruction,\n getInitializeGroupMemberPointerInstruction,\n getInitializeGroupPointerInstruction,\n getInitializeInterestBearingMintInstruction,\n getInitializeMetadataPointerInstruction,\n getInitializeMintCloseAuthorityInstruction,\n getInitializeTokenGroupInstruction,\n getInitializeTokenMetadataInstruction,\n getInitializeTransferFeeConfigInstruction,\n getInitializeNonTransferableMintInstruction,\n getInitializeTransferHookInstruction,\n getInitializePermanentDelegateInstruction,\n getInitializeScaledUiAmountMintInstruction,\n getInitializeConfidentialTransferFeeInstruction,\n getInitializePausableConfigInstruction,\n} from './generated';\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _before_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPreInitializeInstructionsForMintExtensions(\n mint: Address,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'ConfidentialTransferMint':\n return [\n getInitializeConfidentialTransferMintInstruction({\n mint,\n ...extension,\n }),\n ];\n case 'DefaultAccountState':\n return [\n getInitializeDefaultAccountStateInstruction({\n mint,\n state: extension.state,\n }),\n ];\n case 'TransferFeeConfig':\n return [\n getInitializeTransferFeeConfigInstruction({\n mint,\n transferFeeConfigAuthority: extension.transferFeeConfigAuthority,\n withdrawWithheldAuthority: extension.withdrawWithheldAuthority,\n transferFeeBasisPoints:\n extension.newerTransferFee.transferFeeBasisPoints,\n maximumFee: extension.newerTransferFee.maximumFee,\n }),\n ];\n case 'MetadataPointer':\n return [\n getInitializeMetadataPointerInstruction({\n mint,\n authority: extension.authority,\n metadataAddress: extension.metadataAddress,\n }),\n ];\n case 'InterestBearingConfig':\n return [\n getInitializeInterestBearingMintInstruction({\n mint,\n rateAuthority: extension.rateAuthority,\n rate: extension.currentRate,\n }),\n ];\n case 'ScaledUiAmountConfig':\n return [\n getInitializeScaledUiAmountMintInstruction({\n mint,\n authority: extension.authority,\n multiplier: extension.multiplier,\n }),\n ];\n case 'PausableConfig':\n return [\n getInitializePausableConfigInstruction({\n mint,\n authority: extension.authority,\n }),\n ];\n case 'GroupPointer':\n return [\n getInitializeGroupPointerInstruction({\n mint,\n authority: extension.authority,\n groupAddress: extension.groupAddress,\n }),\n ];\n case 'GroupMemberPointer':\n return [\n getInitializeGroupMemberPointerInstruction({\n mint,\n authority: extension.authority,\n memberAddress: extension.memberAddress,\n }),\n ];\n case 'NonTransferable':\n return getInitializeNonTransferableMintInstruction({ mint });\n case 'TransferHook':\n return [\n getInitializeTransferHookInstruction({\n mint,\n authority: extension.authority,\n programId: extension.programId,\n }),\n ];\n case 'PermanentDelegate':\n return getInitializePermanentDelegateInstruction({\n mint,\n delegate: extension.delegate,\n });\n case 'ConfidentialTransferFee':\n return [\n getInitializeConfidentialTransferFeeInstruction({\n mint,\n authority: extension.authority,\n withdrawWithheldAuthorityElGamalPubkey: extension.elgamalPubkey,\n }),\n ];\n case 'MintCloseAuthority':\n return getInitializeMintCloseAuthorityInstruction({\n closeAuthority: extension.closeAuthority,\n mint,\n });\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a mint address and a list of mint extensions, returns a list of\n * instructions that MUST be run _after_ the `initializeMint` instruction\n * to properly initialize the given extensions on the mint account.\n */\nexport function getPostInitializeInstructionsForMintExtensions(\n mint: Address,\n authority: TransactionSigner,\n extensions: ExtensionArgs[]\n): Instruction[] {\n return extensions.flatMap((extension): Instruction[] => {\n switch (extension.__kind) {\n case 'TokenMetadata':\n // eslint-disable-next-line no-case-declarations\n const tokenMetadataUpdateAuthority = isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority);\n if (isNone(tokenMetadataUpdateAuthority)) {\n return [];\n }\n return [\n getInitializeTokenMetadataInstruction({\n metadata: mint,\n updateAuthority: tokenMetadataUpdateAuthority.value,\n mint,\n mintAuthority: authority,\n name: extension.name,\n symbol: extension.symbol,\n uri: extension.uri,\n }),\n ];\n case 'TokenGroup':\n return [\n getInitializeTokenGroupInstruction({\n group: mint,\n updateAuthority: isOption(extension.updateAuthority)\n ? extension.updateAuthority\n : wrapNullable(extension.updateAuthority),\n mint,\n mintAuthority: authority,\n maxSize: extension.maxSize,\n }),\n ];\n default:\n return [];\n }\n });\n}\n\n/**\n * Given a token address, its owner and a list of token extensions, returns a list\n * of instructions that MUST be run _after_ the `initializeAccount` instruction\n * to properly initialize the given extensions on the token account.\n */\nexport function getPostInitializeInstructionsForTokenExtensions(\n token: Address,\n owner: TransactionSigner | Address,\n extensions: ExtensionArgs[],\n multiSigners?: TransactionSigner[]\n): Instruction[] {\n return extensions.flatMap((extension) => {\n switch (extension.__kind) {\n case 'MemoTransfer':\n return [\n extension.requireIncomingTransferMemos\n ? getEnableMemoTransfersInstruction({ owner, token, multiSigners })\n : getDisableMemoTransfersInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n case 'CpiGuard':\n return [\n extension.lockCpi\n ? getEnableCpiGuardInstruction({ owner, token, multiSigners })\n : getDisableCpiGuardInstruction({\n owner,\n token,\n multiSigners,\n }),\n ];\n default:\n return [];\n }\n });\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst TOKEN_BASE_SIZE = 165;\n\nexport function getTokenSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return TOKEN_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(getU8Encoder().encode(2))]\n );\n return TOKEN_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","import {\n getArrayEncoder,\n getConstantEncoder,\n getHiddenPrefixEncoder,\n getU8Encoder,\n padLeftEncoder,\n} from '@solana/kit';\nimport { ExtensionArgs, getExtensionEncoder } from './generated';\n\nconst MINT_BASE_SIZE = 82;\n\nexport function getMintSize(extensions?: ExtensionArgs[]): number {\n if (extensions == null) return MINT_BASE_SIZE;\n const tvlEncoder = getHiddenPrefixEncoder(\n getArrayEncoder(getExtensionEncoder(), { size: 'remainder' }),\n [getConstantEncoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]\n );\n return MINT_BASE_SIZE + tvlEncoder.encode(extensions).length;\n}\n","/**\n * Token program addresses for SPL Token and Token-2022\n * These addresses are the same across all Solana networks (mainnet, devnet, testnet)\n */\nexport const TOKEN_PROGRAM_ADDRESS = \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\";\nexport const TOKEN_2022_PROGRAM_ADDRESS = \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\";\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS = \"ComputeBudget111111111111111111111111111111\";\nexport const MEMO_PROGRAM_ADDRESS = \"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\";\n\n/**\n * Phantom/Solflare Lighthouse program address\n * Phantom and Solflare wallets inject Lighthouse instructions for user protection on mainnet transactions.\n * - Phantom adds 1 Lighthouse instruction (4th instruction)\n * - Solflare adds 2 Lighthouse instructions (4th and 5th instructions)\n * We allow these as optional instructions to support these wallets.\n * See: https://github.com/coinbase/x402/issues/828\n */\nexport const LIGHTHOUSE_PROGRAM_ADDRESS = \"L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95\";\n\n/**\n * Default RPC URLs for Solana networks\n */\nexport const DEVNET_RPC_URL = \"https://api.devnet.solana.com\";\nexport const TESTNET_RPC_URL = \"https://api.testnet.solana.com\";\nexport const MAINNET_RPC_URL = \"https://api.mainnet-beta.solana.com\";\nexport const DEVNET_WS_URL = \"wss://api.devnet.solana.com\";\nexport const TESTNET_WS_URL = \"wss://api.testnet.solana.com\";\nexport const MAINNET_WS_URL = \"wss://api.mainnet-beta.solana.com\";\n\n/**\n * USDC token mint addresses (default stablecoin)\n */\nexport const USDC_MAINNET_ADDRESS = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nexport const USDC_DEVNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\";\nexport const USDC_TESTNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\"; // Same as devnet\n\n/**\n * Compute budget configuration\n * All prices are in microlamports (1 lamport = 1,000,000 microlamports)\n */\nexport const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;\nexport const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 5_000_000; // 5 lamports\nexport const DEFAULT_COMPUTE_UNIT_LIMIT = 20_000;\n\n/**\n * How long a transaction is held in the duplicate settlement cache (ms).\n * Covers the Solana blockhash lifetime (~60-90s) with margin.\n */\nexport const SETTLEMENT_TTL_MS = 120_000;\n\n/**\n * Solana address validation regex (base58, 32-44 characters)\n */\nexport const SVM_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * CAIP-2 network identifiers for Solana (V2)\n */\nexport const SOLANA_MAINNET_CAIP2 = \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\";\nexport const SOLANA_DEVNET_CAIP2 = \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\";\nexport const SOLANA_TESTNET_CAIP2 = \"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z\";\n\n/**\n * V1 to V2 network identifier mappings (for backwards compatibility)\n * V1 used simple names like solana, V2 uses CAIP-2\n */\nexport const V1_TO_V2_NETWORK_MAP: Record = {\n solana: SOLANA_MAINNET_CAIP2,\n \"solana-devnet\": SOLANA_DEVNET_CAIP2,\n \"solana-testnet\": SOLANA_TESTNET_CAIP2,\n};\n","import {\n getBase64Encoder,\n getTransactionDecoder,\n getCompiledTransactionMessageDecoder,\n type Transaction,\n createSolanaRpc,\n devnet,\n testnet,\n mainnet,\n type RpcDevnet,\n type SolanaRpcApiDevnet,\n type RpcTestnet,\n type SolanaRpcApiTestnet,\n type RpcMainnet,\n type SolanaRpcApiMainnet,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { TOKEN_2022_PROGRAM_ADDRESS } from \"@solana-program/token-2022\";\nimport type { Network } from \"@x402/core/types\";\nimport {\n SVM_ADDRESS_REGEX,\n DEVNET_RPC_URL,\n TESTNET_RPC_URL,\n MAINNET_RPC_URL,\n USDC_MAINNET_ADDRESS,\n USDC_DEVNET_ADDRESS,\n USDC_TESTNET_ADDRESS,\n SOLANA_MAINNET_CAIP2,\n SOLANA_DEVNET_CAIP2,\n SOLANA_TESTNET_CAIP2,\n V1_TO_V2_NETWORK_MAP,\n} from \"./constants\";\nimport type { ExactSvmPayloadV1 } from \"./types\";\n\n/**\n * Normalize network identifier to CAIP-2 format\n * Handles both V1 names (solana, solana-devnet) and V2 CAIP-2 format\n *\n * @param network - Network identifier (V1 or V2 format)\n * @returns CAIP-2 network identifier\n */\nexport function normalizeNetwork(network: Network): string {\n // If it's already CAIP-2 format (contains \":\"), validate it's supported\n if (network.includes(\":\")) {\n const supported = [SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];\n if (!supported.includes(network)) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return network;\n }\n\n // Otherwise, it's a V1 network name, convert to CAIP-2\n const caip2Network = V1_TO_V2_NETWORK_MAP[network];\n if (!caip2Network) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return caip2Network;\n}\n\n/**\n * Validate Solana address format\n *\n * @param address - Base58 encoded address string\n * @returns true if address is valid, false otherwise\n */\nexport function validateSvmAddress(address: string): boolean {\n return SVM_ADDRESS_REGEX.test(address);\n}\n\n/**\n * Decode a base64 encoded transaction from an SVM payload\n *\n * @param svmPayload - The SVM payload containing a base64 encoded transaction\n * @returns Decoded Transaction object\n */\nexport function decodeTransactionFromPayload(svmPayload: ExactSvmPayloadV1): Transaction {\n try {\n const base64Encoder = getBase64Encoder();\n const transactionBytes = base64Encoder.encode(svmPayload.transaction);\n const transactionDecoder = getTransactionDecoder();\n return transactionDecoder.decode(transactionBytes);\n } catch (error) {\n console.error(\"Error decoding transaction:\", error);\n throw new Error(\"invalid_exact_svm_payload_transaction\");\n }\n}\n\n/**\n * Extract the token sender (owner of the source token account) from a TransferChecked instruction\n *\n * @param transaction - The decoded transaction\n * @returns The token payer address as a base58 string\n */\nexport function getTokenPayerFromTransaction(transaction: Transaction): string {\n const compiled = getCompiledTransactionMessageDecoder().decode(transaction.messageBytes);\n const staticAccounts = compiled.staticAccounts ?? [];\n const instructions = compiled.instructions ?? [];\n\n for (const ix of instructions) {\n const programIndex = ix.programAddressIndex;\n const programAddress = staticAccounts[programIndex].toString();\n\n // Check if this is a token program instruction\n if (\n programAddress === TOKEN_PROGRAM_ADDRESS.toString() ||\n programAddress === TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n const accountIndices: number[] = ix.accountIndices ?? [];\n // TransferChecked account order: [source, mint, destination, owner, ...]\n if (accountIndices.length >= 4) {\n const ownerIndex = accountIndices[3];\n const ownerAddress = staticAccounts[ownerIndex].toString();\n if (ownerAddress) return ownerAddress;\n }\n }\n }\n\n return \"\";\n}\n\n/**\n * Create an RPC client for the specified network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @param customRpcUrl - Optional custom RPC URL\n * @returns RPC client for the specified network\n */\nexport function createRpcClient(\n network: Network,\n customRpcUrl?: string,\n):\n | RpcDevnet\n | RpcTestnet\n | RpcMainnet {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_DEVNET_CAIP2: {\n const url = customRpcUrl || DEVNET_RPC_URL;\n return createSolanaRpc(devnet(url)) as RpcDevnet;\n }\n case SOLANA_TESTNET_CAIP2: {\n const url = customRpcUrl || TESTNET_RPC_URL;\n return createSolanaRpc(testnet(url)) as RpcTestnet;\n }\n case SOLANA_MAINNET_CAIP2: {\n const url = customRpcUrl || MAINNET_RPC_URL;\n return createSolanaRpc(mainnet(url)) as RpcMainnet;\n }\n default:\n throw new Error(`Unsupported network: ${network}`);\n }\n}\n\n/**\n * Get the default USDC mint address for a network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @returns USDC mint address for the network\n */\nexport function getUsdcAddress(network: Network): string {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_MAINNET_CAIP2:\n return USDC_MAINNET_ADDRESS;\n case SOLANA_DEVNET_CAIP2:\n return USDC_DEVNET_ADDRESS;\n case SOLANA_TESTNET_CAIP2:\n return USDC_TESTNET_ADDRESS;\n default:\n throw new Error(`No USDC address configured for network: ${network}`);\n }\n}\n\n/**\n * Convert a decimal amount to token smallest units\n *\n * @param decimalAmount - The decimal amount (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n const amount = parseFloat(decimalAmount);\n if (isNaN(amount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n // Convert to smallest unit (e.g., for USDC with 6 decimals: 0.10 * 10^6 = 100000)\n const [intPart, decPart = \"\"] = String(amount).split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n return tokenAmount;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n getU8Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n type ParsedRequestHeapFrameInstruction,\n type ParsedRequestUnitsInstruction,\n type ParsedSetComputeUnitLimitInstruction,\n type ParsedSetComputeUnitPriceInstruction,\n type ParsedSetLoadedAccountsDataSizeLimitInstruction,\n} from '../instructions';\n\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS =\n 'ComputeBudget111111111111111111111111111111' as Address<'ComputeBudget111111111111111111111111111111'>;\n\nexport enum ComputeBudgetInstruction {\n RequestUnits,\n RequestHeapFrame,\n SetComputeUnitLimit,\n SetComputeUnitPrice,\n SetLoadedAccountsDataSizeLimit,\n}\n\nexport function identifyComputeBudgetInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ComputeBudgetInstruction {\n const data = 'data' in instruction ? instruction.data : instruction;\n if (containsBytes(data, getU8Encoder().encode(0), 0)) {\n return ComputeBudgetInstruction.RequestUnits;\n }\n if (containsBytes(data, getU8Encoder().encode(1), 0)) {\n return ComputeBudgetInstruction.RequestHeapFrame;\n }\n if (containsBytes(data, getU8Encoder().encode(2), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitLimit;\n }\n if (containsBytes(data, getU8Encoder().encode(3), 0)) {\n return ComputeBudgetInstruction.SetComputeUnitPrice;\n }\n if (containsBytes(data, getU8Encoder().encode(4), 0)) {\n return ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n }\n throw new Error(\n 'The provided instruction could not be identified as a computeBudget instruction.'\n );\n}\n\nexport type ParsedComputeBudgetInstruction<\n TProgram extends string = 'ComputeBudget111111111111111111111111111111',\n> =\n | ({\n instructionType: ComputeBudgetInstruction.RequestUnits;\n } & ParsedRequestUnitsInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.RequestHeapFrame;\n } & ParsedRequestHeapFrameInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitLimit;\n } & ParsedSetComputeUnitLimitInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetComputeUnitPrice;\n } & ParsedSetComputeUnitPriceInstruction)\n | ({\n instructionType: ComputeBudgetInstruction.SetLoadedAccountsDataSizeLimit;\n } & ParsedSetLoadedAccountsDataSizeLimitInstruction);\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_HEAP_FRAME_DISCRIMINATOR = 1;\n\nexport function getRequestHeapFrameDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_HEAP_FRAME_DISCRIMINATOR);\n}\n\nexport type RequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestHeapFrameInstructionData = {\n discriminator: number;\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport type RequestHeapFrameInstructionDataArgs = {\n /**\n * Requested transaction-wide program heap size in bytes.\n * Must be multiple of 1024. Applies to each program, including CPIs.\n */\n bytes: number;\n};\n\nexport function getRequestHeapFrameInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['bytes', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_HEAP_FRAME_DISCRIMINATOR })\n );\n}\n\nexport function getRequestHeapFrameInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['bytes', getU32Decoder()],\n ]);\n}\n\nexport function getRequestHeapFrameInstructionDataCodec(): FixedSizeCodec<\n RequestHeapFrameInstructionDataArgs,\n RequestHeapFrameInstructionData\n> {\n return combineCodec(\n getRequestHeapFrameInstructionDataEncoder(),\n getRequestHeapFrameInstructionDataDecoder()\n );\n}\n\nexport type RequestHeapFrameInput = {\n bytes: RequestHeapFrameInstructionDataArgs['bytes'];\n};\n\nexport function getRequestHeapFrameInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestHeapFrameInput,\n config?: { programAddress?: TProgramAddress }\n): RequestHeapFrameInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestHeapFrameInstructionDataEncoder().encode(\n args as RequestHeapFrameInstructionDataArgs\n ),\n programAddress,\n } as RequestHeapFrameInstruction);\n}\n\nexport type ParsedRequestHeapFrameInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: RequestHeapFrameInstructionData;\n};\n\nexport function parseRequestHeapFrameInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestHeapFrameInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestHeapFrameInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const REQUEST_UNITS_DISCRIMINATOR = 0;\n\nexport function getRequestUnitsDiscriminatorBytes() {\n return getU8Encoder().encode(REQUEST_UNITS_DISCRIMINATOR);\n}\n\nexport type RequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type RequestUnitsInstructionData = {\n discriminator: number;\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport type RequestUnitsInstructionDataArgs = {\n /** Units to request for transaction-wide compute. */\n units: number;\n /** Prioritization fee lamports. */\n additionalFee: number;\n};\n\nexport function getRequestUnitsInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ['additionalFee', getU32Encoder()],\n ]),\n (value) => ({ ...value, discriminator: REQUEST_UNITS_DISCRIMINATOR })\n );\n}\n\nexport function getRequestUnitsInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ['additionalFee', getU32Decoder()],\n ]);\n}\n\nexport function getRequestUnitsInstructionDataCodec(): FixedSizeCodec<\n RequestUnitsInstructionDataArgs,\n RequestUnitsInstructionData\n> {\n return combineCodec(\n getRequestUnitsInstructionDataEncoder(),\n getRequestUnitsInstructionDataDecoder()\n );\n}\n\nexport type RequestUnitsInput = {\n units: RequestUnitsInstructionDataArgs['units'];\n additionalFee: RequestUnitsInstructionDataArgs['additionalFee'];\n};\n\nexport function getRequestUnitsInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: RequestUnitsInput,\n config?: { programAddress?: TProgramAddress }\n): RequestUnitsInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRequestUnitsInstructionDataEncoder().encode(\n args as RequestUnitsInstructionDataArgs\n ),\n programAddress,\n } as RequestUnitsInstruction);\n}\n\nexport type ParsedRequestUnitsInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = { programAddress: Address; data: RequestUnitsInstructionData };\n\nexport function parseRequestUnitsInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedRequestUnitsInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getRequestUnitsInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR = 2;\n\nexport function getSetComputeUnitLimitDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitLimitInstructionData = {\n discriminator: number;\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport type SetComputeUnitLimitInstructionDataArgs = {\n /** Transaction-wide compute unit limit. */\n units: number;\n};\n\nexport function getSetComputeUnitLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['units', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['units', getU32Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitLimitInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitLimitInstructionDataArgs,\n SetComputeUnitLimitInstructionData\n> {\n return combineCodec(\n getSetComputeUnitLimitInstructionDataEncoder(),\n getSetComputeUnitLimitInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitLimitInput = {\n units: SetComputeUnitLimitInstructionDataArgs['units'];\n};\n\nexport function getSetComputeUnitLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitLimitInstructionDataEncoder().encode(\n args as SetComputeUnitLimitInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitLimitInstruction);\n}\n\nexport type ParsedSetComputeUnitLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitLimitInstructionData;\n};\n\nexport function parseSetComputeUnitLimitInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR = 3;\n\nexport function getSetComputeUnitPriceDiscriminatorBytes() {\n return getU8Encoder().encode(SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR);\n}\n\nexport type SetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetComputeUnitPriceInstructionData = {\n discriminator: number;\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: bigint;\n};\n\nexport type SetComputeUnitPriceInstructionDataArgs = {\n /** Transaction compute unit price used for prioritization fees. */\n microLamports: number | bigint;\n};\n\nexport function getSetComputeUnitPriceInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['microLamports', getU64Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetComputeUnitPriceInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['microLamports', getU64Decoder()],\n ]);\n}\n\nexport function getSetComputeUnitPriceInstructionDataCodec(): FixedSizeCodec<\n SetComputeUnitPriceInstructionDataArgs,\n SetComputeUnitPriceInstructionData\n> {\n return combineCodec(\n getSetComputeUnitPriceInstructionDataEncoder(),\n getSetComputeUnitPriceInstructionDataDecoder()\n );\n}\n\nexport type SetComputeUnitPriceInput = {\n microLamports: SetComputeUnitPriceInstructionDataArgs['microLamports'];\n};\n\nexport function getSetComputeUnitPriceInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetComputeUnitPriceInput,\n config?: { programAddress?: TProgramAddress }\n): SetComputeUnitPriceInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetComputeUnitPriceInstructionDataEncoder().encode(\n args as SetComputeUnitPriceInstructionDataArgs\n ),\n programAddress,\n } as SetComputeUnitPriceInstruction);\n}\n\nexport type ParsedSetComputeUnitPriceInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetComputeUnitPriceInstructionData;\n};\n\nexport function parseSetComputeUnitPriceInstruction(\n instruction: Instruction & InstructionWithData\n): ParsedSetComputeUnitPriceInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetComputeUnitPriceInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport { COMPUTE_BUDGET_PROGRAM_ADDRESS } from '../programs';\n\nexport const SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR = 4;\n\nexport function getSetLoadedAccountsDataSizeLimitDiscriminatorBytes() {\n return getU8Encoder().encode(\n SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta[] = [],\n> = Instruction &\n InstructionWithData &\n InstructionWithAccounts;\n\nexport type SetLoadedAccountsDataSizeLimitInstructionData = {\n discriminator: number;\n accountDataSizeLimit: number;\n};\n\nexport type SetLoadedAccountsDataSizeLimitInstructionDataArgs = {\n accountDataSizeLimit: number;\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(): FixedSizeEncoder {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', getU8Encoder()],\n ['accountDataSizeLimit', getU32Encoder()],\n ]),\n (value) => ({\n ...value,\n discriminator: SET_LOADED_ACCOUNTS_DATA_SIZE_LIMIT_DISCRIMINATOR,\n })\n );\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataDecoder(): FixedSizeDecoder {\n return getStructDecoder([\n ['discriminator', getU8Decoder()],\n ['accountDataSizeLimit', getU32Decoder()],\n ]);\n}\n\nexport function getSetLoadedAccountsDataSizeLimitInstructionDataCodec(): FixedSizeCodec<\n SetLoadedAccountsDataSizeLimitInstructionDataArgs,\n SetLoadedAccountsDataSizeLimitInstructionData\n> {\n return combineCodec(\n getSetLoadedAccountsDataSizeLimitInstructionDataEncoder(),\n getSetLoadedAccountsDataSizeLimitInstructionDataDecoder()\n );\n}\n\nexport type SetLoadedAccountsDataSizeLimitInput = {\n accountDataSizeLimit: SetLoadedAccountsDataSizeLimitInstructionDataArgs['accountDataSizeLimit'];\n};\n\nexport function getSetLoadedAccountsDataSizeLimitInstruction<\n TProgramAddress extends Address = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n>(\n input: SetLoadedAccountsDataSizeLimitInput,\n config?: { programAddress?: TProgramAddress }\n): SetLoadedAccountsDataSizeLimitInstruction {\n // Program address.\n const programAddress =\n config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getSetLoadedAccountsDataSizeLimitInstructionDataEncoder().encode(\n args as SetLoadedAccountsDataSizeLimitInstructionDataArgs\n ),\n programAddress,\n } as SetLoadedAccountsDataSizeLimitInstruction);\n}\n\nexport type ParsedSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string = typeof COMPUTE_BUDGET_PROGRAM_ADDRESS,\n> = {\n programAddress: Address;\n data: SetLoadedAccountsDataSizeLimitInstructionData;\n};\n\nexport function parseSetLoadedAccountsDataSizeLimitInstruction<\n TProgram extends string,\n>(\n instruction: Instruction & InstructionWithData\n): ParsedSetLoadedAccountsDataSizeLimitInstruction {\n return {\n programAddress: instruction.programAddress,\n data: getSetLoadedAccountsDataSizeLimitInstructionDataDecoder().decode(\n instruction.data\n ),\n };\n}\n","/**\n * A provisory compute unit limit is used to indicate that the transaction\n * should be estimated for compute units before being sent to the network.\n *\n * Setting it to zero ensures the transaction fails unless it is properly estimated.\n */\nexport const PROVISORY_COMPUTE_UNIT_LIMIT = 0;\n\n/**\n * The maximum compute unit limit that can be set for a transaction.\n */\nexport const MAX_COMPUTE_UNIT_LIMIT = 1_400_000;\n","import {\n BaseTransactionMessage,\n getU32Decoder,\n getU64Decoder,\n Instruction,\n MicroLamports,\n ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n COMPUTE_BUDGET_PROGRAM_ADDRESS,\n ComputeBudgetInstruction,\n identifyComputeBudgetInstruction,\n SetComputeUnitLimitInstruction,\n SetComputeUnitPriceInstruction,\n} from './generated';\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message\n * and its set limit, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndexAndUnits(\n transactionMessage: BaseTransactionMessage\n): { index: number; units: number } | null {\n const index = getSetComputeUnitLimitInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const units = getU32Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n );\n\n return { index, units };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitLimit` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitLimitInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitLimitInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitLimit` instruction.\n */\nexport function isSetComputeUnitLimitInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitLimitInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitLimit\n );\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message\n * and its set micro-lamports, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndexAndMicroLamports(\n transactionMessage: BaseTransactionMessage\n): { index: number; microLamports: MicroLamports } | null {\n const index = getSetComputeUnitPriceInstructionIndex(transactionMessage);\n if (index < 0) {\n return null;\n }\n\n const microLamports = getU64Decoder().decode(\n transactionMessage.instructions[index].data as ReadonlyUint8Array,\n 1\n ) as MicroLamports;\n\n return { index, microLamports };\n}\n\n/**\n * Finds the index of the first `SetComputeUnitPrice` instruction in a transaction message, if any.\n */\nexport function getSetComputeUnitPriceInstructionIndex(\n transactionMessage: BaseTransactionMessage\n) {\n return transactionMessage.instructions.findIndex(\n isSetComputeUnitPriceInstruction\n );\n}\n\n/**\n * Checks if the given instruction is a `SetComputeUnitPrice` instruction.\n */\nexport function isSetComputeUnitPriceInstruction(\n instruction: Instruction\n): instruction is SetComputeUnitPriceInstruction {\n return (\n instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS &&\n identifyComputeBudgetInstruction(instruction.data as Uint8Array) ===\n ComputeBudgetInstruction.SetComputeUnitPrice\n );\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n} from '@solana/kit';\nimport { PROVISORY_COMPUTE_UNIT_LIMIT } from './constants';\nimport { getSetComputeUnitLimitInstruction } from './generated';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\n\n/**\n * Appends a `SetComputeUnitLimit` instruction with a provisory\n * compute unit limit to a given transaction message\n * if and only if it does not already have one.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * fillProvisorySetComputeUnitLimitInstruction,\n * // ...\n * );\n * ```\n */\nexport function fillProvisorySetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(transactionMessage: TTransactionMessage) {\n return updateOrAppendSetComputeUnitLimitInstruction(\n (previousUnits) =>\n previousUnits === null ? PROVISORY_COMPUTE_UNIT_LIMIT : previousUnits,\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitLimit` instruction in a transaction message\n * with the given units, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param units - The new compute unit limit, or a function that takes the previous\n * compute unit limit and returns the new limit.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitLimitInstruction(\n * // E.g. Keep the current limit if it is set, otherwise set it to the maximum.\n * (currentUnits) => currentUnits === null ? MAX_COMPUTE_UNIT_LIMIT : currentUnits,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitLimitInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n units: number | ((previousUnits: number | null) => number),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getUnits = (previousUnits: number | null): number =>\n typeof units === 'function' ? units(previousUnits) : units;\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: getUnits(null) }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, units: previousUnits } = instructionDetails;\n const newUnits = getUnits(previousUnits);\n if (newUnits === previousUnits) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitLimitInstruction({ units: newUnits });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n BaseTransactionMessage,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport {\n MAX_COMPUTE_UNIT_LIMIT,\n PROVISORY_COMPUTE_UNIT_LIMIT,\n} from './constants';\nimport {\n EstimateComputeUnitLimitFactoryFunction,\n EstimateComputeUnitLimitFactoryFunctionConfig,\n} from './estimateComputeLimitInternal';\nimport { getSetComputeUnitLimitInstructionIndexAndUnits } from './internal';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\n\ntype EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction = <\n TTransactionMessage extends BaseTransactionMessage &\n TransactionMessageWithFeePayer,\n>(\n transactionMessage: TTransactionMessage,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\n/**\n * Given a transaction message, if it does not have an explicit compute unit limit,\n * estimates the compute unit limit and updates the transaction message with\n * the estimated limit. Otherwise, returns the transaction message unchanged.\n *\n * It requires a function that estimates the compute unit limit.\n *\n * @example\n * ```ts\n * const estimateAndUpdateCUs = estimateAndUpdateProvisoryComputeUnitLimitFactory(\n * estimateComputeUnitLimitFactory({ rpc })\n * );\n *\n * const transactionMessageWithCUs = await estimateAndUpdateCUs(transactionMessage);\n * ```\n *\n * @see {@link estimateAndUpdateProvisoryComputeUnitLimitFactory}\n */\nexport function estimateAndUpdateProvisoryComputeUnitLimitFactory(\n estimateComputeUnitLimit: EstimateComputeUnitLimitFactoryFunction\n): EstimateAndUpdateProvisoryComputeUnitLimitFactoryFunction {\n return async function fn(transactionMessage, config) {\n const instructionDetails =\n getSetComputeUnitLimitInstructionIndexAndUnits(transactionMessage);\n\n // If the transaction message already has a compute unit limit instruction\n // which is set to a specific value — i.e. not 0 or the maximum limit —\n // we don't need to estimate the compute unit limit.\n if (\n instructionDetails &&\n instructionDetails.units !== PROVISORY_COMPUTE_UNIT_LIMIT &&\n instructionDetails.units !== MAX_COMPUTE_UNIT_LIMIT\n ) {\n return transactionMessage;\n }\n\n return updateOrAppendSetComputeUnitLimitInstruction(\n await estimateComputeUnitLimit(transactionMessage, config),\n transactionMessage\n );\n };\n}\n","import {\n BaseTransactionMessage,\n Commitment,\n compileTransaction,\n getBase64EncodedWireTransaction,\n isSolanaError,\n isTransactionMessageWithDurableNonceLifetime,\n pipe,\n Rpc,\n SimulateTransactionApi,\n Slot,\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n SolanaError,\n Transaction,\n TransactionMessageWithFeePayer,\n} from '@solana/kit';\nimport { updateOrAppendSetComputeUnitLimitInstruction } from './setComputeLimit';\nimport { MAX_COMPUTE_UNIT_LIMIT } from './constants';\n\nexport type EstimateComputeUnitLimitFactoryConfig = Readonly<{\n /** An object that supports the {@link SimulateTransactionApi} of the Solana RPC API */\n rpc: Rpc;\n}>;\n\nexport type EstimateComputeUnitLimitFactoryFunction = (\n transactionMessage: BaseTransactionMessage & TransactionMessageWithFeePayer,\n config?: EstimateComputeUnitLimitFactoryFunctionConfig\n) => Promise;\n\nexport type EstimateComputeUnitLimitFactoryFunctionConfig = {\n abortSignal?: AbortSignal;\n /**\n * Compute the estimate as of the highest slot that has reached this level of commitment.\n *\n * @defaultValue Whichever default is applied by the underlying {@link RpcApi} in use. For\n * example, when using an API created by a `createSolanaRpc*()` helper, the default commitment\n * is `\"confirmed\"` unless configured otherwise. Unmitigated by an API layer on the client, the\n * default commitment applied by the server is `\"finalized\"`.\n */\n commitment?: Commitment;\n /**\n * Prevents accessing stale data by enforcing that the RPC node has processed transactions up to\n * this slot\n */\n minContextSlot?: Slot;\n};\n\ntype EstimateComputeUnitLimitConfig =\n EstimateComputeUnitLimitFactoryFunctionConfig &\n Readonly<{\n rpc: Rpc;\n transactionMessage: BaseTransactionMessage &\n TransactionMessageWithFeePayer;\n }>;\n\n/**\n * Simulates a transaction message on the network and returns the number of compute units it\n * consumed during simulation.\n *\n * The estimate this function returns can be used to set a compute unit limit on the transaction.\n * Correctly budgeting a compute unit limit for your transaction message can increase the probability\n * that your transaction will be accepted for processing.\n *\n * If you don't declare a compute unit limit on your transaction, validators will assume an upper\n * limit of 200K compute units (CU) per instruction. Since validators have an incentive to pack as\n * many transactions into each block as possible, they may choose to include transactions that they\n * know will fit into the remaining compute budget for the current block over transactions that\n * might not. For this reason, you should set a compute unit limit on each of your transaction\n * messages, whenever possible.\n *\n * ## Example\n *\n * ```ts\n * import { getSetComputeLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const getComputeUnitEstimateForTransactionMessage =\n * getComputeUnitEstimateForTransactionMessageFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume.\n * const computeUnitsEstimate =\n * await getComputeUnitEstimateForTransactionMessage(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeLimitInstruction({ units: computeUnitsEstimate }),\n * transactionMessage,\n * );\n * ```\n *\n * > [!WARNING]\n * > The compute unit estimate is just that – an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n */\nexport async function estimateComputeUnitLimit({\n transactionMessage,\n ...configs\n}: EstimateComputeUnitLimitConfig): Promise {\n const replaceRecentBlockhash =\n !isTransactionMessageWithDurableNonceLifetime(transactionMessage);\n const transaction = pipe(\n transactionMessage,\n (m) =>\n updateOrAppendSetComputeUnitLimitInstruction(MAX_COMPUTE_UNIT_LIMIT, m),\n compileTransaction\n );\n\n return await simulateTransactionAndGetConsumedUnits({\n transaction,\n replaceRecentBlockhash,\n ...configs,\n });\n}\n\ntype SimulateTransactionAndGetConsumedUnitsConfig = Omit<\n EstimateComputeUnitLimitConfig,\n 'transactionMessage'\n> &\n Readonly<{ replaceRecentBlockhash?: boolean; transaction: Transaction }>;\n\nasync function simulateTransactionAndGetConsumedUnits({\n abortSignal,\n rpc,\n transaction,\n ...simulateConfig\n}: SimulateTransactionAndGetConsumedUnitsConfig): Promise {\n const wireTransactionBytes = getBase64EncodedWireTransaction(transaction);\n\n try {\n const {\n value: { err: transactionError, unitsConsumed },\n } = await rpc\n .simulateTransaction(wireTransactionBytes, {\n ...simulateConfig,\n encoding: 'base64',\n sigVerify: false,\n })\n .send({ abortSignal });\n if (unitsConsumed == null) {\n // This should never be hit, because all RPCs should support `unitsConsumed` by now.\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT\n );\n }\n // FIXME(https://github.com/anza-xyz/agave/issues/1295): The simulation response returns\n // compute units as a u64, but the `SetComputeLimit` instruction only accepts a u32. Until\n // this changes, downcast it.\n const downcastUnitsConsumed =\n unitsConsumed > 4_294_967_295n ? 4_294_967_295 : Number(unitsConsumed);\n if (transactionError) {\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,\n {\n cause: transactionError,\n unitsConsumed: downcastUnitsConsumed,\n }\n );\n }\n return downcastUnitsConsumed;\n } catch (e) {\n if (\n isSolanaError(\n e,\n SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT\n )\n )\n throw e;\n throw new SolanaError(\n SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,\n { cause: e }\n );\n }\n}\n","import {\n estimateComputeUnitLimit,\n EstimateComputeUnitLimitFactoryConfig,\n EstimateComputeUnitLimitFactoryFunction,\n} from './estimateComputeLimitInternal';\n\n/**\n * Use this utility to estimate the actual compute unit cost of a given transaction message.\n *\n * Correctly budgeting a compute unit limit for your transaction message can increase the\n * probability that your transaction will be accepted for processing. If you don't declare a compute\n * unit limit on your transaction, validators will assume an upper limit of 200K compute units (CU)\n * per instruction.\n *\n * Since validators have an incentive to pack as many transactions into each block as possible, they\n * may choose to include transactions that they know will fit into the remaining compute budget for\n * the current block over transactions that might not. For this reason, you should set a compute\n * unit limit on each of your transaction messages, whenever possible.\n *\n * > [!WARNING]\n * > The compute unit estimate is just that -- an estimate. The compute unit consumption of the\n * > actual transaction might be higher or lower than what was observed in simulation. Unless you\n * > are confident that your particular transaction message will consume the same or fewer compute\n * > units as was estimated, you might like to augment the estimate by either a fixed number of CUs\n * > or a multiplier.\n *\n * > [!NOTE]\n * > If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the\n * > network by a wallet, you might like to leave it up to the wallet to determine the compute unit\n * > limit. Consider that the wallet might have a more global view of how many compute units certain\n * > types of transactions consume, and might be able to make better estimates of an appropriate\n * > compute unit budget.\n *\n * > [!INFO]\n * > In the event that a transaction message does not already have a `SetComputeUnitLimit`\n * > instruction, this function will add one before simulation. This ensures that the compute unit\n * > consumption of the `SetComputeUnitLimit` instruction itself is included in the estimate.\n *\n * @param config\n *\n * @example\n * ```ts\n * import { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';\n * import { createSolanaRpc, estimateComputeUnitLimitFactory, pipe } from '@solana/kit';\n *\n * // Create an estimator function.\n * const rpc = createSolanaRpc('http://127.0.0.1:8899');\n * const estimateComputeUnitLimit = estimateComputeUnitLimitFactory({ rpc });\n *\n * // Create your transaction message.\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 'legacy' }),\n * /* ... *\\/\n * );\n *\n * // Request an estimate of the actual compute units this message will consume. This is done by\n * // simulating the transaction and grabbing the estimated compute units from the result.\n * const estimatedUnits = await estimateComputeUnitLimit(transactionMessage);\n *\n * // Set the transaction message's compute unit budget.\n * const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n * getSetComputeUnitLimitInstruction({ units: estimatedUnits }),\n * transactionMessage,\n * );\n * ```\n */\nexport function estimateComputeUnitLimitFactory({\n rpc,\n}: EstimateComputeUnitLimitFactoryConfig): EstimateComputeUnitLimitFactoryFunction {\n return async function estimateComputeUnitLimitFactoryFunction(\n transactionMessage,\n config\n ) {\n return await estimateComputeUnitLimit({\n ...config,\n rpc,\n transactionMessage,\n });\n };\n}\n","import {\n appendTransactionMessageInstruction,\n BaseTransactionMessage,\n MicroLamports,\n} from '@solana/kit';\nimport { getSetComputeUnitPriceInstruction } from './generated';\nimport { getSetComputeUnitPriceInstructionIndexAndMicroLamports } from './internal';\n\n/**\n * Sets the compute unit price of a transaction message in micro-Lamports.\n *\n * @example\n * ```ts\n * const transactionMessage = pipe(\n * createTransactionMessage({ version: 0 }),\n * (m) => setTransactionMessageComputeUnitPrice(10_000, m),\n * // ...\n * );\n * ```\n */\nexport function setTransactionMessageComputeUnitPrice<\n TTransactionMessage extends BaseTransactionMessage,\n>(microLamports: number | bigint, transactionMessage: TTransactionMessage) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({ microLamports }),\n transactionMessage\n );\n}\n\n/**\n * Updates the first `SetComputeUnitPrice` instruction in a transaction message\n * with the given micro-Lamports, or appends a new instruction if none exists.\n * A function of the current value can be provided instead of a static value.\n *\n * @param microLamports - The new compute unit price, or a function that\n * takes the previous price and returns the new one.\n * @param transactionMessage - The transaction message to update.\n *\n * @example\n * ```ts\n * const updatedTransactionMessage = updateOrAppendSetComputeUnitPriceInstruction(\n * // E.g. double the current price or set it to 10_000 if it isn't set.\n * (currentPrice) => currentPrice === null ? 10_000 : currentPrice * 2,\n * transactionMessage,\n * );\n * ```\n */\nexport function updateOrAppendSetComputeUnitPriceInstruction<\n TTransactionMessage extends BaseTransactionMessage,\n>(\n microLamports:\n | MicroLamports\n | ((previousMicroLamports: MicroLamports | null) => MicroLamports),\n transactionMessage: TTransactionMessage\n): TTransactionMessage {\n const getMicroLamports = (\n previousMicroLamports: MicroLamports | null\n ): MicroLamports =>\n typeof microLamports === 'function'\n ? microLamports(previousMicroLamports)\n : microLamports;\n const instructionDetails =\n getSetComputeUnitPriceInstructionIndexAndMicroLamports(transactionMessage);\n\n if (!instructionDetails) {\n return appendTransactionMessageInstruction(\n getSetComputeUnitPriceInstruction({\n microLamports: getMicroLamports(null),\n }),\n transactionMessage\n ) as unknown as TTransactionMessage;\n }\n\n const { index, microLamports: previousMicroLamports } = instructionDetails;\n const newMicroLamports = getMicroLamports(previousMicroLamports);\n if (newMicroLamports === previousMicroLamports) {\n return transactionMessage;\n }\n\n const newInstruction = getSetComputeUnitPriceInstruction({\n microLamports: newMicroLamports,\n });\n const newInstructions = [...transactionMessage.instructions];\n newInstructions.splice(index, 1, newInstruction);\n return Object.freeze({\n ...transactionMessage,\n instructions: newInstructions,\n });\n}\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../signer\";\nimport type { ExactSvmPayloadV2 } from \"../../types\";\nimport { createRpcClient } from \"../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme.\n */\nexport class ExactSvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClient instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClient instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise> {\n const rpc = createRpcClient(paymentRequirements.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, paymentRequirements.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: paymentRequirements.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: paymentRequirements.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(paymentRequirements.amount),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = paymentRequirements.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV2 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n}\n","/**\n * V1 exports for the SVM mechanism\n */\nexport { ExactSvmSchemeV1 } from \"../exact/v1\";\n\nexport const NETWORKS: string[] = [\"solana\", \"solana-devnet\", \"solana-testnet\"];\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from \"@solana-program/compute-budget\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from \"@solana/kit\";\nimport type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport type { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n MEMO_PROGRAM_ADDRESS,\n} from \"../../../constants\";\nimport type { ClientSvmConfig, ClientSvmSigner } from \"../../../signer\";\nimport type { ExactSvmPayloadV1 } from \"../../../types\";\nimport { createRpcClient } from \"../../../utils\";\n\n/**\n * SVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactSvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactSvmClientV1 instance.\n *\n * @param signer - The SVM signer for client operations\n * @param config - Optional configuration with custom RPC URL\n * @returns ExactSvmClientV1 instance\n */\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const rpc = createRpcClient(selectedV1.network, this.config?.rpcUrl);\n\n const tokenMint = await fetchMint(rpc, selectedV1.asset as Address);\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error(\"Asset was not created by a known token program\");\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: selectedV1.asset as Address,\n owner: selectedV1.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: selectedV1.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(selectedV1.maxAmountRequired),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress },\n );\n\n // Facilitator must provide feePayer to cover transaction fees\n const feePayer = selectedV1.extra?.feePayer as Address;\n if (!feePayer) {\n throw new Error(\"feePayer is required in paymentRequirements.extra for SVM transactions\");\n }\n\n const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();\n\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n const memoIx = {\n programAddress: MEMO_PROGRAM_ADDRESS as Address,\n accounts: [] as const,\n data: new TextEncoder().encode(\n Array.from(nonce)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n ),\n };\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),\n tx,\n ),\n tx => appendTransactionMessageInstructions([transferIx, memoIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),\n );\n\n const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV1 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientSvmSigner } from \"../../signer\";\nimport { ExactSvmScheme } from \"./scheme\";\nimport { ExactSvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering SVM schemes to an x402Client\n */\nexport interface SvmClientConfig {\n /**\n * The SVM signer to use for creating payment payloads\n */\n signer: ClientSvmSigner;\n\n /**\n * Optional payment requirements selector function\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional specific networks to register\n */\n networks?: Network[];\n}\n\n/**\n * Registers SVM payment schemes to an existing x402Client instance.\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for SVM client registration\n * @returns The client instance for chaining\n */\nexport function registerExactSvmScheme(client: x402Client, config: SvmClientConfig): x402Client {\n // Register V2 scheme\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach(network => {\n client.register(network, new ExactSvmScheme(config.signer));\n });\n } else {\n client.register(\"solana:*\", new ExactSvmScheme(config.signer));\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactSvmSchemeV1(config.signer));\n });\n\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * BlockRun Model Definitions for OpenClaw\n *\n * Maps BlockRun's 55+ AI models to OpenClaw's ModelDefinitionConfig format.\n * All models use the \"openai-completions\" API since BlockRun is OpenAI-compatible.\n *\n * Pricing is in USD per 1M tokens. Operators pay these rates via x402;\n * they set their own markup when reselling to end users (Phase 2).\n */\n\nimport type { ModelDefinitionConfig, ModelProviderConfig } from \"./types.js\";\n\n/**\n * Model aliases for convenient shorthand access.\n * Users can type `/model claude` instead of `/model blockrun/anthropic/claude-sonnet-4-6`.\n */\nexport const MODEL_ALIASES: Record = {\n // Claude - use newest versions (4.6)\n claude: \"anthropic/claude-sonnet-4.6\",\n sonnet: \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4.6\": \"anthropic/claude-sonnet-4.6\",\n \"sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n opus: \"anthropic/claude-opus-4.6\",\n \"opus-4\": \"anthropic/claude-opus-4.6\",\n \"opus-4.6\": \"anthropic/claude-opus-4.6\",\n \"opus-4-6\": \"anthropic/claude-opus-4.6\",\n haiku: \"anthropic/claude-haiku-4.5\",\n // Claude - provider/shortname patterns (common in agent frameworks)\n \"anthropic/sonnet\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/opus\": \"anthropic/claude-opus-4.6\",\n \"anthropic/haiku\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude\": \"anthropic/claude-sonnet-4.6\",\n // Backward compatibility - map all variants to 4.6\n \"anthropic/claude-sonnet-4\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-sonnet-4-6\": \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-opus-4\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4-6\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-opus-4.5\": \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-haiku-4\": \"anthropic/claude-haiku-4.5\",\n \"anthropic/claude-haiku-4-5\": \"anthropic/claude-haiku-4.5\",\n\n // OpenAI\n gpt: \"openai/gpt-4o\",\n gpt4: \"openai/gpt-4o\",\n gpt5: \"openai/gpt-5.4\",\n \"gpt-5.4\": \"openai/gpt-5.4\",\n \"gpt-5.4-pro\": \"openai/gpt-5.4-pro\",\n \"gpt-5.4-nano\": \"openai/gpt-5.4-nano\",\n nano: \"openai/gpt-5.4-nano\",\n \"gpt-5-nano\": \"openai/gpt-5.4-nano\",\n codex: \"openai/gpt-5.3-codex\",\n mini: \"openai/gpt-4o-mini\",\n o1: \"openai/o1\",\n o3: \"openai/o3\",\n\n // DeepSeek\n deepseek: \"deepseek/deepseek-chat\",\n \"deepseek-chat\": \"deepseek/deepseek-chat\",\n reasoner: \"deepseek/deepseek-reasoner\",\n\n // Kimi / Moonshot\n kimi: \"moonshot/kimi-k2.5\",\n moonshot: \"moonshot/kimi-k2.5\",\n \"kimi-k2.5\": \"moonshot/kimi-k2.5\",\n\n // Google\n gemini: \"google/gemini-2.5-pro\",\n flash: \"google/gemini-2.5-flash\",\n \"gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"google/gemini-3.1-pro-preview\": \"google/gemini-3.1-pro\",\n \"gemini-3.1-flash-lite\": \"google/gemini-3.1-flash-lite\",\n\n // xAI\n grok: \"xai/grok-3\",\n \"grok-fast\": \"xai/grok-4-fast-reasoning\",\n \"grok-code\": \"deepseek/deepseek-chat\", // was grok-code-fast-1, delisted due to poor retention\n // Delisted model redirects — full model IDs that were previously valid but removed\n \"grok-code-fast-1\": \"deepseek/deepseek-chat\", // bare alias\n \"xai/grok-code-fast-1\": \"deepseek/deepseek-chat\", // delisted 2026-03-12\n \"xai/grok-3-fast\": \"xai/grok-4-fast-reasoning\", // delisted (too expensive)\n\n // NVIDIA — backward compat aliases (nvidia/xxx → free/xxx)\n nvidia: \"free/gpt-oss-120b\",\n \"gpt-120b\": \"free/gpt-oss-120b\",\n \"gpt-20b\": \"free/gpt-oss-20b\",\n \"nvidia/gpt-oss-120b\": \"free/gpt-oss-120b\",\n \"nvidia/gpt-oss-20b\": \"free/gpt-oss-20b\",\n \"nvidia/nemotron-ultra-253b\": \"free/nemotron-ultra-253b\",\n \"nvidia/nemotron-3-super-120b\": \"free/nemotron-3-super-120b\",\n \"nvidia/nemotron-super-49b\": \"free/nemotron-super-49b\",\n \"nvidia/deepseek-v3.2\": \"free/deepseek-v3.2\",\n \"nvidia/mistral-large-3-675b\": \"free/mistral-large-3-675b\",\n \"nvidia/qwen3-coder-480b\": \"free/qwen3-coder-480b\",\n \"nvidia/devstral-2-123b\": \"free/devstral-2-123b\",\n \"nvidia/glm-4.7\": \"free/glm-4.7\",\n \"nvidia/llama-4-maverick\": \"free/llama-4-maverick\",\n // Free model shorthand aliases\n \"deepseek-free\": \"free/deepseek-v3.2\",\n \"mistral-free\": \"free/mistral-large-3-675b\",\n \"glm-free\": \"free/glm-4.7\",\n \"llama-free\": \"free/llama-4-maverick\",\n nemotron: \"free/nemotron-ultra-253b\",\n \"nemotron-ultra\": \"free/nemotron-ultra-253b\",\n \"nemotron-253b\": \"free/nemotron-ultra-253b\",\n \"nemotron-super\": \"free/nemotron-super-49b\",\n \"nemotron-49b\": \"free/nemotron-super-49b\",\n \"nemotron-120b\": \"free/nemotron-3-super-120b\",\n devstral: \"free/devstral-2-123b\",\n \"devstral-2\": \"free/devstral-2-123b\",\n \"qwen-coder\": \"free/qwen3-coder-480b\",\n \"qwen-coder-free\": \"free/qwen3-coder-480b\",\n maverick: \"free/llama-4-maverick\",\n free: \"free/nemotron-ultra-253b\",\n\n // MiniMax\n minimax: \"minimax/minimax-m2.7\",\n \"minimax-m2.7\": \"minimax/minimax-m2.7\",\n \"minimax-m2.5\": \"minimax/minimax-m2.5\",\n\n // Z.AI GLM-5\n glm: \"zai/glm-5\",\n \"glm-5\": \"zai/glm-5\",\n \"glm-5-turbo\": \"zai/glm-5-turbo\",\n\n // Routing profile aliases (common variations)\n \"auto-router\": \"auto\",\n router: \"auto\",\n\n // Note: auto, eco, premium are virtual routing profiles registered in BLOCKRUN_MODELS\n // They don't need aliases since they're already top-level model IDs\n};\n\n/**\n * Resolve a model alias to its full model ID.\n * Also strips \"blockrun/\" prefix for direct model paths.\n * Examples:\n * - \"claude\" -> \"anthropic/claude-sonnet-4-6\" (alias)\n * - \"blockrun/claude\" -> \"anthropic/claude-sonnet-4-6\" (alias with prefix)\n * - \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\" (prefix stripped)\n * - \"openai/gpt-4o\" -> \"openai/gpt-4o\" (unchanged)\n */\nexport function resolveModelAlias(model: string): string {\n const normalized = model.trim().toLowerCase();\n const resolved = MODEL_ALIASES[normalized];\n if (resolved) return resolved;\n\n // Check with \"blockrun/\" prefix stripped\n if (normalized.startsWith(\"blockrun/\")) {\n const withoutPrefix = normalized.slice(\"blockrun/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // Even if not an alias, strip the prefix for direct model paths\n // e.g., \"blockrun/anthropic/claude-sonnet-4-6\" -> \"anthropic/claude-sonnet-4-6\"\n return withoutPrefix;\n }\n\n // Strip \"openai/\" prefix when it wraps a virtual routing profile or alias.\n // OpenClaw sends virtual models as \"openai/eco\", \"openai/auto\", etc. because\n // the provider uses the openai-completions API type.\n if (normalized.startsWith(\"openai/\")) {\n const withoutPrefix = normalized.slice(\"openai/\".length);\n const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];\n if (resolvedWithoutPrefix) return resolvedWithoutPrefix;\n\n // If it's a known BlockRun virtual profile (eco, auto, premium), return bare id\n const isVirtualProfile = BLOCKRUN_MODELS.some((m) => m.id === withoutPrefix);\n if (isVirtualProfile) return withoutPrefix;\n }\n\n return model;\n}\n\ntype BlockRunModel = {\n id: string;\n name: string;\n /** Model version (e.g., \"4.6\", \"3.1\", \"5.2\") for tracking updates */\n version?: string;\n inputPrice: number;\n outputPrice: number;\n contextWindow: number;\n maxOutput: number;\n reasoning?: boolean;\n vision?: boolean;\n /** Models optimized for agentic workflows (multi-step autonomous tasks) */\n agentic?: boolean;\n /**\n * Model supports OpenAI-compatible structured function/tool calling.\n * Models without this flag output tool invocations as plain text JSON,\n * which leaks raw {\"command\":\"...\"} into visible chat messages.\n * Default: false (must opt-in to prevent silent regressions on new models).\n */\n toolCalling?: boolean;\n /** Model is deprecated — will be routed to fallbackModel if set */\n deprecated?: boolean;\n /** Model ID to route to when this model is deprecated */\n fallbackModel?: string;\n};\n\nexport const BLOCKRUN_MODELS: BlockRunModel[] = [\n // Smart routing meta-models — proxy replaces with actual model\n // NOTE: Model IDs are WITHOUT provider prefix (OpenClaw adds \"blockrun/\" automatically)\n {\n id: \"auto\",\n name: \"Auto (Smart Router - Balanced)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"free\",\n name: \"Free → Nemotron Ultra 253B\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131_072,\n maxOutput: 16_384,\n reasoning: true,\n },\n {\n id: \"eco\",\n name: \"Eco (Smart Router - Cost Optimized)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 1_050_000,\n maxOutput: 128_000,\n },\n {\n id: \"premium\",\n name: \"Premium (Smart Router - Best Quality)\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 2_000_000,\n maxOutput: 200_000,\n },\n\n // OpenAI GPT-5 Family\n {\n id: \"openai/gpt-5.2\",\n name: \"GPT-5.2\",\n version: \"5.2\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-mini\",\n name: \"GPT-5 Mini\",\n version: \"5.0\",\n inputPrice: 0.25,\n outputPrice: 2.0,\n contextWindow: 200000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5-nano\",\n name: \"GPT-5 Nano\",\n version: \"5.0\",\n inputPrice: 0.05,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 32768,\n toolCalling: true,\n deprecated: true,\n fallbackModel: \"openai/gpt-5.4-nano\",\n },\n {\n id: \"openai/gpt-5.2-pro\",\n name: \"GPT-5.2 Pro\",\n version: \"5.2\",\n inputPrice: 21.0,\n outputPrice: 168.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n // GPT-5.4 — newest flagship, same input price as 4o but much more capable\n {\n id: \"openai/gpt-5.4\",\n name: \"GPT-5.4\",\n version: \"5.4\",\n inputPrice: 2.5,\n outputPrice: 15.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-pro\",\n name: \"GPT-5.4 Pro\",\n version: \"5.4\",\n inputPrice: 30.0,\n outputPrice: 180.0,\n contextWindow: 400000,\n maxOutput: 128000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-5.4-nano\",\n name: \"GPT-5.4 Nano\",\n version: \"5.4\",\n inputPrice: 0.2,\n outputPrice: 1.25,\n contextWindow: 1050000,\n maxOutput: 32768,\n toolCalling: true,\n },\n\n // OpenAI GPT-5.3 Family\n {\n id: \"openai/gpt-5.3\",\n name: \"GPT-5.3\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 128000,\n maxOutput: 16000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI Codex Family\n {\n id: \"openai/gpt-5.3-codex\",\n name: \"GPT-5.3 Codex\",\n version: \"5.3\",\n inputPrice: 1.75,\n outputPrice: 14.0,\n contextWindow: 400000,\n maxOutput: 128000,\n agentic: true,\n toolCalling: true,\n },\n\n // OpenAI GPT-4 Family\n {\n id: \"openai/gpt-4.1\",\n name: \"GPT-4.1\",\n version: \"4.1\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-mini\",\n name: \"GPT-4.1 Mini\",\n version: \"4.1\",\n inputPrice: 0.4,\n outputPrice: 1.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4.1-nano\",\n name: \"GPT-4.1 Nano\",\n version: \"4.1\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o\",\n name: \"GPT-4o\",\n version: \"4o\",\n inputPrice: 2.5,\n outputPrice: 10.0,\n contextWindow: 128000,\n maxOutput: 16384,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"openai/gpt-4o-mini\",\n name: \"GPT-4o Mini\",\n version: \"4o-mini\",\n inputPrice: 0.15,\n outputPrice: 0.6,\n contextWindow: 128000,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // OpenAI O-series (Reasoning)\n {\n id: \"openai/o1\",\n name: \"o1\",\n version: \"1\",\n inputPrice: 15.0,\n outputPrice: 60.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o1-mini\",\n name: \"o1-mini\",\n version: \"1-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3\",\n name: \"o3\",\n version: \"3\",\n inputPrice: 2.0,\n outputPrice: 8.0,\n contextWindow: 200000,\n maxOutput: 100000,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o3-mini\",\n name: \"o3-mini\",\n version: \"3-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"openai/o4-mini\",\n name: \"o4-mini\",\n version: \"4-mini\",\n inputPrice: 1.1,\n outputPrice: 4.4,\n contextWindow: 128000,\n maxOutput: 65536,\n reasoning: true,\n toolCalling: true,\n },\n\n // Anthropic - all Claude models excel at agentic workflows\n // Use newest versions (4.6) with full provider prefix\n {\n id: \"anthropic/claude-haiku-4.5\",\n name: \"Claude Haiku 4.5\",\n version: \"4.5\",\n inputPrice: 1.0,\n outputPrice: 5.0,\n contextWindow: 200000,\n maxOutput: 8192,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-sonnet-4.6\",\n name: \"Claude Sonnet 4.6\",\n version: \"4.6\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 200000,\n maxOutput: 64000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"anthropic/claude-opus-4.6\",\n name: \"Claude Opus 4.6\",\n version: \"4.6\",\n inputPrice: 5.0,\n outputPrice: 25.0,\n contextWindow: 200000,\n maxOutput: 32000,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Google\n {\n id: \"google/gemini-3.1-pro\",\n name: \"Gemini 3.1 Pro\",\n version: \"3.1\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-pro-preview\",\n name: \"Gemini 3 Pro Preview\",\n version: \"3.0\",\n inputPrice: 2.0,\n outputPrice: 12.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3-flash-preview\",\n name: \"Gemini 3 Flash Preview\",\n version: \"3.0\",\n inputPrice: 0.5,\n outputPrice: 3.0,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n },\n {\n id: \"google/gemini-2.5-pro\",\n name: \"Gemini 2.5 Pro\",\n version: \"2.5\",\n inputPrice: 1.25,\n outputPrice: 10.0,\n contextWindow: 1050000,\n maxOutput: 65536,\n reasoning: true,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash\",\n name: \"Gemini 2.5 Flash\",\n version: \"2.5\",\n inputPrice: 0.3,\n outputPrice: 2.5,\n contextWindow: 1000000,\n maxOutput: 65536,\n vision: true,\n toolCalling: true,\n },\n {\n id: \"google/gemini-2.5-flash-lite\",\n name: \"Gemini 2.5 Flash Lite\",\n version: \"2.5\",\n inputPrice: 0.1,\n outputPrice: 0.4,\n contextWindow: 1000000,\n maxOutput: 65536,\n toolCalling: true,\n },\n {\n id: \"google/gemini-3.1-flash-lite\",\n name: \"Gemini 3.1 Flash Lite\",\n version: \"3.1\",\n inputPrice: 0.25,\n outputPrice: 1.5,\n contextWindow: 1000000,\n maxOutput: 8192,\n toolCalling: true,\n },\n\n // DeepSeek\n {\n id: \"deepseek/deepseek-chat\",\n name: \"DeepSeek V3.2 Chat\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n toolCalling: true,\n },\n {\n id: \"deepseek/deepseek-reasoner\",\n name: \"DeepSeek V3.2 Reasoner\",\n version: \"3.2\",\n inputPrice: 0.28,\n outputPrice: 0.42,\n contextWindow: 128000,\n maxOutput: 8192,\n reasoning: true,\n toolCalling: true,\n },\n\n // Moonshot / Kimi - optimized for agentic workflows\n {\n id: \"moonshot/kimi-k2.5\",\n name: \"Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 8192,\n reasoning: true,\n vision: true,\n agentic: true,\n toolCalling: true,\n },\n\n // xAI / Grok\n {\n id: \"xai/grok-3\",\n name: \"Grok 3\",\n version: \"3\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n // grok-3-fast removed - too expensive ($5/$25), use grok-4-fast instead\n {\n id: \"xai/grok-3-mini\",\n name: \"Grok 3 Mini\",\n version: \"3-mini\",\n inputPrice: 0.3,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // xAI Grok 4 Family - Ultra-cheap fast models\n {\n id: \"xai/grok-4-fast-reasoning\",\n name: \"Grok 4 Fast Reasoning\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-fast-non-reasoning\",\n name: \"Grok 4 Fast\",\n version: \"4\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-reasoning\",\n name: \"Grok 4.1 Fast Reasoning\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-4-1-fast-non-reasoning\",\n name: \"Grok 4.1 Fast\",\n version: \"4.1\",\n inputPrice: 0.2,\n outputPrice: 0.5,\n contextWindow: 131072,\n maxOutput: 16384,\n toolCalling: true,\n },\n // xai/grok-code-fast-1 delisted 2026-03-12: poor retention (coding users churn),\n // no structured tool calling, alias \"grok-code\" redirected to deepseek-chat\n {\n id: \"xai/grok-4-0709\",\n name: \"Grok 4 (0709)\",\n version: \"4-0709\",\n inputPrice: 3.0,\n outputPrice: 15.0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n toolCalling: true,\n },\n {\n id: \"xai/grok-2-vision\",\n name: \"Grok 2 Vision\",\n version: \"2\",\n inputPrice: 2.0,\n outputPrice: 10.0,\n contextWindow: 131072,\n maxOutput: 16384,\n vision: true,\n toolCalling: true,\n },\n\n // MiniMax\n {\n id: \"minimax/minimax-m2.7\",\n name: \"MiniMax M2.7\",\n version: \"m2.7\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n {\n id: \"minimax/minimax-m2.5\",\n name: \"MiniMax M2.5\",\n version: \"m2.5\",\n inputPrice: 0.3,\n outputPrice: 1.2,\n contextWindow: 204800,\n maxOutput: 16384,\n reasoning: true,\n agentic: true,\n toolCalling: true,\n },\n\n // Free models (hosted by NVIDIA, billingMode: \"free\" on server)\n // IDs use \"free/\" prefix so users see them as free in the /model picker.\n // ClawRouter maps free/xxx → nvidia/xxx before sending to BlockRun upstream.\n // toolCalling intentionally omitted: structured function calling unverified.\n {\n id: \"free/gpt-oss-120b\",\n name: \"[Free] GPT-OSS 120B\",\n version: \"120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/gpt-oss-20b\",\n name: \"[Free] GPT-OSS 20B\",\n version: \"20b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 128000,\n maxOutput: 16384,\n },\n {\n id: \"free/nemotron-ultra-253b\",\n name: \"[Free] Nemotron Ultra 253B\",\n version: \"253b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-3-super-120b\",\n name: \"[Free] Nemotron 3 Super 120B\",\n version: \"3-super-120b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/nemotron-super-49b\",\n name: \"[Free] Nemotron Super 49B\",\n version: \"super-49b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/deepseek-v3.2\",\n name: \"[Free] DeepSeek V3.2\",\n version: \"v3.2\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/mistral-large-3-675b\",\n name: \"[Free] Mistral Large 675B\",\n version: \"3-675b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/qwen3-coder-480b\",\n name: \"[Free] Qwen3 Coder 480B\",\n version: \"480b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/devstral-2-123b\",\n name: \"[Free] Devstral 2 123B\",\n version: \"2-123b\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n },\n {\n id: \"free/glm-4.7\",\n name: \"[Free] GLM-4.7\",\n version: \"4.7\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n {\n id: \"free/llama-4-maverick\",\n name: \"[Free] Llama 4 Maverick\",\n version: \"4-maverick\",\n inputPrice: 0,\n outputPrice: 0,\n contextWindow: 131072,\n maxOutput: 16384,\n reasoning: true,\n },\n\n // NVIDIA - Paid models\n {\n id: \"nvidia/kimi-k2.5\",\n name: \"NVIDIA Kimi K2.5\",\n version: \"k2.5\",\n inputPrice: 0.6,\n outputPrice: 3.0,\n contextWindow: 262144,\n maxOutput: 16384,\n toolCalling: true,\n },\n\n // Z.AI GLM-5 Models\n {\n id: \"zai/glm-5\",\n name: \"GLM-5\",\n version: \"5\",\n inputPrice: 1.0,\n outputPrice: 3.2,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n {\n id: \"zai/glm-5-turbo\",\n name: \"GLM-5 Turbo\",\n version: \"5-turbo\",\n inputPrice: 1.2,\n outputPrice: 4.0,\n contextWindow: 200000,\n maxOutput: 128000,\n toolCalling: true,\n },\n];\n\n/**\n * Convert BlockRun model definitions to OpenClaw ModelDefinitionConfig format.\n */\nfunction toOpenClawModel(m: BlockRunModel): ModelDefinitionConfig {\n return {\n id: m.id,\n name: m.name,\n api: \"openai-completions\",\n reasoning: m.reasoning ?? false,\n input: m.vision ? [\"text\", \"image\"] : [\"text\"],\n cost: {\n input: m.inputPrice,\n output: m.outputPrice,\n cacheRead: 0,\n cacheWrite: 0,\n },\n contextWindow: m.contextWindow,\n maxTokens: m.maxOutput,\n };\n}\n\n/**\n * Alias models that map to real models.\n * These allow users to use friendly names like \"free\" or \"gpt-120b\".\n */\nconst ALIAS_MODELS: ModelDefinitionConfig[] = Object.entries(MODEL_ALIASES)\n .map(([alias, targetId]) => {\n const target = BLOCKRUN_MODELS.find((m) => m.id === targetId);\n if (!target) return null;\n return toOpenClawModel({ ...target, id: alias, name: `${alias} → ${target.name}` });\n })\n .filter((m): m is ModelDefinitionConfig => m !== null);\n\n/**\n * All BlockRun models in OpenClaw format (including aliases).\n */\nexport const OPENCLAW_MODELS: ModelDefinitionConfig[] = [\n ...BLOCKRUN_MODELS.map(toOpenClawModel),\n ...ALIAS_MODELS,\n];\n\n/**\n * Build a ModelProviderConfig for BlockRun.\n *\n * @param baseUrl - The proxy's local base URL (e.g., \"http://127.0.0.1:12345\")\n */\nexport function buildProviderModels(baseUrl: string): ModelProviderConfig {\n return {\n baseUrl: `${baseUrl}/v1`,\n api: \"openai-completions\",\n models: OPENCLAW_MODELS,\n };\n}\n\n/**\n * Check if a model is optimized for agentic workflows.\n * Agentic models continue autonomously with multi-step tasks\n * instead of stopping and waiting for user input.\n */\nexport function isAgenticModel(modelId: string): boolean {\n const model = BLOCKRUN_MODELS.find(\n (m) => m.id === modelId || m.id === modelId.replace(\"blockrun/\", \"\"),\n );\n return model?.agentic ?? false;\n}\n\n/**\n * Get all agentic-capable models.\n */\nexport function getAgenticModels(): string[] {\n return BLOCKRUN_MODELS.filter((m) => m.agentic).map((m) => m.id);\n}\n\n/**\n * Check if a model supports OpenAI-compatible structured tool/function calling.\n * Models without this flag (e.g. grok-code-fast-1) output tool invocations as\n * plain text JSON, which leaks {\"command\":\"...\"} into visible chat messages.\n */\nexport function supportsToolCalling(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.toolCalling ?? false;\n}\n\n/**\n * Check if a model supports vision (image inputs).\n * Models without this flag cannot process image_url content parts.\n */\nexport function supportsVision(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.vision ?? false;\n}\n\n/**\n * Get context window size for a model.\n * Returns undefined if model not found.\n */\nexport function getModelContextWindow(modelId: string): number | undefined {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.contextWindow;\n}\n\n/**\n * Check if a model has reasoning/thinking capabilities.\n * Reasoning models may require reasoning_content in assistant tool_call messages.\n */\nexport function isReasoningModel(modelId: string): boolean {\n const normalized = modelId.replace(\"blockrun/\", \"\");\n const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);\n return model?.reasoning ?? false;\n}\n","/**\n * BlockRun ProviderPlugin for OpenClaw\n *\n * Registers BlockRun as an LLM provider in OpenClaw.\n * Uses a local x402 proxy to handle micropayments transparently —\n * pi-ai sees a standard OpenAI-compatible API at localhost.\n */\n\nimport type { ProviderPlugin } from \"./types.js\";\nimport { buildProviderModels } from \"./models.js\";\nimport type { ProxyHandle } from \"./proxy.js\";\n\n/**\n * State for the running proxy (set when the plugin activates).\n */\nlet activeProxy: ProxyHandle | null = null;\n\n/**\n * Update the proxy handle (called from index.ts when the proxy starts).\n */\nexport function setActiveProxy(proxy: ProxyHandle): void {\n activeProxy = proxy;\n}\n\nexport function getActiveProxy(): ProxyHandle | null {\n return activeProxy;\n}\n\n/**\n * BlockRun provider plugin definition.\n */\nexport const blockrunProvider: ProviderPlugin = {\n id: \"blockrun\",\n label: \"BlockRun\",\n docsPath: \"https://blockrun.ai/docs\",\n aliases: [\"br\"],\n envVars: [\"BLOCKRUN_WALLET_KEY\"],\n\n // Model definitions — dynamically set to proxy URL\n get models() {\n if (!activeProxy) {\n // Fallback: point to BlockRun API directly (won't handle x402, but\n // allows config loading before proxy starts)\n return buildProviderModels(\"https://blockrun.ai/api\");\n }\n return buildProviderModels(activeProxy.baseUrl);\n },\n\n // No auth required — the x402 proxy handles wallet-based payments internally.\n // The proxy auto-generates a wallet on first run and stores it at\n // ~/.openclaw/blockrun/wallet.key. Users just fund that wallet with USDC.\n auth: [],\n};\n","/**\n * Local x402 Proxy Server\n *\n * Sits between OpenClaw's pi-ai (which makes standard OpenAI-format requests)\n * and BlockRun's API (which requires x402 micropayments).\n *\n * Flow:\n * pi-ai → http://localhost:{port}/v1/chat/completions\n * → proxy forwards to https://blockrun.ai/api/v1/chat/completions\n * → gets 402 → @x402/fetch signs payment → retries\n * → streams response back to pi-ai\n *\n * Optimizations (v0.3.0):\n * - SSE heartbeat: for streaming requests, sends headers + heartbeat immediately\n * before the x402 flow, preventing OpenClaw's 10-15s timeout from firing.\n * - Response dedup: hashes request bodies and caches responses for 30s,\n * preventing double-charging when OpenClaw retries after timeout.\n * - Smart routing: when model is \"blockrun/auto\", classify query and pick cheapest model.\n * - Usage logging: log every request as JSON line to ~/.openclaw/blockrun/logs/\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\n\n// Per-request payment tracking via AsyncLocalStorage (safe for concurrent requests).\n// The x402 onAfterPaymentCreation hook writes the actual payment amount into the\n// request-scoped store, and the logging code reads it after payFetch completes.\nconst paymentStore = new AsyncLocalStorage<{ amountUsd: number; amountUsdText: string }>();\nimport { finished } from \"node:stream\";\nimport type { AddressInfo } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdir, writeFile, readFile, stat as fsStat } from \"node:fs/promises\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { createPublicClient, http } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { x402Client } from \"@x402/fetch\";\nimport { createPayFetchWithPreAuth } from \"./payment-preauth.js\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { toClientEvmSigner } from \"@x402/evm\";\nimport {\n route,\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n DEFAULT_ROUTING_CONFIG,\n type RouterOptions,\n type RoutingDecision,\n type RoutingConfig,\n type ModelPricing,\n type Tier,\n} from \"./router/index.js\";\nimport { classifyByRules } from \"./router/rules.js\";\nimport {\n BLOCKRUN_MODELS,\n OPENCLAW_MODELS,\n resolveModelAlias,\n getModelContextWindow,\n isReasoningModel,\n supportsToolCalling,\n supportsVision,\n} from \"./models.js\";\nimport { logUsage, type UsageEntry } from \"./logger.js\";\nimport { getStats, clearStats } from \"./stats.js\";\nimport { RequestDeduplicator } from \"./dedup.js\";\nimport { ResponseCache, type ResponseCacheConfig } from \"./response-cache.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport type { SolanaBalanceMonitor } from \"./solana-balance.js\";\nimport {\n DEFAULT_BASE_PAYMENT_ASSET,\n fetchBasePaymentAssets,\n type BasePaymentAsset,\n} from \"./payment-asset.js\";\n\n/** Union type for chain-agnostic balance monitoring */\ntype AnyBalanceMonitor = BalanceMonitor | SolanaBalanceMonitor;\nimport { resolvePaymentChain } from \"./auth.js\";\nimport { compressContext, shouldCompress, type NormalizedMessage } from \"./compression/index.js\";\n// Error classes available for programmatic use but not used in proxy\n// (universal free fallback means we don't throw balance errors anymore)\n// import { InsufficientFundsError, EmptyWalletError } from \"./errors.js\";\nimport { USER_AGENT, VERSION } from \"./version.js\";\nimport {\n SessionStore,\n getSessionId,\n deriveSessionId,\n hashRequestContent,\n type SessionConfig,\n} from \"./session.js\";\nimport { checkForUpdates } from \"./updater.js\";\nimport { loadExcludeList } from \"./exclude-models.js\";\nimport { PROXY_PORT } from \"./config.js\";\nimport { SessionJournal } from \"./journal.js\";\n\nconst BLOCKRUN_API = \"https://blockrun.ai/api\";\nconst BLOCKRUN_SOLANA_API = \"https://sol.blockrun.ai/api\";\nconst IMAGE_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"images\");\n// Routing profile models - virtual models that trigger intelligent routing\nconst AUTO_MODEL = \"blockrun/auto\";\n\nconst ROUTING_PROFILES = new Set([\n \"blockrun/eco\",\n \"eco\",\n \"blockrun/auto\",\n \"auto\",\n \"blockrun/premium\",\n \"premium\",\n]);\nconst FREE_MODEL = \"free/gpt-oss-120b\"; // Last-resort single free model fallback\nconst FREE_MODELS = new Set([\n \"free/gpt-oss-120b\",\n \"free/gpt-oss-20b\",\n \"free/nemotron-ultra-253b\",\n \"free/nemotron-3-super-120b\",\n \"free/nemotron-super-49b\",\n \"free/deepseek-v3.2\",\n \"free/mistral-large-3-675b\",\n \"free/qwen3-coder-480b\",\n \"free/devstral-2-123b\",\n \"free/glm-4.7\",\n \"free/llama-4-maverick\",\n]);\n/**\n * Map free/xxx model IDs to nvidia/xxx for upstream BlockRun API.\n * The \"free/\" prefix is a ClawRouter convention for the /model picker;\n * BlockRun server expects \"nvidia/\" prefix.\n */\nfunction toUpstreamModelId(modelId: string): string {\n if (modelId.startsWith(\"free/\")) {\n return \"nvidia/\" + modelId.slice(\"free/\".length);\n }\n return modelId;\n}\nconst MAX_MESSAGES = 200; // BlockRun API limit - truncate older messages if exceeded\nconst CONTEXT_LIMIT_KB = 5120; // Server-side limit: 5MB in KB\nconst HEARTBEAT_INTERVAL_MS = 2_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 180_000; // 3 minutes (allows for on-chain tx + LLM response)\nconst PER_MODEL_TIMEOUT_MS = 60_000; // 60s per individual model attempt (fallback to next on exceed)\nconst MAX_FALLBACK_ATTEMPTS = 5; // Maximum models to try in fallback chain (increased from 3 to ensure cheap models are tried)\nconst HEALTH_CHECK_TIMEOUT_MS = 2_000; // Timeout for checking existing proxy\nconst RATE_LIMIT_COOLDOWN_MS = 60_000; // 60 seconds cooldown for rate-limited models\nconst OVERLOAD_COOLDOWN_MS = 15_000; // 15 seconds cooldown for overloaded providers\nconst PORT_RETRY_ATTEMPTS = 5; // Max attempts to bind port (handles TIME_WAIT)\nconst PORT_RETRY_DELAY_MS = 1_000; // Delay between retry attempts\nconst MODEL_BODY_READ_TIMEOUT_MS = 300_000; // 5 minutes for model responses (reasoning models are slow)\nconst ERROR_BODY_READ_TIMEOUT_MS = 30_000; // 30 seconds for error/partner body reads\n\nasync function readBodyWithTimeout(\n body: ReadableStream | null,\n timeoutMs: number = MODEL_BODY_READ_TIMEOUT_MS,\n): Promise {\n if (!body) return [];\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n\n let timer: ReturnType | undefined;\n try {\n while (true) {\n const result = await Promise.race([\n reader.read(),\n new Promise((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"Body read timeout\")), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (result.done) break;\n chunks.push(result.value);\n }\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n\n return chunks;\n}\n\n/**\n * Transform upstream payment errors into user-friendly messages.\n * Parses the raw x402 error and formats it nicely.\n */\nfunction transformPaymentError(\n errorBody: string,\n opts?: { baseAssetSymbol?: string; baseAssetDecimals?: number },\n): string {\n const baseAssetSymbol = opts?.baseAssetSymbol || DEFAULT_BASE_PAYMENT_ASSET.symbol;\n const baseAssetDecimals = opts?.baseAssetDecimals ?? DEFAULT_BASE_PAYMENT_ASSET.decimals;\n const formatRawAssetAmount = (amountRaw: bigint, decimals: number): string => {\n const divisor = 10n ** BigInt(decimals);\n const whole = amountRaw / divisor;\n const remainder = amountRaw % divisor;\n const scaledFraction = decimals >= 6\n ? remainder / 10n ** BigInt(decimals - 6)\n : remainder * 10n ** BigInt(6 - decimals);\n return `${whole.toString()}.${scaledFraction.toString().padStart(6, \"0\")}`;\n };\n try {\n // Try to parse the error JSON\n const parsed = JSON.parse(errorBody) as {\n error?: string;\n details?: string;\n // blockrun-sol (Solana) format uses code+debug instead of details\n code?: string;\n debug?: string;\n payer?: string;\n };\n\n // Check if this is a payment verification error\n if (parsed.error === \"Payment verification failed\" && parsed.details) {\n // Extract the nested JSON from details\n // Format: \"Verification failed: {json}\\n\"\n const match = parsed.details.match(/Verification failed:\\s*(\\{.*\\})/s);\n if (match) {\n const innerJson = JSON.parse(match[1]) as {\n invalidMessage?: string;\n invalidReason?: string;\n payer?: string;\n };\n\n if (innerJson.invalidReason === \"insufficient_funds\" && innerJson.invalidMessage) {\n // Parse \"insufficient balance: 251 < 11463\"\n const balanceMatch = innerJson.invalidMessage.match(\n /insufficient balance:\\s*(\\d+)\\s*<\\s*(\\d+)/i,\n );\n if (balanceMatch) {\n const currentRaw = BigInt(balanceMatch[1]);\n const requiredRaw = BigInt(balanceMatch[2]);\n const currentUSD = formatRawAssetAmount(currentRaw, baseAssetDecimals);\n const requiredUSD = formatRawAssetAmount(requiredRaw, baseAssetDecimals);\n const wallet = innerJson.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n return JSON.stringify({\n error: {\n message: `Insufficient ${baseAssetSymbol} balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,\n type: \"insufficient_funds\",\n wallet: wallet,\n current_balance_usd: currentUSD,\n required_usd: requiredUSD,\n help: `Fund wallet ${shortWallet} with ${baseAssetSymbol} on Base, or use free model: /model free`,\n },\n });\n }\n }\n\n // Handle invalid_payload errors (signature issues, malformed payment)\n if (innerJson.invalidReason === \"invalid_payload\") {\n return JSON.stringify({\n error: {\n message: \"Payment signature invalid. This may be a temporary issue.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n // Handle transaction simulation failures (Solana on-chain validation)\n if (innerJson.invalidReason === \"transaction_simulation_failed\") {\n console.error(\n `[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage || \"unknown\"}`,\n );\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, check your Solana USDC balance or try: /model free\",\n },\n });\n }\n }\n }\n\n // Handle blockrun-sol (Solana) format: code=PAYMENT_INVALID + debug=invalidReason string\n if (\n parsed.error === \"Payment verification failed\" &&\n parsed.code === \"PAYMENT_INVALID\" &&\n parsed.debug\n ) {\n const debugLower = parsed.debug.toLowerCase();\n const wallet = parsed.payer || \"unknown\";\n const shortWallet =\n wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;\n\n if (debugLower.includes(\"insufficient\")) {\n return JSON.stringify({\n error: {\n message: \"Insufficient Solana USDC balance.\",\n type: \"insufficient_funds\",\n wallet,\n help: `Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base`,\n },\n });\n }\n\n if (\n debugLower.includes(\"transaction_simulation_failed\") ||\n debugLower.includes(\"simulation\")\n ) {\n console.error(`[ClawRouter] Solana transaction simulation failed: ${parsed.debug}`);\n return JSON.stringify({\n error: {\n message: \"Solana payment simulation failed. Retrying with a different model.\",\n type: \"transaction_simulation_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n\n if (debugLower.includes(\"invalid signature\") || debugLower.includes(\"invalid_signature\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment signature invalid.\",\n type: \"invalid_payload\",\n help: \"Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash\",\n },\n });\n }\n\n if (debugLower.includes(\"expired\")) {\n return JSON.stringify({\n error: {\n message: \"Solana payment expired. Retrying.\",\n type: \"expired\",\n help: \"This is usually temporary.\",\n },\n });\n }\n\n // Unknown Solana verification error — surface the debug reason\n console.error(\n `[ClawRouter] Solana payment verification failed: ${parsed.debug} payer=${wallet}`,\n );\n return JSON.stringify({\n error: {\n message: `Solana payment verification failed: ${parsed.debug}`,\n type: \"payment_invalid\",\n wallet,\n help: \"Try again or switch to Base: /wallet base\",\n },\n });\n }\n\n // Handle settlement failures (gas estimation, on-chain errors)\n if (\n parsed.error === \"Settlement failed\" ||\n parsed.error === \"Payment settlement failed\" ||\n parsed.details?.includes(\"Settlement failed\") ||\n parsed.details?.includes(\"transaction_simulation_failed\")\n ) {\n const details = parsed.details || \"\";\n const gasError = details.includes(\"unable to estimate gas\");\n\n return JSON.stringify({\n error: {\n message: gasError\n ? \"Payment failed: network congestion or gas issue. Try again.\"\n : \"Payment settlement failed. Try again in a moment.\",\n type: \"settlement_failed\",\n help: \"This is usually temporary. If it persists, try: /model free\",\n },\n });\n }\n } catch {\n // If parsing fails, return original\n }\n return errorBody;\n}\n\nfunction formatStableAmount(amountRaw: bigint, decimals: number): string {\n const divisor = 10n ** BigInt(decimals);\n const whole = amountRaw / divisor;\n const remainder = amountRaw % divisor;\n const scaledFraction =\n decimals >= 6\n ? remainder / 10n ** BigInt(decimals - 6)\n : remainder * 10n ** BigInt(6 - decimals);\n return `${whole.toString()}.${scaledFraction.toString().padStart(6, \"0\")}`;\n}\n\n/**\n * Semantic error categories from upstream provider responses.\n * Used to distinguish auth failures from rate limits from server errors\n * so each category can be handled independently without cross-contamination.\n */\nexport type ErrorCategory =\n | \"auth_failure\" // 401, 403: Wrong key or forbidden — don't retry with same key\n | \"quota_exceeded\" // 403 with plan/quota body: Plan limit hit\n | \"rate_limited\" // 429: Actual throttling — 60s cooldown\n | \"overloaded\" // 529, 503+overload body: Provider capacity — 15s cooldown\n | \"server_error\" // 5xx general: Transient — fallback immediately\n | \"payment_error\" // 402: x402 payment or funds issue\n | \"config_error\"; // 400, 413: Bad request content — skip this model\n\n/**\n * Classify an upstream error response into a semantic category.\n * Returns null if the status+body is not a provider-side issue worth retrying.\n */\nexport function categorizeError(status: number, body: string): ErrorCategory | null {\n if (status === 401) return \"auth_failure\";\n if (status === 402) return \"payment_error\";\n if (status === 403) {\n if (/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)) return \"quota_exceeded\";\n return \"auth_failure\"; // generic 403 = forbidden = likely auth issue\n }\n if (status === 429) return \"rate_limited\";\n if (status === 529) return \"overloaded\";\n if (status === 503 && /overload|capacity|too.*many.*request/i.test(body)) return \"overloaded\";\n if (status >= 500) return \"server_error\";\n if (status === 400 || status === 413) {\n // Only fallback on content-size or billing patterns; bare 400 = our bug, don't cycle\n if (PROVIDER_ERROR_PATTERNS.some((p) => p.test(body))) return \"config_error\";\n return null;\n }\n return null;\n}\n\n/**\n * Track rate-limited models to avoid hitting them again.\n * Maps model ID to the timestamp when the rate limit was hit.\n */\nconst rateLimitedModels = new Map();\n\n/** Per-model overload tracking (529/503 capacity errors) — shorter cooldown than rate limits. */\nconst overloadedModels = new Map();\n\n/** Per-model error category counts (in-memory, resets on restart). */\ntype ProviderErrorCounts = {\n auth_failure: number;\n quota_exceeded: number;\n rate_limited: number;\n overloaded: number;\n server_error: number;\n payment_error: number;\n config_error: number;\n};\nconst perProviderErrors = new Map();\n\n/** Record an error category hit for a model. */\nfunction recordProviderError(modelId: string, category: ErrorCategory): void {\n if (!perProviderErrors.has(modelId)) {\n perProviderErrors.set(modelId, {\n auth_failure: 0,\n quota_exceeded: 0,\n rate_limited: 0,\n overloaded: 0,\n server_error: 0,\n payment_error: 0,\n config_error: 0,\n });\n }\n perProviderErrors.get(modelId)![category]++;\n}\n\n/**\n * Check if a model is currently rate-limited (in cooldown period).\n */\nfunction isRateLimited(modelId: string): boolean {\n const hitTime = rateLimitedModels.get(modelId);\n if (!hitTime) return false;\n\n const elapsed = Date.now() - hitTime;\n if (elapsed >= RATE_LIMIT_COOLDOWN_MS) {\n rateLimitedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Mark a model as rate-limited.\n */\nfunction markRateLimited(modelId: string): void {\n rateLimitedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`);\n}\n\n/**\n * Mark a model as temporarily overloaded (529/503 capacity).\n * Shorter cooldown than rate limits since capacity restores quickly.\n */\nfunction markOverloaded(modelId: string): void {\n overloadedModels.set(modelId, Date.now());\n console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`);\n}\n\n/** Check if a model is in its overload cooldown period. */\nfunction isOverloaded(modelId: string): boolean {\n const hitTime = overloadedModels.get(modelId);\n if (!hitTime) return false;\n if (Date.now() - hitTime >= OVERLOAD_COOLDOWN_MS) {\n overloadedModels.delete(modelId);\n return false;\n }\n return true;\n}\n\n/**\n * Reorder models to put rate-limited ones at the end.\n */\nfunction prioritizeNonRateLimited(models: string[]): string[] {\n const available: string[] = [];\n const degraded: string[] = [];\n\n for (const model of models) {\n if (isRateLimited(model) || isOverloaded(model)) {\n degraded.push(model);\n } else {\n available.push(model);\n }\n }\n\n return [...available, ...degraded];\n}\n\n/**\n * Check if response socket is writable (prevents write-after-close errors).\n * Returns true only if all conditions are safe for writing.\n */\nfunction canWrite(res: ServerResponse): boolean {\n return (\n !res.writableEnded &&\n !res.destroyed &&\n res.socket !== null &&\n !res.socket.destroyed &&\n res.socket.writable\n );\n}\n\n/**\n * Safe write with backpressure handling.\n * Returns true if write succeeded, false if socket is closed or write failed.\n */\nfunction safeWrite(res: ServerResponse, data: string | Buffer): boolean {\n if (!canWrite(res)) {\n const bytes = typeof data === \"string\" ? Buffer.byteLength(data) : data.length;\n console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`);\n return false;\n }\n return res.write(data);\n}\n\n// Extra buffer for balance check (on top of estimateAmount's 20% buffer)\n// Total effective buffer: 1.2 * 1.5 = 1.8x (80% safety margin)\n// This prevents x402 payment failures after streaming headers are sent,\n// which would trigger OpenClaw's 5-24 hour billing cooldown.\nconst BALANCE_CHECK_BUFFER = 1.5;\n\n/**\n * Get the proxy port from pre-loaded configuration.\n * Port is validated at module load time, this just returns the cached value.\n */\nexport function getProxyPort(): number {\n return PROXY_PORT;\n}\n\n/**\n * Check if a proxy is already running on the given port.\n * Returns the wallet address if running, undefined otherwise.\n */\nasync function checkExistingProxy(\n port: number,\n): Promise<\n | {\n wallet: string;\n paymentChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n }\n | undefined\n> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);\n\n try {\n const response = await fetch(`http://127.0.0.1:${port}/health`, {\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const data = (await response.json()) as {\n status?: string;\n wallet?: string;\n paymentChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n paymentAsset?: string;\n paymentAssetSymbol?: string;\n paymentAssetDecimals?: number;\n };\n if (data.status === \"ok\" && data.wallet) {\n return {\n wallet: data.wallet,\n paymentChain: data.paymentChain,\n paymentAssets: data.paymentAssets,\n selectedPaymentAsset: data.selectedPaymentAsset ?? data.paymentAsset,\n };\n }\n }\n return undefined;\n } catch {\n clearTimeout(timeoutId);\n return undefined;\n }\n}\n\n/**\n * Error patterns that indicate a provider-side issue (not user's fault).\n * These errors should trigger fallback to the next model in the chain.\n */\nconst PROVIDER_ERROR_PATTERNS = [\n /billing/i,\n /insufficient.*balance/i,\n /credits/i,\n /quota.*exceeded/i,\n /rate.*limit/i,\n /model.*unavailable/i,\n /model.*not.*available/i,\n /service.*unavailable/i,\n /capacity/i,\n /overloaded/i,\n /temporarily.*unavailable/i,\n /api.*key.*invalid/i,\n /authentication.*failed/i,\n /request too large/i,\n /request.*size.*exceeds/i,\n /payload too large/i,\n /payment.*verification.*failed/i,\n /model.*not.*allowed/i,\n /unknown.*model/i,\n];\n\n/**\n * \"Successful\" response bodies that are actually provider degradation placeholders.\n * Some upstream providers occasionally return these with HTTP 200.\n */\nconst DEGRADED_RESPONSE_PATTERNS = [\n /the ai service is temporarily overloaded/i,\n /service is temporarily overloaded/i,\n /please try again in a moment/i,\n];\n\n/**\n * Known low-quality loop signatures seen during provider degradation windows.\n */\nconst DEGRADED_LOOP_PATTERNS = [\n /the boxed is the response\\./i,\n /the response is the text\\./i,\n /the final answer is the boxed\\./i,\n];\n\nfunction extractAssistantContent(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") return undefined;\n const record = payload as Record;\n const choices = record.choices;\n if (!Array.isArray(choices) || choices.length === 0) return undefined;\n\n const firstChoice = choices[0];\n if (!firstChoice || typeof firstChoice !== \"object\") return undefined;\n const choice = firstChoice as Record;\n const message = choice.message;\n if (!message || typeof message !== \"object\") return undefined;\n const content = (message as Record).content;\n return typeof content === \"string\" ? content : undefined;\n}\n\nfunction hasKnownLoopSignature(text: string): boolean {\n const matchCount = DEGRADED_LOOP_PATTERNS.reduce(\n (count, pattern) => (pattern.test(text) ? count + 1 : count),\n 0,\n );\n if (matchCount >= 2) return true;\n\n // Generic repetitive loop fallback for short repeated lines.\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n if (lines.length < 8) return false;\n\n const counts = new Map();\n for (const line of lines) {\n counts.set(line, (counts.get(line) ?? 0) + 1);\n }\n\n const maxRepeat = Math.max(...counts.values());\n const uniqueRatio = counts.size / lines.length;\n return maxRepeat >= 3 && uniqueRatio <= 0.45;\n}\n\n/**\n * Detect degraded 200-response payloads that should trigger model fallback.\n * Returns a short reason when fallback should happen, otherwise undefined.\n */\nexport function detectDegradedSuccessResponse(body: string): string | undefined {\n const trimmed = body.trim();\n if (!trimmed) return undefined;\n\n // Plain-text placeholder response.\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(trimmed))) {\n return \"degraded response: overloaded placeholder\";\n }\n\n // Plain-text looping garbage response.\n if (hasKnownLoopSignature(trimmed)) {\n return \"degraded response: repetitive loop output\";\n }\n\n try {\n const parsed = JSON.parse(trimmed) as Record;\n\n // Some providers return JSON error payloads with HTTP 200.\n const errorField = parsed.error;\n let errorText = \"\";\n if (typeof errorField === \"string\") {\n errorText = errorField;\n } else if (errorField && typeof errorField === \"object\") {\n const errObj = errorField as Record;\n errorText = [\n typeof errObj.message === \"string\" ? errObj.message : \"\",\n typeof errObj.type === \"string\" ? errObj.type : \"\",\n typeof errObj.code === \"string\" ? errObj.code : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n }\n if (errorText && PROVIDER_ERROR_PATTERNS.some((pattern) => pattern.test(errorText))) {\n return `degraded response: ${errorText.slice(0, 120)}`;\n }\n\n // Successful wrapper with bad assistant content.\n const assistantContent = extractAssistantContent(parsed);\n if (!assistantContent) return undefined;\n if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(assistantContent))) {\n return \"degraded response: overloaded assistant content\";\n }\n if (hasKnownLoopSignature(assistantContent)) {\n return \"degraded response: repetitive assistant loop\";\n }\n } catch {\n // Not JSON - handled by plaintext checks above.\n }\n\n return undefined;\n}\n\n/**\n * Valid message roles for OpenAI-compatible APIs.\n * Some clients send non-standard roles (e.g., \"developer\" instead of \"system\").\n */\nconst VALID_ROLES = new Set([\"system\", \"user\", \"assistant\", \"tool\", \"function\"]);\n\n/**\n * Role mappings for non-standard roles.\n * Maps client-specific roles to standard OpenAI roles.\n */\nconst ROLE_MAPPINGS: Record = {\n developer: \"system\", // OpenAI's newer API uses \"developer\" for system messages\n model: \"assistant\", // Some APIs use \"model\" instead of \"assistant\"\n};\n\ntype ChatMessage = { role: string; content: string | unknown };\n\n/**\n * Anthropic tool ID pattern: only alphanumeric, underscore, and hyphen allowed.\n * Error: \"messages.X.content.Y.tool_use.id: String should match pattern '^[a-zA-Z0-9_-]+$'\"\n */\nconst VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\n/**\n * Sanitize a tool ID to match Anthropic's required pattern.\n * Replaces invalid characters with underscores.\n */\nfunction sanitizeToolId(id: string | undefined): string | undefined {\n if (!id || typeof id !== \"string\") return id;\n if (VALID_TOOL_ID_PATTERN.test(id)) return id;\n\n // Replace invalid characters with underscores\n return id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n}\n\n/**\n * Type for messages with tool calls (OpenAI format).\n */\ntype MessageWithTools = ChatMessage & {\n tool_calls?: Array<{ id?: string; type?: string; function?: unknown }>;\n tool_call_id?: string;\n};\n\n/**\n * Type for content blocks that may contain tool IDs (Anthropic format in OpenAI wrapper).\n */\ntype ContentBlock = {\n type?: string;\n id?: string;\n tool_use_id?: string;\n [key: string]: unknown;\n};\n\n/**\n * Sanitize all tool IDs in messages to match Anthropic's pattern.\n * Handles both OpenAI format (tool_calls, tool_call_id) and content block formats.\n */\nfunction sanitizeToolIds(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const sanitized = messages.map((msg) => {\n const typedMsg = msg as MessageWithTools;\n let msgChanged = false;\n let newMsg = { ...msg } as MessageWithTools;\n\n // Sanitize tool_calls[].id in assistant messages\n if (typedMsg.tool_calls && Array.isArray(typedMsg.tool_calls)) {\n const newToolCalls = typedMsg.tool_calls.map((tc) => {\n if (tc.id && typeof tc.id === \"string\") {\n const sanitized = sanitizeToolId(tc.id);\n if (sanitized !== tc.id) {\n msgChanged = true;\n return { ...tc, id: sanitized };\n }\n }\n return tc;\n });\n if (msgChanged) {\n newMsg = { ...newMsg, tool_calls: newToolCalls };\n }\n }\n\n // Sanitize tool_call_id in tool messages\n if (typedMsg.tool_call_id && typeof typedMsg.tool_call_id === \"string\") {\n const sanitized = sanitizeToolId(typedMsg.tool_call_id);\n if (sanitized !== typedMsg.tool_call_id) {\n msgChanged = true;\n newMsg = { ...newMsg, tool_call_id: sanitized };\n }\n }\n\n // Sanitize content blocks if content is an array (Anthropic-style content)\n if (Array.isArray(typedMsg.content)) {\n const newContent = (typedMsg.content as ContentBlock[]).map((block) => {\n if (!block || typeof block !== \"object\") return block;\n\n let blockChanged = false;\n let newBlock = { ...block };\n\n // tool_use blocks have \"id\"\n if (block.type === \"tool_use\" && block.id && typeof block.id === \"string\") {\n const sanitized = sanitizeToolId(block.id);\n if (sanitized !== block.id) {\n blockChanged = true;\n newBlock = { ...newBlock, id: sanitized };\n }\n }\n\n // tool_result blocks have \"tool_use_id\"\n if (\n block.type === \"tool_result\" &&\n block.tool_use_id &&\n typeof block.tool_use_id === \"string\"\n ) {\n const sanitized = sanitizeToolId(block.tool_use_id);\n if (sanitized !== block.tool_use_id) {\n blockChanged = true;\n newBlock = { ...newBlock, tool_use_id: sanitized };\n }\n }\n\n if (blockChanged) {\n msgChanged = true;\n return newBlock;\n }\n return block;\n });\n\n if (msgChanged) {\n newMsg = { ...newMsg, content: newContent };\n }\n }\n\n if (msgChanged) {\n hasChanges = true;\n return newMsg;\n }\n return msg;\n });\n\n return hasChanges ? sanitized : messages;\n}\n\n/**\n * Normalize message roles to standard OpenAI format.\n * Converts non-standard roles (e.g., \"developer\") to valid ones.\n */\nfunction normalizeMessageRoles(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n if (VALID_ROLES.has(msg.role)) return msg;\n\n const mappedRole = ROLE_MAPPINGS[msg.role];\n if (mappedRole) {\n hasChanges = true;\n return { ...msg, role: mappedRole };\n }\n\n // Unknown role - default to \"user\" to avoid API errors\n hasChanges = true;\n return { ...msg, role: \"user\" };\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Normalize messages for Google models.\n * Google's Gemini API requires the first non-system message to be from \"user\".\n * If conversation starts with \"assistant\"/\"model\", prepend a placeholder user message.\n */\n\nfunction normalizeMessagesForGoogle(messages: ChatMessage[]): ChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n // Find first non-system message\n let firstNonSystemIdx = -1;\n for (let i = 0; i < messages.length; i++) {\n if (messages[i].role !== \"system\") {\n firstNonSystemIdx = i;\n break;\n }\n }\n\n // If no non-system messages, return as-is\n if (firstNonSystemIdx === -1) return messages;\n\n const firstRole = messages[firstNonSystemIdx].role;\n\n // If first non-system message is already \"user\", no change needed\n if (firstRole === \"user\") return messages;\n\n // If first non-system message is \"assistant\" or \"model\", prepend a user message\n if (firstRole === \"assistant\" || firstRole === \"model\") {\n const normalized = [...messages];\n normalized.splice(firstNonSystemIdx, 0, {\n role: \"user\",\n content: \"(continuing conversation)\",\n });\n return normalized;\n }\n\n return messages;\n}\n\n/**\n * Check if a model is a Google model that requires message normalization.\n */\nfunction isGoogleModel(modelId: string): boolean {\n return modelId.startsWith(\"google/\") || modelId.startsWith(\"gemini\");\n}\n\n/**\n * Extended message type for thinking-enabled conversations.\n */\ntype ExtendedChatMessage = ChatMessage & {\n tool_calls?: unknown[];\n reasoning_content?: unknown;\n};\n\n/**\n * Normalize messages for thinking-enabled requests.\n * When thinking/extended_thinking is enabled, assistant messages with tool_calls\n * must have reasoning_content (can be empty string if not present).\n * Error: \"400 thinking is enabled but reasoning_content is missing in assistant tool call message\"\n */\nfunction normalizeMessagesForThinking(messages: ExtendedChatMessage[]): ExtendedChatMessage[] {\n if (!messages || messages.length === 0) return messages;\n\n let hasChanges = false;\n const normalized = messages.map((msg) => {\n // Skip if not assistant or already has reasoning_content\n if (msg.role !== \"assistant\" || msg.reasoning_content !== undefined) {\n return msg;\n }\n\n // Check for OpenAI format: tool_calls array\n const hasOpenAIToolCalls =\n msg.tool_calls && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;\n\n // Check for Anthropic format: content array with tool_use blocks\n const hasAnthropicToolUse =\n Array.isArray(msg.content) &&\n (msg.content as Array<{ type?: string }>).some((block) => block?.type === \"tool_use\");\n\n if (hasOpenAIToolCalls || hasAnthropicToolUse) {\n hasChanges = true;\n return { ...msg, reasoning_content: \"\" };\n }\n return msg;\n });\n\n return hasChanges ? normalized : messages;\n}\n\n/**\n * Remove \"blockrun\" branding from system messages before sending upstream.\n *\n * OpenClaw embeds `model=blockrun/auto` and `default_model=blockrun/auto` in its\n * system prompt Runtime section. LLMs pick up \"blockrun\" and adopt it as their\n * identity (e.g. \"I'm Blockrun\"), overriding the user's SOUL.md persona.\n *\n * This function replaces `blockrun/` references with the actual resolved\n * model name, and strips any remaining \"blockrun/\" prefix so the upstream LLM\n * never sees \"blockrun\" as an identity to adopt.\n */\nexport function debrandSystemMessages(\n messages: ChatMessage[],\n resolvedModel: string,\n): ChatMessage[] {\n // Routing profile names that get replaced with the actual model\n const PROFILE_NAMES = [\"auto\", \"free\", \"eco\", \"premium\"];\n const profilePattern = new RegExp(`\\\\bblockrun/(${PROFILE_NAMES.join(\"|\")})\\\\b`, \"gi\");\n // Also handle \"blockrun//\" → \"/\"\n const prefixPattern = /\\bblockrun\\/(?=[a-z])/gi;\n\n let hasChanges = false;\n const result = messages.map((msg) => {\n if (msg.role !== \"system\" || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n\n // Replace routing profiles (blockrun/auto etc.) with resolved model\n const afterProfiles = content.replace(profilePattern, resolvedModel);\n\n // Replace remaining blockrun/ prefix (e.g. blockrun/openai/gpt-4o → openai/gpt-4o)\n const afterPrefix = afterProfiles.replace(prefixPattern, \"\");\n\n if (afterPrefix !== content) {\n hasChanges = true;\n content = afterPrefix;\n }\n\n return content !== msg.content ? { ...msg, content } : msg;\n });\n\n return hasChanges ? result : messages;\n}\n\n/**\n * Result of truncating messages.\n */\ntype TruncationResult = {\n messages: T[];\n wasTruncated: boolean;\n originalCount: number;\n truncatedCount: number;\n};\n\n/**\n * Truncate messages to stay under BlockRun's MAX_MESSAGES limit.\n * Keeps all system messages and the most recent conversation history.\n * Returns the messages and whether truncation occurred.\n */\nfunction truncateMessages(messages: T[]): TruncationResult {\n if (!messages || messages.length <= MAX_MESSAGES) {\n return {\n messages,\n wasTruncated: false,\n originalCount: messages?.length ?? 0,\n truncatedCount: messages?.length ?? 0,\n };\n }\n\n // Separate system messages from conversation\n const systemMsgs = messages.filter((m) => m.role === \"system\");\n const conversationMsgs = messages.filter((m) => m.role !== \"system\");\n\n // Keep all system messages + most recent conversation messages\n const maxConversation = MAX_MESSAGES - systemMsgs.length;\n const truncatedConversation = conversationMsgs.slice(-maxConversation);\n\n const result = [...systemMsgs, ...truncatedConversation];\n\n console.log(\n `[ClawRouter] Truncated messages: ${messages.length} → ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`,\n );\n\n return {\n messages: result,\n wasTruncated: true,\n originalCount: messages.length,\n truncatedCount: result.length,\n };\n}\n\n// Kimi/Moonshot models use special Unicode tokens for thinking boundaries.\n// Pattern: <|begin▁of▁thinking|>content<|end▁of▁thinking|>\n// The | is fullwidth vertical bar (U+FF5C), ▁ is lower one-eighth block (U+2581).\n\n// Match full Kimi thinking blocks: <|begin...|>content<|end...|>\nconst KIMI_BLOCK_RE = /<[||][^<>]*begin[^<>]*[||]>[\\s\\S]*?<[||][^<>]*end[^<>]*[||]>/gi;\n\n// Match standalone Kimi tokens like <|end▁of▁thinking|>\nconst KIMI_TOKEN_RE = /<[||][^<>]*[||]>/g;\n\n// Standard thinking tags that may leak through from various models\nconst THINKING_TAG_RE = /<\\s*\\/?\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>/gi;\n\n// Full thinking blocks: content\nconst THINKING_BLOCK_RE =\n /<\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>[\\s\\S]*?<\\s*\\/\\s*(?:think(?:ing)?|thought|antthinking)\\s*>/gi;\n\n/**\n * Strip thinking tokens and blocks from model response content.\n * Handles both Kimi-style Unicode tokens and standard XML-style tags.\n *\n * NOTE: DSML tags (<|DSML|...>) are NOT stripped - those are tool calls\n * that should be handled by the API, not hidden from users.\n */\nfunction stripThinkingTokens(content: string): string {\n if (!content) return content;\n // Strip full Kimi thinking blocks first (begin...end with content)\n let cleaned = content.replace(KIMI_BLOCK_RE, \"\");\n // Strip remaining standalone Kimi tokens\n cleaned = cleaned.replace(KIMI_TOKEN_RE, \"\");\n // Strip full thinking blocks (...)\n cleaned = cleaned.replace(THINKING_BLOCK_RE, \"\");\n // Strip remaining standalone thinking tags\n cleaned = cleaned.replace(THINKING_TAG_RE, \"\");\n return cleaned;\n}\n\n/** Callback info for low balance warning */\nexport type LowBalanceInfo = {\n balanceUSD: string;\n walletAddress: string;\n assetSymbol: string;\n};\n\n/** Callback info for insufficient funds error */\nexport type InsufficientFundsInfo = {\n balanceUSD: string;\n requiredUSD: string;\n walletAddress: string;\n assetSymbol: string;\n};\n\n/**\n * Wallet config: either a plain EVM private key string, or the full\n * resolution object from resolveOrGenerateWalletKey() which may include\n * Solana keys. Using the full object prevents callers from accidentally\n * forgetting to forward Solana key bytes.\n */\nexport type WalletConfig = string | { key: string; solanaPrivateKeyBytes?: Uint8Array };\n\nexport type PaymentChain = \"base\" | \"solana\";\n\nexport type ProxyOptions = {\n wallet: WalletConfig;\n apiBase?: string;\n /** Payment chain: \"base\" (default) or \"solana\". Can also be set via CLAWROUTER_PAYMENT_CHAIN env var. */\n paymentChain?: PaymentChain;\n /** Port to listen on (default: 8402) */\n port?: number;\n routingConfig?: Partial;\n /** Request timeout in ms (default: 180000 = 3 minutes). Covers on-chain tx + LLM response. */\n requestTimeoutMs?: number;\n /** Skip balance checks (for testing only). Default: false */\n skipBalanceCheck?: boolean;\n /** Override the balance monitor with a mock (for testing only). */\n _balanceMonitorOverride?: AnyBalanceMonitor;\n /**\n * Session persistence config. When enabled, maintains model selection\n * across requests within a session to prevent mid-task model switching.\n */\n sessionConfig?: Partial;\n /**\n * Auto-compress large requests to reduce network usage.\n * When enabled, requests are automatically compressed using\n * LLM-safe context compression (15-40% reduction).\n * Default: true\n */\n autoCompressRequests?: boolean;\n /**\n * Threshold in KB to trigger auto-compression (default: 180).\n * Requests larger than this are compressed before sending.\n * Set to 0 to compress all requests.\n */\n compressionThresholdKB?: number;\n /**\n * Response caching config. When enabled, identical requests return\n * cached responses instead of making new API calls.\n * Default: enabled with 10 minute TTL, 200 max entries.\n */\n cacheConfig?: ResponseCacheConfig;\n /**\n * Maximum total spend (in USD) per session run.\n * Default: undefined (no limit). Example: 0.5 = $0.50 per session.\n */\n maxCostPerRunUsd?: number;\n /**\n * How to enforce the per-run cost cap.\n * - 'graceful' (default): when budget runs low, downgrade to cheaper models; use free model\n * as last resort. Only hard-stops when no model can serve the request.\n * - 'strict': immediately return 429 once the session spend reaches the cap.\n */\n maxCostPerRunMode?: \"graceful\" | \"strict\";\n /**\n * Set of model IDs to exclude from routing.\n * Excluded models are filtered out of fallback chains.\n * Loaded from ~/.openclaw/blockrun/exclude-models.json\n */\n excludeModels?: Set;\n onReady?: (port: number) => void;\n onError?: (error: Error) => void;\n onPayment?: (info: { model: string; amount: string; network: string }) => void;\n onRouted?: (decision: RoutingDecision) => void;\n /** Called when balance drops below $1.00 (warning, request still proceeds) */\n onLowBalance?: (info: LowBalanceInfo) => void;\n /** Called when balance is insufficient for a request (request fails) */\n onInsufficientFunds?: (info: InsufficientFundsInfo) => void;\n};\n\nexport type ProxyHandle = {\n port: number;\n baseUrl: string;\n walletAddress: string;\n solanaAddress?: string;\n paymentAsset?: BasePaymentAsset;\n paymentAssets?: BasePaymentAsset[];\n balanceMonitor: AnyBalanceMonitor;\n close: () => Promise;\n};\n\n/**\n * Build model pricing map from BLOCKRUN_MODELS.\n */\nfunction buildModelPricing(): Map {\n const map = new Map();\n for (const m of BLOCKRUN_MODELS) {\n if (m.id === AUTO_MODEL) continue; // skip meta-model\n map.set(m.id, { inputPrice: m.inputPrice, outputPrice: m.outputPrice });\n }\n return map;\n}\n\ntype ModelListEntry = {\n id: string;\n object: \"model\";\n created: number;\n owned_by: string;\n};\n\n/**\n * Build `/v1/models` response entries from the full OpenClaw model registry.\n * This includes alias IDs (e.g., `flash`, `kimi`) so `/model ` works reliably.\n */\nexport function buildProxyModelList(\n createdAt: number = Math.floor(Date.now() / 1000),\n): ModelListEntry[] {\n const seen = new Set();\n return OPENCLAW_MODELS.filter((model) => {\n if (seen.has(model.id)) return false;\n seen.add(model.id);\n return true;\n }).map((model) => ({\n id: model.id,\n object: \"model\",\n created: createdAt,\n owned_by: model.id.includes(\"/\") ? (model.id.split(\"/\")[0] ?? \"blockrun\") : \"blockrun\",\n }));\n}\n\n/**\n * Merge partial routing config overrides with defaults.\n */\nfunction mergeRoutingConfig(overrides?: Partial): RoutingConfig {\n if (!overrides) return DEFAULT_ROUTING_CONFIG;\n return {\n ...DEFAULT_ROUTING_CONFIG,\n ...overrides,\n classifier: { ...DEFAULT_ROUTING_CONFIG.classifier, ...overrides.classifier },\n scoring: { ...DEFAULT_ROUTING_CONFIG.scoring, ...overrides.scoring },\n tiers: { ...DEFAULT_ROUTING_CONFIG.tiers, ...overrides.tiers },\n overrides: { ...DEFAULT_ROUTING_CONFIG.overrides, ...overrides.overrides },\n };\n}\n\n/**\n * Estimate stablecoin cost for a request based on model pricing.\n * Returns amount string in USD micros (6-decimal integer, i.e. 1 = $0.000001) or undefined if unknown.\n * This is an internal unit used for balance checks; conversion to on-chain token units happens elsewhere.\n */\nfunction estimateAmount(\n modelId: string,\n bodyLength: number,\n maxTokens: number,\n): string | undefined {\n const model = BLOCKRUN_MODELS.find((m) => m.id === modelId);\n if (!model) return undefined;\n\n // Rough estimate: ~4 chars per token for input\n const estimatedInputTokens = Math.ceil(bodyLength / 4);\n const estimatedOutputTokens = maxTokens || model.maxOutput || 4096;\n\n const costUsd =\n (estimatedInputTokens / 1_000_000) * model.inputPrice +\n (estimatedOutputTokens / 1_000_000) * model.outputPrice;\n\n // Convert to USD micros (6-decimal integer), add 20% buffer for estimation error\n // Minimum 1000 ($0.001) to match CDP Facilitator's enforced minimum payment\n const amountMicros = Math.max(1000, Math.ceil(costUsd * 1.2 * 1_000_000));\n return amountMicros.toString();\n}\n\n// Image pricing table (must match server's IMAGE_MODELS in blockrun/src/lib/models.ts)\n// Server applies 5% margin on top of these prices.\nconst IMAGE_PRICING: Record }> = {\n \"openai/dall-e-3\": {\n default: 0.04,\n sizes: { \"1024x1024\": 0.04, \"1792x1024\": 0.08, \"1024x1792\": 0.08 },\n },\n \"openai/gpt-image-1\": {\n default: 0.02,\n sizes: { \"1024x1024\": 0.02, \"1536x1024\": 0.04, \"1024x1536\": 0.04 },\n },\n \"black-forest/flux-1.1-pro\": { default: 0.04 },\n \"google/nano-banana\": { default: 0.05 },\n \"google/nano-banana-pro\": {\n default: 0.1,\n sizes: { \"1024x1024\": 0.1, \"2048x2048\": 0.1, \"4096x4096\": 0.15 },\n },\n};\n\n/**\n * Estimate the cost of an image generation/editing request.\n * Matches server-side calculateImagePrice() including 5% margin.\n */\nfunction estimateImageCost(model: string, size?: string, n: number = 1): number {\n const pricing = IMAGE_PRICING[model];\n if (!pricing) return 0.04 * n * 1.05; // fallback: assume $0.04/image + margin\n const sizePrice = size && pricing.sizes ? pricing.sizes[size] : undefined;\n const pricePerImage = sizePrice ?? pricing.default;\n return pricePerImage * n * 1.05; // 5% server margin\n}\n\n/**\n * Proxy a partner API request through x402 payment flow.\n *\n * Simplified proxy for partner endpoints (/v1/x/*, /v1/partner/*).\n * No smart routing, SSE, compression, or sessions — just collect body,\n * forward via payFetch (which handles 402 automatically), and stream back.\n */\nasync function proxyPartnerRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n getActualPaymentUsd: () => number,\n): Promise {\n const startTime = Date.now();\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const body = Buffer.concat(bodyChunks);\n\n // Forward headers (strip hop-by-hop)\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") headers[key] = value;\n }\n if (!headers[\"content-type\"]) headers[\"content-type\"] = \"application/json\";\n headers[\"user-agent\"] = USER_AGENT;\n\n console.log(`[ClawRouter] Partner request: ${req.method} ${req.url}`);\n\n const upstream = await payFetch(upstreamUrl, {\n method: req.method ?? \"POST\",\n headers,\n body: body.length > 0 ? new Uint8Array(body) : undefined,\n });\n\n // Forward response headers\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\") return;\n responseHeaders[key] = value;\n });\n\n res.writeHead(upstream.status, responseHeaders);\n\n // Stream response body\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body, ERROR_BODY_READ_TIMEOUT_MS);\n for (const chunk of chunks) {\n safeWrite(res, Buffer.from(chunk));\n }\n }\n\n res.end();\n\n const latencyMs = Date.now() - startTime;\n console.log(`[ClawRouter] Partner response: ${upstream.status} (${latencyMs}ms)`);\n\n // Log partner usage with actual x402 payment amount (previously logged cost: 0)\n const partnerCost = getActualPaymentUsd();\n logUsage({\n timestamp: new Date().toISOString(),\n model: \"partner\",\n tier: \"PARTNER\",\n cost: partnerCost,\n baselineCost: partnerCost,\n savings: 0,\n latencyMs,\n partnerId:\n (req.url?.split(\"?\")[0] ?? \"\").replace(/^\\/v1\\//, \"\").replace(/\\//g, \"_\") || \"unknown\",\n service: \"partner\",\n }).catch(() => {});\n}\n\n/**\n * Read a local image file and return it as a base64 data URI.\n * Supports ~/ home directory expansion.\n */\nfunction readImageFileAsDataUri(filePath: string): string {\n const resolved = filePath.startsWith(\"~/\") ? join(homedir(), filePath.slice(2)) : filePath;\n\n if (!existsSync(resolved)) {\n throw new Error(`Image file not found: ${resolved}`);\n }\n\n const ext = resolved.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mimeMap: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n };\n const mime = mimeMap[ext] ?? \"image/png\";\n const data = readFileSync(resolved);\n return `data:${mime};base64,${data.toString(\"base64\")}`;\n}\n\n/**\n * Upload a base64 data URI to catbox.moe and return a public URL.\n * Google image models (nano-banana) return data URIs instead of hosted URLs,\n * which breaks Telegram and other clients that can't render raw base64.\n */\nasync function uploadDataUriToHost(dataUri: string): Promise {\n const match = dataUri.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (!match) throw new Error(\"Invalid data URI format\");\n const [, mimeType, b64Data] = match;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType.split(\"/\")[1] ?? \"png\");\n\n const buffer = Buffer.from(b64Data, \"base64\");\n const blob = new Blob([buffer], { type: mimeType });\n\n const form = new FormData();\n form.append(\"reqtype\", \"fileupload\");\n form.append(\"fileToUpload\", blob, `image.${ext}`);\n\n const uploadController = new AbortController();\n const uploadTimeout = setTimeout(() => uploadController.abort(), 30_000);\n try {\n const resp = await fetch(\"https://catbox.moe/user/api.php\", {\n method: \"POST\",\n body: form,\n signal: uploadController.signal,\n });\n\n if (!resp.ok) throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);\n const result = await resp.text();\n if (result.startsWith(\"https://\")) {\n return result.trim();\n }\n throw new Error(`catbox.moe upload failed: ${result}`);\n } finally {\n clearTimeout(uploadTimeout);\n }\n}\n\n/**\n * Start the local x402 proxy server.\n *\n * If a proxy is already running on the target port, reuses it instead of failing.\n * Port can be configured via BLOCKRUN_PROXY_PORT environment variable.\n *\n * Returns a handle with the assigned port, base URL, and a close function.\n */\nexport async function startProxy(options: ProxyOptions): Promise {\n // Normalize wallet config: string = EVM-only, object = full resolution\n const walletKey = typeof options.wallet === \"string\" ? options.wallet : options.wallet.key;\n const solanaPrivateKeyBytes =\n typeof options.wallet === \"string\" ? undefined : options.wallet.solanaPrivateKeyBytes;\n\n // Payment chain: options > env var > persisted file > default \"base\".\n // No dynamic switching — user selects chain via /wallet solana or /wallet base.\n const paymentChain = options.paymentChain ?? (await resolvePaymentChain());\n const apiBase =\n options.apiBase ??\n (paymentChain === \"solana\" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API);\n let activeBasePaymentAssets =\n paymentChain === \"base\"\n ? (await fetchBasePaymentAssets(apiBase).catch(() => undefined)) ?? [DEFAULT_BASE_PAYMENT_ASSET]\n : [DEFAULT_BASE_PAYMENT_ASSET];\n let activeBasePaymentAsset = activeBasePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET;\n let lastSelectedBasePaymentAsset = activeBasePaymentAsset;\n if (paymentChain === \"solana\" && !solanaPrivateKeyBytes) {\n console.warn(\n `[ClawRouter] ⚠ Payment chain is Solana but no mnemonic found — falling back to Base (EVM).`,\n );\n console.warn(\n `[ClawRouter] To fix: run \"npx @blockrun/clawrouter wallet recover\" if your mnemonic exists,`,\n );\n console.warn(`[ClawRouter] or run \"npx @blockrun/clawrouter chain base\" to switch to EVM.`);\n } else if (paymentChain === \"solana\") {\n console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`);\n }\n\n // Determine port: options.port > env var > default\n const listenPort = options.port ?? getProxyPort();\n\n const buildReuseHandle = async (existingProxyData: {\n wallet: string;\n paymentChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n }): Promise => {\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const baseUrl = `http://127.0.0.1:${listenPort}`;\n\n if (existingProxyData.wallet !== account.address) {\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxyData.wallet}, but current config uses ${account.address}. Reusing existing proxy.`,\n );\n }\n\n if (existingProxyData.paymentChain) {\n if (existingProxyData.paymentChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${existingProxyData.paymentChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n } else if (paymentChain !== \"base\") {\n console.warn(\n `[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`,\n );\n throw new Error(\n `Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n );\n }\n\n let reuseSolanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n reuseSolanaAddress = solanaSigner.address;\n }\n\n let reuseBalanceMonitor: AnyBalanceMonitor;\n if (paymentChain === \"solana\" && reuseSolanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n reuseBalanceMonitor = new SolanaBalanceMonitor(reuseSolanaAddress);\n } else {\n if (existingProxyData.paymentAssets?.length) {\n activeBasePaymentAssets = existingProxyData.paymentAssets;\n }\n const selectedPaymentAssetId =\n typeof existingProxyData.selectedPaymentAsset === \"string\"\n ? existingProxyData.selectedPaymentAsset.toLowerCase()\n : existingProxyData.selectedPaymentAsset?.asset?.toLowerCase();\n const selectedPaymentAsset = selectedPaymentAssetId\n ? activeBasePaymentAssets.find((asset) => asset.asset.toLowerCase() === selectedPaymentAssetId)\n : undefined;\n if (selectedPaymentAsset) {\n activeBasePaymentAsset = selectedPaymentAsset;\n lastSelectedBasePaymentAsset = selectedPaymentAsset;\n }\n reuseBalanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset);\n }\n\n options.onReady?.(listenPort);\n\n return {\n port: listenPort,\n baseUrl,\n walletAddress: existingProxyData.wallet,\n solanaAddress: reuseSolanaAddress,\n paymentAsset: paymentChain === \"base\" ? activeBasePaymentAsset : undefined,\n paymentAssets: paymentChain === \"base\" ? activeBasePaymentAssets : undefined,\n balanceMonitor: reuseBalanceMonitor,\n close: async () => {\n // No-op: we didn't start this proxy, so we shouldn't close it\n },\n };\n };\n\n // Check if a proxy is already running on this port\n const existingProxy = await checkExistingProxy(listenPort);\n if (existingProxy) {\n return buildReuseHandle(existingProxy);\n }\n\n // Create x402 payment client with EVM scheme (always available)\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n const evmPublicClient = createPublicClient({ chain: base, transport: http() });\n const evmSigner = toClientEvmSigner(account, evmPublicClient);\n const x402 = new x402Client();\n registerExactEvmScheme(x402, { signer: evmSigner });\n\n // Register Solana scheme if key is available\n // Uses registerExactSvmScheme helper which registers:\n // - solana:* wildcard (catches any CAIP-2 Solana network)\n // - V1 compat names: \"solana\", \"solana-devnet\", \"solana-testnet\"\n let solanaAddress: string | undefined;\n if (solanaPrivateKeyBytes) {\n const { registerExactSvmScheme } = await import(\"@x402/svm/exact/client\");\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n solanaAddress = solanaSigner.address;\n registerExactSvmScheme(x402, { signer: solanaSigner });\n console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`);\n }\n\n // Log which chain is used for each payment and capture actual payment amount\n x402.onAfterPaymentCreation(async (context) => {\n const network = context.selectedRequirements.network;\n if (network.startsWith(\"eip155\")) {\n activeBasePaymentAssets =\n (await fetchBasePaymentAssets(apiBase).catch(() => undefined)) ?? activeBasePaymentAssets;\n const refreshedActiveAsset = activeBasePaymentAssets.find(\n (asset) => asset.asset.toLowerCase() === activeBasePaymentAsset.asset.toLowerCase(),\n );\n if (refreshedActiveAsset) {\n activeBasePaymentAsset = refreshedActiveAsset;\n }\n }\n const chain = network.startsWith(\"eip155\")\n ? \"Base (EVM)\"\n : network.startsWith(\"solana\")\n ? \"Solana\"\n : network;\n const amountRaw = BigInt(context.selectedRequirements.amount || \"0\");\n const selectedRequirementsWithDecimals = context.selectedRequirements as { decimals?: number };\n const amountDecimals =\n selectedRequirementsWithDecimals.decimals ??\n (network.startsWith(\"eip155\") ? activeBasePaymentAsset.decimals : 6);\n const amountUsdText = formatStableAmount(amountRaw, amountDecimals);\n const amountUsd = Number.parseFloat(amountUsdText);\n // Write to request-scoped store (if available)\n const store = paymentStore.getStore();\n if (store) {\n store.amountUsd = amountUsd;\n store.amountUsdText = amountUsdText;\n }\n console.log(`[ClawRouter] Payment signed on ${chain} (${network}) — $${amountUsdText}`);\n });\n\n const payFetch = createPayFetchWithPreAuth(fetch, x402, undefined, {\n skipPreAuth: paymentChain === \"solana\",\n });\n\n // Create balance monitor for pre-request checks (lazy import to avoid loading @solana/kit on Base chain)\n let balanceMonitor: AnyBalanceMonitor;\n if (options._balanceMonitorOverride) {\n balanceMonitor = options._balanceMonitorOverride;\n } else if (paymentChain === \"solana\" && solanaAddress) {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n balanceMonitor = new SolanaBalanceMonitor(solanaAddress);\n } else {\n balanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset);\n }\n\n // Build router options (100% local — no external API calls for routing)\n const routingConfig = mergeRoutingConfig(options.routingConfig);\n const modelPricing = buildModelPricing();\n const routerOpts: RouterOptions = {\n config: routingConfig,\n modelPricing,\n };\n\n // Request deduplicator (shared across all requests)\n const deduplicator = new RequestDeduplicator();\n\n // Response cache for identical requests (longer TTL than dedup)\n const responseCache = new ResponseCache(options.cacheConfig);\n\n // Session store for model persistence (prevents mid-task model switching)\n const sessionStore = new SessionStore(options.sessionConfig);\n\n // Session journal for memory (enables agents to recall earlier work)\n const sessionJournal = new SessionJournal();\n\n // Track active connections for graceful cleanup\n const connections = new Set();\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n // Wrap in paymentStore.run() so x402 hook can write actual payment amount per-request\n paymentStore.run({ amountUsd: 0, amountUsdText: \"0.000000\" }, async () => {\n // Add stream error handlers to prevent server crashes\n req.on(\"error\", (err) => {\n console.error(`[ClawRouter] Request stream error: ${err.message}`);\n // Don't throw - just log and let request handler deal with it\n });\n\n res.on(\"error\", (err) => {\n console.error(`[ClawRouter] Response stream error: ${err.message}`);\n // Don't try to write to failed socket - just log\n });\n\n // Finished wrapper for guaranteed cleanup on response completion/error\n finished(res, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Response finished with error: ${err.message}`);\n }\n // Note: heartbeatInterval cleanup happens in res.on(\"close\") handler\n // Note: completed and dedup cleanup happens in the res.on(\"close\") handler below\n });\n\n // Request finished wrapper for complete stream lifecycle tracking\n finished(req, (err) => {\n if (err && err.code !== \"ERR_STREAM_DESTROYED\") {\n console.error(`[ClawRouter] Request finished with error: ${err.message}`);\n }\n });\n\n // Health check with optional balance info\n if (req.url === \"/health\" || req.url?.startsWith(\"/health?\")) {\n const url = new URL(req.url, \"http://localhost\");\n const full = url.searchParams.get(\"full\") === \"true\";\n\n const response: Record = {\n status: \"ok\",\n wallet: account.address,\n paymentChain,\n };\n if (paymentChain === \"base\") {\n response.paymentAsset = activeBasePaymentAsset.asset;\n response.paymentAssetSymbol = activeBasePaymentAsset.symbol;\n response.paymentAssetDecimals = activeBasePaymentAsset.decimals;\n response.paymentAssets = activeBasePaymentAssets;\n response.selectedPaymentAsset = lastSelectedBasePaymentAsset.asset;\n response.selectedPaymentAssetSymbol = lastSelectedBasePaymentAsset.symbol;\n }\n if (solanaAddress) {\n response.solana = solanaAddress;\n }\n\n if (full) {\n try {\n if (paymentChain === \"base\") {\n const assetBalances = await Promise.all(\n activeBasePaymentAssets.map(async (asset) => {\n const monitor = new BalanceMonitor(account.address, asset);\n const balanceInfo = await monitor.checkBalance();\n return {\n asset: asset.asset,\n symbol: asset.symbol,\n decimals: asset.decimals,\n balance: balanceInfo.balanceUSD,\n isLow: balanceInfo.isLow,\n isEmpty: balanceInfo.isEmpty,\n };\n }),\n );\n response.assetBalances = assetBalances;\n response.balance = assetBalances[0]?.balance ?? \"$0.00\";\n response.isLow = assetBalances[0]?.isLow ?? true;\n response.isEmpty = assetBalances.every((asset) => asset.isEmpty);\n } else {\n const balanceInfo = await balanceMonitor.checkBalance();\n response.balance = balanceInfo.balanceUSD;\n response.isLow = balanceInfo.isLow;\n response.isEmpty = balanceInfo.isEmpty;\n }\n } catch {\n response.balanceError = \"Could not fetch balance\";\n }\n }\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(response));\n return;\n }\n\n // Cache stats endpoint\n if (req.url === \"/cache\" || req.url?.startsWith(\"/cache?\")) {\n const stats = responseCache.getStats();\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(JSON.stringify(stats, null, 2));\n return;\n }\n\n // Stats clear endpoint - delete all log files\n if (req.url === \"/stats\" && req.method === \"DELETE\") {\n try {\n const result = await clearStats();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ cleared: true, deletedFiles: result.deletedFiles }));\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // Stats API endpoint - returns JSON for programmatic access\n if (req.url === \"/stats\" || req.url?.startsWith(\"/stats?\")) {\n try {\n const url = new URL(req.url, \"http://localhost\");\n const days = parseInt(url.searchParams.get(\"days\") || \"7\", 10);\n const stats = await getStats(Math.min(days, 30));\n\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n });\n res.end(\n JSON.stringify(\n {\n ...stats,\n providerErrors: Object.fromEntries(perProviderErrors),\n },\n null,\n 2,\n ),\n );\n } catch (err) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Failed to get stats: ${err instanceof Error ? err.message : String(err)}`,\n }),\n );\n }\n return;\n }\n\n // --- Handle /v1/models locally (no upstream call needed) ---\n if (req.url === \"/v1/models\" && req.method === \"GET\") {\n const models = buildProxyModelList();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ object: \"list\", data: models }));\n return;\n }\n\n // --- Serve locally cached images (~/.openclaw/blockrun/images/) ---\n if (req.url?.startsWith(\"/images/\") && req.method === \"GET\") {\n const filename = req.url\n .slice(\"/images/\".length)\n .split(\"?\")[0]!\n .replace(/[^a-zA-Z0-9._-]/g, \"\");\n if (!filename) {\n res.writeHead(400);\n res.end(\"Bad request\");\n return;\n }\n const filePath = join(IMAGE_DIR, filename);\n try {\n const s = await fsStat(filePath);\n if (!s.isFile()) throw new Error(\"not a file\");\n const ext = filename.split(\".\").pop()?.toLowerCase() ?? \"png\";\n const mime: Record = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n };\n const data = await readFile(filePath);\n res.writeHead(200, {\n \"Content-Type\": mime[ext] ?? \"application/octet-stream\",\n \"Content-Length\": data.length,\n });\n res.end(data);\n } catch {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image not found\" }));\n }\n return;\n }\n\n // --- Handle /v1/images/generations: proxy with x402 payment + save data URIs locally ---\n // NOTE: image generation endpoints bypass maxCostPerRun budget tracking entirely.\n // Cost is charged via x402 micropayment directly — no session accumulation or cap enforcement.\n if (req.url === \"/v1/images/generations\" && req.method === \"POST\") {\n const imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const reqBody = Buffer.concat(chunks);\n // Parse request for usage logging\n let imgModel = \"unknown\";\n let imgCost = 0;\n try {\n const parsed = JSON.parse(reqBody.toString());\n imgModel = parsed.model || \"openai/dall-e-3\";\n const n = parsed.n || 1;\n imgCost = estimateImageCost(imgModel, parsed.size, n);\n } catch {\n /* use defaults */\n }\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/generations`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image generation usage with actual x402 payment (previously missing entirely)\n const imgActualCost = paymentStore.getStore()?.amountUsd ?? imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: imgModel,\n tier: \"IMAGE\",\n cost: imgActualCost,\n baselineCost: imgActualCost,\n savings: 0,\n latencyMs: Date.now() - imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image generation error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image generation failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle /v1/images/image2image: proxy with x402 payment + save images locally ---\n // Accepts image as: data URI, local file path, ~/path, or HTTP(S) URL\n if (req.url === \"/v1/images/image2image\" && req.method === \"POST\") {\n const img2imgStartTime = Date.now();\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const rawBody = Buffer.concat(chunks);\n\n // Resolve image/mask fields: file paths and URLs → data URIs\n let reqBody: string;\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgModel = \"openai/gpt-image-1\";\n // eslint-disable-next-line no-useless-assignment -- reassigned in try, used after catch\n let img2imgCost = 0;\n try {\n const parsed = JSON.parse(rawBody.toString());\n for (const field of [\"image\", \"mask\"] as const) {\n const val = parsed[field];\n if (typeof val !== \"string\" || !val) continue;\n if (val.startsWith(\"data:\")) {\n // Already a data URI — pass through\n } else if (val.startsWith(\"https://\") || val.startsWith(\"http://\")) {\n // Download URL → data URI\n const imgResp = await fetch(val);\n if (!imgResp.ok)\n throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const buf = Buffer.from(await imgResp.arrayBuffer());\n parsed[field] = `data:${contentType};base64,${buf.toString(\"base64\")}`;\n console.log(\n `[ClawRouter] img2img: downloaded ${field} URL → data URI (${buf.length} bytes)`,\n );\n } else {\n // Local file path → data URI\n parsed[field] = readImageFileAsDataUri(val);\n console.log(`[ClawRouter] img2img: read ${field} file → data URI`);\n }\n }\n // Default model if not specified\n if (!parsed.model) parsed.model = \"openai/gpt-image-1\";\n img2imgModel = parsed.model;\n img2imgCost = estimateImageCost(img2imgModel, parsed.size, parsed.n || 1);\n reqBody = JSON.stringify(parsed);\n } catch (parseErr) {\n const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\", details: msg }));\n return;\n }\n\n try {\n const upstream = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: reqBody,\n });\n const text = await upstream.text();\n if (!upstream.ok) {\n res.writeHead(upstream.status, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n let result: { created?: number; data?: Array<{ url?: string; revised_prompt?: string }> };\n try {\n result = JSON.parse(text);\n } catch {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(text);\n return;\n }\n // Save images to ~/.openclaw/blockrun/images/ and replace with localhost URLs\n // Handles both base64 data URIs (Google) and HTTP URLs (DALL-E 3)\n if (result.data?.length) {\n await mkdir(IMAGE_DIR, { recursive: true });\n const port = (server.address() as AddressInfo | null)?.port ?? 8402;\n for (const img of result.data) {\n const dataUriMatch = img.url?.match(/^data:(image\\/\\w+);base64,(.+)$/);\n if (dataUriMatch) {\n const [, mimeType, b64] = dataUriMatch;\n const ext = mimeType === \"image/jpeg\" ? \"jpg\" : (mimeType!.split(\"/\")[1] ?? \"png\");\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n await writeFile(join(IMAGE_DIR, filename), Buffer.from(b64!, \"base64\"));\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image saved → ${img.url}`);\n } else if (img.url?.startsWith(\"https://\") || img.url?.startsWith(\"http://\")) {\n try {\n const imgResp = await fetch(img.url);\n if (imgResp.ok) {\n const contentType = imgResp.headers.get(\"content-type\") ?? \"image/png\";\n const ext =\n contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")\n ? \"jpg\"\n : contentType.includes(\"webp\")\n ? \"webp\"\n : \"png\";\n const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;\n const buf = Buffer.from(await imgResp.arrayBuffer());\n await writeFile(join(IMAGE_DIR, filename), buf);\n img.url = `http://localhost:${port}/images/${filename}`;\n console.log(`[ClawRouter] Image downloaded & saved → ${img.url}`);\n }\n } catch (downloadErr) {\n console.warn(\n `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`,\n );\n }\n }\n }\n }\n // Log image editing usage with actual x402 payment (previously missing entirely)\n const img2imgActualCost = paymentStore.getStore()?.amountUsd ?? img2imgCost;\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost,\n baselineCost: img2imgActualCost,\n savings: 0,\n latencyMs: Date.now() - img2imgStartTime,\n }).catch(() => {});\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(result));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Image editing error: ${msg}`);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image editing failed\", details: msg }));\n }\n }\n return;\n }\n\n // --- Handle partner API paths (/v1/x/*, /v1/partner/*) ---\n if (req.url?.match(/^\\/v1\\/(?:x|partner)\\//)) {\n try {\n await proxyPartnerRequest(\n req,\n res,\n apiBase,\n payFetch,\n () => paymentStore.getStore()?.amountUsd ?? 0,\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Partner proxy error: ${error.message}`, type: \"partner_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Only proxy paths starting with /v1\n if (!req.url?.startsWith(\"/v1\")) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not found\" }));\n return;\n }\n\n try {\n await proxyRequest(\n req,\n res,\n apiBase,\n payFetch,\n options,\n routerOpts,\n deduplicator,\n balanceMonitor,\n sessionStore,\n responseCache,\n sessionJournal,\n () => activeBasePaymentAsset.symbol,\n () => activeBasePaymentAssets,\n (asset) => {\n lastSelectedBasePaymentAsset = asset;\n activeBasePaymentAsset = asset;\n },\n );\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n options.onError?.(error);\n\n if (!res.headersSent) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Proxy error: ${error.message}`, type: \"proxy_error\" },\n }),\n );\n } else if (!res.writableEnded) {\n // Headers already sent (streaming) — send error as SSE event\n res.write(\n `data: ${JSON.stringify({ error: { message: error.message, type: \"proxy_error\" } })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n }\n }\n }); // end paymentStore.run()\n });\n\n // Listen on configured port with retry logic for TIME_WAIT handling\n // When gateway restarts quickly, the port may still be in TIME_WAIT state.\n // We retry with delay instead of incorrectly assuming a proxy is running.\n const tryListen = (attempt: number): Promise => {\n return new Promise((resolveAttempt, rejectAttempt) => {\n const onError = async (err: NodeJS.ErrnoException) => {\n server.removeListener(\"error\", onError);\n\n if (err.code === \"EADDRINUSE\") {\n // Port is in use - check if a proxy is actually running\n const existingProxy2 = await checkExistingProxy(listenPort);\n if (existingProxy2) {\n // Proxy is actually running - this is fine, reuse it\n console.log(`[ClawRouter] Existing proxy detected on port ${listenPort}, reusing`);\n rejectAttempt({\n code: \"REUSE_EXISTING\",\n wallet: existingProxy2.wallet,\n existingChain: existingProxy2.paymentChain,\n paymentAssets: existingProxy2.paymentAssets,\n selectedPaymentAsset: existingProxy2.selectedPaymentAsset,\n });\n return;\n }\n\n // Port is in TIME_WAIT (no proxy responding) - retry after delay\n if (attempt < PORT_RETRY_ATTEMPTS) {\n console.log(\n `[ClawRouter] Port ${listenPort} in TIME_WAIT, retrying in ${PORT_RETRY_DELAY_MS}ms (attempt ${attempt}/${PORT_RETRY_ATTEMPTS})`,\n );\n rejectAttempt({ code: \"RETRY\", attempt });\n return;\n }\n\n // Max retries exceeded\n console.error(\n `[ClawRouter] Port ${listenPort} still in use after ${PORT_RETRY_ATTEMPTS} attempts`,\n );\n rejectAttempt(err);\n return;\n }\n\n rejectAttempt(err);\n };\n\n server.once(\"error\", onError);\n server.listen(listenPort, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onError);\n resolveAttempt();\n });\n });\n };\n\n // Retry loop for port binding\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= PORT_RETRY_ATTEMPTS; attempt++) {\n try {\n await tryListen(attempt);\n break; // Success\n } catch (err: unknown) {\n const error = err as {\n code?: string;\n wallet?: string;\n existingChain?: string;\n paymentAssets?: BasePaymentAsset[];\n selectedPaymentAsset?: string | BasePaymentAsset;\n attempt?: number;\n };\n\n if (error.code === \"REUSE_EXISTING\" && error.wallet) {\n // Validate payment chain matches (same check as pre-listen reuse path)\n if (error.existingChain && error.existingChain !== paymentChain) {\n throw new Error(\n `Existing proxy on port ${listenPort} is using ${error.existingChain} but ${paymentChain} was requested. ` +\n `Stop the existing proxy first or use a different port.`,\n { cause: err },\n );\n }\n\n return buildReuseHandle({\n wallet: error.wallet,\n paymentChain: error.existingChain,\n paymentAssets: error.paymentAssets,\n selectedPaymentAsset: error.selectedPaymentAsset,\n });\n }\n\n if (error.code === \"RETRY\") {\n // Wait before retry\n await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS));\n continue;\n }\n\n // Other error - throw\n lastError = err as Error;\n break;\n }\n }\n\n if (lastError) {\n throw lastError;\n }\n\n // Server is now listening - set up remaining handlers\n const addr = server.address() as AddressInfo;\n const port = addr.port;\n const baseUrl = `http://127.0.0.1:${port}`;\n\n options.onReady?.(port);\n\n // Check for updates (non-blocking)\n checkForUpdates();\n\n // Add runtime error handler AFTER successful listen\n // This handles errors that occur during server operation (not just startup)\n server.on(\"error\", (err) => {\n console.error(`[ClawRouter] Server runtime error: ${err.message}`);\n options.onError?.(err);\n // Don't crash - log and continue\n });\n\n // Handle client connection errors (bad requests, socket errors)\n server.on(\"clientError\", (err, socket) => {\n console.error(`[ClawRouter] Client error: ${err.message}`);\n // Send 400 Bad Request if socket is still writable\n if (socket.writable && !socket.destroyed) {\n socket.end(\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\");\n }\n });\n\n // Track connections for graceful cleanup\n server.on(\"connection\", (socket) => {\n connections.add(socket);\n\n // Set 5-minute timeout for streaming requests\n socket.setTimeout(300_000);\n\n socket.on(\"timeout\", () => {\n console.error(`[ClawRouter] Socket timeout, destroying connection`);\n socket.destroy();\n });\n\n socket.on(\"end\", () => {\n // Half-closed by client (FIN received)\n });\n\n socket.on(\"error\", (err) => {\n console.error(`[ClawRouter] Socket error: ${err.message}`);\n });\n\n socket.on(\"close\", () => {\n connections.delete(socket);\n });\n });\n\n return {\n port,\n baseUrl,\n walletAddress: account.address,\n solanaAddress,\n paymentAsset: paymentChain === \"base\" ? activeBasePaymentAsset : undefined,\n paymentAssets: paymentChain === \"base\" ? activeBasePaymentAssets : undefined,\n balanceMonitor,\n close: () =>\n new Promise((res, rej) => {\n const timeout = setTimeout(() => {\n rej(new Error(\"[ClawRouter] Close timeout after 4s\"));\n }, 4000);\n\n sessionStore.close();\n // Destroy all active connections before closing server\n for (const socket of connections) {\n socket.destroy();\n }\n connections.clear();\n server.close((err) => {\n clearTimeout(timeout);\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n }),\n };\n}\n\n/** Result of attempting a model request */\ntype ModelRequestResult = {\n success: boolean;\n response?: Response;\n errorBody?: string;\n errorStatus?: number;\n isProviderError?: boolean;\n errorCategory?: ErrorCategory; // Semantic error classification\n};\n\n/**\n * Attempt a request with a specific model.\n * Returns the response or error details for fallback decision.\n */\nasync function tryModelRequest(\n upstreamUrl: string,\n method: string,\n headers: Record,\n body: Buffer,\n modelId: string,\n maxTokens: number,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n balanceMonitor: AnyBalanceMonitor,\n signal: AbortSignal,\n): Promise {\n // Update model in body and normalize messages\n let requestBody = body;\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(modelId);\n\n // Normalize message roles (e.g., \"developer\" -> \"system\")\n if (Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessageRoles(parsed.messages as ChatMessage[]);\n }\n\n // Remove \"blockrun\" branding from system messages so upstream LLMs don't\n // adopt \"Blockrun\" as their identity (overriding user's SOUL.md persona).\n if (Array.isArray(parsed.messages)) {\n parsed.messages = debrandSystemMessages(parsed.messages as ChatMessage[], modelId);\n }\n\n // Truncate messages to stay under BlockRun's limit (200 messages)\n if (Array.isArray(parsed.messages)) {\n const truncationResult = truncateMessages(parsed.messages as ChatMessage[]);\n parsed.messages = truncationResult.messages;\n }\n\n // Sanitize tool IDs to match Anthropic's pattern (alphanumeric, underscore, hyphen only)\n if (Array.isArray(parsed.messages)) {\n parsed.messages = sanitizeToolIds(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for Google models (first non-system message must be \"user\")\n if (isGoogleModel(modelId) && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForGoogle(parsed.messages as ChatMessage[]);\n }\n\n // Normalize messages for thinking-enabled requests (add reasoning_content to tool calls)\n // Check request flags AND target model - reasoning models have thinking enabled server-side\n const hasThinkingEnabled = !!(\n parsed.thinking ||\n parsed.extended_thinking ||\n isReasoningModel(modelId)\n );\n if (hasThinkingEnabled && Array.isArray(parsed.messages)) {\n parsed.messages = normalizeMessagesForThinking(parsed.messages as ExtendedChatMessage[]);\n }\n\n requestBody = Buffer.from(JSON.stringify(parsed));\n } catch {\n // If body isn't valid JSON, use as-is\n }\n\n try {\n const response = await payFetch(upstreamUrl, {\n method,\n headers,\n body: requestBody.length > 0 ? new Uint8Array(requestBody) : undefined,\n signal,\n });\n\n // Check for provider errors\n if (response.status !== 200) {\n // Clone response to read body without consuming it\n const errorBodyChunks = await readBodyWithTimeout(response.body, ERROR_BODY_READ_TIMEOUT_MS);\n const errorBody = Buffer.concat(errorBodyChunks).toString();\n const category = categorizeError(response.status, errorBody);\n\n return {\n success: false,\n errorBody,\n errorStatus: response.status,\n isProviderError: category !== null,\n errorCategory: category ?? undefined,\n };\n }\n\n // Detect provider degradation hidden inside HTTP 200 responses.\n const contentType = response.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"json\") || contentType.includes(\"text\")) {\n try {\n const clonedChunks = await readBodyWithTimeout(\n response.clone().body,\n ERROR_BODY_READ_TIMEOUT_MS,\n );\n const responseBody = Buffer.concat(clonedChunks).toString();\n const degradedReason = detectDegradedSuccessResponse(responseBody);\n if (degradedReason) {\n return {\n success: false,\n errorBody: degradedReason,\n errorStatus: 503,\n isProviderError: true,\n };\n }\n } catch {\n // Ignore body inspection failures and pass through response.\n }\n }\n\n return { success: true, response };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return {\n success: false,\n errorBody: errorMsg,\n errorStatus: 500,\n isProviderError: true, // Network errors are retryable\n };\n }\n}\n\n/**\n * Proxy a single request through x402 payment flow to BlockRun API.\n *\n * Optimizations applied in order:\n * 1. Dedup check — if same request body seen within 30s, replay cached response\n * 2. Streaming heartbeat — for stream:true, send 200 + heartbeats immediately\n * 3. Smart routing — when model is \"blockrun/auto\", pick cheapest capable model\n * 4. Fallback chain — on provider errors, try next model in tier's fallback list\n */\nasync function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse,\n apiBase: string,\n payFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise,\n options: ProxyOptions,\n routerOpts: RouterOptions,\n deduplicator: RequestDeduplicator,\n balanceMonitor: AnyBalanceMonitor,\n sessionStore: SessionStore,\n responseCache: ResponseCache,\n sessionJournal: SessionJournal,\n getBaseAssetSymbol: () => string,\n getBasePaymentAssets: () => BasePaymentAsset[],\n onBaseAssetSelected: (asset: BasePaymentAsset) => void,\n): Promise {\n const startTime = Date.now();\n\n // Build upstream URL: /v1/chat/completions → https://blockrun.ai/api/v1/chat/completions\n const upstreamUrl = `${apiBase}${req.url}`;\n\n // Collect request body\n const bodyChunks: Buffer[] = [];\n for await (const chunk of req) {\n bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n let body = Buffer.concat(bodyChunks);\n\n // Track original context size for response headers\n const originalContextSizeKB = Math.ceil(body.length / 1024);\n\n // Routing debug info is on by default; disable with x-clawrouter-debug: false\n const debugMode = req.headers[\"x-clawrouter-debug\"] !== \"false\";\n\n // --- Smart routing ---\n let routingDecision: RoutingDecision | undefined;\n let hasTools = false; // true when request includes a tools schema\n let hasVision = false; // true when request includes image_url content parts\n let isStreaming = false;\n let modelId = \"\";\n let maxTokens = 4096;\n let routingProfile: \"eco\" | \"auto\" | \"premium\" | null = null;\n let balanceFallbackNotice: string | undefined;\n let budgetDowngradeNotice: string | undefined;\n let budgetDowngradeHeaderMode: \"downgraded\" | undefined;\n let accumulatedContent = \"\"; // For session journal event extraction\n let responseInputTokens: number | undefined;\n let responseOutputTokens: number | undefined;\n let requestBalanceMonitor = balanceMonitor;\n let requestBasePaymentAsset = getBasePaymentAssets()[0];\n const isChatCompletion = req.url?.includes(\"/chat/completions\");\n\n // Extract session ID early for journal operations (header-only at this point)\n const sessionId = getSessionId(req.headers as Record);\n // Full session ID (header + content-derived) — populated once messages are parsed\n let effectiveSessionId: string | undefined = sessionId;\n\n if (isChatCompletion && body.length > 0) {\n try {\n const parsed = JSON.parse(body.toString()) as Record;\n isStreaming = parsed.stream === true;\n modelId = (parsed.model as string) || \"\";\n maxTokens = (parsed.max_tokens as number) || 4096;\n let bodyModified = false;\n\n // Extract last user message content (used by session journal + /debug command)\n const parsedMessages = Array.isArray(parsed.messages)\n ? (parsed.messages as Array<{ role: string; content: unknown }>)\n : [];\n const lastUserMsg = [...parsedMessages].reverse().find((m) => m.role === \"user\");\n\n // Early tool detection for ALL request types (explicit model + routing profile).\n // The routing-profile branch may re-assign below (no-op since same value).\n hasTools = Array.isArray(parsed.tools) && (parsed.tools as unknown[]).length > 0;\n const rawLastContent = lastUserMsg?.content;\n const lastContent =\n typeof rawLastContent === \"string\"\n ? rawLastContent\n : Array.isArray(rawLastContent)\n ? (rawLastContent as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n\n // --- Session Journal: Inject context if needed ---\n // Check if the last user message asks about past work\n if (sessionId && parsedMessages.length > 0) {\n const messages = parsedMessages;\n\n if (sessionJournal.needsContext(lastContent)) {\n const journalText = sessionJournal.format(sessionId);\n if (journalText) {\n // Find system message and prepend journal, or add a new system message\n const sysIdx = messages.findIndex((m) => m.role === \"system\");\n if (sysIdx >= 0 && typeof messages[sysIdx].content === \"string\") {\n messages[sysIdx] = {\n ...messages[sysIdx],\n content: journalText + \"\\n\\n\" + messages[sysIdx].content,\n };\n } else {\n messages.unshift({ role: \"system\", content: journalText });\n }\n parsed.messages = messages;\n bodyModified = true;\n console.log(\n `[ClawRouter] Injected session journal (${journalText.length} chars) for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n }\n\n // --- /debug command: return routing diagnostics without calling upstream ---\n if (lastContent.startsWith(\"/debug\")) {\n const debugPrompt = lastContent.slice(\"/debug\".length).trim() || \"hello\";\n const messages = parsed.messages as Array<{ role: string; content: unknown }>;\n const systemMsg = messages?.find((m) => m.role === \"system\");\n const systemPrompt = typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n const fullText = `${systemPrompt ?? \"\"} ${debugPrompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // Determine routing profile\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n const profileName = normalizedModel.replace(\"blockrun/\", \"\");\n const debugProfile = (\n [\"eco\", \"auto\", \"premium\"].includes(profileName) ? profileName : \"auto\"\n ) as \"eco\" | \"auto\" | \"premium\";\n\n // Run scoring\n const scoring = classifyByRules(\n debugPrompt,\n systemPrompt,\n estimatedTokens,\n DEFAULT_ROUTING_CONFIG.scoring,\n );\n\n // Run full routing decision\n const debugRouting = route(debugPrompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: debugProfile,\n });\n\n // Format dimension scores\n const dimLines = (scoring.dimensions ?? [])\n .map((d) => {\n const nameStr = (d.name + \":\").padEnd(24);\n const scoreStr = d.score.toFixed(2).padStart(6);\n const sigStr = d.signal ? ` [${d.signal}]` : \"\";\n return ` ${nameStr}${scoreStr}${sigStr}`;\n })\n .join(\"\\n\");\n\n // Session info\n const sess = sessionId ? sessionStore.getSession(sessionId) : undefined;\n const sessLine = sess\n ? `Session: ${sessionId!.slice(0, 8)}... → pinned: ${sess.model} (${sess.requestCount} requests)`\n : sessionId\n ? `Session: ${sessionId.slice(0, 8)}... → no pinned model`\n : \"Session: none\";\n\n const { simpleMedium, mediumComplex, complexReasoning } =\n DEFAULT_ROUTING_CONFIG.scoring.tierBoundaries;\n\n const debugText = [\n \"ClawRouter Debug\",\n \"\",\n `Profile: ${debugProfile} | Tier: ${debugRouting.tier} | Model: ${debugRouting.model}`,\n `Confidence: ${debugRouting.confidence.toFixed(2)} | Cost: $${debugRouting.costEstimate.toFixed(4)} | Savings: ${(debugRouting.savings * 100).toFixed(0)}%`,\n `Reasoning: ${debugRouting.reasoning}`,\n \"\",\n `Scoring (weighted: ${scoring.score.toFixed(3)})`,\n dimLines,\n \"\",\n `Tier Boundaries: SIMPLE <${simpleMedium.toFixed(2)} | MEDIUM <${mediumComplex.toFixed(2)} | COMPLEX <${complexReasoning.toFixed(2)} | REASONING >=${complexReasoning.toFixed(2)}`,\n \"\",\n sessLine,\n ].join(\"\\n\");\n\n // Build synthetic OpenAI chat completion response\n const completionId = `chatcmpl-debug-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n const syntheticResponse = {\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: debugText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n\n if (isStreaming) {\n // SSE streaming response\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n const sseChunk = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [\n {\n index: 0,\n delta: { role: \"assistant\", content: debugText },\n finish_reason: null,\n },\n ],\n };\n const sseDone = {\n id: completionId,\n object: \"chat.completion.chunk\",\n created: timestamp,\n model: \"clawrouter/debug\",\n choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }],\n };\n res.write(`data: ${JSON.stringify(sseChunk)}\\n\\n`);\n res.write(`data: ${JSON.stringify(sseDone)}\\n\\n`);\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(syntheticResponse));\n }\n console.log(`[ClawRouter] /debug command → ${debugRouting.tier} | ${debugRouting.model}`);\n return;\n }\n\n // --- /imagegen command: generate an image via BlockRun image API ---\n if (lastContent.startsWith(\"/imagegen\")) {\n const imageArgs = lastContent.slice(\"/imagegen\".length).trim();\n\n // Parse optional flags: /imagegen --model dall-e-3 --size 1792x1024 a cute cat\n let imageModel = \"google/nano-banana\";\n let imageSize = \"1024x1024\";\n let imagePrompt = imageArgs;\n\n // Extract --model flag\n const modelMatch = imageArgs.match(/--model\\s+(\\S+)/);\n if (modelMatch) {\n const raw = modelMatch[1];\n // Resolve shorthand aliases\n const IMAGE_MODEL_ALIASES: Record = {\n \"dall-e-3\": \"openai/dall-e-3\",\n dalle3: \"openai/dall-e-3\",\n dalle: \"openai/dall-e-3\",\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n flux: \"black-forest/flux-1.1-pro\",\n \"flux-pro\": \"black-forest/flux-1.1-pro\",\n banana: \"google/nano-banana\",\n \"nano-banana\": \"google/nano-banana\",\n \"banana-pro\": \"google/nano-banana-pro\",\n \"nano-banana-pro\": \"google/nano-banana-pro\",\n };\n imageModel = IMAGE_MODEL_ALIASES[raw] ?? raw;\n imagePrompt = imagePrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n // Extract --size flag\n const sizeMatch = imageArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (sizeMatch) {\n imageSize = sizeMatch[1];\n imagePrompt = imagePrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n if (!imagePrompt) {\n const errorText = [\n \"Usage: /imagegen \",\n \"\",\n \"Options:\",\n \" --model Model to use (default: nano-banana)\",\n \" --size Image size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" nano-banana Google Gemini Flash — $0.05/image\",\n \" banana-pro Google Gemini Pro — $0.10/image (up to 4K)\",\n \" dall-e-3 OpenAI DALL-E 3 — $0.04/image\",\n \" gpt-image OpenAI GPT Image 1 — $0.02/image\",\n \" flux Black Forest Flux 1.1 Pro — $0.04/image\",\n \"\",\n \"Examples:\",\n \" /imagegen a cat wearing sunglasses\",\n \" /imagegen --model dall-e-3 a futuristic city at sunset\",\n \" /imagegen --model banana-pro --size 2048x2048 mountain landscape\",\n ].join(\"\\n\");\n\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: errorText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: errorText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n console.log(`[ClawRouter] /imagegen command → showing usage help`);\n return;\n }\n\n // Call upstream image generation API\n console.log(\n `[ClawRouter] /imagegen command → ${imageModel} (${imageSize}): ${imagePrompt.slice(0, 80)}...`,\n );\n try {\n const imageUpstreamUrl = `${apiBase}/v1/images/generations`;\n const imageBody = JSON.stringify({\n model: imageModel,\n prompt: imagePrompt,\n size: imageSize,\n n: 1,\n });\n const imageResponse = await payFetch(imageUpstreamUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: imageBody,\n });\n\n const imageResult = (await imageResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!imageResponse.ok || imageResult.error) {\n const errMsg =\n typeof imageResult.error === \"string\"\n ? imageResult.error\n : ((imageResult.error as { message?: string })?.message ??\n `HTTP ${imageResponse.status}`);\n responseText = `Image generation failed: ${errMsg}`;\n console.log(`[ClawRouter] /imagegen error: ${errMsg}`);\n } else {\n const images = imageResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image generation returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /imagegen: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\n \"Image generated but upload failed. Try again or use --model dall-e-3.\",\n );\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${imageModel} | Size: ${imageSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /imagegen success: ${images.length} image(s) generated`);\n // Log /imagegen usage with actual x402 payment\n const imagegenActualCost =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(imageModel, imageSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: imageModel,\n tier: \"IMAGE\",\n cost: imagegenActualCost,\n baselineCost: imagegenActualCost,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n // Return as synthetic chat completion\n const completionId = `chatcmpl-image-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: { role: \"assistant\", content: responseText }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/image\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/image\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: responseText },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /imagegen error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image generation failed: ${errMsg}`, type: \"image_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // --- /img2img command: edit an image via BlockRun image2image API ---\n if (lastContent.startsWith(\"/img2img\")) {\n const imgArgs = lastContent.slice(\"/img2img\".length).trim();\n\n let img2imgModel = \"openai/gpt-image-1\";\n let img2imgSize = \"1024x1024\";\n let imagePath: string | null = null;\n let maskPath: string | null = null;\n let img2imgPrompt = imgArgs;\n\n const imageMatch = imgArgs.match(/--image\\s+(\\S+)/);\n if (imageMatch) {\n imagePath = imageMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--image\\s+\\S+/, \"\").trim();\n }\n\n const maskMatch = imgArgs.match(/--mask\\s+(\\S+)/);\n if (maskMatch) {\n maskPath = maskMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--mask\\s+\\S+/, \"\").trim();\n }\n\n const img2imgSizeMatch = imgArgs.match(/--size\\s+(\\d+x\\d+)/);\n if (img2imgSizeMatch) {\n img2imgSize = img2imgSizeMatch[1];\n img2imgPrompt = img2imgPrompt.replace(/--size\\s+\\d+x\\d+/, \"\").trim();\n }\n\n const img2imgModelMatch = imgArgs.match(/--model\\s+(\\S+)/);\n if (img2imgModelMatch) {\n const raw = img2imgModelMatch[1];\n const IMG2IMG_ALIASES: Record = {\n \"gpt-image\": \"openai/gpt-image-1\",\n \"gpt-image-1\": \"openai/gpt-image-1\",\n };\n img2imgModel = IMG2IMG_ALIASES[raw] ?? raw;\n img2imgPrompt = img2imgPrompt.replace(/--model\\s+\\S+/, \"\").trim();\n }\n\n const usageText = [\n \"Usage: /img2img --image \",\n \"\",\n \"Options:\",\n \" --image Source image path (required)\",\n \" --mask Mask image path (optional, white = area to edit)\",\n \" --model Model (default: gpt-image-1)\",\n \" --size Output size (default: 1024x1024)\",\n \"\",\n \"Models:\",\n \" gpt-image-1 OpenAI GPT Image 1 — $0.02/image\",\n \"\",\n \"Examples:\",\n \" /img2img --image ~/photo.png change background to starry sky\",\n \" /img2img --image ./cat.jpg --mask ./mask.png remove the background\",\n \" /img2img --image /tmp/portrait.png --size 1536x1024 add a hat\",\n ].join(\"\\n\");\n\n const sendImg2ImgText = (text: string) => {\n const completionId = `chatcmpl-img2img-${Date.now()}`;\n const timestamp = Math.floor(Date.now() / 1000);\n if (isStreaming) {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: { role: \"assistant\", content: text }, finish_reason: null }] })}\\n\\n`,\n );\n res.write(\n `data: ${JSON.stringify({ id: completionId, object: \"chat.completion.chunk\", created: timestamp, model: \"clawrouter/img2img\", choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }] })}\\n\\n`,\n );\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: completionId,\n object: \"chat.completion\",\n created: timestamp,\n model: \"clawrouter/img2img\",\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n }),\n );\n }\n };\n\n if (!imagePath || !img2imgPrompt) {\n sendImg2ImgText(usageText);\n return;\n }\n\n let imageDataUri: string;\n let maskDataUri: string | undefined;\n try {\n imageDataUri = readImageFileAsDataUri(imagePath);\n if (maskPath) maskDataUri = readImageFileAsDataUri(maskPath);\n } catch (fileErr) {\n const fileErrMsg = fileErr instanceof Error ? fileErr.message : String(fileErr);\n sendImg2ImgText(`Failed to read image file: ${fileErrMsg}`);\n return;\n }\n\n console.log(\n `[ClawRouter] /img2img → ${img2imgModel} (${img2imgSize}): ${img2imgPrompt.slice(0, 80)}`,\n );\n\n try {\n const img2imgBody = JSON.stringify({\n model: img2imgModel,\n prompt: img2imgPrompt,\n image: imageDataUri,\n ...(maskDataUri ? { mask: maskDataUri } : {}),\n size: img2imgSize,\n n: 1,\n });\n\n const img2imgResponse = await payFetch(`${apiBase}/v1/images/image2image`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"user-agent\": USER_AGENT },\n body: img2imgBody,\n });\n\n const img2imgResult = (await img2imgResponse.json()) as {\n created?: number;\n data?: Array<{ url?: string; revised_prompt?: string }>;\n error?: string | { message?: string };\n };\n\n let responseText: string;\n if (!img2imgResponse.ok || img2imgResult.error) {\n const errMsg =\n typeof img2imgResult.error === \"string\"\n ? img2imgResult.error\n : ((img2imgResult.error as { message?: string })?.message ??\n `HTTP ${img2imgResponse.status}`);\n responseText = `Image editing failed: ${errMsg}`;\n console.log(`[ClawRouter] /img2img error: ${errMsg}`);\n } else {\n const images = img2imgResult.data ?? [];\n if (images.length === 0) {\n responseText = \"Image editing returned no results.\";\n } else {\n const lines: string[] = [];\n for (const img of images) {\n if (img.url) {\n if (img.url.startsWith(\"data:\")) {\n try {\n const hostedUrl = await uploadDataUriToHost(img.url);\n lines.push(hostedUrl);\n } catch (uploadErr) {\n console.error(\n `[ClawRouter] /img2img: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,\n );\n lines.push(\"Image edited but upload failed. Try again.\");\n }\n } else {\n lines.push(img.url);\n }\n }\n if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);\n }\n lines.push(\"\", `Model: ${img2imgModel} | Size: ${img2imgSize}`);\n responseText = lines.join(\"\\n\");\n }\n console.log(`[ClawRouter] /img2img success: ${images.length} image(s)`);\n // Log /img2img usage with actual x402 payment\n const img2imgActualCost2 =\n paymentStore.getStore()?.amountUsd ?? estimateImageCost(img2imgModel, img2imgSize, 1);\n logUsage({\n timestamp: new Date().toISOString(),\n model: img2imgModel,\n tier: \"IMAGE\",\n cost: img2imgActualCost2,\n baselineCost: img2imgActualCost2,\n savings: 0,\n latencyMs: 0,\n }).catch(() => {});\n }\n\n sendImg2ImgText(responseText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] /img2img error: ${errMsg}`);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Image editing failed: ${errMsg}`, type: \"img2img_error\" },\n }),\n );\n }\n }\n return;\n }\n\n // Force stream: false — BlockRun API doesn't support streaming yet\n // ClawRouter handles SSE heartbeat simulation for upstream compatibility\n if (parsed.stream === true) {\n parsed.stream = false;\n bodyModified = true;\n }\n\n // Normalize model name for comparison (trim whitespace, lowercase)\n const normalizedModel =\n typeof parsed.model === \"string\" ? parsed.model.trim().toLowerCase() : \"\";\n\n // Resolve model aliases (e.g., \"claude\" -> \"anthropic/claude-sonnet-4-6\")\n const resolvedModel = resolveModelAlias(normalizedModel);\n const wasAlias = resolvedModel !== normalizedModel;\n\n // Check both normalizedModel and resolvedModel — OpenClaw may send \"openai/eco\"\n // which resolveModelAlias strips to \"eco\" (a valid routing profile)\n const isRoutingProfile =\n ROUTING_PROFILES.has(normalizedModel) || ROUTING_PROFILES.has(resolvedModel);\n\n // Extract routing profile type (free/eco/auto/premium)\n if (isRoutingProfile) {\n const profileName = resolvedModel.replace(\"blockrun/\", \"\");\n routingProfile = profileName as \"eco\" | \"auto\" | \"premium\";\n }\n\n // Debug: log received model name\n console.log(\n `[ClawRouter] Received model: \"${parsed.model}\" -> normalized: \"${normalizedModel}\"${wasAlias ? ` -> alias: \"${resolvedModel}\"` : \"\"}${routingProfile ? `, profile: ${routingProfile}` : \"\"}`,\n );\n\n // For explicit model requests, always canonicalize the model ID before upstream calls.\n // This ensures case/whitespace variants (e.g. \"DEEPSEEK/...\" or \" model \") route correctly.\n if (!isRoutingProfile) {\n if (parsed.model !== resolvedModel) {\n parsed.model = resolvedModel;\n bodyModified = true;\n }\n modelId = resolvedModel;\n }\n\n // Handle routing profiles (free/eco/auto/premium)\n if (isRoutingProfile) {\n {\n // eco/auto/premium - use tier routing\n // Check for session persistence - use pinned model if available\n // Fall back to deriving a session ID from message content when OpenClaw\n // doesn't send an explicit x-session-id header (the default behaviour).\n effectiveSessionId =\n getSessionId(req.headers as Record) ??\n deriveSessionId(parsedMessages);\n const existingSession = effectiveSessionId\n ? sessionStore.getSession(effectiveSessionId)\n : undefined;\n\n // Extract prompt from last user message (handles both string and Anthropic array content)\n const rawPrompt = lastUserMsg?.content;\n const prompt =\n typeof rawPrompt === \"string\"\n ? rawPrompt\n : Array.isArray(rawPrompt)\n ? (rawPrompt as Array<{ type: string; text?: string }>)\n .filter((b) => b.type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\" \")\n : \"\";\n const systemMsg = parsedMessages.find((m) => m.role === \"system\");\n const systemPrompt =\n typeof systemMsg?.content === \"string\" ? systemMsg.content : undefined;\n\n // Tool detection — when tools are present, force agentic tiers for reliable tool use\n const tools = parsed.tools as unknown[] | undefined;\n hasTools = Array.isArray(tools) && tools.length > 0;\n\n if (hasTools && tools) {\n console.log(`[ClawRouter] Tools detected (${tools.length}), forcing agentic tiers`);\n }\n\n // Vision detection: scan messages for image_url content parts\n hasVision = parsedMessages.some((m) => {\n if (Array.isArray(m.content)) {\n return (m.content as Array<{ type: string }>).some((p) => p.type === \"image_url\");\n }\n return false;\n });\n if (hasVision) {\n console.log(`[ClawRouter] Vision content detected, filtering to vision-capable models`);\n }\n\n // Always route based on current request content\n routingDecision = route(prompt, systemPrompt, maxTokens, {\n ...routerOpts,\n routingProfile: routingProfile ?? undefined,\n hasTools,\n });\n\n // Keep agentic routing when tools are present, even for SIMPLE queries.\n // Tool-using requests need models with reliable function-call support;\n // demoting to non-agentic tiers causes fallback to models that refuse\n // tool schemas (gemini-flash-lite, deepseek) or lack tool support entirely.\n if (hasTools && routingDecision.tier === \"SIMPLE\") {\n console.log(\n `[ClawRouter] SIMPLE+tools: keeping agentic model ${routingDecision.model} (tools need reliable function-call support)`,\n );\n }\n\n if (existingSession) {\n // Never downgrade: only upgrade the session when the current request needs a higher\n // tier. This fixes the OpenClaw startup-message bias (the startup message always\n // scores low-complexity, which previously pinned all subsequent real queries to a\n // cheap model) while still preventing mid-task model switching on simple follow-ups.\n const tierRank: Record = {\n SIMPLE: 0,\n MEDIUM: 1,\n COMPLEX: 2,\n REASONING: 3,\n };\n const existingRank = tierRank[existingSession.tier] ?? 0;\n const newRank = tierRank[routingDecision.tier] ?? 0;\n\n if (newRank > existingRank) {\n // Current request needs higher capability — upgrade the session\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... upgrading: ${existingSession.tier} → ${routingDecision.tier} (${routingDecision.model})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n }\n } else if (routingDecision.tier === \"SIMPLE\") {\n // SIMPLE follow-up in an active session: let it use cheap routing.\n // e.g. \"你好\" or \"thanks\" after a complex task should not inherit the\n // expensive session model or recount all context tokens on a paid model.\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... SIMPLE follow-up, using cheap model: ${routingDecision.model} (bypassing pinned ${existingSession.tier})`,\n );\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // routingDecision already reflects cheap model — no override needed\n } else {\n // Keep existing higher-tier model (prevent downgrade mid-task)\n console.log(\n `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... keeping pinned model: ${existingSession.model} (${existingSession.tier} >= ${routingDecision.tier})`,\n );\n parsed.model = existingSession.model;\n modelId = existingSession.model;\n bodyModified = true;\n sessionStore.touchSession(effectiveSessionId!);\n // Reflect the actual model used in the routing decision for logging/fallback\n routingDecision = {\n ...routingDecision,\n model: existingSession.model,\n tier: existingSession.tier as Tier,\n };\n }\n\n // --- Three-strike escalation: detect repetitive request patterns ---\n const lastAssistantMsg = [...parsedMessages]\n .reverse()\n .find((m) => m.role === \"assistant\");\n const assistantToolCalls = (\n lastAssistantMsg as { tool_calls?: Array<{ function?: { name?: string } }> }\n )?.tool_calls;\n const toolCallNames = Array.isArray(assistantToolCalls)\n ? assistantToolCalls\n .map((tc) => tc.function?.name)\n .filter((n): n is string => Boolean(n))\n : undefined;\n const contentHash = hashRequestContent(prompt, toolCallNames);\n const shouldEscalate = sessionStore.recordRequestHash(effectiveSessionId!, contentHash);\n\n if (shouldEscalate) {\n const activeTierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n const escalation = sessionStore.escalateSession(\n effectiveSessionId!,\n activeTierConfigs,\n );\n if (escalation) {\n console.log(\n `[ClawRouter] ⚡ 3-strike escalation: ${existingSession.model} → ${escalation.model} (${existingSession.tier} → ${escalation.tier})`,\n );\n parsed.model = escalation.model;\n modelId = escalation.model;\n routingDecision = {\n ...routingDecision,\n model: escalation.model,\n tier: escalation.tier as Tier,\n };\n }\n }\n } else {\n // No session — pin this routing decision for future requests\n parsed.model = routingDecision.model;\n modelId = routingDecision.model;\n bodyModified = true;\n if (effectiveSessionId) {\n sessionStore.setSession(\n effectiveSessionId,\n routingDecision.model,\n routingDecision.tier,\n );\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... pinned to model: ${routingDecision.model}`,\n );\n }\n }\n\n options.onRouted?.(routingDecision);\n }\n }\n\n // Ensure effectiveSessionId is set for explicit model requests via content hash fallback.\n // Routing profile requests already derive session ID from message content (see line above).\n // Explicit model requests (openai/gpt-4o, anthropic/claude-*, etc.) without an\n // x-session-id header would otherwise have no session ID → maxCostPerRun not tracked.\n if (!effectiveSessionId && parsedMessages.length > 0) {\n effectiveSessionId = deriveSessionId(parsedMessages);\n }\n\n // Rebuild body if modified — map free/xxx → nvidia/xxx for upstream\n if (bodyModified) {\n if (parsed.model && typeof parsed.model === \"string\") {\n parsed.model = toUpstreamModelId(parsed.model);\n }\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Log routing errors so they're not silently swallowed\n const errorMsg = err instanceof Error ? err.message : String(err);\n console.error(`[ClawRouter] Routing error: ${errorMsg}`);\n console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);\n options.onError?.(new Error(`Routing failed: ${errorMsg}`));\n }\n }\n\n // --- Auto-compression ---\n // Compress large requests to reduce network usage and improve performance\n const autoCompress = options.autoCompressRequests ?? true;\n const compressionThreshold = options.compressionThresholdKB ?? 180;\n const requestSizeKB = Math.ceil(body.length / 1024);\n\n if (autoCompress && requestSizeKB > compressionThreshold) {\n try {\n console.log(\n `[ClawRouter] Request size ${requestSizeKB}KB exceeds threshold ${compressionThreshold}KB, applying compression...`,\n );\n\n // Parse messages for compression\n const parsed = JSON.parse(body.toString()) as {\n messages?: NormalizedMessage[];\n [key: string]: unknown;\n };\n\n if (parsed.messages && parsed.messages.length > 0 && shouldCompress(parsed.messages)) {\n // Apply compression with conservative settings\n const compressionResult = await compressContext(parsed.messages, {\n enabled: true,\n preserveRaw: false, // Don't need originals in proxy\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // Disabled: requires model to understand codebook\n paths: false, // Disabled: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // Disabled: may lose important context\n dynamicCodebook: false, // Disabled: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false,\n },\n });\n\n const compressedSizeKB = Math.ceil(compressionResult.compressedChars / 1024);\n const savings = (((requestSizeKB - compressedSizeKB) / requestSizeKB) * 100).toFixed(1);\n\n console.log(\n `[ClawRouter] Compressed ${requestSizeKB}KB → ${compressedSizeKB}KB (${savings}% reduction)`,\n );\n\n // Update request body with compressed messages\n parsed.messages = compressionResult.messages;\n body = Buffer.from(JSON.stringify(parsed));\n }\n } catch (err) {\n // Compression failed - continue with original request\n console.warn(\n `[ClawRouter] Compression failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // --- Response cache check (long-term, 10min TTL) ---\n const cacheKey = ResponseCache.generateKey(body);\n const reqHeaders: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (typeof value === \"string\") reqHeaders[key] = value;\n }\n if (responseCache.shouldCache(body, reqHeaders)) {\n const cachedResponse = responseCache.get(cacheKey);\n if (cachedResponse) {\n console.log(`[ClawRouter] Cache HIT for ${cachedResponse.model} (saved API call)`);\n res.writeHead(cachedResponse.status, cachedResponse.headers);\n res.end(cachedResponse.body);\n return;\n }\n }\n\n // --- Dedup check (short-term, 30s TTL for retries) ---\n const dedupKey = RequestDeduplicator.hash(body);\n\n // Check dedup cache (catches retries within 30s)\n const cached = deduplicator.getCached(dedupKey);\n if (cached) {\n res.writeHead(cached.status, cached.headers);\n res.end(cached.body);\n return;\n }\n\n // Check in-flight — wait for the original request to complete\n const inflight = deduplicator.getInflight(dedupKey);\n if (inflight) {\n const result = await inflight;\n res.writeHead(result.status, result.headers);\n res.end(result.body);\n return;\n }\n\n // Register this request as in-flight\n deduplicator.markInflight(dedupKey);\n\n // --- Pre-request balance check ---\n // Estimate cost and check if wallet has sufficient balance\n // Skip if skipBalanceCheck is set (for testing) or if using free model\n let estimatedCostMicros: bigint | undefined;\n // Use `let` so the balance-fallback path can update this when modelId is switched to a free model.\n let isFreeModel = FREE_MODELS.has(modelId ?? \"\");\n\n if (modelId && !options.skipBalanceCheck && !isFreeModel) {\n const estimated = estimateAmount(modelId, body.length, maxTokens);\n if (estimated) {\n estimatedCostMicros = BigInt(estimated);\n\n // Apply extra buffer for balance check to prevent x402 failures after streaming starts.\n // This is aggressive to avoid triggering OpenClaw's 5-24 hour billing cooldown.\n const bufferedCostMicros =\n (estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100))) / 100n;\n\n if (balanceMonitor instanceof BalanceMonitor) {\n const baseAssets = getBasePaymentAssets();\n let selected:\n | {\n asset: BasePaymentAsset;\n monitor: BalanceMonitor;\n sufficiency: Awaited>;\n }\n | undefined;\n\n for (const asset of baseAssets) {\n const monitor = balanceMonitor.getSharedMonitorForAsset(asset);\n const sufficiency = await monitor.checkSufficient(bufferedCostMicros);\n if (!selected) {\n selected = { asset, monitor, sufficiency };\n }\n if (sufficiency.sufficient) {\n selected = { asset, monitor, sufficiency };\n break;\n }\n }\n\n if (selected) {\n requestBasePaymentAsset = selected.asset;\n requestBalanceMonitor = selected.monitor;\n onBaseAssetSelected(selected.asset);\n console.log(\n `[ClawRouter] Base payment asset selected: ${selected.asset.symbol} (${selected.sufficiency.info.balanceUSD})`,\n );\n }\n }\n\n // Check balance before proceeding (using buffered amount)\n const sufficiency = await requestBalanceMonitor.checkSufficient(bufferedCostMicros);\n\n if (sufficiency.info.isEmpty || !sufficiency.sufficient) {\n // Wallet is empty or insufficient — fallback to free model\n const originalModel = modelId;\n console.log(\n `[ClawRouter] Wallet ${sufficiency.info.isEmpty ? \"empty\" : \"insufficient\"} (${sufficiency.info.balanceUSD}), falling back to free model: ${FREE_MODEL} (requested: ${originalModel})`,\n );\n modelId = FREE_MODEL;\n isFreeModel = true; // keep in sync — budget logic gates on !isFreeModel\n // Update the body with new model (map free/ → nvidia/ for upstream)\n const parsed = JSON.parse(body.toString()) as Record;\n parsed.model = toUpstreamModelId(FREE_MODEL);\n body = Buffer.from(JSON.stringify(parsed));\n\n // Set notice to prepend to response so user knows about the fallback\n balanceFallbackNotice = sufficiency.info.isEmpty\n ? `> **⚠️ Wallet empty** — using free model. Fund your wallet to use ${originalModel}.\\n\\n`\n : `> **⚠️ Insufficient balance** (${sufficiency.info.balanceUSD}) — using free model instead of ${originalModel}.\\n\\n`;\n\n // Notify about the fallback\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n assetSymbol: sufficiency.info.assetSymbol,\n });\n } else if (sufficiency.info.isLow) {\n // Balance is low but sufficient — warn and proceed\n options.onLowBalance?.({\n balanceUSD: sufficiency.info.balanceUSD,\n walletAddress: sufficiency.info.walletAddress,\n assetSymbol: sufficiency.info.assetSymbol,\n });\n }\n }\n }\n\n // --- Cost cap check: strict mode hard-stop ---\n // In 'strict' mode, reject if the projected session spend (accumulated + this request's\n // estimate) would exceed the cap. Checking projected cost (not just historical) prevents\n // a single large request from overshooting the cap before it's recorded.\n // In 'graceful' mode (default), the cap is enforced via model downgrade below.\n // Must happen before streaming headers are sent.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"strict\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n // Include this request's estimated cost so even the first request is blocked\n // if it would push the session over the cap.\n const thisReqEstStr =\n estimatedCostMicros !== undefined\n ? estimatedCostMicros.toString()\n : modelId\n ? estimateAmount(modelId, body.length, maxTokens)\n : undefined;\n const thisReqEstUsd = thisReqEstStr ? Number(thisReqEstStr) / 1_000_000 : 0;\n const projectedCostUsd = runCostUsd + thisReqEstUsd;\n if (projectedCostUsd > options.maxCostPerRunUsd) {\n console.log(\n `[ClawRouter] Cost cap exceeded for session ${effectiveSessionId.slice(0, 8)}...: projected $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) > $${options.maxCostPerRunUsd} limit`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter cost cap exceeded: projected spend $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) would exceed limit $${options.maxCostPerRunUsd}`,\n type: \"cost_cap_exceeded\",\n code: \"cost_cap_exceeded\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n\n // --- Budget pre-check: block when remaining budget can't cover the request ---\n // Must happen BEFORE streaming headers (429 can't be sent after SSE headers are flushed).\n // Three cases that require a hard block rather than graceful downgrade:\n // (A) tool/COMPLEX/REASONING routing profile — free model can't substitute\n // (B) explicit model request (no routing profile) — user chose a specific model,\n // silently substituting with free model would be deceptive regardless of task type\n // Simple routing profile requests are handled later via graceful downgrade.\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const isComplexOrAgentic =\n hasTools || routingDecision?.tier === \"COMPLEX\" || routingDecision?.tier === \"REASONING\";\n\n if (isComplexOrAgentic) {\n // Case A: tool/complex/agentic routing profile — check global model table\n // Intentionally exclude free models: they cannot handle complex/agentic tasks.\n const canAffordAnyNonFreeModel = BLOCKRUN_MODELS.some((m) => {\n if (FREE_MODELS.has(m.id)) return false;\n const est = estimateAmount(m.id, body.length, maxTokens);\n return est !== undefined && Number(est) / 1_000_000 <= remainingUsd;\n });\n if (!canAffordAnyNonFreeModel) {\n console.log(\n `[ClawRouter] Budget insufficient for agentic/complex session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (silent downgrade would corrupt tool/complex responses)`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n } else if (!routingDecision && modelId && !FREE_MODELS.has(modelId)) {\n // Case B: explicit model request (user chose a specific model, not a routing profile).\n // Silently substituting their choice with free model is deceptive — block instead.\n const est = estimateAmount(modelId, body.length, maxTokens);\n const canAfford = !est || Number(est) / 1_000_000 <= remainingUsd;\n if (!canAfford) {\n console.log(\n `[ClawRouter] Budget insufficient for explicit model ${modelId} in session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining — blocking (user explicitly chose ${modelId})`,\n );\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(\n JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue using ${modelId}.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n }),\n );\n deduplicator.removeInflight(dedupKey);\n return;\n }\n }\n }\n\n // --- Streaming: early header flush + heartbeat ---\n let heartbeatInterval: ReturnType | undefined;\n let headersSentEarly = false;\n\n if (isStreaming) {\n // Send 200 + SSE headers immediately, before x402 flow\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n headersSentEarly = true;\n\n // First heartbeat immediately\n safeWrite(res, \": heartbeat\\n\\n\");\n\n // Continue heartbeats every 2s while waiting for upstream\n heartbeatInterval = setInterval(() => {\n if (canWrite(res)) {\n safeWrite(res, \": heartbeat\\n\\n\");\n } else {\n // Socket closed, stop heartbeat\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n }, HEARTBEAT_INTERVAL_MS);\n }\n\n // Forward headers, stripping host, connection, and content-length\n const headers: Record = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (\n key === \"host\" ||\n key === \"connection\" ||\n key === \"transfer-encoding\" ||\n key === \"content-length\"\n )\n continue;\n if (typeof value === \"string\") {\n headers[key] = value;\n }\n }\n if (!headers[\"content-type\"]) {\n headers[\"content-type\"] = \"application/json\";\n }\n headers[\"user-agent\"] = USER_AGENT;\n\n // --- Client disconnect cleanup ---\n let completed = false;\n res.on(\"close\", () => {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n // Remove from in-flight if client disconnected before completion\n if (!completed) {\n deduplicator.removeInflight(dedupKey);\n }\n });\n\n // --- Request timeout ---\n // Global controller: hard deadline for the entire request (all model attempts combined).\n // Each model attempt gets its own per-model controller (PER_MODEL_TIMEOUT_MS).\n // If a model times out individually, we fall back to the next model instead of failing.\n // Only the global timeout causes an immediate error.\n const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const globalController = new AbortController();\n const timeoutId = setTimeout(() => globalController.abort(), timeoutMs);\n\n try {\n // --- Build fallback chain ---\n // If we have a routing decision, get the full fallback chain for the tier\n // Otherwise, just use the current model (no fallback for explicit model requests)\n let modelsToTry: string[];\n const excludeList = options.excludeModels ?? loadExcludeList();\n if (routingDecision) {\n // Estimate total context: input tokens (~4 chars per token) + max output tokens\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const estimatedTotalTokens = estimatedInputTokens + maxTokens;\n\n // Use tier configs from the routing decision (set by RouterStrategy)\n const tierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;\n\n // Get full chain first, then filter by context\n const fullChain = getFallbackChain(routingDecision.tier, tierConfigs);\n const contextFiltered = getFallbackChainFiltered(\n routingDecision.tier,\n tierConfigs,\n estimatedTotalTokens,\n getModelContextWindow,\n );\n\n // Log if models were filtered out due to context limits\n const contextExcluded = fullChain.filter((m) => !contextFiltered.includes(m));\n if (contextExcluded.length > 0) {\n console.log(\n `[ClawRouter] Context filter (~${estimatedTotalTokens} tokens): excluded ${contextExcluded.join(\", \")}`,\n );\n }\n\n // Filter out user-excluded models\n const excludeFiltered = filterByExcludeList(contextFiltered, excludeList);\n const excludeExcluded = contextFiltered.filter((m) => !excludeFiltered.includes(m));\n if (excludeExcluded.length > 0) {\n console.log(\n `[ClawRouter] Exclude filter: excluded ${excludeExcluded.join(\", \")} (user preference)`,\n );\n }\n\n // Filter to models that support tool calling when request has tools.\n // Prevents models like grok-code-fast-1 from outputting tool invocations\n // as plain text JSON (the \"talking to itself\" bug).\n let toolFiltered = filterByToolCalling(excludeFiltered, hasTools, supportsToolCalling);\n const toolExcluded = excludeFiltered.filter((m) => !toolFiltered.includes(m));\n if (toolExcluded.length > 0) {\n console.log(\n `[ClawRouter] Tool-calling filter: excluded ${toolExcluded.join(\", \")} (no structured function call support)`,\n );\n }\n\n // Filter out models that declare toolCalling but fail tool compliance in practice.\n // gemini-2.5-flash-lite refuses certain tool schemas (e.g. brave search) while\n // cheaper models like nvidia/gpt-oss-120b handle them fine.\n const TOOL_NONCOMPLIANT_MODELS = [\n \"google/gemini-2.5-flash-lite\",\n \"google/gemini-3-pro-preview\",\n \"google/gemini-3.1-pro\",\n ];\n if (hasTools && toolFiltered.length > 1) {\n const compliant = toolFiltered.filter((m) => !TOOL_NONCOMPLIANT_MODELS.includes(m));\n if (compliant.length > 0 && compliant.length < toolFiltered.length) {\n const dropped = toolFiltered.filter((m) => TOOL_NONCOMPLIANT_MODELS.includes(m));\n console.log(\n `[ClawRouter] Tool-compliance filter: excluded ${dropped.join(\", \")} (unreliable tool schema handling)`,\n );\n toolFiltered = compliant;\n }\n }\n\n // Filter to models that support vision when request has image_url content\n const visionFiltered = filterByVision(toolFiltered, hasVision, supportsVision);\n const visionExcluded = toolFiltered.filter((m) => !visionFiltered.includes(m));\n if (visionExcluded.length > 0) {\n console.log(\n `[ClawRouter] Vision filter: excluded ${visionExcluded.join(\", \")} (no vision support)`,\n );\n }\n\n // Limit to MAX_FALLBACK_ATTEMPTS to prevent infinite loops\n modelsToTry = visionFiltered.slice(0, MAX_FALLBACK_ATTEMPTS);\n\n // Deprioritize rate-limited models (put them at the end)\n modelsToTry = prioritizeNonRateLimited(modelsToTry);\n } else {\n // For explicit model requests, use the requested model\n modelsToTry = modelId ? [modelId] : [];\n }\n\n // Ensure free model is the last-resort fallback for non-tool requests.\n // Skip free fallback when tools are present — nvidia/gpt-oss-120b lacks\n // tool calling support and would produce broken responses for agentic tasks.\n if (!hasTools && !modelsToTry.includes(FREE_MODEL) && !excludeList.has(FREE_MODEL)) {\n modelsToTry.push(FREE_MODEL); // last-resort free fallback\n }\n\n // --- Budget-aware routing (graceful mode) ---\n // Filter modelsToTry to only models that fit within the remaining session budget.\n // Simple tasks (no tools, non-complex tier): downgrade with visible warning.\n // Complex/agentic tasks with no affordable model: already blocked above (before streaming headers).\n if (\n options.maxCostPerRunUsd &&\n effectiveSessionId &&\n !isFreeModel &&\n (options.maxCostPerRunMode ?? \"graceful\") === \"graceful\"\n ) {\n const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);\n const remainingUsd = options.maxCostPerRunUsd - runCostUsd;\n\n const beforeFilter = [...modelsToTry];\n modelsToTry = modelsToTry.filter((m) => {\n if (FREE_MODELS.has(m)) return true; // free models always fit (no cost)\n const est = estimateAmount(m, body.length, maxTokens);\n if (!est) return true; // no pricing data → keep (permissive)\n return Number(est) / 1_000_000 <= remainingUsd;\n });\n\n const excluded = beforeFilter.filter((m) => !modelsToTry.includes(m));\n\n // Second-pass block: the pre-check caught obvious cases early (before streaming headers).\n // Here we recheck against the actual filtered modelsToTry chain. If the ONLY remaining\n // models are free, we must block rather than silently degrade for:\n // (A) complex/agentic routing profile tasks (tools / COMPLEX / REASONING tier)\n // (B) explicit model requests (user chose a specific model; free substitution is deceptive)\n // The pre-check already handles case (B) for non-streaming; this is a safety net for\n // streaming requests where SSE headers may have already been sent.\n const isComplexOrAgenticFilter =\n hasTools ||\n routingDecision?.tier === \"COMPLEX\" ||\n routingDecision?.tier === \"REASONING\" ||\n routingDecision === undefined; // explicit model: no routing profile → user chose the model\n const filteredToFreeOnly =\n modelsToTry.length > 0 && modelsToTry.every((m) => FREE_MODELS.has(m));\n\n if (isComplexOrAgenticFilter && filteredToFreeOnly) {\n const budgetSummary = `$${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget filter left only free model for complex/agentic session — blocking (${budgetSummary})`,\n );\n const errPayload = JSON.stringify({\n error: {\n message: `ClawRouter budget exhausted: remaining budget (${budgetSummary}) cannot support a complex/tool request. Increase maxCostPerRun to continue.`,\n type: \"cost_cap_exceeded\",\n code: \"budget_exhausted\",\n },\n });\n if (heartbeatInterval) clearInterval(heartbeatInterval);\n if (headersSentEarly) {\n // Streaming: inject error SSE event + [DONE] and close\n safeWrite(res, `data: ${errPayload}\\n\\ndata: [DONE]\\n\\n`);\n res.end();\n } else {\n res.writeHead(429, {\n \"Content-Type\": \"application/json\",\n \"X-ClawRouter-Cost-Cap-Exceeded\": \"1\",\n \"X-ClawRouter-Budget-Mode\": \"blocked\",\n });\n res.end(errPayload);\n }\n deduplicator.removeInflight(dedupKey);\n return;\n }\n\n if (excluded.length > 0) {\n const budgetSummary =\n remainingUsd > 0\n ? `$${remainingUsd.toFixed(4)} remaining`\n : `budget exhausted ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd})`;\n console.log(\n `[ClawRouter] Budget downgrade (${budgetSummary}): excluded ${excluded.join(\", \")}`,\n );\n\n // A: Set visible warning notice — prepended to response so user sees the downgrade\n const fromModel = excluded[0];\n const usingFree = modelsToTry.length === 1 && FREE_MODELS.has(modelsToTry[0]);\n if (usingFree) {\n budgetDowngradeNotice = `> **⚠️ Budget cap reached** ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd}) — downgraded to free model. Quality may be reduced. Increase \\`maxCostPerRun\\` to continue with ${fromModel}.\\n\\n`;\n } else {\n const toModel = modelsToTry[0] ?? FREE_MODEL; // last resort\n budgetDowngradeNotice = `> **⚠️ Budget low** ($${remainingUsd > 0 ? remainingUsd.toFixed(4) : \"0.0000\"} remaining) — using ${toModel} instead of ${fromModel}.\\n\\n`;\n }\n // B: Header flag for orchestration layers (e.g. OpenClaw can pause/warn the user)\n budgetDowngradeHeaderMode = \"downgraded\";\n }\n }\n\n // --- Fallback loop: try each model until success ---\n let upstream: Response | undefined;\n let lastError: { body: string; status: number } | undefined;\n let actualModelUsed = modelId;\n const failedAttempts: Array<{ model: string; reason: string; status: number }> = [];\n\n for (let i = 0; i < modelsToTry.length; i++) {\n const tryModel = modelsToTry[i];\n const isLastAttempt = i === modelsToTry.length - 1;\n\n // Abort immediately if global deadline has already fired\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n console.log(`[ClawRouter] Trying model ${i + 1}/${modelsToTry.length}: ${tryModel}`);\n\n // Per-model abort controller — each model attempt gets its own 60s window.\n // When it fires, the fallback loop moves to the next model rather than failing.\n const modelController = new AbortController();\n const modelTimeoutId = setTimeout(() => modelController.abort(), PER_MODEL_TIMEOUT_MS);\n const combinedSignal = AbortSignal.any([globalController.signal, modelController.signal]);\n\n const result = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n combinedSignal,\n );\n clearTimeout(modelTimeoutId);\n\n // If the global deadline fired during this attempt, bail out entirely\n if (globalController.signal.aborted) {\n throw new Error(`Request timed out after ${timeoutMs}ms`);\n }\n\n // If the per-model timeout fired (but not global), treat as fallback-worthy error\n if (!result.success && modelController.signal.aborted && !isLastAttempt) {\n console.log(\n `[ClawRouter] Model ${tryModel} timed out after ${PER_MODEL_TIMEOUT_MS}ms, trying fallback`,\n );\n recordProviderError(tryModel, \"server_error\");\n continue;\n }\n\n if (result.success && result.response) {\n upstream = result.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Success with model: ${tryModel}`);\n // Accumulate estimated cost to session for maxCostPerRun tracking\n if (options.maxCostPerRunUsd && effectiveSessionId && !FREE_MODELS.has(tryModel)) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n\n // Request failed\n lastError = {\n body: result.errorBody || \"Unknown error\",\n status: result.errorStatus || 500,\n };\n failedAttempts.push({\n model: tryModel,\n reason: result.errorCategory || `HTTP ${result.errorStatus || 500}`,\n status: result.errorStatus || 500,\n });\n\n // Payment error (insufficient funds, simulation failure) — skip remaining\n // paid models, jump straight to free model. No point trying other paid\n // models with the same wallet state.\n // Must be checked BEFORE isProviderError gate: payment settlement failures\n // may return non-standard HTTP codes that categorizeError doesn't recognize,\n // causing isProviderError=false and breaking out of the fallback loop.\n const isPaymentErr =\n /payment.*verification.*failed|payment.*settlement.*failed|insufficient.*funds|transaction_simulation_failed/i.test(\n result.errorBody || \"\",\n );\n if (isPaymentErr && !FREE_MODELS.has(tryModel) && !isLastAttempt) {\n failedAttempts.push({\n ...failedAttempts[failedAttempts.length - 1],\n reason: \"payment_error\",\n });\n const freeIdx = modelsToTry.indexOf(FREE_MODEL);\n if (freeIdx > i + 1) {\n console.log(`[ClawRouter] Payment error — skipping to free model: ${FREE_MODEL}`);\n i = freeIdx - 1; // loop will increment to freeIdx\n continue;\n }\n // Free model not in chain — add it and try\n if (freeIdx === -1 && !excludeList.has(FREE_MODEL)) {\n modelsToTry.push(FREE_MODEL);\n console.log(`[ClawRouter] Payment error — appending free model: ${FREE_MODEL}`);\n continue;\n }\n }\n\n // If it's a provider error and not the last attempt, try next model\n if (result.isProviderError && !isLastAttempt) {\n const isExplicitModelError = !routingDecision;\n const isUnknownExplicitModel =\n isExplicitModelError && /unknown.*model|invalid.*model/i.test(result.errorBody || \"\");\n if (isUnknownExplicitModel) {\n console.log(\n `[ClawRouter] Explicit model error from ${tryModel}, not falling back: ${result.errorBody?.slice(0, 100)}`,\n );\n break;\n }\n\n // Record error and apply category-specific handling\n const errorCat = result.errorCategory;\n if (errorCat) {\n recordProviderError(tryModel, errorCat);\n }\n\n if (errorCat === \"rate_limited\") {\n // --- Stepped backoff retry (429) ---\n // Token-bucket rate limits often recover within milliseconds.\n // Retry once after 200ms before treating this as a model-level failure.\n if (!isLastAttempt && !globalController.signal.aborted) {\n console.log(\n `[ClawRouter] Rate-limited on ${tryModel}, retrying in 200ms before failover`,\n );\n await new Promise((resolve) => setTimeout(resolve, 200));\n if (!globalController.signal.aborted) {\n const retryController = new AbortController();\n const retryTimeoutId = setTimeout(\n () => retryController.abort(),\n PER_MODEL_TIMEOUT_MS,\n );\n const retrySignal = AbortSignal.any([\n globalController.signal,\n retryController.signal,\n ]);\n const retryResult = await tryModelRequest(\n upstreamUrl,\n req.method ?? \"POST\",\n headers,\n body,\n tryModel,\n maxTokens,\n payFetch,\n balanceMonitor,\n retrySignal,\n );\n clearTimeout(retryTimeoutId);\n if (retryResult.success && retryResult.response) {\n upstream = retryResult.response;\n actualModelUsed = tryModel;\n console.log(`[ClawRouter] Rate-limit retry succeeded for: ${tryModel}`);\n if (options.maxCostPerRunUsd && effectiveSessionId && tryModel !== FREE_MODEL) {\n const costEst = estimateAmount(tryModel, body.length, maxTokens);\n if (costEst) {\n sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));\n }\n }\n break;\n }\n // Retry also failed — fall through to markRateLimited\n }\n }\n markRateLimited(tryModel);\n // Check for server-side update hint in 429 response\n try {\n const parsed = JSON.parse(result.errorBody || \"{}\");\n if (parsed.update_available) {\n console.log(\"\");\n console.log(\n `\\x1b[33m⬆️ ClawRouter ${parsed.update_available} available (you have ${VERSION})\\x1b[0m`,\n );\n console.log(\n ` Run: \\x1b[36mcurl -fsSL ${parsed.update_url || \"https://blockrun.ai/ClawRouter-update\"} | bash\\x1b[0m`,\n );\n console.log(\"\");\n }\n } catch {\n /* ignore parse errors */\n }\n } else if (errorCat === \"overloaded\") {\n markOverloaded(tryModel);\n } else if (errorCat === \"auth_failure\" || errorCat === \"quota_exceeded\") {\n console.log(\n `[ClawRouter] 🔑 ${errorCat === \"auth_failure\" ? \"Auth failure\" : \"Quota exceeded\"} for ${tryModel} — check provider config`,\n );\n }\n\n console.log(\n `[ClawRouter] Provider error from ${tryModel}, trying fallback: ${result.errorBody?.slice(0, 100)}`,\n );\n continue;\n }\n\n // Not a provider error or last attempt — stop trying\n if (!result.isProviderError) {\n console.log(\n `[ClawRouter] Non-provider error from ${tryModel}, not retrying: ${result.errorBody?.slice(0, 100)}`,\n );\n }\n break;\n }\n\n // Clear timeout — request attempts completed\n clearTimeout(timeoutId);\n\n // Clear heartbeat — real data is about to flow\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // --- Emit routing debug info (opt-in via x-clawrouter-debug: true header) ---\n // For streaming: SSE comment (invisible to most clients, visible in raw stream)\n // For non-streaming: response headers added later\n if (debugMode && headersSentEarly && routingDecision) {\n const debugComment = `: x-clawrouter-debug profile=${routingProfile ?? \"auto\"} tier=${routingDecision.tier} model=${actualModelUsed} agentic=${routingDecision.agenticScore?.toFixed(2) ?? \"n/a\"} confidence=${routingDecision.confidence.toFixed(2)} reasoning=${routingDecision.reasoning}\\n\\n`;\n safeWrite(res, debugComment);\n }\n\n // Update routing decision with actual model used (for logging)\n // IMPORTANT: Recalculate cost for the actual model, not the original primary\n if (routingDecision && actualModelUsed !== routingDecision.model) {\n const estimatedInputTokens = Math.ceil(body.length / 4);\n const newCosts = calculateModelCost(\n actualModelUsed,\n routerOpts.modelPricing,\n estimatedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n routingDecision = {\n ...routingDecision,\n model: actualModelUsed,\n reasoning: `${routingDecision.reasoning} | fallback to ${actualModelUsed}`,\n costEstimate: newCosts.costEstimate,\n baselineCost: newCosts.baselineCost,\n savings: newCosts.savings,\n };\n options.onRouted?.(routingDecision);\n\n // Update session pin to the actual model used — ensures the next request in\n // this conversation starts from the fallback model rather than retrying the\n // primary and falling back again (prevents the \"model keeps jumping\" issue).\n if (effectiveSessionId) {\n sessionStore.setSession(effectiveSessionId, actualModelUsed, routingDecision.tier);\n console.log(\n `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... updated pin to fallback: ${actualModelUsed}`,\n );\n }\n }\n\n // --- Handle case where all models failed ---\n if (!upstream) {\n // Build structured error summary listing all attempted models\n const attemptSummary =\n failedAttempts.length > 0\n ? failedAttempts.map((a) => `${a.model} (${a.reason})`).join(\", \")\n : \"unknown\";\n const structuredMessage =\n failedAttempts.length > 0\n ? `All ${failedAttempts.length} models failed. Tried: ${attemptSummary}`\n : \"All models in fallback chain failed\";\n console.log(`[ClawRouter] ${structuredMessage}`);\n const rawErrBody = lastError?.body || structuredMessage;\n const errStatus = lastError?.status || 502;\n\n // Transform payment errors into user-friendly messages\n const transformedErr = transformPaymentError(rawErrBody, {\n baseAssetSymbol: requestBasePaymentAsset.symbol,\n baseAssetDecimals: requestBasePaymentAsset.decimals,\n });\n\n if (headersSentEarly) {\n // Streaming: send error as SSE event\n // If transformed error is already JSON, parse and use it; otherwise wrap in standard format\n let errPayload: string;\n try {\n const parsed = JSON.parse(transformedErr);\n errPayload = JSON.stringify(parsed);\n } catch {\n errPayload = JSON.stringify({\n error: { message: rawErrBody, type: \"provider_error\", status: errStatus },\n });\n }\n const errEvent = `data: ${errPayload}\\n\\n`;\n safeWrite(res, errEvent);\n safeWrite(res, \"data: [DONE]\\n\\n\");\n res.end();\n\n const errBuf = Buffer.from(errEvent + \"data: [DONE]\\n\\n\");\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: errBuf,\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: send transformed error response with context headers\n res.writeHead(errStatus, {\n \"Content-Type\": \"application/json\",\n \"x-context-used-kb\": String(originalContextSizeKB),\n \"x-context-limit-kb\": String(CONTEXT_LIMIT_KB),\n });\n res.end(transformedErr);\n\n deduplicator.complete(dedupKey, {\n status: errStatus,\n headers: { \"content-type\": \"application/json\" },\n body: Buffer.from(transformedErr),\n completedAt: Date.now(),\n });\n }\n return;\n }\n\n // --- Stream response and collect for dedup cache ---\n const responseChunks: Buffer[] = [];\n\n if (headersSentEarly) {\n // Streaming: headers already sent. Response should be 200 at this point\n // (non-200 responses are handled in the fallback loop above)\n\n // Convert non-streaming JSON response to SSE streaming format for client\n // (BlockRun API returns JSON since we forced stream:false)\n // OpenClaw expects: object=\"chat.completion.chunk\" with choices[].delta (not message)\n // We emit proper incremental deltas to match OpenAI's streaming format exactly\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n\n // Combine chunks and transform to streaming format\n const jsonBody = Buffer.concat(chunks);\n const jsonStr = jsonBody.toString();\n try {\n const rsp = JSON.parse(jsonStr) as {\n id?: string;\n object?: string;\n created?: number;\n model?: string;\n choices?: Array<{\n index?: number;\n message?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n delta?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n id: string;\n type: string;\n function: { name: string; arguments: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: unknown;\n };\n\n // Extract input token count from upstream response\n if (rsp.usage && typeof rsp.usage === \"object\") {\n const u = rsp.usage as Record;\n if (typeof u.prompt_tokens === \"number\") responseInputTokens = u.prompt_tokens;\n if (typeof u.completion_tokens === \"number\") responseOutputTokens = u.completion_tokens;\n }\n\n // Build base chunk structure (reused for all chunks)\n // Match OpenAI's exact format including system_fingerprint\n const baseChunk = {\n id: rsp.id ?? `chatcmpl-${Date.now()}`,\n object: \"chat.completion.chunk\",\n created: rsp.created ?? Math.floor(Date.now() / 1000),\n model: actualModelUsed || rsp.model || \"unknown\",\n system_fingerprint: null,\n };\n\n // Process each choice (usually just one)\n if (rsp.choices && Array.isArray(rsp.choices)) {\n for (const choice of rsp.choices) {\n // Strip thinking tokens (Kimi <|...|> and standard tags)\n const rawContent = choice.message?.content ?? choice.delta?.content ?? \"\";\n const content = stripThinkingTokens(rawContent);\n const role = choice.message?.role ?? choice.delta?.role ?? \"assistant\";\n const index = choice.index ?? 0;\n\n // Accumulate content for session journal\n if (content) {\n accumulatedContent += content;\n }\n\n // Chunk 1: role only (mimics OpenAI's first chunk)\n const roleChunk = {\n ...baseChunk,\n choices: [{ index, delta: { role }, logprobs: null, finish_reason: null }],\n };\n const roleData = `data: ${JSON.stringify(roleChunk)}\\n\\n`;\n safeWrite(res, roleData);\n responseChunks.push(Buffer.from(roleData));\n\n // Chunk 1.5: balance fallback notice (tells user they got free model)\n if (balanceFallbackNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: balanceFallbackNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n balanceFallbackNotice = undefined; // Only inject once\n }\n\n // Chunk 1.6: budget downgrade notice (A: visible warning when model downgraded)\n if (budgetDowngradeNotice) {\n const noticeChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { content: budgetDowngradeNotice },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const noticeData = `data: ${JSON.stringify(noticeChunk)}\\n\\n`;\n safeWrite(res, noticeData);\n responseChunks.push(Buffer.from(noticeData));\n budgetDowngradeNotice = undefined; // Only inject once\n }\n\n // Chunk 2: content (single chunk with full content)\n if (content) {\n const contentChunk = {\n ...baseChunk,\n choices: [{ index, delta: { content }, logprobs: null, finish_reason: null }],\n };\n const contentData = `data: ${JSON.stringify(contentChunk)}\\n\\n`;\n safeWrite(res, contentData);\n responseChunks.push(Buffer.from(contentData));\n }\n\n // Chunk 2b: tool_calls (forward tool calls from upstream)\n const toolCalls = choice.message?.tool_calls ?? choice.delta?.tool_calls;\n if (toolCalls && toolCalls.length > 0) {\n const toolCallChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: { tool_calls: toolCalls },\n logprobs: null,\n finish_reason: null,\n },\n ],\n };\n const toolCallData = `data: ${JSON.stringify(toolCallChunk)}\\n\\n`;\n safeWrite(res, toolCallData);\n responseChunks.push(Buffer.from(toolCallData));\n }\n\n // Chunk 3: finish_reason (signals completion)\n const finishChunk = {\n ...baseChunk,\n choices: [\n {\n index,\n delta: {},\n logprobs: null,\n finish_reason:\n toolCalls && toolCalls.length > 0\n ? \"tool_calls\"\n : (choice.finish_reason ?? \"stop\"),\n },\n ],\n };\n const finishData = `data: ${JSON.stringify(finishChunk)}\\n\\n`;\n safeWrite(res, finishData);\n responseChunks.push(Buffer.from(finishData));\n }\n }\n } catch {\n // If parsing fails, send raw response as single chunk\n const sseData = `data: ${jsonStr}\\n\\n`;\n safeWrite(res, sseData);\n responseChunks.push(Buffer.from(sseData));\n }\n }\n\n // Send cost summary as SSE comment before terminator\n if (routingDecision) {\n const costComment = `: cost=$${routingDecision.costEstimate.toFixed(4)} savings=${(routingDecision.savings * 100).toFixed(0)}% model=${actualModelUsed} tier=${routingDecision.tier}\\n\\n`;\n safeWrite(res, costComment);\n responseChunks.push(Buffer.from(costComment));\n }\n\n // Send SSE terminator\n safeWrite(res, \"data: [DONE]\\n\\n\");\n responseChunks.push(Buffer.from(\"data: [DONE]\\n\\n\"));\n res.end();\n\n // Cache for dedup\n deduplicator.complete(dedupKey, {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n body: Buffer.concat(responseChunks),\n completedAt: Date.now(),\n });\n } else {\n // Non-streaming: forward status and headers from upstream\n const responseHeaders: Record = {};\n upstream.headers.forEach((value, key) => {\n // Skip hop-by-hop headers and content-encoding (fetch already decompresses)\n if (key === \"transfer-encoding\" || key === \"connection\" || key === \"content-encoding\")\n return;\n responseHeaders[key] = value;\n });\n\n // Add context usage headers\n responseHeaders[\"x-context-used-kb\"] = String(originalContextSizeKB);\n responseHeaders[\"x-context-limit-kb\"] = String(CONTEXT_LIMIT_KB);\n\n // Add routing debug headers (opt-in via x-clawrouter-debug: true header)\n if (debugMode && routingDecision) {\n responseHeaders[\"x-clawrouter-profile\"] = routingProfile ?? \"auto\";\n responseHeaders[\"x-clawrouter-tier\"] = routingDecision.tier;\n responseHeaders[\"x-clawrouter-model\"] = actualModelUsed;\n responseHeaders[\"x-clawrouter-confidence\"] = routingDecision.confidence.toFixed(2);\n responseHeaders[\"x-clawrouter-reasoning\"] = routingDecision.reasoning;\n if (routingDecision.agenticScore !== undefined) {\n responseHeaders[\"x-clawrouter-agentic-score\"] = routingDecision.agenticScore.toFixed(2);\n }\n }\n\n // Always include cost visibility headers when routing is active\n if (routingDecision) {\n responseHeaders[\"x-clawrouter-cost\"] = routingDecision.costEstimate.toFixed(6);\n responseHeaders[\"x-clawrouter-savings\"] = `${(routingDecision.savings * 100).toFixed(0)}%`;\n }\n\n // Collect full body for possible notice injection\n const bodyParts: Buffer[] = [];\n if (upstream.body) {\n const chunks = await readBodyWithTimeout(upstream.body);\n for (const chunk of chunks) {\n bodyParts.push(Buffer.from(chunk));\n }\n }\n\n let responseBody = Buffer.concat(bodyParts);\n\n // Prepend balance fallback notice to response content\n if (balanceFallbackNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n balanceFallbackNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n balanceFallbackNotice = undefined;\n }\n\n // A: Prepend budget downgrade notice to response content\n if (budgetDowngradeNotice && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n if (parsed.choices?.[0]?.message?.content !== undefined) {\n parsed.choices[0].message.content =\n budgetDowngradeNotice + parsed.choices[0].message.content;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip notice */\n }\n budgetDowngradeNotice = undefined;\n }\n\n // Inject actualModelUsed into non-streaming response model field\n if (actualModelUsed && responseBody.length > 0) {\n try {\n const parsed = JSON.parse(responseBody.toString()) as { model?: string };\n if (parsed.model !== undefined) {\n parsed.model = actualModelUsed;\n responseBody = Buffer.from(JSON.stringify(parsed));\n }\n } catch {\n /* not JSON, skip model injection */\n }\n }\n\n // B: Add budget downgrade headers for orchestration layers\n if (budgetDowngradeHeaderMode) {\n responseHeaders[\"x-clawrouter-budget-downgrade\"] = \"1\";\n responseHeaders[\"x-clawrouter-budget-mode\"] = budgetDowngradeHeaderMode;\n budgetDowngradeHeaderMode = undefined;\n }\n\n // Update content-length header since body may have changed\n responseHeaders[\"content-length\"] = String(responseBody.length);\n res.writeHead(upstream.status, responseHeaders);\n safeWrite(res, responseBody);\n responseChunks.push(responseBody);\n res.end();\n\n // Cache for dedup (short-term, 30s)\n deduplicator.complete(dedupKey, {\n status: upstream.status,\n headers: responseHeaders,\n body: responseBody,\n completedAt: Date.now(),\n });\n\n // Cache for response cache (long-term, 10min) - only successful non-streaming\n if (upstream.status === 200 && responseCache.shouldCache(body)) {\n responseCache.set(cacheKey, {\n body: responseBody,\n status: upstream.status,\n headers: responseHeaders,\n model: actualModelUsed,\n });\n console.log(\n `[ClawRouter] Cached response for ${actualModelUsed} (${responseBody.length} bytes)`,\n );\n }\n\n // Extract content and token usage from non-streaming response\n try {\n const rspJson = JSON.parse(responseBody.toString()) as {\n choices?: Array<{ message?: { content?: string } }>;\n usage?: Record;\n };\n if (rspJson.choices?.[0]?.message?.content) {\n accumulatedContent = rspJson.choices[0].message.content;\n }\n if (rspJson.usage && typeof rspJson.usage === \"object\") {\n if (typeof rspJson.usage.prompt_tokens === \"number\")\n responseInputTokens = rspJson.usage.prompt_tokens;\n if (typeof rspJson.usage.completion_tokens === \"number\")\n responseOutputTokens = rspJson.usage.completion_tokens;\n }\n } catch {\n // Ignore parse errors - journal just won't have content for this response\n }\n }\n\n // --- Session Journal: Extract and record events from response ---\n if (sessionId && accumulatedContent) {\n const events = sessionJournal.extractEvents(accumulatedContent);\n if (events.length > 0) {\n sessionJournal.record(sessionId, events, actualModelUsed);\n console.log(\n `[ClawRouter] Recorded ${events.length} events to session journal for session ${sessionId.slice(0, 8)}...`,\n );\n }\n }\n\n // --- Optimistic balance deduction after successful response ---\n if (estimatedCostMicros !== undefined) {\n requestBalanceMonitor.deductEstimated(estimatedCostMicros);\n }\n\n // Mark request as completed (for client disconnect cleanup)\n completed = true;\n } catch (err) {\n // Clear timeout on error\n clearTimeout(timeoutId);\n\n // Clear heartbeat on error\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n heartbeatInterval = undefined;\n }\n\n // Remove in-flight entry so retries aren't blocked\n deduplicator.removeInflight(dedupKey);\n\n // Invalidate balance cache on payment failure (might be out of date)\n requestBalanceMonitor.invalidate();\n\n // Convert abort error to more descriptive timeout error\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err });\n }\n\n throw err;\n }\n\n // --- Usage logging (fire-and-forget) ---\n // Use actual x402 payment amount from the per-request AsyncLocalStorage store.\n // This is the real amount the user paid — no estimation needed.\n // Falls back to local estimate only for free models (no x402 payment).\n const logModel = routingDecision?.model ?? modelId;\n if (logModel) {\n const actualPayment = paymentStore.getStore()?.amountUsd ?? 0;\n\n // For free models (no x402 payment), use local cost calculation as fallback\n let logCost: number;\n let logBaseline: number;\n let logSavings: number;\n if (actualPayment > 0) {\n logCost = actualPayment;\n // Calculate baseline for savings comparison\n const chargedInputTokens = Math.ceil(body.length / 4);\n const modelDef = BLOCKRUN_MODELS.find((m) => m.id === logModel);\n const chargedOutputTokens = modelDef ? Math.min(maxTokens, modelDef.maxOutput) : maxTokens;\n const baseline = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n chargedOutputTokens,\n routingProfile ?? undefined,\n );\n logBaseline = baseline.baselineCost;\n logSavings = logBaseline > 0 ? Math.max(0, (logBaseline - logCost) / logBaseline) : 0;\n } else {\n // Free model — no payment, calculate locally\n const chargedInputTokens = Math.ceil(body.length / 4);\n const costs = calculateModelCost(\n logModel,\n routerOpts.modelPricing,\n chargedInputTokens,\n maxTokens,\n routingProfile ?? undefined,\n );\n logCost = costs.costEstimate;\n logBaseline = costs.baselineCost;\n logSavings = costs.savings;\n }\n\n const entry: UsageEntry = {\n timestamp: new Date().toISOString(),\n model: logModel,\n tier: routingDecision?.tier ?? \"DIRECT\",\n cost: logCost,\n baselineCost: logBaseline,\n savings: logSavings,\n latencyMs: Date.now() - startTime,\n ...(responseInputTokens !== undefined && { inputTokens: responseInputTokens }),\n ...(responseOutputTokens !== undefined && { outputTokens: responseOutputTokens }),\n };\n logUsage(entry).catch(() => {});\n }\n}\n","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\n}\n","import type {\n Abi,\n AbiParameter,\n AbiParameterToPrimitiveType,\n ExtractAbiEvents,\n} from 'abitype'\n\nimport {\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeEventTopics'\n\nexport type EncodeEventTopicsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n ///\n hasEvents = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiEvents] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >,\n allErrorNames = ContractEventName,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { eventName?: eventName | allErrorNames | undefined }\n : { eventName: eventName | allErrorNames }\n : { eventName?: eventName | allErrorNames | undefined }\n> &\n (hasEvents extends true ? unknown : never)\n\nexport type EncodeEventTopicsReturnType = [Hex, ...(Hex | Hex[] | null)[]]\n\nexport type EncodeEventTopicsErrorType =\n | AbiEventNotFoundErrorType\n | EncodeArgErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nexport function encodeEventTopics<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n>(\n parameters: EncodeEventTopicsParameters,\n): EncodeEventTopicsReturnType {\n const { abi, eventName, args } = parameters as EncodeEventTopicsParameters\n\n let abiItem = abi[0]\n if (eventName) {\n const item = getAbiItem({ abi, name: eventName })\n if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'event')\n throw new AbiEventNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toEventSelector(definition as EventDefinition)\n\n let topics: (Hex | Hex[] | null)[] = []\n if (args && 'inputs' in abiItem) {\n const indexedInputs = abiItem.inputs?.filter(\n (param) => 'indexed' in param && param.indexed,\n )\n const args_ = Array.isArray(args)\n ? args\n : Object.values(args).length > 0\n ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])\n : []\n\n if (args_.length > 0) {\n topics =\n indexedInputs?.map((param, i) => {\n if (Array.isArray(args_[i]))\n return args_[i].map((_: any, j: number) =>\n encodeArg({ param, value: args_[i][j] }),\n )\n return typeof args_[i] !== 'undefined' && args_[i] !== null\n ? encodeArg({ param, value: args_[i] })\n : null\n }) ?? []\n }\n }\n return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | EncodeAbiParametersErrorType\n | FilterTypeNotSupportedErrorType\n | ErrorType\n\nfunction encodeArg({\n param,\n value,\n}: {\n param: AbiParameter\n value: AbiParameterToPrimitiveType\n}) {\n if (param.type === 'string' || param.type === 'bytes')\n return keccak256(toBytes(value as string))\n if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n throw new FilterTypeNotSupportedError(param.type)\n return encodeAbiParameters([param], [value])\n}\n","import { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n constructor(type: string) {\n super(`Filter type \"${type}\" is not supported.`, {\n name: 'FilterTypeNotSupportedError',\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n abi: abi\n eventName?: eventName | ContractEventName | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n * @default false\n */\n strict?: strict | boolean | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (undefined extends eventName\n ? {\n args?: undefined\n }\n : MaybeExtractEventArgsFromAbi extends infer eventFilterArgs\n ? {\n args?:\n | eventFilterArgs\n | (args extends eventFilterArgs ? args : never)\n | undefined\n }\n : {\n args?: undefined\n })\n\nexport type CreateContractEventFilterReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', abi, eventName, args, strict, fromBlock, toBlock>\n\nexport type CreateContractEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const { address, abi, args, eventName, fromBlock, strict, toBlock } =\n parameters as CreateContractEventFilterParameters\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n const topics = eventName\n ? encodeEventTopics({\n abi,\n args,\n eventName,\n } as unknown as EncodeEventTopicsParameters)\n : undefined\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n topics,\n },\n ],\n })\n\n return {\n abi,\n args,\n eventName,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n type: 'event',\n } as unknown as CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn, PublicRpcSchema } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n method:\n | 'eth_newFilter'\n | 'eth_newPendingTransactionFilter'\n | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n PublicRpcSchema,\n { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n id: Hex,\n) => EIP1193RequestFn\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope(\n client: Client,\n { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n const requestMap: Record = {}\n\n if (client.transport.type === 'fallback')\n client.transport.onResponse?.(\n ({\n method: method_,\n response: id,\n status,\n transport,\n }: Parameters[0]) => {\n if (status === 'success' && method === method_)\n requestMap[id as Hex] = transport.request\n },\n )\n\n return ((id) =>\n requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi } 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 type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n GetValue,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from './estimateGas.js'\n\nexport type EstimateContractGasParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n> = ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit, 'data' | 'to' | 'value'> &\n GetValue<\n abi,\n functionName,\n EstimateGasParameters extends EstimateGasParameters\n ? EstimateGasParameters['value']\n : EstimateGasParameters['value']\n > & {\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n }\n\nexport type EstimateContractGasReturnType = bigint\n\nexport type EstimateContractGasErrorType = GetContractErrorReturnType<\n EncodeFunctionDataErrorType | EstimateGasErrorType | ParseAccountErrorType\n>\n\n/**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateContractGas } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await estimateContractGas(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\nexport async function estimateContractGas<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs,\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n parameters: EstimateContractGasParameters,\n): Promise {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...request\n } = parameters as EstimateContractGasParameters\n const data = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n\n try {\n const gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n data: `${data}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...request,\n } as unknown as EstimateGasParameters)\n return gas\n } catch (error) {\n const account = request.account ? parseAccount(request.account) : undefined\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/estimateContractGas',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport { InternalRpcError, InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType = Omit<\n ContractFunctionExecutionErrorType,\n 'cause'\n> & {\n cause:\n | cause\n | ContractFunctionZeroDataErrorType\n | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError>(\n err: err,\n {\n abi,\n address,\n args,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args: any\n address?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const error = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as BaseError\n const { code, data, details, message, shortMessage } =\n error as RawContractError\n\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName })\n if (\n ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || details || message || shortMessage)) ||\n (code === InvalidInputRpcError.code &&\n details === 'execution reverted' &&\n data)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message:\n error instanceof RpcRequestError\n ? details\n : (shortMessage ?? message),\n })\n }\n return err\n })()\n\n return new ContractFunctionExecutionError(cause as BaseError, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n }) as GetContractErrorReturnType\n}\n","import type { Address } from 'abitype'\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 { BaseError } from '../../errors/base.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestParameterType,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n account?: Account | Address | undefined\n prepare?:\n | boolean\n | readonly PrepareTransactionRequestParameterType[]\n | undefined\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 FormattedEstimateGas =\n FormattedTransactionRequest\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\n | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in gas units). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n args: EstimateGasParameters,\n): Promise {\n const { account: account_ = client.account, prepare = true } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n const parameters = (() => {\n if (Array.isArray(prepare)) return prepare\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n if (account?.type !== 'local') return ['blobVersionedHashes']\n return undefined\n })()\n\n try {\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (args.to) return args.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (args.authorizationList && args.authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: args.authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = prepare\n ? ((await prepareTransactionRequest(client, {\n ...args,\n parameters,\n to,\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters)\n : args\n\n // If we get `gas` back from the prepared transaction request, which is\n // different from the `gas` we provided, it was likely filled by other means\n // during request preparation (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n // (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n if (gas && args.gas !== gas) return gas\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\n\n assertRequest(args as AssertRequestParameters)\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest,\n 'estimateGas',\n )\n\n return BigInt(\n await client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [\n request,\n block ?? client.experimental_blockTag ?? 'latest',\n rpcStateOverride,\n ]\n : block\n ? [request, block]\n : [request],\n }),\n )\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise {\n return publicKeyToAddress(await recoverPublicKey({ hash, signature }))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { size } from '../data/size.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n if (size(signatureHex) !== 65) throw new Error('invalid signature length')\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../signature/recoverAddress.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n > = OneOf,\n //\n _signature = Hex | ByteArray | OneOf,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization:\n | authorization\n | OneOf\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n >,\n>(\n parameters: RecoverAuthorizationAddressParameters,\n): Promise {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as AuthorizationRequest),\n signature: (signature ?? authorization) as Signature,\n })\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError 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, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Estimate Gas Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'EstimateGasExecutionError',\n })\n this.cause = cause\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.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 GetEstimateGasErrorReturnType = Omit<\n EstimateGasExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError>(\n err: err,\n {\n docsPath,\n ...args\n }: Omit & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n): GetEstimateGasErrorReturnType {\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 EstimateGasExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetEstimateGasErrorReturnType\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n type EstimateFeesPerGasErrorType,\n internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type GetBlockErrorType,\n getBlock as getBlock_,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetTransactionCountErrorType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { LruMap } from '../../utils/lru.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport {\n type FillTransactionErrorType,\n type FillTransactionParameters,\n fillTransaction,\n} from '../public/fillTransaction.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\n/** @internal */\nexport const eip1559NetworkCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport const supportsFillTransaction = /*#__PURE__*/ new LruMap(128)\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType extends 'legacy'\n ? unknown\n : GetTransactionType,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick)\n>\n\nexport type PrepareTransactionRequestErrorType =\n | AccountNotFoundErrorType\n | AssertRequestErrorType\n | ParseAccountErrorType\n | GetBlockErrorType\n | GetTransactionCountErrorType\n | EstimateGasErrorType\n | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n let request = args as PrepareTransactionRequestParameters\n\n request.account ??= client.account\n request.parameters ??= defaultParameters\n\n const {\n account: account_,\n chain = client.chain,\n nonceManager,\n parameters,\n } = request\n\n const prepareTransactionRequest = (() => {\n if (typeof chain?.prepareTransactionRequest === 'function')\n return {\n fn: chain.prepareTransactionRequest,\n runAt: ['beforeFillTransaction'],\n }\n if (Array.isArray(chain?.prepareTransactionRequest))\n return {\n fn: chain.prepareTransactionRequest[0],\n runAt: chain.prepareTransactionRequest[1].runAt,\n }\n return undefined\n })()\n\n let chainId: number | undefined\n async function getChainId(): Promise {\n if (chainId) return chainId\n if (typeof request.chainId !== 'undefined') return request.chainId\n if (chain) return chain.id\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n const account = account_ ? parseAccount(account_) : account_\n\n let nonce = request.nonce\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n nonceManager\n ) {\n const chainId = await getChainId()\n nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n }\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillTransaction')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillTransaction',\n },\n )\n nonce ??= request.nonce\n }\n\n const attemptFill = (() => {\n // Do not attempt if blobs are provided.\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n request.kzg &&\n request.blobs\n )\n return false\n\n // Do not attempt if `eth_fillTransaction` is not supported.\n if (supportsFillTransaction.get(client.uid) === false) return false\n\n // Should attempt `eth_fillTransaction` if \"fees\" or \"gas\" are required to be populated,\n // otherwise, can just use the other individual calls.\n const shouldAttempt = ['fees', 'gas'].some((parameter) =>\n parameters.includes(parameter as PrepareTransactionRequestParameterType),\n )\n if (!shouldAttempt) return false\n\n // Check if `eth_fillTransaction` needs to be called.\n if (parameters.includes('chainId') && typeof request.chainId !== 'number')\n return true\n if (parameters.includes('nonce') && typeof nonce !== 'number') return true\n if (\n parameters.includes('fees') &&\n typeof request.gasPrice !== 'bigint' &&\n (typeof request.maxFeePerGas !== 'bigint' ||\n typeof (request as any).maxPriorityFeePerGas !== 'bigint')\n )\n return true\n if (parameters.includes('gas') && typeof request.gas !== 'bigint')\n return true\n return false\n })()\n\n const fillResult = attemptFill\n ? await getAction(\n client,\n fillTransaction,\n 'fillTransaction',\n )({ ...request, nonce } as FillTransactionParameters)\n .then((result) => {\n const {\n chainId,\n from,\n gas,\n gasPrice,\n nonce,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n type,\n ...rest\n } = result.transaction\n supportsFillTransaction.set(client.uid, true)\n return {\n ...request,\n ...(from ? { from } : {}),\n ...(type ? { type } : {}),\n ...(typeof chainId !== 'undefined' ? { chainId } : {}),\n ...(typeof gas !== 'undefined' ? { gas } : {}),\n ...(typeof gasPrice !== 'undefined' ? { gasPrice } : {}),\n ...(typeof nonce !== 'undefined' ? { nonce } : {}),\n ...(typeof maxFeePerBlobGas !== 'undefined'\n ? { maxFeePerBlobGas }\n : {}),\n ...(typeof maxFeePerGas !== 'undefined' ? { maxFeePerGas } : {}),\n ...(typeof maxPriorityFeePerGas !== 'undefined'\n ? { maxPriorityFeePerGas }\n : {}),\n ...('nonceKey' in rest && typeof rest.nonceKey !== 'undefined'\n ? { nonceKey: rest.nonceKey }\n : {}),\n }\n })\n .catch((e) => {\n const error = e as FillTransactionErrorType\n\n if (error.name !== 'TransactionExecutionError') return request\n\n const unsupported = error.walk?.((e) => {\n const error = e as BaseError\n return (\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n )\n })\n if (unsupported) supportsFillTransaction.set(client.uid, false)\n\n return request\n })\n : request\n\n nonce ??= fillResult.nonce\n\n request = {\n ...(fillResult as any),\n ...(account ? { from: account?.address } : {}),\n ...(nonce ? { nonce } : {}),\n }\n const { blobs, gas, kzg, type } = request\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillParameters')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillParameters',\n },\n )\n }\n\n let block: Block | undefined\n async function getBlock(): Promise {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n !nonceManager\n )\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n let isEip1559Network = eip1559NetworkCache.get(client.uid)\n if (typeof isEip1559Network === 'undefined') {\n const block = await getBlock()\n isEip1559Network = typeof block?.baseFeePerGas === 'bigint'\n eip1559NetworkCache.set(client.uid, isEip1559Network)\n }\n request.type = isEip1559Network ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof request.maxPriorityFeePerGas === 'undefined' &&\n request.maxFeePerGas &&\n request.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof request.maxFeePerGas !== 'undefined' ||\n typeof request.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n if (typeof request.gasPrice === 'undefined') {\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account,\n prepare: account?.type === 'local' ? [] : ['blobVersionedHashes'],\n } as EstimateGasParameters)\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('afterFillParameters')\n )\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'afterFillParameters',\n },\n )\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\n )\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToBigIntErrorType,\n hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChainParameter\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n | GetBlockErrorType\n | HexToBigIntErrorType\n | RequestErrorType\n | GetBlockErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n): Promise {\n return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args: EstimateMaxPriorityFeePerGasParameters & {\n block?: Block | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\n const maxPriorityFeePerGasHex = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n })\n return hexToBigInt(maxPriorityFeePerGasHex)\n } catch {\n // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n const [block, gasPrice] = await Promise.all([\n block_\n ? Promise.resolve(block_)\n : getAction(client, getBlock, 'getBlock')({}),\n getAction(client, getGasPrice, 'getGasPrice')({}),\n ])\n\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n if (maxPriorityFeePerGas < 0n) return 0n\n return maxPriorityFeePerGas\n }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n }) {\n let identifier = 'Block'\n if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n super(`${identifier} could not be found.`, { name: 'BlockNotFoundError' })\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetBlockErrorType =\n | BlockNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n includeTransactions: includeTransactions_,\n }: GetBlockParameters = {},\n): Promise> {\n const includeTransactions = includeTransactions_ ?? false\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let block: RpcBlock | null = null\n if (blockHash) {\n block = await client.request(\n {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n const format = client.chain?.formatters?.block?.format || formatBlock\n return format(block, 'getBlock')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(\n block: ExactPartial,\n _?: string | undefined,\n) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string') return transaction\n return formatTransaction(transaction)\n })\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { SignedAuthorizationList } from '../../types/authorization.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcAuthorizationList, RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n | 'blockHash'\n | 'blockNumber'\n | 'transactionIndex'\n\nexport type FormattedTransaction<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(\n transaction: ExactPartial,\n _?: string | undefined,\n) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? (transactionType as any)[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n } as Transaction\n\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\n\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity) return Number(transaction.yParity)\n\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n) return 0\n if (transaction_.v === 1n || transaction_.v === 28n) return 1\n if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n }\n\n return undefined\n })()\n\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') delete transaction_.maxFeePerBlobGas\n\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map((authorization) => ({\n address: (authorization as any).address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n })) as SignedAuthorizationList\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const gasPrice = await client.request({\n method: 'eth_gasPrice',\n })\n return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesLegacy,\n FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n type EstimateMaxPriorityFeePerGasErrorType,\n internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n type extends FeeValuesType = FeeValuesType,\n> = {\n /**\n * The type of fee values to return.\n *\n * - `legacy`: Returns the legacy gas price.\n * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n *\n * @default 'eip1559'\n */\n type?: type | FeeValuesType | undefined\n} & GetChainParameter\n\nexport type EstimateFeesPerGasReturnType<\n type extends FeeValuesType = FeeValuesType,\n> =\n | (type extends 'legacy' ? FeeValuesLegacy : never)\n | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n | BaseFeeScalarErrorType\n | EstimateMaxPriorityFeePerGasErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args?: EstimateFeesPerGasParameters | undefined,\n): Promise> {\n return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args: EstimateFeesPerGasParameters & {\n block?: Block | undefined\n request?: PrepareTransactionRequestParameters | undefined\n },\n): Promise> {\n const {\n block: block_,\n chain = client.chain,\n request,\n type = 'eip1559',\n } = args || {}\n\n const baseFeeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n return chain.fees.baseFeeMultiplier({\n block: block_ as Block,\n client,\n request,\n } as ChainFeesFnParameters)\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiply = (base: bigint) =>\n (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n BigInt(denominator)\n\n const block = block_\n ? block_\n : await getAction(client, getBlock, 'getBlock')({})\n\n if (typeof chain?.fees?.estimateFeesPerGas === 'function') {\n const fees = (await chain.fees.estimateFeesPerGas({\n block: block_ as Block,\n client,\n multiply,\n request,\n type,\n } as ChainEstimateFeesPerGasFnParameters)) as unknown as EstimateFeesPerGasReturnType\n\n if (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client,\n {\n block: block as Block,\n chain,\n request,\n },\n )\n\n const baseFeePerGas = multiply(block.baseFeePerGas)\n const maxFeePerGas =\n request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as EstimateFeesPerGasReturnType\n }\n\n const gasPrice =\n request?.gasPrice ??\n multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n return {\n gasPrice,\n } as EstimateFeesPerGasReturnType\n}\n","import type { Address } from 'abitype'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { BaseFeeScalarError } from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport { getBlock } from './getBlock.js'\nimport { getChainId as getChainId_ } from './getChainId.js'\n\nexport type FillTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetAccountParameter &\n GetChainParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n }\n\nexport type FillTransactionReturnType<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = {\n raw: Hex\n transaction: FormattedTransaction<_derivedChain>\n}\n\nexport type FillTransactionErrorType =\n | GetTransactionErrorReturnType\n | ErrorType\n\n/**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { fillTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await fillTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function fillTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n): Promise> {\n const {\n account = client.account,\n accessList,\n authorizationList,\n chain = client.chain,\n blobVersionedHashes,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce: nonce_,\n nonceManager,\n to,\n type,\n value,\n ...rest\n } = parameters\n\n const nonce = await (async () => {\n if (!account) return nonce_\n if (!nonceManager) return nonce_\n if (typeof nonce_ !== 'undefined') return nonce_\n const account_ = parseAccount(account)\n const chainId = chain\n ? chain.id\n : await getAction(client, getChainId_, 'getChainId')({})\n return await nonceManager.consume({\n address: account_.address,\n chainId,\n client,\n })\n })()\n\n assertRequest(parameters)\n\n const chainFormat = chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account: account ? parseAccount(account) : undefined,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'fillTransaction',\n )\n\n try {\n const response = await client.request({\n method: 'eth_fillTransaction',\n params: [request],\n })\n const format = chain?.formatters?.transaction?.format || formatTransaction\n\n const transaction = format(response.tx)\n\n // Remove unnecessary fields.\n delete transaction.blockHash\n delete transaction.blockNumber\n delete transaction.r\n delete transaction.s\n delete transaction.transactionIndex\n delete transaction.v\n delete transaction.yParity\n\n // Rewrite fields.\n transaction.data = transaction.input\n\n // Preference supplied fees (some nodes do not take these preferences).\n if (transaction.gas) transaction.gas = parameters.gas ?? transaction.gas\n if (transaction.gasPrice)\n transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice\n if (transaction.maxFeePerBlobGas)\n transaction.maxFeePerBlobGas =\n parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas\n if (transaction.maxFeePerGas)\n transaction.maxFeePerGas =\n parameters.maxFeePerGas ?? transaction.maxFeePerGas\n if (transaction.maxPriorityFeePerGas)\n transaction.maxPriorityFeePerGas =\n parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas\n if (transaction.nonce)\n transaction.nonce = parameters.nonce ?? transaction.nonce\n\n // Build fee multiplier function.\n const feeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function') {\n const block = await getAction(client, getBlock, 'getBlock')({})\n return chain.fees.baseFeeMultiplier({\n block,\n client,\n request: parameters,\n } as ChainFeesFnParameters)\n }\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (feeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = feeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiplyFee = (base: bigint) =>\n (base * BigInt(Math.ceil(feeMultiplier * denominator))) /\n BigInt(denominator)\n\n // Apply fee multiplier.\n if (transaction.maxFeePerGas && !parameters.maxFeePerGas)\n transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas)\n if (transaction.gasPrice && !parameters.gasPrice)\n transaction.gasPrice = multiplyFee(transaction.gasPrice)\n\n return {\n raw: response.raw,\n transaction: {\n from: request.from,\n ...transaction,\n },\n }\n } catch (err) {\n throw getTransactionError(\n err as BaseError,\n {\n ...parameters,\n chain: client.chain,\n } as never,\n )\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport {\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n} from '../../errors/transaction.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 GetTransactionErrorParameters = Omit<\n SendTransactionParameters,\n 'account' | 'chain'\n> & {\n account: Account | null\n chain?: Chain | undefined\n docsPath?: string | undefined\n}\n\nexport type GetTransactionErrorReturnType = Omit<\n TransactionExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getTransactionError>(\n err: err,\n { docsPath, ...args }: GetTransactionErrorParameters,\n): GetTransactionErrorReturnType {\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 TransactionExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetTransactionErrorReturnType\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type GetLogsErrorType,\n type GetLogsParameters,\n getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n)\n\nexport type GetContractEventsReturnType<\n abi extends Abi | readonly unknown[] = readonly unknown[],\n eventName extends ContractEventName | undefined =\n | ContractEventName\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n ///\n isPending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetContractEventsErrorType =\n | GetAbiItemErrorType\n | GetLogsErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/contract/getContractEvents#getcontractevents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n parameters: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetContractEventsReturnType\n> {\n const {\n abi,\n address,\n args,\n blockHash,\n eventName,\n fromBlock,\n toBlock,\n strict,\n } = parameters\n const event = eventName\n ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n : undefined\n const events = !event\n ? (abi as Abi).filter((x) => x.type === 'event')\n : undefined\n return getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n blockHash,\n event,\n events,\n fromBlock,\n toBlock,\n strict,\n } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","// TODO(v3): checksum address.\n\nimport type { Abi, AbiEvent, AbiEventParameter, Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractEventName, GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport { toBytes } from '../encoding/toBytes.js'\nimport { formatLog } from '../formatters/log.js'\nimport { keccak256 } from '../hash/keccak256.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type DecodeEventLogErrorType,\n decodeEventLog,\n} from './decodeEventLog.js'\n\nexport type ParseEventLogsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n allArgs = GetEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n {\n EnableUnion: true\n IndexedOnly: false\n Required: false\n }\n >,\n> = {\n /** Contract ABI. */\n abi: abi\n /** Arguments for the event. */\n args?: allArgs | undefined\n /** Contract event. */\n eventName?:\n | eventName\n | ContractEventName\n | ContractEventName[]\n | undefined\n /** List of logs. */\n logs: (Log | RpcLog)[]\n strict?: strict | boolean | undefined\n}\n\nexport type ParseEventLogsReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = ContractEventName,\n strict extends boolean | undefined = boolean | undefined,\n ///\n derivedEventName extends\n | ContractEventName\n | undefined = eventName extends ContractEventName[]\n ? eventName[number]\n : eventName,\n> = Log[]\n\nexport type ParseEventLogsErrorType = DecodeEventLogErrorType | ErrorType\n\n/**\n * Extracts & decodes logs matching the provided signature(s) (`abi` + optional `eventName`)\n * from a set of opaque logs.\n *\n * @param parameters - {@link ParseEventLogsParameters}\n * @returns The logs. {@link ParseEventLogsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { parseEventLogs } from 'viem/op-stack'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const receipt = await getTransactionReceipt(client, {\n * hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea',\n * })\n *\n * const logs = parseEventLogs({ logs: receipt.logs })\n * // [{ args: { ... }, eventName: 'TransactionDeposited', ... }, ...]\n */\nexport function parseEventLogs<\n abi extends Abi | readonly unknown[],\n strict extends boolean | undefined = true,\n eventName extends\n | ContractEventName\n | ContractEventName[]\n | undefined = undefined,\n>(\n parameters: ParseEventLogsParameters,\n): ParseEventLogsReturnType {\n const { abi, args, logs, strict = true } = parameters\n\n const eventName = (() => {\n if (!parameters.eventName) return undefined\n if (Array.isArray(parameters.eventName)) return parameters.eventName\n return [parameters.eventName as string]\n })()\n\n const abiTopics = (abi as Abi)\n .filter((abiItem) => abiItem.type === 'event')\n .map((abiItem) => ({\n abi: abiItem,\n selector: toEventSelector(abiItem),\n }))\n\n return logs\n .map((log) => {\n // Normalize RpcLog (hex-encoded quantities) to Log (bigint/number).\n // When logs come directly from an RPC response (e.g. eth_getLogs),\n // fields like blockNumber are hex strings instead of bigints.\n const formattedLog =\n typeof log.blockNumber === 'string' ? formatLog(log as RpcLog) : log\n\n // Find all matching ABI items with the same selector.\n // Multiple events can share the same selector but differ in indexed parameters\n // (e.g., ERC20 vs ERC721 Transfer events).\n const abiItems = abiTopics.filter(\n (abiTopic) => formattedLog.topics[0] === abiTopic.selector,\n )\n if (abiItems.length === 0) return null\n\n // Try each matching ABI item until one successfully decodes.\n let event: { eventName: string; args: unknown } | undefined\n let abiItem: { abi: AbiEvent; selector: Address } | undefined\n\n for (const item of abiItems) {\n try {\n event = decodeEventLog({\n ...formattedLog,\n abi: [item.abi],\n strict: true,\n })\n abiItem = item\n break\n } catch {\n // Try next ABI item\n }\n }\n\n // If strict decoding failed for all, and we're in non-strict mode,\n // fall back to the first matching ABI item.\n if (!event && !strict) {\n abiItem = abiItems[0]\n try {\n event = decodeEventLog({\n data: formattedLog.data,\n topics: formattedLog.topics,\n abi: [abiItem.abi],\n strict: false,\n })\n } catch {\n // If decoding still fails, return partial log in non-strict mode.\n const isUnnamed = abiItem.abi.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n return {\n ...formattedLog,\n args: isUnnamed ? [] : {},\n eventName: abiItem.abi.name,\n }\n }\n }\n\n // If no event was found, return null.\n if (!event || !abiItem) return null\n\n // Check that the decoded event name matches the provided event name.\n if (eventName && !eventName.includes(event.eventName)) return null\n\n // Check that the decoded event args match the provided args.\n if (\n !includesArgs({\n args: event.args,\n inputs: abiItem.abi.inputs,\n matchArgs: args,\n })\n )\n return null\n\n return { ...event, ...formattedLog }\n })\n .filter(Boolean) as unknown as ParseEventLogsReturnType<\n abi,\n eventName,\n strict\n >\n}\n\nfunction includesArgs(parameters: {\n args: unknown\n inputs: AbiEvent['inputs']\n matchArgs: unknown\n}) {\n const { args, inputs, matchArgs } = parameters\n\n if (!matchArgs) return true\n if (!args) return false\n\n function isEqual(input: AbiEventParameter, value: unknown, arg: unknown) {\n try {\n if (input.type === 'address')\n return isAddressEqual(value as Address, arg as Address)\n if (input.type === 'string' || input.type === 'bytes')\n return keccak256(toBytes(value as string)) === arg\n return value === arg\n } catch {\n return false\n }\n }\n\n if (Array.isArray(args) && Array.isArray(matchArgs)) {\n return matchArgs.every((value, index) => {\n if (value === null || value === undefined) return true\n const input = inputs[index]\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) => isEqual(input, value, args[index]))\n })\n }\n\n if (\n typeof args === 'object' &&\n !Array.isArray(args) &&\n typeof matchArgs === 'object' &&\n !Array.isArray(matchArgs)\n )\n return Object.entries(matchArgs).every(([key, value]) => {\n if (value === null || value === undefined) return true\n const input = inputs.find((input) => input.name === key)\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) =>\n isEqual(input, value, (args as Record)[key]),\n )\n })\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n blockTimestamp: log.blockTimestamp\n ? BigInt(log.blockTimestamp)\n : log.blockTimestamp === null\n ? null\n : undefined,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n } as Log\n}\n","import type { Abi, AbiParameter } from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgsFromTopics,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n Prettify,\n UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n> = {\n abi: abi\n data?: data | undefined\n eventName?: eventName | ContractEventName | undefined\n strict?: strict | boolean | undefined\n topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n ///\n allEventNames extends\n ContractEventName = eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n> = IsNarrowable extends true\n ? {\n [name in allEventNames]: Prettify<\n {\n eventName: name\n } & UnionEvaluate<\n ContractEventArgsFromTopics extends infer allArgs\n ? topics extends readonly []\n ? data extends undefined\n ? { args?: undefined }\n : { args?: allArgs | undefined }\n : { args: allArgs }\n : never\n >\n >\n }[allEventNames]\n : {\n eventName: eventName\n args: readonly unknown[] | undefined\n }\n\nexport type DecodeEventLogErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiEventSignatureEmptyTopicsErrorType\n | AbiEventSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | DecodeLogTopicsMismatchErrorType\n | DecodeLogDataMismatchErrorType\n | FormatAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n>(\n parameters: DecodeEventLogParameters,\n): DecodeEventLogReturnType {\n const {\n abi,\n data,\n strict: strict_,\n topics,\n } = parameters as DecodeEventLogParameters\n\n const strict = strict_ ?? true\n const [signature, ...argTopics] = topics\n if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n const abiItem = abi.find(\n (x) =>\n x.type === 'event' &&\n signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n )\n\n if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n const { name, inputs } = abiItem\n const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n const args: any = isUnnamed ? [] : {}\n\n // Decode topics (indexed args).\n const indexedInputs = inputs\n .map((x, i) => [x, i] as const)\n .filter(([x]) => 'indexed' in x && x.indexed)\n\n const missingIndexedInputs: [AbiParameter, number][] = []\n\n for (let i = 0; i < indexedInputs.length; i++) {\n const [param, argIndex] = indexedInputs[i]\n const topic = argTopics[i]\n if (!topic) {\n if (strict)\n throw new DecodeLogTopicsMismatch({\n abiItem,\n param: param as AbiParameter & { indexed: boolean },\n })\n // Track missing indexed inputs to decode from data when strict is false\n missingIndexedInputs.push([param, argIndex])\n continue\n }\n args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({\n param,\n value: topic,\n })\n }\n\n // Decode data (non-indexed args + missing indexed args when strict is false).\n const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n\n // When strict is false, missing indexed inputs should be decoded from data\n const inputsToDecode = strict\n ? nonIndexedInputs\n : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]\n\n if (inputsToDecode.length > 0) {\n if (data && data !== '0x') {\n try {\n const decodedData = decodeAbiParameters(\n inputsToDecode,\n data,\n ) as unknown[]\n if (decodedData) {\n let dataIndex = 0\n // First, assign missing indexed parameters (when strict is false)\n if (!strict) {\n for (const [param, argIndex] of missingIndexedInputs) {\n args[isUnnamed ? argIndex : param.name || argIndex] =\n decodedData[dataIndex++]\n }\n }\n // Then, assign non-indexed parameters\n if (isUnnamed) {\n for (let i = 0; i < inputs.length; i++)\n if (args[i] === undefined && dataIndex < decodedData.length)\n args[i] = decodedData[dataIndex++]\n } else\n for (let i = 0; i < nonIndexedInputs.length; i++)\n args[nonIndexedInputs[i].name!] = decodedData[dataIndex++]\n }\n } catch (err) {\n if (strict) {\n if (\n err instanceof AbiDecodingDataSizeTooSmallError ||\n err instanceof PositionOutOfBoundsError\n )\n throw new DecodeLogDataMismatch({\n abiItem,\n data: data,\n params: inputsToDecode,\n size: size(data),\n })\n throw err\n }\n }\n } else if (strict) {\n throw new DecodeLogDataMismatch({\n abiItem,\n data: '0x',\n params: inputsToDecode,\n size: 0,\n })\n }\n }\n\n return {\n eventName: name,\n args: Object.values(args).length > 0 ? args : undefined,\n } as unknown as DecodeEventLogReturnType\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n if (\n param.type === 'string' ||\n param.type === 'bytes' ||\n param.type === 'tuple' ||\n param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n )\n return value\n const decodedArg = decodeAbiParameters([param], value) || []\n return decodedArg[0]\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** Address or list of addresses from which logs originated */\n address?: Address | Address[] | undefined\n} & (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events: abiEvents\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n) &\n (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n )\n\nexport type GetLogsReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetLogsErrorType =\n | DecodeEventLogErrorType\n | EncodeEventTopicsErrorType\n | FormatLogErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client,\n {\n address,\n blockHash,\n fromBlock,\n toBlock,\n event,\n events: events_,\n args,\n strict: strict_,\n }: GetLogsParameters = {},\n): Promise> {\n const strict = strict_ ?? false\n const events = events_ ?? (event ? [event] : undefined)\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args: events_ ? undefined : args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n let logs: RpcLog[]\n if (blockHash) {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [{ address, topics, blockHash }],\n })\n } else {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [\n {\n address,\n topics,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n },\n ],\n })\n }\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!events)\n return formattedLogs as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: events,\n args: args as any,\n logs: formattedLogs,\n strict,\n }) as unknown as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = ContractFunctionReturnType\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n>(\n client: Client,\n parameters: ReadContractParameters,\n): Promise> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { Abi, AbiFunction, AbiStateMutability, Address } from 'abitype'\n\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 type { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, ParseAccount } from '../../types/account.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n ExtractAbiFunctionForArgs,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type {\n IsNarrowable,\n NoInfer,\n Prettify,\n UnionEvaluate,\n UnionOmit,\n} from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { WriteContractParameters } from '../wallet/writeContract.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type GetMutabilityAwareValue<\n abi extends Abi | readonly unknown[],\n mutability extends AbiStateMutability = AbiStateMutability,\n functionName extends ContractFunctionName<\n abi,\n mutability\n > = ContractFunctionName,\n valueType = TransactionRequest['value'],\n args extends ContractFunctionArgs<\n abi,\n mutability,\n functionName\n > = ContractFunctionArgs,\n abiFunction extends AbiFunction = abi extends Abi\n ? ExtractAbiFunctionForArgs\n : AbiFunction,\n _Narrowable extends boolean = IsNarrowable,\n> = _Narrowable extends true\n ? abiFunction['stateMutability'] extends 'payable'\n ? { value?: NoInfer | undefined }\n : abiFunction['payable'] extends true\n ? { value?: NoInfer | undefined }\n : { value?: undefined }\n : { value?: NoInfer | undefined }\n\nexport type SimulateContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n ///\n derivedChain extends Chain | undefined = DeriveChain,\n callParameters extends\n CallParameters = CallParameters,\n> = {\n account?: accountOverride | null | undefined\n chain?: chainOverride | undefined\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n} & ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit<\n callParameters,\n | 'account'\n | 'batch'\n | 'code'\n | 'to'\n | 'data'\n | 'factory'\n | 'factoryData'\n | 'value'\n > &\n GetMutabilityAwareValue<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n callParameters['value'],\n args\n >\n\nexport type SimulateContractReturnType<\n out abi extends Abi | readonly unknown[] = Abi,\n in out functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName,\n in out args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs,\n /** @ts-expect-error cast variance */\n out chain extends Chain | undefined = Chain | undefined,\n out account extends Account | undefined = Account | undefined,\n out chainOverride extends Chain | undefined = Chain | undefined,\n out accountOverride extends Account | Address | null | undefined =\n | Account\n | Address\n | null\n | undefined,\n ///\n in out minimizedAbi extends Abi = readonly [\n ExtractAbiFunctionForArgs<\n abi extends Abi ? abi : Abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >,\n ],\n out resolvedAccount extends\n | Account\n | null\n | undefined = accountOverride extends Account | Address | null\n ? ParseAccount\n : account,\n> = {\n result: ContractFunctionReturnType<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >\n request: Prettify<\n UnionEvaluate<\n UnionOmit<\n WriteContractParameters<\n minimizedAbi,\n functionName,\n args,\n chain,\n undefined,\n chainOverride\n >,\n 'account' | 'abi' | 'args' | 'chain' | 'functionName'\n >\n > &\n ContractFunctionParameters<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n > & {\n chain: DeriveChain\n } & (resolvedAccount extends Account | null\n ? { account: resolvedAccount }\n : { account?: undefined })\n >\n}\n\nexport type SimulateContractErrorType =\n | ParseAccountErrorType\n | EncodeFunctionDataErrorType\n | GetContractErrorReturnType\n | ErrorType\n\n/**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await simulateContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function simulateContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n): Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n> {\n const {\n abi,\n address,\n args,\n functionName,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n ...callRequest\n } = parameters as SimulateContractParameters\n\n const account = callRequest.account\n ? parseAccount(callRequest.account)\n : client.account\n const calldata = encodeFunctionData({ abi, args, functionName })\n\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n batch: false,\n data: `${calldata}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...callRequest,\n account,\n })\n const result = decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n })\n const minimizedAbi = abi.filter(\n (abiItem) =>\n 'name' in abiItem && abiItem.name === parameters.functionName,\n )\n return {\n result,\n request: {\n abi: minimizedAbi,\n address,\n args,\n dataSuffix,\n functionName,\n ...callRequest,\n account,\n },\n } as unknown as SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/simulateContract',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport { createContractEventFilter } from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n type GetContractEventsParameters,\n getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchContractEventOnLogsParameter<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = abi extends Abi\n ? Abi extends abi\n ? Log[]\n : Log, strict>[]\n : Log[]\n\nexport type WatchContractEventOnLogsFn<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName = ContractEventName,\n strict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter) => void\n\nexport type WatchContractEventParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName | undefined = ContractEventName,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchContractEventOnLogsFn<\n abi,\n eventName extends ContractEventName\n ? eventName\n : ContractEventName,\n strict\n >\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & GetPollOptions\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n>(\n client: Client,\n parameters: WatchContractEventParameters,\n): WatchContractEventReturnType {\n const {\n abi,\n address,\n args,\n batch = true,\n eventName,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n } = parameters\n\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n const pollContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abi, eventName> | undefined\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createContractEventFilter,\n 'createContractEventFilter',\n )({\n abi,\n address,\n args: args as any,\n eventName: eventName as any,\n strict: strict as any,\n fromBlock,\n })) as Filter<'event', abi, eventName>\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber < blockNumber) {\n logs = await getAction(\n client,\n getContractEvents,\n 'getContractEvents',\n )({\n abi,\n address,\n args,\n eventName,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n strict,\n } as {} as GetContractEventsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n ])\n\n let active = true\n let unsubscribe = () => (active = false)\n return observe(observerId, { onLogs, onError }, (emit) => {\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const topics: LogTopic[] = eventName\n ? encodeEventTopics({\n abi: abi,\n eventName: eventName,\n args,\n } as EncodeEventTopicsParameters)\n : []\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: abi,\n data: log.data,\n topics: log.topics as any,\n strict: strict_,\n })\n const formatted = formatLog(log, {\n args,\n eventName: eventName as string,\n })\n emit.onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n emit.onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollContractEvent() : subscribeContractEvent()\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record\n\nexport type ObserveErrorType = ErrorType\n\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map<\n string,\n () => void | Promise\n>()\n\ntype EmitFunction = (\n emit: callbacks,\n) => MaybePromise void) | (() => Promise)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction,\n) {\n const callbackId = ++callbackCount\n\n const getListeners = () => listenersCache.get(observerId) || []\n\n const unsubscribe = () => {\n const listeners = getListeners()\n listenersCache.set(\n observerId,\n listeners.filter((cb: any) => cb.id !== callbackId),\n )\n }\n\n const unwatch = () => {\n const listeners = getListeners()\n if (!listeners.some((cb: any) => cb.id === callbackId)) return\n const cleanup = cleanupCache.get(observerId)\n if (listeners.length === 1 && cleanup) {\n const p = cleanup()\n if (p instanceof Promise) p.catch(() => {})\n }\n unsubscribe()\n }\n\n const listeners = getListeners()\n listenersCache.set(observerId, [\n ...listeners,\n { id: callbackId, fns: callbacks },\n ])\n\n if (listeners && listeners.length > 0) return unwatch\n\n const emit: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract]\n }\n\n const cleanup = fn(emit)\n if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n return unwatch\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise) | undefined\n // The interval (in ms).\n interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise,\n { emitOnBegin, initialWaitTime, interval }: PollOptions,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | undefined | void\n if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n const initialWait = (await initialWaitTime?.(data)) ?? interval\n await wait(initialWait)\n\n const poll = async () => {\n if (!active) return\n await fn({ unpoll: unwatch })\n await wait(interval)\n poll()\n }\n\n poll()\n }\n watch()\n\n return unwatch\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache(cacheKey: string) {\n const buildCache = (cacheKey: string, cache: Map) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype WithCacheParameters = {\n /** The key to cache the data against. */\n cacheKey: string\n /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n cacheTime?: number | undefined\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache(\n fn: () => Promise,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache(cacheKey)\n\n // If a response exists in the cache, and it's not expired, return it\n // and do not invoke the promise.\n // If the max age is 0, the cache is disabled.\n const response = cache.response.get()\n if (response && cacheTime > 0) {\n const age = Date.now() - response.created.getTime()\n if (age < cacheTime) return response.data\n }\n\n let promise = cache.promise.get()\n if (!promise) {\n promise = fn()\n\n // Store the promise in the cache so that subsequent invocations\n // will wait for the same promise to resolve (deduping).\n cache.promise.set(promise)\n }\n\n try {\n const data = await promise\n\n // Store the response in the cache so that subsequent invocations\n // will return the same response.\n cache.response.set({ created: new Date(), data })\n\n return data\n } finally {\n // Clear the promise cache so that subsequent invocations will\n // invoke the promise again.\n cache.promise.clear()\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\nexport function getBlockNumberCache(id: string) {\n return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber(\n client: Client,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcLog } from '../../index.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter\n}\n\nexport type GetFilterChangesReturnType<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = filterType extends 'event'\n ? Log[]\n : Hash[]\n\nexport type GetFilterChangesErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n transport extends Transport,\n chain extends Chain | undefined,\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const strict = 'strict' in filter && filter.strict\n\n const logs = await filter.request({\n method: 'eth_getFilterChanges',\n params: [filter.id],\n })\n\n if (typeof logs[0] === 'string')\n return logs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n\n const formattedLogs = logs.map((log) => formatLog(log as RpcLog))\n if (!('abi' in filter) || !filter.abi)\n return formattedLogs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n filter: Filter\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n _client: Client,\n { filter }: UninstallFilterParameters,\n): Promise {\n return filter.request({\n method: 'eth_uninstallFilter',\n params: [filter.id],\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction(\n client: Client,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry(\n fn: () => Promise,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial,\n _?: string | undefined,\n) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[\n transactionReceipt.type as keyof typeof transactionType\n ] || transactionReceipt.type\n : null,\n } as TransactionReceipt\n\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { DataSuffix } from '../types/dataSuffix.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify | undefined\n }\n | undefined\n /**\n * Default block tag to use for RPC requests.\n *\n * If the chain supports a pre-confirmation mechanism\n * (set via `chain.experimental_preconfirmationTime`), defaults to `'pending'`.\n *\n * @default 'latest'\n */\n experimental_blockTag?: BlockTag | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default chain.blockTime / 3\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default chain.blockTime / 3\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial>,\n >(\n fn: (\n client: Client,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** Default block tag to use for RPC requests. */\n experimental_blockTag?: BlockTag | undefined\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType['config'] & ReturnType['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n chain,\n ccipRead,\n dataSuffix,\n key = 'base',\n name = 'Base Client',\n type = 'base',\n } = parameters\n\n const experimental_blockTag =\n parameters.experimental_blockTag ??\n (typeof chain?.experimental_preconfirmationTime === 'number'\n ? 'pending'\n : undefined)\n const blockTime = chain?.blockTime ?? 12_000\n\n const defaultPollingInterval = Math.min(\n Math.max(Math.floor(blockTime / 2), 500),\n 4_000,\n )\n const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval\n const cacheTime = parameters.cacheTime ?? pollingInterval\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n account,\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n dataSuffix,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n ...(experimental_blockTag ? { experimental_blockTag } : {}),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema(): rpcSchema {\n return null as any\n}\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n addressResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n Pick & {\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS address for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Name to get the address for.\n */\n name: string\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n | GetChainContractAddressErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | DecodeFunctionResultErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress(\n client: Client,\n parameters: GetEnsAddressParameters,\n): Promise {\n const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } =\n parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n const args = (() => {\n if (coinType != null) return [namehash(name), BigInt(coinType)] as const\n return [namehash(name)] as const\n })()\n\n try {\n const functionData = encodeFunctionData({\n abi: addressResolverAbi,\n functionName: 'addr',\n args,\n })\n\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolveWithGateways',\n args: [\n toHex(packetToBytes(name)),\n functionData,\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const address = decodeFunctionResult({\n abi: addressResolverAbi,\n args,\n functionName: 'addr',\n data: res[0],\n })\n\n if (address === '0x') return null\n if (trim(address) === '0x00') return null\n return address\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(err: unknown): boolean {\n if (!(err instanceof BaseError)) return false\n const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (!(cause instanceof ContractFunctionRevertedError)) return false\n\n if (cause.data?.errorName === 'HttpError') return true\n if (cause.data?.errorName === 'ResolverError') return true\n if (cause.data?.errorName === 'ResolverNotContract') return true\n if (cause.data?.errorName === 'ResolverNotFound') return true\n if (cause.data?.errorName === 'ReverseAddressMismatch') return true\n if (cause.data?.errorName === 'UnsupportedResolverProfile') return true\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n type ToBytesErrorType,\n toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | ToBytesErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ConcatErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0x08c85f2f4059e930c45a6aeff9dcd3bd95dc3c5c1cddef6a0626b31152248560'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n let result = new Uint8Array(32).fill(0) as ByteArray\n if (!name) return bytesToHex(result)\n\n const labels = name.split('.')\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n const hashed = hashFromEncodedLabel\n ? toBytes(hashFromEncodedLabel)\n : keccak256(stringToBytes(labels[i]), 'bytes')\n result = keccak256(concat([result, hashed]), 'bytes')\n }\n\n return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n if (label.length !== 66) return null\n if (label.indexOf('[') !== 0) return null\n if (label.indexOf(']') !== 65) return null\n const hash = `0x${label.slice(1, 65)}`\n if (!isHex(hash)) return null\n return hash\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n type EncodeLabelhashErrorType,\n encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n | EncodeLabelhashErrorType\n | LabelhashErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n *\n * @example\n * packetToBytes('awkweb.eth')\n * '0x0661776b7765620365746800'\n *\n * @see https://docs.ens.domains/resolution/names#dns\n *\n */\nexport function packetToBytes(packet: string): ByteArray {\n // strip leading and trailing `.`\n const value = packet.replace(/^\\.|\\.$/gm, '')\n if (value.length === 0) return new Uint8Array(1)\n\n const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n let offset = 0\n const list = value.split('.')\n for (let i = 0; i < list.length; i++) {\n let encoded = stringToBytes(list[i])\n // if the length is > 255, make the encoded label value a labelhash\n // this is compatible with the universal resolver\n if (encoded.byteLength > 255)\n encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n bytes[offset] = encoded.length\n bytes.set(encoded, offset + 1)\n offset += encoded.length + 1\n }\n\n if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n return bytes\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n const result = new Uint8Array(32).fill(0)\n if (!label) return bytesToHex(result)\n return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","import { BaseError } from './base.js'\n\nexport type EnsAvatarInvalidMetadataErrorType =\n EnsAvatarInvalidMetadataError & {\n name: 'EnsAvatarInvalidMetadataError'\n }\nexport class EnsAvatarInvalidMetadataError extends BaseError {\n constructor({ data }: { data: any }) {\n super(\n 'Unable to extract image from metadata. The metadata may be malformed or invalid.',\n {\n metaMessages: [\n '- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.',\n '',\n `Provided data: ${JSON.stringify(data)}`,\n ],\n name: 'EnsAvatarInvalidMetadataError',\n },\n )\n }\n}\n\nexport type EnsAvatarInvalidNftUriErrorType = EnsAvatarInvalidNftUriError & {\n name: 'EnsAvatarInvalidNftUriError'\n}\nexport class EnsAvatarInvalidNftUriError extends BaseError {\n constructor({ reason }: { reason: string }) {\n super(`ENS NFT avatar URI is invalid. ${reason}`, {\n name: 'EnsAvatarInvalidNftUriError',\n })\n }\n}\n\nexport type EnsAvatarUriResolutionErrorType = EnsAvatarUriResolutionError & {\n name: 'EnsAvatarUriResolutionError'\n}\nexport class EnsAvatarUriResolutionError extends BaseError {\n constructor({ uri }: { uri: string }) {\n super(\n `Unable to resolve ENS avatar URI \"${uri}\". The URI may be malformed, invalid, or does not respond with a valid image.`,\n { name: 'EnsAvatarUriResolutionError' },\n )\n }\n}\n\nexport type EnsAvatarUnsupportedNamespaceErrorType =\n EnsAvatarUnsupportedNamespaceError & {\n name: 'EnsAvatarUnsupportedNamespaceError'\n }\nexport class EnsAvatarUnsupportedNamespaceError extends BaseError {\n constructor({ namespace }: { namespace: string }) {\n super(\n `ENS NFT avatar namespace \"${namespace}\" is not supported. Must be \"erc721\" or \"erc1155\".`,\n { name: 'EnsAvatarUnsupportedNamespaceError' },\n )\n }\n}\n\nexport type EnsInvalidChainIdErrorType = EnsInvalidChainIdError & {\n name: 'EnsInvalidChainIdError'\n}\nexport class EnsInvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId: number }) {\n super(\n `Invalid ENSIP-11 chainId: ${chainId}. Must be between 0 and 0x7fffffff, or 1.`,\n {\n name: 'EnsInvalidChainIdError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n type ReadContractErrorType,\n readContract,\n} from '../../../actions/public/readContract.js'\nimport type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport {\n EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n} from '../../../errors/ens.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\ntype UriItem = {\n uri: string\n isOnChain: boolean\n isEncoded: boolean\n}\n\nconst networkRegex =\n /(?https?:\\/\\/[^/]*|ipfs:\\/|ipns:\\/|ar:\\/)?(?\\/)?(?ipfs\\/|ipns\\/)?(?[\\w\\-.]+)(?\\/.*)?/\nconst ipfsHashRegex =\n /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\\/(?[\\w\\-.]+))?(?\\/.*)?$/\nconst base64Regex = /^data:([a-zA-Z\\-/+]*);base64,([^\"].*)/\nconst dataURIRegex = /^data:([a-zA-Z\\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/\n\ntype IsImageUriErrorType = ErrorType\n\n/** @internal */\nexport async function isImageUri(uri: string) {\n try {\n const res = await fetch(uri, { method: 'HEAD' })\n // retrieve content type header to check if content is image\n if (res.status === 200) {\n const contentType = res.headers.get('content-type')\n return contentType?.startsWith('image/')\n }\n return false\n } catch (error: any) {\n // if error is not cors related then fail\n if (typeof error === 'object' && typeof error.response !== 'undefined') {\n return false\n }\n // fail in NodeJS, since the error is not cors but any other network issue\n if (!Object.hasOwn(globalThis, 'Image')) return false\n // in case of cors, use image api to validate if given url is an actual image\n return new Promise((resolve) => {\n const img = new Image()\n img.onload = () => {\n resolve(true)\n }\n img.onerror = () => {\n resolve(false)\n }\n img.src = uri\n })\n }\n}\n\ntype GetGatewayErrorType = ErrorType\n\n/** @internal */\nexport function getGateway(custom: string | undefined, defaultGateway: string) {\n if (!custom) return defaultGateway\n if (custom.endsWith('/')) return custom.slice(0, -1)\n return custom\n}\n\nexport type ResolveAvatarUriErrorType =\n | GetGatewayErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport function resolveAvatarUri({\n uri,\n gatewayUrls,\n}: {\n uri: string\n gatewayUrls?: AssetGatewayUrls | undefined\n}): UriItem {\n const isEncoded = base64Regex.test(uri)\n if (isEncoded) return { uri, isOnChain: true, isEncoded }\n\n const ipfsGateway = getGateway(gatewayUrls?.ipfs, 'https://ipfs.io')\n const arweaveGateway = getGateway(gatewayUrls?.arweave, 'https://arweave.net')\n\n const networkRegexMatch = uri.match(networkRegex)\n const {\n protocol,\n subpath,\n target,\n subtarget = '',\n } = networkRegexMatch?.groups || {}\n\n const isIPNS = protocol === 'ipns:/' || subpath === 'ipns/'\n const isIPFS =\n protocol === 'ipfs:/' || subpath === 'ipfs/' || ipfsHashRegex.test(uri)\n\n if (uri.startsWith('http') && !isIPNS && !isIPFS) {\n let replacedUri = uri\n if (gatewayUrls?.arweave)\n replacedUri = uri.replace(/https:\\/\\/arweave.net/g, gatewayUrls?.arweave)\n return { uri: replacedUri, isOnChain: false, isEncoded: false }\n }\n\n if ((isIPNS || isIPFS) && target) {\n return {\n uri: `${ipfsGateway}/${isIPNS ? 'ipns' : 'ipfs'}/${target}${subtarget}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n if (protocol === 'ar:/' && target) {\n return {\n uri: `${arweaveGateway}/${target}${subtarget || ''}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n let parsedUri = uri.replace(dataURIRegex, '')\n if (parsedUri.startsWith(' {\n try {\n const res = await fetch(uri).then((res) => res.json())\n const image = await parseAvatarUri({\n gatewayUrls,\n uri: getJsonImage(res),\n })\n return image\n } catch {\n throw new EnsAvatarUriResolutionError({ uri })\n }\n}\n\nexport type ParseAvatarUriErrorType =\n | ResolveAvatarUriErrorType\n | IsImageUriErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport async function parseAvatarUri({\n gatewayUrls,\n uri,\n}: {\n gatewayUrls?: AssetGatewayUrls | undefined\n uri: string\n}): Promise {\n const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls })\n if (isOnChain) return resolvedURI\n\n // check if resolvedURI is an image, if it is return the url\n const isImage = await isImageUri(resolvedURI)\n if (isImage) return resolvedURI\n\n throw new EnsAvatarUriResolutionError({ uri })\n}\n\ntype ParsedNft = {\n chainID: number\n namespace: string\n contractAddress: Address\n tokenID: string\n}\n\nexport type ParseNftUriErrorType = EnsAvatarInvalidNftUriErrorType | ErrorType\n\nexport function parseNftUri(uri_: string): ParsedNft {\n let uri = uri_\n // parse valid nft spec (CAIP-22/CAIP-29)\n // @see: https://github.com/ChainAgnostic/CAIPs/tree/master/CAIPs\n if (uri.startsWith('did:nft:')) {\n // convert DID to CAIP\n uri = uri.replace('did:nft:', '').replace(/_/g, '/')\n }\n\n const [reference, asset_namespace, tokenID] = uri.split('/')\n const [eip_namespace, chainID] = reference.split(':')\n const [erc_namespace, contractAddress] = asset_namespace.split(':')\n\n if (!eip_namespace || eip_namespace.toLowerCase() !== 'eip155')\n throw new EnsAvatarInvalidNftUriError({ reason: 'Only EIP-155 supported' })\n if (!chainID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Chain ID not found' })\n if (!contractAddress)\n throw new EnsAvatarInvalidNftUriError({\n reason: 'Contract address not found',\n })\n if (!tokenID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Token ID not found' })\n if (!erc_namespace)\n throw new EnsAvatarInvalidNftUriError({ reason: 'ERC namespace not found' })\n\n return {\n chainID: Number.parseInt(chainID, 10),\n namespace: erc_namespace.toLowerCase(),\n contractAddress: contractAddress as Address,\n tokenID,\n }\n}\n\nexport type GetNftTokenUriErrorType =\n | ReadContractErrorType\n | EnsAvatarUnsupportedNamespaceErrorType\n | ErrorType\n\nexport async function getNftTokenUri(\n client: Client,\n { nft }: { nft: ParsedNft },\n) {\n if (nft.namespace === 'erc721') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'tokenURI',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'tokenURI',\n args: [BigInt(nft.tokenID)],\n })\n }\n if (nft.namespace === 'erc1155') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'uri',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: '_id', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'uri',\n args: [BigInt(nft.tokenID)],\n })\n }\n throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace })\n}\n","import type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\nimport {\n type GetJsonImageErrorType,\n type GetMetadataAvatarUriErrorType,\n type GetNftTokenUriErrorType,\n getJsonImage,\n getMetadataAvatarUri,\n getNftTokenUri,\n type ParseAvatarUriErrorType,\n type ParseNftUriErrorType,\n parseAvatarUri,\n parseNftUri,\n type ResolveAvatarUriErrorType,\n resolveAvatarUri,\n} from './utils.js'\n\nexport type ParseAvatarRecordErrorType =\n | ParseNftAvatarUriErrorType\n | ParseAvatarUriErrorType\n | ErrorType\n\n/*\n * @description Parses an ENS avatar record.\n *\n * @example\n * parseAvatarRecord('eip155:1/erc1155:0xb32979486938aa9694bfc898f35dbed459f44424/10063')\n * 'https://ipfs.io/ipfs/QmSP4nq9fnN9dAiCj42ug9Wa79rqmQerZXZch82VqpiH7U/image.gif'\n *\n * @see https://docs.ens.domains/web/avatars\n *\n */\nexport async function parseAvatarRecord(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n if (/eip155:/i.test(record))\n return parseNftAvatarUri(client, { gatewayUrls, record })\n return parseAvatarUri({ uri: record, gatewayUrls })\n}\n\ntype ParseNftAvatarUriErrorType =\n | ParseNftUriErrorType\n | GetNftTokenUriErrorType\n | ResolveAvatarUriErrorType\n | ParseAvatarUriErrorType\n | GetJsonImageErrorType\n | GetMetadataAvatarUriErrorType\n | ErrorType\n\nasync function parseNftAvatarUri(\n client: Client,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise {\n // parse NFT URI into properties\n const nft = parseNftUri(record)\n // fetch tokenURI from the NFT contract\n const nftUri = await getNftTokenUri(client, { nft })\n // resolve the URI from the fetched tokenURI\n const {\n uri: resolvedNftUri,\n isOnChain,\n isEncoded,\n } = resolveAvatarUri({ uri: nftUri, gatewayUrls })\n\n // if the resolved URI is on chain, return the data\n if (\n isOnChain &&\n (resolvedNftUri.includes('data:application/json;base64,') ||\n resolvedNftUri.startsWith('{'))\n ) {\n const encodedJson = isEncoded\n ? // if it is encoded, decode it\n atob(resolvedNftUri.replace('data:application/json;base64,', ''))\n : // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)\n resolvedNftUri\n\n const decoded = JSON.parse(encodedJson)\n return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls })\n }\n\n let uriTokenId = nft.tokenID\n if (nft.namespace === 'erc1155')\n uriTokenId = uriTokenId.replace('0x', '').padStart(64, '0')\n\n return getMetadataAvatarUri({\n gatewayUrls,\n uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId),\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n textResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsTextParameters = Prettify<\n Pick & {\n /** ENS name to get Text for. */\n name: string\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Text record to retrieve. */\n key: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsTextReturnType = string | null\n\nexport type GetEnsTextErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | DecodeFunctionResultErrorType\n\n/**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsText, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await getEnsText(client, {\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\nexport async function getEnsText(\n client: Client,\n parameters: GetEnsTextParameters,\n): Promise {\n const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld))) return null\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n args: [\n toHex(packetToBytes(name)),\n encodeFunctionData({\n abi: textResolverAbi,\n functionName: 'text',\n args: [namehash(name), key],\n }),\n gatewayUrls ?? [localBatchGatewayUrl],\n ],\n functionName: 'resolveWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const record = decodeFunctionResult({\n abi: textResolverAbi,\n functionName: 'text',\n data: res[0],\n })\n\n return record === '' ? null : record\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../types/ens.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type ParseAvatarRecordErrorType,\n parseAvatarRecord,\n} from '../../utils/ens/avatar/parseAvatarRecord.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetEnsTextErrorType,\n type GetEnsTextParameters,\n getEnsText,\n} from './getEnsText.js'\n\nexport type GetEnsAvatarParameters = Prettify<\n Omit & {\n /** Gateway urls to resolve IPFS and/or Arweave assets. */\n assetGatewayUrls?: AssetGatewayUrls | undefined\n }\n>\n\nexport type GetEnsAvatarReturnType = string | null\n\nexport type GetEnsAvatarErrorType =\n | GetEnsTextErrorType\n | ParseAvatarRecordErrorType\n | ErrorType\n\n/**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAvatar, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await getEnsAvatar(client, {\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\nexport async function getEnsAvatar(\n client: Client,\n {\n blockNumber,\n blockTag,\n assetGatewayUrls,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress,\n }: GetEnsAvatarParameters,\n): Promise {\n const record = await getAction(\n client,\n getEnsText,\n 'getEnsText',\n )({\n blockNumber,\n blockTag,\n key: 'avatar',\n name,\n universalResolverAddress,\n gatewayUrls,\n strict,\n })\n if (!record) return null\n try {\n return await parseAvatarRecord(client, {\n record,\n gatewayUrls: assetGatewayUrls,\n })\n } catch {\n return null\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalResolverReverseAbi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js'\nimport type { PacketToBytesErrorType } from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsNameParameters = Prettify<\n Pick & {\n /**\n * Address to get ENS name for.\n */\n address: Address\n /**\n * ENSIP-9 compliant coinType (chain) to get ENS name for.\n *\n * To get the `coinType` for a chain id, use the `toCoinType` function:\n * ```ts\n * import { toCoinType } from 'viem'\n * import { base } from 'viem/chains'\n *\n * const coinType = toCoinType(base.id)\n * ```\n *\n * @default 60n\n */\n coinType?: bigint | undefined\n /**\n * Universal Resolver gateway URLs to use for resolving CCIP-read requests.\n */\n gatewayUrls?: string[] | undefined\n /**\n * Whether or not to throw errors propagated from the ENS Universal Resolver Contract.\n */\n strict?: boolean | undefined\n /**\n * Address of ENS Universal Resolver Contract.\n */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsNameReturnType = string | null\n\nexport type GetEnsNameErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName(\n client: Client,\n parameters: GetEnsNameParameters,\n): Promise {\n const {\n address,\n blockNumber,\n blockTag,\n coinType = 60n,\n gatewayUrls,\n strict,\n } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverReverseAbi,\n args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]],\n functionName: 'reverseWithGateways',\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const [name] = await readContractAction(readContractParameters)\n\n return name || null\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err)) return null\n throw err\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsResolverParameters = Prettify<\n Pick & {\n /** Name to get the address for. */\n name: string\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsResolverReturnType = Address\n\nexport type GetEnsResolverErrorType =\n | GetChainContractAddressErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsResolver, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await getEnsResolver(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\nexport async function getEnsResolver(\n client: Client,\n parameters: GetEnsResolverParameters,\n): Promise {\n const { blockNumber, blockTag, name } = parameters\n const { chain } = client\n\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress\n if (!chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n })\n })()\n\n const tlds = chain?.ensTlds\n if (tlds && !tlds.some((tld) => name.endsWith(tld)))\n throw new Error(\n `${name} is not a valid ENS TLD (${tlds?.join(', ')}) for chain \"${chain.name}\" (id: ${chain.id}).`,\n )\n\n const [resolverAddress] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address: universalResolverAddress,\n abi: [\n {\n inputs: [{ type: 'bytes' }],\n name: 'findResolver',\n outputs: [\n { type: 'address' },\n { type: 'bytes32' },\n { type: 'uint256' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ],\n functionName: 'findResolver',\n args: [toHex(packetToBytes(name))],\n blockNumber,\n blockTag,\n })\n return resolverAddress\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport {\n type GetEnsAddressParameters,\n type GetEnsAddressReturnType,\n getEnsAddress,\n} from '../../actions/ens/getEnsAddress.js'\nimport {\n type GetEnsAvatarParameters,\n type GetEnsAvatarReturnType,\n getEnsAvatar,\n} from '../../actions/ens/getEnsAvatar.js'\nimport {\n type GetEnsNameParameters,\n type GetEnsNameReturnType,\n getEnsName,\n} from '../../actions/ens/getEnsName.js'\nimport {\n type GetEnsResolverParameters,\n type GetEnsResolverReturnType,\n getEnsResolver,\n} from '../../actions/ens/getEnsResolver.js'\nimport {\n type GetEnsTextParameters,\n type GetEnsTextReturnType,\n getEnsText,\n} from '../../actions/ens/getEnsText.js'\nimport {\n type CallParameters,\n type CallReturnType,\n call,\n} from '../../actions/public/call.js'\nimport {\n type CreateAccessListParameters,\n type CreateAccessListReturnType,\n createAccessList,\n} from '../../actions/public/createAccessList.js'\nimport {\n type CreateBlockFilterReturnType,\n createBlockFilter,\n} from '../../actions/public/createBlockFilter.js'\nimport {\n type CreateContractEventFilterParameters,\n type CreateContractEventFilterReturnType,\n createContractEventFilter,\n} from '../../actions/public/createContractEventFilter.js'\nimport {\n type CreateEventFilterParameters,\n type CreateEventFilterReturnType,\n createEventFilter,\n} from '../../actions/public/createEventFilter.js'\nimport {\n type CreatePendingTransactionFilterReturnType,\n createPendingTransactionFilter,\n} from '../../actions/public/createPendingTransactionFilter.js'\nimport {\n type EstimateContractGasParameters,\n type EstimateContractGasReturnType,\n estimateContractGas,\n} from '../../actions/public/estimateContractGas.js'\nimport {\n type EstimateFeesPerGasParameters,\n type EstimateFeesPerGasReturnType,\n estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasParameters,\n type EstimateGasReturnType,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type EstimateMaxPriorityFeePerGasParameters,\n type EstimateMaxPriorityFeePerGasReturnType,\n estimateMaxPriorityFeePerGas,\n} from '../../actions/public/estimateMaxPriorityFeePerGas.js'\nimport {\n type FillTransactionParameters,\n type FillTransactionReturnType,\n fillTransaction,\n} from '../../actions/public/fillTransaction.js'\nimport {\n type GetBalanceParameters,\n type GetBalanceReturnType,\n getBalance,\n} from '../../actions/public/getBalance.js'\nimport {\n type GetBlobBaseFeeReturnType,\n getBlobBaseFee,\n} from '../../actions/public/getBlobBaseFee.js'\nimport {\n type GetBlockParameters,\n type GetBlockReturnType,\n getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetBlockNumberParameters,\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from '../../actions/public/getBlockNumber.js'\nimport {\n type GetBlockTransactionCountParameters,\n type GetBlockTransactionCountReturnType,\n getBlockTransactionCount,\n} from '../../actions/public/getBlockTransactionCount.js'\nimport {\n type GetChainIdReturnType,\n getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n type GetCodeParameters,\n type GetCodeReturnType,\n getCode,\n} from '../../actions/public/getCode.js'\nimport {\n type GetContractEventsParameters,\n type GetContractEventsReturnType,\n getContractEvents,\n} from '../../actions/public/getContractEvents.js'\nimport {\n type GetDelegationParameters,\n type GetDelegationReturnType,\n getDelegation,\n} from '../../actions/public/getDelegation.js'\nimport {\n type GetEip712DomainParameters,\n type GetEip712DomainReturnType,\n getEip712Domain,\n} from '../../actions/public/getEip712Domain.js'\nimport {\n type GetFeeHistoryParameters,\n type GetFeeHistoryReturnType,\n getFeeHistory,\n} from '../../actions/public/getFeeHistory.js'\nimport {\n type GetFilterChangesParameters,\n type GetFilterChangesReturnType,\n getFilterChanges,\n} from '../../actions/public/getFilterChanges.js'\nimport {\n type GetFilterLogsParameters,\n type GetFilterLogsReturnType,\n getFilterLogs,\n} from '../../actions/public/getFilterLogs.js'\nimport {\n type GetGasPriceReturnType,\n getGasPrice,\n} from '../../actions/public/getGasPrice.js'\nimport {\n type GetLogsParameters,\n type GetLogsReturnType,\n getLogs,\n} from '../../actions/public/getLogs.js'\nimport {\n type GetProofParameters,\n type GetProofReturnType,\n getProof,\n} from '../../actions/public/getProof.js'\nimport {\n type GetStorageAtParameters,\n type GetStorageAtReturnType,\n getStorageAt,\n} from '../../actions/public/getStorageAt.js'\nimport {\n type GetTransactionParameters,\n type GetTransactionReturnType,\n getTransaction,\n} from '../../actions/public/getTransaction.js'\nimport {\n type GetTransactionConfirmationsParameters,\n type GetTransactionConfirmationsReturnType,\n getTransactionConfirmations,\n} from '../../actions/public/getTransactionConfirmations.js'\nimport {\n type GetTransactionCountParameters,\n type GetTransactionCountReturnType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport {\n type GetTransactionReceiptParameters,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from '../../actions/public/getTransactionReceipt.js'\nimport {\n type MulticallParameters,\n type MulticallReturnType,\n multicall,\n} from '../../actions/public/multicall.js'\nimport {\n type ReadContractParameters,\n type ReadContractReturnType,\n readContract,\n} from '../../actions/public/readContract.js'\nimport {\n type SimulateBlocksParameters,\n type SimulateBlocksReturnType,\n simulateBlocks,\n} from '../../actions/public/simulateBlocks.js'\nimport {\n type SimulateCallsParameters,\n type SimulateCallsReturnType,\n simulateCalls,\n} from '../../actions/public/simulateCalls.js'\nimport {\n type SimulateContractParameters,\n type SimulateContractReturnType,\n simulateContract,\n} from '../../actions/public/simulateContract.js'\nimport {\n type UninstallFilterParameters,\n type UninstallFilterReturnType,\n uninstallFilter,\n} from '../../actions/public/uninstallFilter.js'\nimport {\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from '../../actions/public/verifyHash.js'\nimport {\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from '../../actions/public/verifyMessage.js'\nimport {\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from '../../actions/public/verifyTypedData.js'\nimport {\n type WaitForTransactionReceiptParameters,\n type WaitForTransactionReceiptReturnType,\n waitForTransactionReceipt,\n} from '../../actions/public/waitForTransactionReceipt.js'\nimport {\n type WatchBlockNumberParameters,\n type WatchBlockNumberReturnType,\n watchBlockNumber,\n} from '../../actions/public/watchBlockNumber.js'\nimport {\n type WatchBlocksParameters,\n type WatchBlocksReturnType,\n watchBlocks,\n} from '../../actions/public/watchBlocks.js'\nimport {\n type WatchContractEventParameters,\n type WatchContractEventReturnType,\n watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n type WatchEventParameters,\n type WatchEventReturnType,\n watchEvent,\n} from '../../actions/public/watchEvent.js'\nimport {\n type WatchPendingTransactionsParameters,\n type WatchPendingTransactionsReturnType,\n watchPendingTransactions,\n} from '../../actions/public/watchPendingTransactions.js'\nimport {\n type VerifySiweMessageParameters,\n type VerifySiweMessageReturnType,\n verifySiweMessage,\n} from '../../actions/siwe/verifySiweMessage.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\n type PrepareTransactionRequestReturnType,\n prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n type SendRawTransactionSyncParameters,\n type SendRawTransactionSyncReturnType,\n sendRawTransactionSync,\n} from '../../actions/wallet/sendRawTransactionSync.js'\nimport type { Account } from '../../types/account.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { FeeValuesType } from '../../types/fee.js'\nimport type { FilterType } from '../../types/filter.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type PublicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\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 args - {@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 *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await client.call({\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n call: (parameters: CallParameters) => Promise\n /**\n * Creates an EIP-2930 access list that you can include in a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param args - {@link CreateAccessListParameters}\n * @returns The call data. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const data = await client.createAccessList({\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n createAccessList: (\n parameters: CreateAccessListParameters,\n ) => Promise\n /**\n * Creates a Filter to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @returns Filter. {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, createBlockFilter, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\n createBlockFilter: () => Promise\n /**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param args - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\n createContractEventFilter: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined,\n args extends MaybeExtractEventArgsFromAbi | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param args - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\n createEventFilter: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _EventName extends string | undefined = MaybeAbiEventName,\n _Args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n >(\n args?:\n | CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n | undefined,\n ) => Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n >\n /**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\n createPendingTransactionFilter: () => Promise\n /**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * @remarks\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await client.estimateContractGas({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\n estimateContractGas: <\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n >(\n args: EstimateContractGasParameters,\n ) => Promise\n /**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param args - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await client.estimateGas({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n estimateGas: (\n args: EstimateGasParameters,\n ) => Promise\n /**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.fillTransaction({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n fillTransaction: <\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n ) => Promise>\n /**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * @remarks\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param args - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await client.getBalance({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\n getBalance: (args: GetBalanceParameters) => Promise\n /**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await client.getBlobBaseFee()\n */\n getBlobBaseFee: () => Promise\n /**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getBlock()\n */\n getBlock: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args?: GetBlockParameters | undefined,\n ) => Promise>\n /**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param args - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await client.getBlockNumber()\n * // 69420n\n */\n getBlockNumber: (\n args?: GetBlockNumberParameters | undefined,\n ) => Promise\n /**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await client.getBlockTransactionCount()\n */\n getBlockTransactionCount: (\n args?: GetBlockTransactionCountParameters | undefined,\n ) => Promise\n /** @deprecated Use `getCode` instead. */\n getBytecode: (args: GetCodeParameters) => Promise\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await client.getChainId()\n * // 1\n */\n getChainId: () => Promise\n /**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param args - {@link GetBytecodeParameters}\n * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getCode({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\n getCode: (args: GetCodeParameters) => Promise\n /**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/actions/public/getContractEvents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { wagmiAbi } from './abi'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\n getContractEvents: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetContractEventsReturnType\n >\n /**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param args - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await client.getDelegation({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getDelegation: (\n args: GetDelegationParameters,\n ) => Promise\n /**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await client.getEip712Domain({\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\n getEip712Domain: (\n args: GetEip712DomainParameters,\n ) => Promise\n /**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await client.getEnsAddress({\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\n getEnsAddress: (\n args: GetEnsAddressParameters,\n ) => Promise\n /**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await client.getEnsAvatar({\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\n getEnsAvatar: (\n args: GetEnsAvatarParameters,\n ) => Promise\n /**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param args - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await client.getEnsName({\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\n getEnsName: (args: GetEnsNameParameters) => Promise\n /**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await client.getEnsResolver({\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\n getEnsResolver: (\n args: GetEnsResolverParameters,\n ) => Promise\n /**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await client.getEnsText({\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\n getEnsText: (args: GetEnsTextParameters) => Promise\n /**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param args - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await client.getFeeHistory({\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\n getFeeHistory: (\n args: GetFeeHistoryParameters,\n ) => Promise\n /**\n * Returns an estimate for the fees per gas for a transaction to be included\n * in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateFeesPerGas()\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\n estimateFeesPerGas: <\n chainOverride extends Chain | undefined = undefined,\n type extends FeeValuesType = 'eip1559',\n >(\n args?: EstimateFeesPerGasParameters | undefined,\n ) => Promise>\n /**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * @remarks\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param args - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createBlockFilter()\n * const hashes = await client.getFilterChanges({ filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * const hashes = await client.getFilterChanges({ filter })\n */\n getFilterChanges: <\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * @remarks\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param args - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterLogs({ filter })\n */\n getFilterLogs: <\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterLogsParameters,\n ) => Promise<\n GetFilterLogsReturnType\n >\n /**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await client.getGasPrice()\n */\n getGasPrice: () => Promise\n /**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param args - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getLogs()\n */\n getLogs: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args?:\n | GetLogsParameters\n | undefined,\n ) => Promise<\n GetLogsReturnType\n >\n /**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getProof({\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\n getProof: (args: GetProofParameters) => Promise\n /**\n * Returns an estimate for the max priority fee per gas (in wei) for a transaction\n * to be included in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()\n * // 10000000n\n */\n estimateMaxPriorityFeePerGas: <\n chainOverride extends Chain | undefined = undefined,\n >(\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n ) => Promise\n /**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param args - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getStorageAt({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\n getStorageAt: (\n args: GetStorageAtParameters,\n ) => Promise\n /**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param args - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await client.getTransaction({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransaction: (\n args: GetTransactionParameters,\n ) => Promise>\n /**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param args - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await client.getTransactionConfirmations({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionConfirmations: (\n args: GetTransactionConfirmationsParameters,\n ) => Promise\n /**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has broadcast / sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param args - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await client.getTransactionCount({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getTransactionCount: (\n args: GetTransactionCountParameters,\n ) => Promise\n /**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt)\n *\n * @param args - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.getTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionReceipt: (\n args: GetTransactionReceiptParameters,\n ) => Promise>\n /**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param args - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const result = await client.multicall({\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\n multicall: <\n const contracts extends readonly unknown[],\n allowFailure extends boolean = true,\n >(\n args: MulticallParameters,\n ) => Promise>\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\n prepareTransactionRequest: <\n const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * @remarks\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.readContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\n readContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n >(\n args: ReadContractParameters,\n ) => Promise>\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await client.sendRawTransaction({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransaction: (\n args: SendRawTransactionParameters,\n ) => Promise\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionSyncParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await client.sendRawTransactionSync({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransactionSync: (\n args: SendRawTransactionSyncParameters,\n ) => Promise>\n /**\n * @deprecated Use `simulateBlocks` instead.\n */\n simulate: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateBlocks({\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateParameters}\n * @returns Simulated blocks. {@link SimulateReturnType}\n */\n simulateBlocks: (\n args: SimulateBlocksParameters,\n ) => Promise>\n /**\n * Simulates a set of calls.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateCalls({\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n */\n simulateCalls: (\n args: SimulateCallsParameters,\n ) => Promise>\n /**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * @remarks\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.simulateContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n simulateContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n ) => Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n >\n /**\n * Verify that a hash was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyHash}\n *\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\n verifyHash: (args: VerifyHashParameters) => Promise\n /**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\n verifyMessage: (\n args: VerifyMessageParameters,\n ) => Promise\n /**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\n verifySiweMessage: (\n args: VerifySiweMessageParameters,\n ) => Promise\n /**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\n verifyTypedData: (\n args: VerifyTypedDataParameters,\n ) => Promise\n /**\n * Destroys a Filter that was created from one of the following Actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * @param args - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await client.createPendingTransactionFilter()\n * const uninstalled = await client.uninstallFilter({ filter })\n * // true\n */\n uninstallFilter: (\n args: UninstallFilterParameters,\n ) => Promise\n /**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * @remarks\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param args - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.waitForTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n waitForTransactionReceipt: (\n args: WaitForTransactionReceiptParameters,\n ) => Promise>\n /**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlockNumber({\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\n watchBlockNumber: (\n args: WatchBlockNumberParameters,\n ) => WatchBlockNumberReturnType\n /**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlocks({\n * onBlock: (block) => console.log(block),\n * })\n */\n watchBlocks: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args: WatchBlocksParameters<\n transport,\n chain,\n includeTransactions,\n blockTag\n >,\n ) => WatchBlocksReturnType\n /**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * @remarks\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchContractEvent({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchContractEvent: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchContractEventParameters,\n ) => WatchContractEventReturnType\n /**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * @remarks\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchEvent({\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchEvent: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchEventParameters,\n ) => WatchEventReturnType\n /**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * @remarks\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param args - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchPendingTransactions({\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\n watchPendingTransactions: (\n args: WatchPendingTransactionsParameters,\n ) => WatchPendingTransactionsReturnType\n}\n\nexport function publicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(\n client: Client,\n): PublicActions {\n return {\n call: (args) => call(client, args),\n createAccessList: (args) => createAccessList(client, args),\n createBlockFilter: () => createBlockFilter(client),\n createContractEventFilter: (args) =>\n createContractEventFilter(client, args),\n createEventFilter: (args) => createEventFilter(client, args),\n createPendingTransactionFilter: () =>\n createPendingTransactionFilter(client),\n estimateContractGas: (args) => estimateContractGas(client, args as any),\n estimateGas: (args) => estimateGas(client, args),\n getBalance: (args) => getBalance(client, args),\n getBlobBaseFee: () => getBlobBaseFee(client),\n getBlock: (args) => getBlock(client, args),\n getBlockNumber: (args) => getBlockNumber(client, args),\n getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),\n getBytecode: (args) => getCode(client, args),\n getChainId: () => getChainId(client),\n getCode: (args) => getCode(client, args),\n getContractEvents: (args) => getContractEvents(client, args),\n getDelegation: (args) => getDelegation(client, args),\n getEip712Domain: (args) => getEip712Domain(client, args),\n getEnsAddress: (args) => getEnsAddress(client, args),\n getEnsAvatar: (args) => getEnsAvatar(client, args),\n getEnsName: (args) => getEnsName(client, args),\n getEnsResolver: (args) => getEnsResolver(client, args),\n getEnsText: (args) => getEnsText(client, args),\n getFeeHistory: (args) => getFeeHistory(client, args),\n estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),\n getFilterChanges: (args) => getFilterChanges(client, args),\n getFilterLogs: (args) => getFilterLogs(client, args),\n getGasPrice: () => getGasPrice(client),\n getLogs: (args) => getLogs(client, args as any),\n getProof: (args) => getProof(client, args),\n estimateMaxPriorityFeePerGas: (args) =>\n estimateMaxPriorityFeePerGas(client, args),\n fillTransaction: (args) => fillTransaction(client, args),\n getStorageAt: (args) => getStorageAt(client, args),\n getTransaction: (args) => getTransaction(client, args),\n getTransactionConfirmations: (args) =>\n getTransactionConfirmations(client, args),\n getTransactionCount: (args) => getTransactionCount(client, args),\n getTransactionReceipt: (args) => getTransactionReceipt(client, args),\n multicall: (args) => multicall(client, args),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n readContract: (args) => readContract(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n sendRawTransactionSync: (args) => sendRawTransactionSync(client, args),\n simulate: (args) => simulateBlocks(client, args),\n simulateBlocks: (args) => simulateBlocks(client, args),\n simulateCalls: (args) => simulateCalls(client, args),\n simulateContract: (args) => simulateContract(client, args),\n verifyHash: (args) => verifyHash(client, args),\n verifyMessage: (args) => verifyMessage(client, args),\n verifySiweMessage: (args) => verifySiweMessage(client, args),\n verifyTypedData: (args) => verifyTypedData(client, args),\n uninstallFilter: (args) => uninstallFilter(client, args),\n waitForTransactionReceipt: (args) =>\n waitForTransactionReceipt(client, args),\n watchBlocks: (args) => watchBlocks(client, args),\n watchBlockNumber: (args) => watchBlockNumber(client, args),\n watchContractEvent: (args) => watchContractEvent(client, args),\n watchEvent: (args) => watchEvent(client, args),\n watchPendingTransactions: (args) => watchPendingTransactions(client, args),\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { AccessList, TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, Prettify, UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.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 type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\n\nexport type CreateAccessListParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n FormattedTransactionRequest,\n 'from' | 'nonce' | 'accessList'\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | 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 )\n\nexport type CreateAccessListReturnType = Prettify<{\n accessList: AccessList\n gasUsed: bigint\n}>\n\nexport type CreateAccessListErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | RequestErrorType\n>\n\n/**\n * Creates an EIP-2930 access list.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param client - Client to use\n * @param parameters - {@link CreateAccessListParameters}\n * @returns The access list. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createAccessList } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await createAccessList(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function createAccessList(\n client: Client,\n args: CreateAccessListParameters,\n): Promise {\n const {\n account: account_ = client.account,\n blockNumber,\n blockTag = 'latest',\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n } as TransactionRequest,\n 'createAccessList',\n ) as TransactionRequest\n\n const response = await client.request({\n method: 'eth_createAccessList',\n params: [request as ExactPartial, block],\n })\n return {\n accessList: response.accessList,\n gasUsed: BigInt(response.gasUsed),\n }\n } catch (err) {\n throw getCallError(err as ErrorType, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateBlockFilterReturnType = Filter<'block'>\n\nexport type CreateBlockFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\nexport async function createBlockFilter(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newBlockFilter',\n })\n const id = await client.request({\n method: 'eth_newBlockFilter',\n })\n return { id, request: getRequest(id), type: 'block' }\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex, LogTopic } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateEventFilterParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (MaybeExtractEventArgsFromAbi<\n abiEvents,\n _eventName\n> extends infer eventFilterArgs\n ?\n | {\n args:\n | eventFilterArgs\n | (_args extends eventFilterArgs ? _args : never)\n event: abiEvent\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: abiEvent | undefined\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events: abiEvents | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n }\n : {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n })\n\nexport type CreateEventFilterReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n> = Prettify<\n Filter<'event', abiEvents, _eventName, _args, strict, fromBlock, toBlock>\n>\n\nexport type CreateEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param client - Client to use\n * @param parameters - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\nexport async function createEventFilter<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName,\n _args extends\n | MaybeExtractEventArgsFromAbi\n | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n event,\n events: events_,\n fromBlock,\n strict,\n toBlock,\n }: CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n > = {} as any,\n): Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n> {\n const events = events_ ?? (event ? [event] : undefined)\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n ...(topics.length ? { topics } : {}),\n },\n ],\n })\n\n return {\n abi: events,\n args,\n eventName: event ? (event as AbiEvent).name : undefined,\n fromBlock,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n toBlock,\n type: 'event',\n } as unknown as CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreatePendingTransactionFilterReturnType = Filter<'transaction'>\n\nexport type CreatePendingTransactionFilterErrorType =\n | RequestErrorType\n | ErrorType\n\n/**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\nexport async function createPendingTransactionFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n): Promise {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newPendingTransactionFilter',\n })\n const id = await client.request({\n method: 'eth_newPendingTransactionFilter',\n })\n return { id, request: getRequest(id), type: 'transaction' }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport { decodeFunctionResult } from '../../utils/abi/decodeFunctionResult.js'\nimport { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type CallParameters, call } from './call.js'\n\nexport type GetBalanceParameters = {\n /** The address of the account. */\n address: Address\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 /** The balance of the account at a block tag. */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance(\n client: Client,\n {\n address,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n }: GetBalanceParameters,\n): Promise {\n if (client.batch?.multicall && client.chain?.contracts?.multicall3) {\n const multicall3Address = client.chain.contracts.multicall3.address\n\n const calldata = encodeFunctionData({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n })\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n to: multicall3Address,\n data: calldata,\n blockNumber,\n blockTag,\n } as unknown as CallParameters)\n\n return decodeFunctionResult({\n abi: multicall3Abi,\n functionName: 'getEthBalance',\n args: [address],\n data: data || '0x',\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n\n const balance = await client.request({\n method: 'eth_getBalance',\n params: [address, blockNumberHex || blockTag],\n })\n return BigInt(balance)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetBlobBaseFeeReturnType = bigint\n\nexport type GetBlobBaseFeeErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await getBlobBaseFee(client)\n */\nexport async function getBlobBaseFee<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n): Promise {\n const baseFee = await client.request({\n method: 'eth_blobBaseFee',\n })\n return BigInt(baseFee)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Quantity } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBlockTransactionCountParameters =\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n\nexport type GetBlockTransactionCountReturnType = number\n\nexport type GetBlockTransactionCountErrorType =\n | NumberToHexErrorType\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await getBlockTransactionCount(client)\n */\nexport async function getBlockTransactionCount(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag = 'latest',\n }: GetBlockTransactionCountParameters = {},\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let count: Quantity\n if (blockHash) {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByHash',\n params: [blockHash],\n },\n { dedupe: true },\n )\n } else {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByNumber',\n params: [blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n return hexToNumber(count)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetCodeParameters = {\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetCodeReturnType = Hex | undefined\n\nexport type GetCodeErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetCodeParameters}\n * @returns The contract's bytecode. {@link GetCodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCode } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getCode(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getCode(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetCodeParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const hex = await client.request(\n {\n method: 'eth_getCode',\n params: [address, blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n if (hex === '0x') return undefined\n return hex\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport { type SizeErrorType, size } from '../../utils/data/size.js'\nimport { type SliceErrorType, slice } from '../../utils/data/slice.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\n\nexport type GetDelegationParameters = {\n /** The address to check for delegation. */\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetDelegationReturnType = Address | undefined\n\nexport type GetDelegationErrorType =\n | GetAddressErrorType\n | GetCodeErrorType\n | SliceErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Returns the address that an account has delegated to via EIP-7702.\n *\n * - Docs: https://viem.sh/docs/actions/public/getDelegation\n *\n * @param client - Client to use\n * @param parameters - {@link GetDelegationParameters}\n * @returns The delegated address, or undefined if not delegated. {@link GetDelegationReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getDelegation } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const delegation = await getDelegation(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getDelegation(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetDelegationParameters,\n): Promise {\n const code = await getCode(client, {\n address,\n ...(blockNumber !== undefined ? { blockNumber } : { blockTag }),\n } as GetDelegationParameters)\n\n if (!code) return undefined\n\n // EIP-7702 delegation designator: 0xef0100 prefix (3 bytes) + address (20 bytes) = 23 bytes\n if (size(code) !== 23) return undefined\n\n // Check for EIP-7702 delegation designator prefix\n if (!code.startsWith('0xef0100')) return undefined\n\n // Extract the delegated address (bytes 3-23) and checksum it\n return getAddress(slice(code, 3, 23))\n}\n","import type { Address } from 'abitype'\nimport { BaseError } from './base.js'\n\nexport type Eip712DomainNotFoundErrorType = Eip712DomainNotFoundError & {\n name: 'Eip712DomainNotFoundError'\n}\nexport class Eip712DomainNotFoundError extends BaseError {\n constructor({ address }: { address: Address }) {\n super(`No EIP-712 domain found on contract \"${address}\".`, {\n metaMessages: [\n 'Ensure that:',\n `- The contract is deployed at the address \"${address}\".`,\n '- `eip712Domain()` function exists on the contract.',\n '- `eip712Domain()` function matches signature to ERC-5267 specification.',\n ],\n name: 'Eip712DomainNotFoundError',\n })\n }\n}\n","import type { Address, TypedDataDomain } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip712DomainNotFoundError,\n type Eip712DomainNotFoundErrorType,\n} from '../../errors/eip712.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequiredBy } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from './readContract.js'\n\nexport type GetEip712DomainParameters = {\n address: Address\n} & Pick\n\nexport type GetEip712DomainReturnType = {\n domain: RequiredBy<\n TypedDataDomain,\n 'chainId' | 'name' | 'verifyingContract' | 'salt' | 'version'\n >\n fields: Hex\n extensions: readonly bigint[]\n}\n\nexport type GetEip712DomainErrorType =\n | Eip712DomainNotFoundErrorType\n | ReadContractErrorType\n | ErrorType\n\n/**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, getEip712Domain } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await getEip712Domain(client, {\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\nexport async function getEip712Domain(\n client: Client,\n parameters: GetEip712DomainParameters,\n): Promise {\n const { address, factory, factoryData } = parameters\n\n try {\n const [\n fields,\n name,\n version,\n chainId,\n verifyingContract,\n salt,\n extensions,\n ] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi,\n address,\n functionName: 'eip712Domain',\n factory,\n factoryData,\n })\n\n return {\n domain: {\n name,\n version,\n chainId: Number(chainId),\n verifyingContract,\n salt,\n },\n extensions,\n fields,\n }\n } catch (e) {\n const error = e as ReadContractErrorType\n if (\n error.name === 'ContractFunctionExecutionError' &&\n error.cause.name === 'ContractFunctionZeroDataError'\n ) {\n throw new Eip712DomainNotFoundError({ address })\n }\n throw error\n }\n}\n\nconst abi = [\n {\n inputs: [],\n name: 'eip712Domain',\n outputs: [\n { name: 'fields', type: 'bytes1' },\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n { name: 'extensions', type: 'uint256[]' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatFeeHistoryErrorType,\n formatFeeHistory,\n} from '../../utils/formatters/feeHistory.js'\n\nexport type GetFeeHistoryParameters = {\n /**\n * Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.\n */\n blockCount: number\n /**\n * A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used.\n */\n rewardPercentiles: number[]\n} & (\n | {\n blockNumber?: undefined\n /**\n * Highest number block of the requested range.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n | {\n /** Highest number block of the requested range. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\nexport type GetFeeHistoryReturnType = FeeHistory\n\nexport type GetFeeHistoryErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | FormatFeeHistoryErrorType\n\n/**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param client - Client to use\n * @param parameters - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getFeeHistory } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await getFeeHistory(client, {\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\nexport async function getFeeHistory(\n client: Client,\n {\n blockCount,\n blockNumber,\n blockTag = 'latest',\n rewardPercentiles,\n }: GetFeeHistoryParameters,\n): Promise {\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const feeHistory = await client.request(\n {\n method: 'eth_feeHistory',\n params: [\n numberToHex(blockCount),\n blockNumberHex || blockTag,\n rewardPercentiles,\n ],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n return formatFeeHistory(feeHistory)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RpcFeeHistory } from '../../types/rpc.js'\n\nexport type FormatFeeHistoryErrorType = ErrorType\n\nexport function formatFeeHistory(feeHistory: RpcFeeHistory): FeeHistory {\n return {\n baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),\n gasUsedRatio: feeHistory.gasUsedRatio,\n oldestBlock: BigInt(feeHistory.oldestBlock),\n reward: feeHistory.reward?.map((reward) =>\n reward.map((value) => BigInt(value)),\n ),\n }\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterLogsParameters<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<'event', abi, eventName, any, strict, fromBlock, toBlock>\n}\nexport type GetFilterLogsReturnType<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log[]\n\nexport type GetFilterLogsErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterLogs(client, { filter })\n */\nexport async function getFilterLogs<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client,\n {\n filter,\n }: GetFilterLogsParameters,\n): Promise<\n GetFilterLogsReturnType\n> {\n const strict = filter.strict ?? false\n\n const logs = await filter.request({\n method: 'eth_getFilterLogs',\n params: [filter.id],\n })\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!filter.abi)\n return formattedLogs as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Address } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatProofErrorType,\n formatProof,\n} from '../../utils/formatters/proof.js'\n\nexport type GetProofParameters = {\n /** Account address. */\n address: Address\n /** Array of storage-keys that should be proofed and included. */\n storageKeys: Hash[]\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetProofReturnType = Proof\n\nexport type GetProofErrorType =\n | NumberToHexErrorType\n | FormatProofErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getProof } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getProof(client, {\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\nexport async function getProof(\n client: Client,\n {\n address,\n blockNumber,\n blockTag: blockTag_,\n storageKeys,\n }: GetProofParameters,\n): Promise {\n const blockTag = blockTag_ ?? 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n const proof = await client.request({\n method: 'eth_getProof',\n params: [address, storageKeys, blockNumberHex || blockTag],\n })\n\n return formatProof(proof)\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type GetAddressErrorType, getAddress } from '../address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../address/isAddressEqual.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n recoverAuthorizationAddress,\n} from './recoverAuthorizationAddress.js'\n\nexport type VerifyAuthorizationParameters =\n RecoverAuthorizationAddressParameters & {\n /** The address that signed the Authorization object. */\n address: Address\n }\n\nexport type VerifyAuthorizationReturnType = boolean\n\nexport type VerifyAuthorizationErrorType =\n | IsAddressEqualErrorType\n | GetAddressErrorType\n | RecoverAuthorizationAddressErrorType\n | ErrorType\n\n/**\n * Verify that an Authorization object was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/utilities/verifyAuthorization}\n *\n * @param parameters - {@link VerifyAuthorizationParameters}\n * @returns Whether or not the signature is valid. {@link VerifyAuthorizationReturnType}\n */\nexport async function verifyAuthorization({\n address,\n authorization,\n signature,\n}: VerifyAuthorizationParameters): Promise {\n return isAddressEqual(\n getAddress(address),\n await recoverAuthorizationAddress({\n authorization,\n signature,\n }),\n )\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n WalletConnectSessionSettlementError,\n type WalletConnectSessionSettlementErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | AtomicityNotSupportedErrorType\n | AtomicReadyWalletRejectedUpgradeErrorType\n | BundleTooLargeErrorType\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | DuplicateIdErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownBundleIdErrorType\n | UnknownRpcErrorType\n | UnsupportedChainIdErrorType\n | UnsupportedNonOptionalCapabilityErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WalletConnectSessionSettlementErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest Promise>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n methods,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n\n const { method } = args\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n\n const requestId = dedupe\n ? stringToHex(`${uid}.${stringify(args)}`)\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n\n // 5700\n case UnsupportedNonOptionalCapabilityError.code:\n throw new UnsupportedNonOptionalCapabilityError(err)\n // 5710\n case UnsupportedChainIdError.code:\n throw new UnsupportedChainIdError(err)\n // 5720\n case DuplicateIdError.code:\n throw new DuplicateIdError(err)\n // 5730\n case UnknownBundleIdError.code:\n throw new UnknownBundleIdError(err)\n // 5740\n case BundleTooLargeError.code:\n throw new BundleTooLargeError(err)\n // 5750\n case AtomicReadyWalletRejectedUpgradeError.code:\n throw new AtomicReadyWalletRejectedUpgradeError(err)\n // 5760\n case AtomicityNotSupportedError.code:\n throw new AtomicityNotSupportedError(err)\n\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n\n // WalletConnect: Session Settlement Failed\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n case WalletConnectSessionSettlementError.code:\n throw new WalletConnectSessionSettlementError(err)\n\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter, 10) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe(\n fn: () => Promise,\n { enabled = true, id }: WithDedupeOptions,\n): Promise {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport type DefineChainReturnType = Prettify<\n chain &\n (chain['extendSchema'] extends Record\n ? {\n extend: (\n extended: extended,\n ) => Assign\n }\n : {})\n>\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain,\n>(chain: chain): DefineChainReturnType, chain>> {\n const chainInstance = {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign, chain>\n\n function extend(base: typeof chainInstance) {\n type ExtendFn = (base: typeof chainInstance) => unknown\n return (fnOrExtended: ExtendFn | Record) => {\n const properties = (\n typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended\n ) as (typeof chainInstance)['extendSchema']\n const combined = { ...base, ...properties }\n return Object.assign(combined, { extend: extend(combined) })\n }\n }\n\n return Object.assign(chainInstance, {\n extend: extend(chainInstance),\n }) as never\n}\n\nexport function extendSchema>(): schema {\n return {} as schema\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n} from 'abitype'\nexport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nexport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from '../accounts/utils/publicKeyToAddress.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './abi/decodeAbiParameters.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n encodeDeployData,\n} from './abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n encodeErrorResult,\n} from './abi/encodeErrorResult.js'\nexport {\n type EncodeArgErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from './abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n encodeFunctionResult,\n} from './abi/encodeFunctionResult.js'\nexport { type EncodePackedErrorType, encodePacked } from './abi/encodePacked.js'\nexport {\n type FormatAbiItemErrorType,\n type FormatAbiParamErrorType,\n type FormatAbiParamsErrorType,\n formatAbiItem,\n formatAbiParams,\n} from './abi/formatAbiItem.js'\nexport {\n type FormatAbiItemWithArgsErrorType,\n formatAbiItemWithArgs,\n} from './abi/formatAbiItemWithArgs.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './abi/parseEventLogs.js'\nexport {\n type ChecksumAddressErrorType,\n getAddress,\n} from './address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './address/getContractAddress.js'\nexport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from './address/isAddressEqual.js'\nexport {\n type HashAuthorizationErrorType,\n type HashAuthorizationParameters,\n type HashAuthorizationReturnType,\n hashAuthorization,\n} from './authorization/hashAuthorization.js'\nexport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n type RecoverAuthorizationAddressReturnType,\n recoverAuthorizationAddress,\n} from './authorization/recoverAuthorizationAddress.js'\nexport {\n type SerializeAuthorizationListErrorType,\n type SerializeAuthorizationListReturnType,\n serializeAuthorizationList,\n} from './authorization/serializeAuthorizationList.js'\nexport {\n type VerifyAuthorizationErrorType,\n type VerifyAuthorizationParameters,\n type VerifyAuthorizationReturnType,\n verifyAuthorization,\n} from './authorization/verifyAuthorization.js'\nexport {\n buildRequest,\n type RequestErrorType,\n} from './buildRequest.js'\nexport {\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './chain/assertCurrentChain.js'\nexport { defineChain } from './chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n concat,\n concatBytes,\n concatHex,\n} from './data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n pad,\n padBytes,\n padHex,\n} from './data/pad.js'\nexport { type SizeErrorType, size } from './data/size.js'\nexport {\n type AssertEndOffsetErrorType,\n type AssertStartOffsetErrorType,\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n type SliceReturnType,\n slice,\n sliceBytes,\n sliceHex,\n} from './data/slice.js'\nexport { type TrimErrorType, type TrimReturnType, trim } from './data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBigInt as bytesToBigint,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n type FromBytesReturnType,\n fromBytes,\n} from './encoding/fromBytes.js'\nexport {\n type AssertSizeErrorType,\n type FromHexErrorType,\n type FromHexParameters,\n type FromHexReturnType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBigIntOpts,\n type HexToBoolErrorType,\n type HexToBoolOpts,\n type HexToNumberErrorType,\n type HexToNumberOpts,\n type HexToStringErrorType,\n type HexToStringOpts,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n fromRlp,\n} from './encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n type HexToRlpErrorType,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './encoding/toRlp.js'\nexport {\n type GetCallErrorReturnType,\n getCallError,\n} from './errors/getCallError.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './errors/getContractError.js'\nexport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from './errors/getEstimateGasError.js'\nexport {\n containsNodeError,\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './errors/getNodeError.js'\nexport {\n type GetTransactionErrorParameters,\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from './errors/getTransactionError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './formatters/block.js'\nexport { type ExtractErrorType, extract } from './formatters/extract.js'\nexport {\n type DefineFormatterErrorType,\n defineFormatter,\n} from './formatters/formatter.js'\nexport { type FormatLogErrorType, formatLog } from './formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n} from './formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from './formatters/transactionRequest.js'\nexport { getAction } from './getAction.js'\nexport { type IsHashErrorType, isHash } from './hash/isHash.js'\nexport { type Keccak256ErrorType, keccak256 } from './hash/keccak256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './hash/ripemd160.js'\nexport { type Sha256ErrorType, sha256 } from './hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './hash/toFunctionSignature.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './nonceManager.js'\nexport { arrayRegex, bytesRegex, integerRegex } from './regex.js'\nexport {\n getSocket,\n rpc,\n type WebSocketAsyncErrorType,\n type WebSocketAsyncOptions,\n type WebSocketAsyncReturnType,\n type WebSocketErrorType,\n type WebSocketOptions,\n type WebSocketReturnType,\n} from './rpc/compat.js'\nexport {\n getHttpRpcClient,\n type HttpRequestErrorType,\n type HttpRequestParameters,\n type HttpRequestReturnType,\n type HttpRpcClient,\n type HttpRpcClientOptions,\n} from './rpc/http.js'\nexport {\n type GetSocketParameters,\n type GetSocketRpcClientErrorType,\n type GetSocketRpcClientParameters,\n getSocketRpcClient,\n type Socket,\n type SocketRpcClient,\n socketClientCache,\n} from './rpc/socket.js'\nexport { getWebSocketRpcClient } from './rpc/webSocket.js'\nexport {\n type HashMessageErrorType,\n type HashMessageReturnType,\n hashMessage,\n} from './signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashStruct,\n hashTypedData,\n} from './signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './signature/isErc8010Signature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './signature/parseErc8010Signature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './signature/recoverPublicKey.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './signature/recoverTypedDataAddress.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './signature/serializeErc8010Signature.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n parseTransaction,\n} from './transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './transaction/serializeAccessList.js'\nexport {\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './typedData.js'\nexport { type FormatEtherErrorType, formatEther } from './unit/formatEther.js'\nexport { type FormatGweiErrorType, formatGwei } from './unit/formatGwei.js'\nexport { type FormatUnitsErrorType, formatUnits } from './unit/formatUnits.js'\nexport { type ParseEtherErrorType, parseEther } from './unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './unit/parseGwei.js'\nexport { type ParseUnitsErrorType, parseUnits } from './unit/parseUnits.js'\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport type { MaybePromise } from '../../types/utils.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Override for the fetch function used to make requests. */\n fetchFn?:\n | ((input: string | URL | Request, init?: RequestInit) => Promise)\n | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit | undefined\n /** A callback to handle the request. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Override for the fetch function used to make requests. */\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request(\n params: HttpRequestParameters,\n ): Promise>\n}\n\nexport function getHttpRpcClient(\n url_: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n const { url, headers: headers_url } = parseUrl(url_)\n\n return {\n async request(params) {\n const {\n body,\n fetchFn = options.fetchFn ?? fetch,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n ...headers_url,\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n const args = (await onRequest?.(request, init)) ?? { ...init, url }\n const response = await fetchFn(args.url ?? url, args)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n\n/** @internal */\nexport function parseUrl(url_: string) {\n try {\n const url = new URL(url_)\n\n const result = (() => {\n // Handle Basic authentication credentials\n if (url.username) {\n const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`\n url.username = ''\n url.password = ''\n\n return {\n url: url.toString(),\n headers: { Authorization: `Basic ${btoa(credentials)}` },\n }\n }\n\n return\n })()\n\n return { url: url.toString(), ...result }\n } catch {\n return { url: url_ }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout(\n fn: ({\n signal,\n }: {\n signal: AbortController['signal'] | null\n }) => Promise,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\n","import * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Authorization from '../core/Authorization.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport * as Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-8010 signature. */\nexport type Unwrapped = {\n /** Authorization signed by the delegatee. */\n authorization: Authorization.Authorization\n /** Data to initialize the delegation. */\n data?: Hex.Hex | undefined\n /** The original signature. */\n signature: Hex.Hex\n /** Address of the initializer. */\n to?: Address.Address | undefined\n}\n\n/** Wrapped ERC-8010 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-8010 wrapped signatures.\n */\nexport const magicBytes =\n '0x8010801080108010801080108010801080108010801080108010801080108010' as const\n\n/** Suffix ABI parameters for the ERC-8010 wrapped signature. */\nexport const suffixParameters = AbiParameters.from(\n '(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data',\n)\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * SignatureErc8010.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-8010 wrapped signature.\n * ```\n *\n * @param value - The value to assert.\n */\nexport function assert(value: Unwrapped | Wrapped) {\n if (typeof value === 'string') {\n if (Hex.slice(value, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(value)\n } else Signature.assert(value.authorization)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc8010.from('0x...') // [!code focus]\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc8010.from({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * })\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } }\n * ```\n *\n * @param value - Value to parse.\n * @returns Parsed value.\n */\nexport function from(value: Unwrapped | Wrapped): Unwrapped {\n if (typeof value === 'string') return unwrap(value)\n return value\n}\n\nexport declare namespace from {\n type ErrorType = unwrap.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Unwraps an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const { authorization, data, signature } = SignatureErc8010.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to unwrap.\n * @returns Unwrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const suffixLength = Hex.toNumber(Hex.slice(wrapped, -64, -32))\n const suffix = Hex.slice(wrapped, -suffixLength - 64, -64)\n const signature = Hex.slice(wrapped, 0, -suffixLength - 64)\n\n const [auth, to, data] = AbiParameters.decode(suffixParameters, suffix)\n\n const authorization = Authorization.from({\n address: auth.delegation,\n chainId: Number(auth.chainId),\n nonce: auth.nonce,\n yParity: auth.yParity,\n r: auth.r,\n s: auth.s,\n })\n\n return {\n authorization,\n signature,\n ...(data && data !== '0x' ? { data, to } : {}),\n }\n}\n\nexport declare namespace unwrap {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Wraps a signature into [ERC-8010 format](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md).\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc8010.wrap({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Values to wrap.\n * @returns Wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature } = value\n\n assert(value)\n\n const self = Secp256k1.recoverAddress({\n payload: Authorization.getSignPayload(value.authorization),\n signature: Signature.from(value.authorization),\n })\n\n const suffix = AbiParameters.encode(suffixParameters, [\n {\n ...value.authorization,\n delegation: value.authorization.address,\n chainId: BigInt(value.authorization.chainId),\n },\n value.to ?? self,\n data ?? '0x',\n ])\n const suffixLength = Hex.fromNumber(Hex.size(suffix), { size: 32 })\n return Hex.concat(signature, suffix, suffixLength, magicBytes)\n}\n\nexport declare namespace wrap {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const valid = SignatureErc8010.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param value - The value to validate.\n * @returns `true` if the value is valid, `false` otherwise.\n */\nexport function validate(value: Unwrapped | Wrapped): boolean {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-8010 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc8010.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-8010 wrapped signature.`)\n }\n}\n","import * as abitype from 'abitype'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiParameters.js'\nimport * as Cursor from './internal/cursor.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for ABI parameters. */\nexport type AbiParameters = readonly abitype.AbiParameter[]\n\n/** A parameter on an {@link ox#AbiParameters.AbiParameters}. */\nexport type Parameter = abitype.AbiParameter\n\n/** A packed ABI type. */\nexport type PackedAbiType =\n | abitype.SolidityAddress\n | abitype.SolidityBool\n | abitype.SolidityBytes\n | abitype.SolidityInt\n | abitype.SolidityString\n | abitype.SolidityArrayWithoutTuple\n\n/**\n * Decodes ABI-encoded data into its respective primitive values based on ABI Parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * You can pass **JSON ABI** Parameters:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' },\n * ],\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @param parameters - The set of ABI parameters to decode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param data - ABI encoded data.\n * @param options - Decoding options.\n * @returns Array of decoded values.\n */\nexport function decode<\n const parameters extends AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n>(\n parameters: parameters,\n data: Bytes.Bytes | Hex.Hex,\n options?: decode.Options,\n): decode.ReturnType\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n parameters: AbiParameters,\n data: Bytes.Bytes | Hex.Hex,\n options: {\n as?: 'Array' | 'Object' | undefined\n checksumAddress?: boolean | undefined\n } = {},\n): readonly unknown[] | Record {\n const { as = 'Array', checksumAddress = false } = options\n\n const bytes = typeof data === 'string' ? Bytes.fromHex(data) : data\n const cursor = Cursor.create(bytes)\n\n if (Bytes.size(bytes) === 0 && parameters.length > 0)\n throw new ZeroDataError()\n if (Bytes.size(bytes) && Bytes.size(bytes) < 32)\n throw new DataSizeTooSmallError({\n data: typeof data === 'string' ? data : Hex.fromBytes(data),\n parameters: parameters as readonly Parameter[],\n size: Bytes.size(bytes),\n })\n\n let consumed = 0\n const values: any = as === 'Array' ? [] : {}\n for (let i = 0; i < parameters.length; ++i) {\n const param = parameters[i] as Parameter\n cursor.setPosition(consumed)\n const [data, consumed_] = internal.decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: 0,\n })\n consumed += consumed_\n if (as === 'Array') values.push(data)\n else values[param.name ?? i] = data\n }\n return values\n}\n\nexport declare namespace decode {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Object' | 'Array' | undefined\n /**\n * Whether decoded addresses should be checksummed.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n\n type ReturnType<\n parameters extends AbiParameters = AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n > = parameters extends readonly []\n ? as extends 'Object'\n ? {}\n : []\n : as extends 'Object'\n ? internal.ToObject\n : internal.ToPrimitiveTypes\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | internal.decodeParameter.ErrorType\n | ZeroDataError\n | DataSizeTooSmallError\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes primitive values into ABI encoded data as per the [Application Binary Interface (ABI) Specification](https://docs.soliditylang.org/en/latest/abi-spec).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * Specify **JSON ABI** Parameters as schema:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * [\n * { type: 'string', name: 'name' },\n * { type: 'uint', name: 'age' },\n * { type: 'bool', name: 'isOwner' },\n * ],\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @param parameters - The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param values - The set of primitive values that correspond to the ABI types defined in `parameters`.\n * @returns ABI encoded data.\n */\nexport function encode<\n const parameters extends AbiParameters | readonly unknown[],\n>(\n parameters: parameters,\n values: parameters extends AbiParameters\n ? internal.ToPrimitiveTypes\n : never,\n options?: encode.Options,\n): Hex.Hex {\n const { checksumAddress = false } = options ?? {}\n\n if (parameters.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: parameters.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParameters = internal.prepareParameters({\n checksumAddress,\n parameters: parameters as readonly Parameter[],\n values: values as any,\n })\n const data = internal.encode(preparedParameters)\n if (data.length === 0) return '0x'\n return data\n}\n\nexport declare namespace encode {\n type ErrorType =\n | LengthMismatchError\n | internal.encode.ErrorType\n | internal.prepareParameters.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /**\n * Whether addresses should be checked against their checksum.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n}\n\n/**\n * Encodes an array of primitive values to a [packed ABI encoding](https://docs.soliditylang.org/en/latest/abi-spec.html#non-standard-packed-mode).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const encoded = AbiParameters.encodePacked(\n * ['address', 'string'],\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 'hello world'],\n * )\n * // @log: '0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64'\n * ```\n *\n * @param types - Set of ABI types to pack encode.\n * @param values - The set of primitive values that correspond to the ABI types defined in `types`.\n * @returns The encoded packed data.\n */\nexport function encodePacked<\n const packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: packedAbiTypes, values: encodePacked.Values): Hex.Hex {\n if (types.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: types.length as number,\n givenLength: values.length as number,\n })\n\n const data: Hex.Hex[] = []\n for (let i = 0; i < (types as unknown[]).length; i++) {\n const type = types[i]\n const value = values[i]\n data.push(encodePacked.encode(type, value))\n }\n return Hex.concat(...data)\n}\n\nexport namespace encodePacked {\n export type ErrorType =\n | Hex.concat.ErrorType\n | LengthMismatchError\n | Errors.GlobalErrorType\n\n export type Values<\n packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n > = {\n [key in keyof packedAbiTypes]: packedAbiTypes[key] extends abitype.AbiType\n ? abitype.AbiParameterToPrimitiveType<{ type: packedAbiTypes[key] }>\n : unknown\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc\n export function encode(\n type: packedAbiType,\n value: Values<[packedAbiType]>[0],\n isArray = false,\n ): Hex.Hex {\n if (type === 'address') {\n const address = value as Address.Address\n Address.assert(address)\n return Hex.padLeft(\n address.toLowerCase() as Hex.Hex,\n isArray ? 32 : 0,\n ) as Address.Address\n }\n if (type === 'string') return Hex.fromString(value as string)\n if (type === 'bytes') return value as Hex.Hex\n if (type === 'bool')\n return Hex.padLeft(Hex.fromBoolean(value as boolean), isArray ? 32 : 1)\n\n const intMatch = (type as string).match(Solidity.integerRegex)\n if (intMatch) {\n const [_type, baseType, bits = '256'] = intMatch\n const size = Number.parseInt(bits, 10) / 8\n return Hex.fromNumber(value as number, {\n size: isArray ? 32 : size,\n signed: baseType === 'int',\n })\n }\n\n const bytesMatch = (type as string).match(Solidity.bytesRegex)\n if (bytesMatch) {\n const [_type, size] = bytesMatch\n if (Number.parseInt(size!, 10) !== ((value as Hex.Hex).length - 2) / 2)\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size!, 10),\n value: value as Hex.Hex,\n })\n return Hex.padRight(value as Hex.Hex, isArray ? 32 : 0) as Hex.Hex\n }\n\n const arrayMatch = (type as string).match(Solidity.arrayRegex)\n if (arrayMatch && Array.isArray(value)) {\n const [_type, childType] = arrayMatch\n const data: Hex.Hex[] = []\n for (let i = 0; i < value.length; i++) {\n data.push(encode(childType, value[i], true))\n }\n if (data.length === 0) return '0x'\n return Hex.concat(...data)\n }\n\n throw new InvalidTypeError(type as string)\n }\n}\n\n/**\n * Formats {@link ox#AbiParameters.AbiParameters} into **Human Readable ABI Parameters**.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const formatted = AbiParameters.format([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param parameters - The ABI Parameters to format.\n * @returns The formatted ABI Parameters .\n */\nexport function format<\n const parameters extends readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n>(\n parameters:\n | parameters\n | readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n): abitype.FormatAbiParameters {\n return abitype.formatAbiParameters(parameters)\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses arbitrary **JSON ABI Parameters** or **Human Readable ABI Parameters** into typed {@link ox#AbiParameters.AbiParameters}.\n *\n * @example\n * ### JSON Parameters\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable Parameters\n *\n * Human Readable ABI Parameters can be parsed into a typed {@link ox#AbiParameters.AbiParameters}:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from('address spender, uint256 amount')\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'Foo foo, address bar',\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param parameters - The ABI Parameters to parse.\n * @returns The typed ABI Parameters.\n */\nexport function from<\n const parameters extends AbiParameters | string | readonly string[],\n>(\n parameters: parameters | AbiParameters | string | readonly string[],\n): from.ReturnType {\n if (Array.isArray(parameters) && typeof parameters[0] === 'string')\n return abitype.parseAbiParameters(parameters) as never\n if (typeof parameters === 'string')\n return abitype.parseAbiParameters(parameters) as never\n return parameters as never\n}\n\nexport declare namespace from {\n type ReturnType<\n parameters extends AbiParameters | string | readonly string[],\n > = parameters extends string\n ? abitype.ParseAbiParameters\n : parameters extends readonly string[]\n ? abitype.ParseAbiParameters\n : parameters\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Throws when the data size is too small for the given parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x010f')\n * // ↑ ❌ 2 bytes\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass a valid data size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class DataSizeTooSmallError extends Errors.BaseError {\n override readonly name = 'AbiParameters.DataSizeTooSmallError'\n constructor({\n data,\n parameters,\n size,\n }: { data: Hex.Hex; parameters: readonly Parameter[]; size: number }) {\n super(`Data size of ${size} bytes is too small for given parameters.`, {\n metaMessages: [\n `Params: (${abitype.formatAbiParameters(parameters as readonly [Parameter])})`,\n `Data: ${data} (${size} bytes)`,\n ],\n })\n }\n}\n\n/**\n * Throws when zero data is provided, but data is expected.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x')\n * // ↑ ❌ zero data\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass valid data.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class ZeroDataError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\n/**\n * The length of the array value does not match the length specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('uint256[3]'), [[69n, 420n]])\n * // ↑ expected: 3 ↑ ❌ length: 2\n * // @error: AbiParameters.ArrayLengthMismatchError: ABI encoding array length mismatch\n * // @error: for type `uint256[3]`. Expected: `3`. Given: `2`.\n * ```\n *\n * ### Solution\n *\n * Pass an array of the correct length.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [[69n, 420n, 69n]])\n * // ↑ ✅ length: 3\n * ```\n */\nexport class ArrayLengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n `Array length mismatch for type \\`${type}\\`. Expected: \\`${expectedLength}\\`. Given: \\`${givenLength}\\`.`,\n )\n }\n}\n\n/**\n * The size of the bytes value does not match the size specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('bytes8'), [['0xdeadbeefdeadbeefdeadbeef']])\n * // ↑ expected: 8 bytes ↑ ❌ size: 12 bytes\n * // @error: BytesSizeMismatchError: Size of bytes \"0xdeadbeefdeadbeefdeadbeef\"\n * // @error: (bytes12) does not match expected size (bytes8).\n * ```\n *\n * ### Solution\n *\n * Pass a bytes value of the correct size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['bytes8']), ['0xdeadbeefdeadbeef'])\n * // ↑ ✅ size: 8 bytes\n * ```\n */\nexport class BytesSizeMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.BytesSizeMismatchError'\n constructor({\n expectedSize,\n value,\n }: { expectedSize: number; value: Hex.Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${Hex.size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\n/**\n * The length of the values to encode does not match the length of the ABI parameters.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['string', 'uint256']), ['hello'])\n * // @error: LengthMismatchError: ABI encoding params/values length mismatch.\n * // @error: Expected length (params): 2\n * // @error: Given length (values): 1\n * ```\n *\n * ### Solution\n *\n * Pass the correct number of values to encode.\n *\n * ### Solution\n *\n * Pass a [valid ABI type](https://docs.soliditylang.org/en/develop/abi-spec.html#types).\n */\nexport class LengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.LengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding parameters/values length mismatch.',\n `Expected length (parameters): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * The value provided is not a valid array as specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [69])\n * ```\n *\n * ### Solution\n *\n * Pass an array value.\n */\nexport class InvalidArrayError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidArrayError'\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is not a valid array.`)\n }\n}\n\n/**\n * Throws when the ABI parameter type is invalid.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'lol' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ❌ invalid type\n * // @error: AbiParameters.InvalidTypeError: Type `lol` is not a valid ABI Type.\n * ```\n */\nexport class InvalidTypeError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidTypeError'\n constructor(type: string) {\n super(`Type \\`${type}\\` is not a valid ABI Type.`)\n }\n}\n","import type { Address as abitype_Address } from 'abitype'\nimport * as Bytes from './Bytes.js'\nimport * as Caches from './Caches.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as PublicKey from './PublicKey.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** Root type for Address. */\nexport type Address = abitype_Address\n\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(\n value: string,\n options: assert.Options = {},\n): asserts value is Address {\n const { strict = true } = options\n\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n })\n\n if (strict) {\n if (value.toLowerCase() === value) return\n if (checksum(value as Address) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n })\n }\n}\n\nexport declare namespace assert {\n type Options = {\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\n type ErrorType = InvalidAddressError | Errors.GlobalErrorType\n}\n\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address: string): Address {\n if (Caches.checksum.has(address)) return Caches.checksum.get(address)!\n\n assert(address, { strict: false })\n\n const hexAddress = address.substring(2).toLowerCase()\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' })\n\n const characters = hexAddress.split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1]! >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i]!.toUpperCase()\n }\n if ((hash[i >> 1]! & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1]!.toUpperCase()\n }\n }\n\n const result = `0x${characters.join('')}` as const\n Caches.checksum.set(address, result)\n return result\n}\n\nexport declare namespace checksum {\n type ErrorType =\n | assert.ErrorType\n | Hash.keccak256.ErrorType\n | Bytes.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a stringified address to a typed (optionally checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: true\n * })\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address: string, options: from.Options = {}): Address {\n const { checksum: checksumVal = false } = options\n assert(address)\n if (checksumVal) return checksum(address)\n return address as Address\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | assert.ErrorType\n | checksum.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(\n publicKey: PublicKey.PublicKey,\n options: fromPublicKey.Options = {},\n): Address {\n const address = Hash.keccak256(\n `0x${PublicKey.toHex(publicKey).slice(4)}`,\n ).substring(26)\n return from(`0x${address}`, options)\n}\n\nexport declare namespace fromPublicKey {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA: Address, addressB: Address): boolean {\n assert(addressA, { strict: false })\n assert(addressB, { strict: false })\n return addressA.toLowerCase() === addressB.toLowerCase()\n}\n\nexport declare namespace isEqual {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(\n address: string,\n options: validate.Options = {},\n): address is Address {\n const { strict = true } = options ?? {}\n try {\n assert(address, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\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}\n\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError<\n cause extends InvalidInputError | InvalidChecksumError =\n | InvalidInputError\n | InvalidChecksumError,\n> extends Errors.BaseError {\n override readonly name = 'Address.InvalidAddressError'\n\n constructor({ address, cause }: { address: string; cause: cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n override readonly name = 'Address.InvalidInputError'\n\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.')\n }\n}\n\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n override readonly name = 'Address.InvalidChecksumError'\n\n constructor() {\n super('Address does not match its checksum counterpart.')\n }\n}\n","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see 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 * as Address from './Address.js'\nimport { LruMap } from './internal/lru.js'\n\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap(8192),\n}\n\nexport const checksum = caches.checksum\n\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches)) cache.clear()\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3'\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: keccak256.Options = {},\n): keccak256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_keccak256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace keccak256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [HMAC-SHA256](https://en.wikipedia.org/wiki/HMAC) of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `hmac` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef')\n * // @log: '0x...'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param key - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} key.\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns HMAC-SHA256 hash.\n */\nexport function hmac256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n key: Hex.Hex | Bytes.Bytes,\n value: value | Hex.Hex | Bytes.Bytes,\n options: hmac256.Options = {},\n): hmac256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = hmac(noble_sha256, Bytes.from(key), Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace hmac256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: ripemd160.Options = {},\n): ripemd160.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_ripemd160(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace ripemd160 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: sha256.Options = {},\n): sha256.ReturnType {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_sha256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace sha256 {\n type Options = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value: string): value is Hex.Hex {\n return Hex.validate(value) && Hex.size(value) === 32\n}\n\nexport declare namespace validate {\n type ErrorType =\n | Hex.validate.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial } from './internal/types.js'\nimport * as Json from './Json.js'\n\n/** Root type for an ECDSA Public Key. */\nexport type PublicKey<\n compressed extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n compressed extends true\n ? {\n prefix: numberType\n x: bigintType\n y?: undefined\n }\n : {\n prefix: numberType\n x: bigintType\n y: bigintType\n }\n>\n\n/**\n * Asserts that a {@link ox#PublicKey.PublicKey} is valid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @error: PublicKey.InvalidError: Value \\`{\"y\":\"1\"}\\` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function assert(\n publicKey: ExactPartial,\n options: assert.Options = {},\n): asserts publicKey is PublicKey {\n const { compressed } = options\n const { prefix, x, y } = publicKey\n\n // Uncompressed\n if (\n compressed === false ||\n (typeof x === 'bigint' && typeof y === 'bigint')\n ) {\n if (prefix !== 4)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidUncompressedPrefixError(),\n })\n return\n }\n\n // Compressed\n if (\n compressed === true ||\n (typeof x === 'bigint' && typeof y === 'undefined')\n ) {\n if (prefix !== 3 && prefix !== 2)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidCompressedPrefixError(),\n })\n return\n }\n\n // Unknown/invalid\n throw new InvalidError({ publicKey })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = InvalidError | InvalidPrefixError | Errors.GlobalErrorType\n}\n\n/**\n * Compresses a {@link ox#PublicKey.PublicKey}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const compressed = PublicKey.compress(publicKey) // [!code focus]\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The public key to compress.\n * @returns The compressed public key.\n */\nexport function compress(publicKey: PublicKey): PublicKey {\n const { x, y } = publicKey\n return {\n prefix: y % 2n === 0n ? 2 : 3,\n x,\n }\n}\n\nexport declare namespace compress {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#PublicKey.PublicKey} object from a {@link ox#PublicKey.PublicKey}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from('0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param value - The public key value to instantiate.\n * @returns The instantiated {@link ox#PublicKey.PublicKey}.\n */\nexport function from<\n const publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes,\n>(value: from.Value): from.ReturnType {\n const publicKey = (() => {\n if (Hex.validate(value)) return fromHex(value)\n if (Bytes.validate(value)) return fromBytes(value)\n\n const { prefix, x, y } = value\n if (typeof x === 'bigint' && typeof y === 'bigint')\n return { prefix: prefix ?? 0x04, x, y }\n return { prefix, x }\n })()\n\n assert(publicKey)\n\n return publicKey as never\n}\n\n/** @internal */\ntype CompressedPublicKey = PublicKey\n\n/** @internal */\ntype UncompressedPublicKey = Omit, 'prefix'> & {\n prefix?: PublicKey['prefix'] | undefined\n}\n\nexport declare namespace from {\n type Value<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey | CompressedPublicKey | UncompressedPublicKey\n\n type ReturnType<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey extends CompressedPublicKey | UncompressedPublicKey\n ? publicKey extends UncompressedPublicKey\n ? Compute\n : publicKey\n : PublicKey\n\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromBytes(publicKey: Bytes.Bytes): PublicKey {\n return fromHex(Hex.fromBytes(publicKey))\n}\n\nexport declare namespace fromBytes {\n type ErrorType =\n | fromHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### Deserializing a Compressed Public Key\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75')\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromHex(publicKey: Hex.Hex): PublicKey {\n if (\n publicKey.length !== 132 &&\n publicKey.length !== 130 &&\n publicKey.length !== 68\n )\n throw new InvalidSerializedSizeError({ publicKey })\n\n if (publicKey.length === 130) {\n const x = BigInt(Hex.slice(publicKey, 0, 32))\n const y = BigInt(Hex.slice(publicKey, 32, 64))\n return {\n prefix: 4,\n x,\n y,\n } as never\n }\n\n if (publicKey.length === 132) {\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n const y = BigInt(Hex.slice(publicKey, 33, 65))\n return {\n prefix,\n x,\n y,\n } as never\n }\n\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n return {\n prefix,\n x,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType = Hex.slice.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const bytes = PublicKey.toBytes(publicKey) // [!code focus]\n * // @log: Uint8Array [128, 3, 131, ...]\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toBytes(\n publicKey: PublicKey,\n options: toBytes.Options = {},\n): Bytes.Bytes {\n return Bytes.fromHex(toHex(publicKey, options))\n}\n\nexport declare namespace toBytes {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const hex = PublicKey.toHex(publicKey) // [!code focus]\n * // @log: '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toHex(\n publicKey: PublicKey,\n options: toHex.Options = {},\n): Hex.Hex {\n assert(publicKey)\n\n const { prefix, x, y } = publicKey\n const { includePrefix = true } = options\n\n const publicKey_ = Hex.concat(\n includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x',\n Hex.fromNumber(x, { size: 32 }),\n // If the public key is not compressed, add the y coordinate.\n typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x',\n )\n\n return publicKey_\n}\n\nexport declare namespace toHex {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Validates a {@link ox#PublicKey.PublicKey}. Returns `true` if valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const valid = PublicKey.validate({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @log: false\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function validate(\n publicKey: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(publicKey, options)\n return true\n } catch (_error) {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a public key is invalid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({ y: 1n })\n * // @error: PublicKey.InvalidError: Value `{\"y\":1n}` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n */\nexport class InvalidError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidError'\n\n constructor({ publicKey }: { publicKey: unknown }) {\n super(`Value \\`${Json.stringify(publicKey)}\\` is not a valid public key.`, {\n metaMessages: [\n 'Public key must contain:',\n '- an `x` and `prefix` value (compressed)',\n '- an `x`, `y`, and `prefix` value (uncompressed)',\n ],\n })\n }\n}\n\n/** Thrown when a public key has an invalid prefix. */\nexport class InvalidPrefixError<\n cause extends InvalidCompressedPrefixError | InvalidUncompressedPrefixError =\n | InvalidCompressedPrefixError\n | InvalidUncompressedPrefixError,\n> extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidPrefixError'\n\n constructor({ prefix, cause }: { prefix: number | undefined; cause: cause }) {\n super(`Prefix \"${prefix}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when the public key has an invalid prefix for a compressed public key. */\nexport class InvalidCompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidCompressedPrefixError'\n\n constructor() {\n super('Prefix must be 2 or 3 for compressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid prefix for an uncompressed public key. */\nexport class InvalidUncompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidUncompressedPrefixError'\n\n constructor() {\n super('Prefix must be 4 for uncompressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid serialized size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidSerializedSizeError'\n\n constructor({ publicKey }: { publicKey: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${publicKey}\\` is an invalid public key size.`, {\n metaMessages: [\n 'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',\n `Received ${Hex.size(Hex.from(publicKey))} bytes.`,\n ],\n })\n }\n}\n","import type {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\n} from 'abitype'\nimport * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Bytes from '../Bytes.js'\nimport * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\nimport { integerRegex } from '../Solidity.js'\nimport type * as Cursor from './cursor.js'\nimport type { Compute, IsNarrowable, UnionToIntersection } from './types.js'\n\n/** @internal */\nexport type ParameterToPrimitiveType<\n abiParameter extends AbiParameter | { name: string; type: unknown },\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParameterToPrimitiveType\n\n/** @internal */\nexport type PreparedParameter = { dynamic: boolean; encoded: Hex.Hex }\n\n/** @internal */\nexport type ToObject<\n parameters extends readonly AbiParameter[],\n kind extends AbiParameterKind = AbiParameterKind,\n> = IsNarrowable extends true\n ? Compute<\n UnionToIntersection<\n {\n [index in keyof parameters]: parameters[index] extends {\n name: infer name extends string\n }\n ? {\n [key in name]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n : {\n [key in index]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n }[number]\n >\n >\n : unknown\n\n/** @internal */\nexport type ToPrimitiveTypes<\n abiParameters extends readonly AbiParameter[],\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParametersToPrimitiveTypes\n\n/** @internal */\nexport type Tuple = ParameterToPrimitiveType\n\n/** @internal */\nexport function decodeParameter(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(\n cursor,\n { ...param, type },\n { checksumAddress, length, staticPosition },\n )\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, {\n checksumAddress,\n staticPosition,\n })\n if (param.type === 'address')\n return decodeAddress(cursor, { checksum: checksumAddress })\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 AbiParameters.InvalidTypeError(param.type)\n}\n\nexport declare namespace decodeParameter {\n type ErrorType =\n | decodeArray.ErrorType\n | decodeTuple.ErrorType\n | decodeAddress.ErrorType\n | decodeBool.ErrorType\n | decodeBytes.ErrorType\n | decodeNumber.ErrorType\n | decodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\n/** @internal */\nexport function decodeAddress(\n cursor: Cursor.Cursor,\n options: { checksum?: boolean | undefined } = {},\n) {\n const { checksum = false } = options\n const value = cursor.readBytes(32)\n const wrap = (address: Hex.Hex) =>\n checksum ? Address.checksum(address) : address\n return [wrap(Hex.fromBytes(Bytes.slice(value, -20))), 32]\n}\n\nexport declare namespace decodeAddress {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeArray(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n staticPosition: number\n },\n) {\n const { checksumAddress, length, staticPosition } = options\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 = Bytes.toNumber(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 = Bytes.toNumber(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 checksumAddress,\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeArray {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBool(cursor: Cursor.Cursor) {\n return [Bytes.toBoolean(cursor.readBytes(32), { size: 32 }), 32]\n}\n\nexport declare namespace decodeBool {\n type ErrorType = Bytes.toBoolean.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBytes(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\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 = Bytes.toNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = Bytes.toNumber(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 [Hex.fromBytes(data), 32]\n }\n\n const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))\n return [value, 32]\n}\n\nexport declare namespace decodeBytes {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeNumber(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10)\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? Bytes.toBigInt(value, { signed })\n : Bytes.toNumber(value, { signed }),\n 32,\n ]\n}\n\nexport declare namespace decodeNumber {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport type TupleAbiParameter = AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n}\n\n/** @internal */\nexport function decodeTuple(\n cursor: Cursor.Cursor,\n param: TupleAbiParameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeTuple {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeString(\n cursor: Cursor.Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = Bytes.toNumber(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 = Bytes.toNumber(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 = Bytes.toString(Bytes.trimLeft(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\nexport declare namespace decodeString {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toString.ErrorType\n | Bytes.trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameters<\n const parameters extends AbiParameters.AbiParameters,\n>({\n checksumAddress,\n parameters,\n values,\n}: {\n checksumAddress?: boolean | undefined\n parameters: parameters\n values: parameters extends AbiParameters.AbiParameters\n ? ToPrimitiveTypes\n : never\n}) {\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameters.length; i++) {\n preparedParameters.push(\n prepareParameter({\n checksumAddress,\n parameter: parameters[i]!,\n value: values[i],\n }),\n )\n }\n return preparedParameters\n}\n\n/** @internal */\nexport declare namespace prepareParameters {\n type ErrorType = prepareParameter.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameter<\n const parameter extends AbiParameters.Parameter,\n>({\n checksumAddress = false,\n parameter: parameter_,\n value,\n}: {\n parameter: parameter\n value: parameter extends AbiParameters.Parameter\n ? ParameterToPrimitiveType\n : never\n checksumAddress?: boolean | undefined\n}): PreparedParameter {\n const parameter = parameter_ as AbiParameters.Parameter\n\n const arrayComponents = getArrayComponents(parameter.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, {\n checksumAddress,\n length,\n parameter: {\n ...parameter,\n type,\n },\n })\n }\n if (parameter.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n checksumAddress,\n parameter: parameter as TupleAbiParameter,\n })\n }\n if (parameter.type === 'address') {\n return encodeAddress(value as unknown as Hex.Hex, {\n checksum: checksumAddress,\n })\n }\n if (parameter.type === 'bool') {\n return encodeBoolean(value as unknown as boolean)\n }\n if (parameter.type.startsWith('uint') || parameter.type.startsWith('int')) {\n const signed = parameter.type.startsWith('int')\n const [, , size = '256'] = integerRegex.exec(parameter.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\n }\n if (parameter.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex.Hex, { type: parameter.type })\n }\n if (parameter.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new AbiParameters.InvalidTypeError(parameter.type)\n}\n\n/** @internal */\nexport declare namespace prepareParameter {\n type ErrorType =\n | encodeArray.ErrorType\n | encodeTuple.ErrorType\n | encodeAddress.ErrorType\n | encodeBoolean.ErrorType\n | encodeBytes.ErrorType\n | encodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encode(preparedParameters: PreparedParameter[]): Hex.Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) staticSize += 32\n else staticSize += Hex.size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParameters: Hex.Hex[] = []\n const dynamicParameters: Hex.Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) {\n staticParameters.push(\n Hex.fromNumber(staticSize + dynamicSize, { size: 32 }),\n )\n dynamicParameters.push(encoded)\n dynamicSize += Hex.size(encoded)\n } else {\n staticParameters.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return Hex.concat(...staticParameters, ...dynamicParameters)\n}\n\n/** @internal */\nexport declare namespace encode {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeAddress(\n value: Hex.Hex,\n options: { checksum: boolean },\n): PreparedParameter {\n const { checksum = false } = options\n Address.assert(value, { strict: checksum })\n return {\n dynamic: false,\n encoded: Hex.padLeft(value.toLowerCase() as Hex.Hex),\n }\n}\n\n/** @internal */\nexport declare namespace encodeAddress {\n type ErrorType =\n | Address.assert.ErrorType\n | Hex.padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeArray(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, length, parameter } = options\n\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new AbiParameters.InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiParameters.ArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${parameter.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter,\n value: value[i],\n })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParameters.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encode(preparedParameters)\n if (dynamic) {\n const length = Hex.fromNumber(preparedParameters.length, { size: 32 })\n return {\n dynamic: true,\n encoded:\n preparedParameters.length > 0 ? Hex.concat(length, data) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeArray {\n type ErrorType =\n | AbiParameters.InvalidArrayError\n | AbiParameters.ArrayLengthMismatchError\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBytes(\n value: Hex.Hex,\n { type }: { type: string },\n): PreparedParameter {\n const [, parametersize] = type.split('bytes')\n const bytesSize = Hex.size(value)\n if (!parametersize) {\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_ = Hex.padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32)\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padLeft(Hex.fromNumber(bytesSize, { size: 32 })),\n value_,\n ),\n }\n }\n if (bytesSize !== Number.parseInt(parametersize, 10))\n throw new AbiParameters.BytesSizeMismatchError({\n expectedSize: Number.parseInt(parametersize, 10),\n value,\n })\n return { dynamic: false, encoded: Hex.padRight(value) }\n}\n\n/** @internal */\nexport declare namespace encodeBytes {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.padRight.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBoolean(value: boolean): PreparedParameter {\n if (typeof value !== 'boolean')\n throw new Errors.BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: Hex.padLeft(Hex.fromBoolean(value)) }\n}\n\n/** @internal */\nexport declare namespace encodeBoolean {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.fromBoolean.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeNumber(\n value: number,\n { signed, size }: { signed: boolean; size: number },\n): PreparedParameter {\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 Hex.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: Hex.fromNumber(value, {\n size: 32,\n signed,\n }),\n }\n}\n\n/** @internal */\nexport declare namespace encodeNumber {\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeString(value: string): PreparedParameter {\n const hexValue = Hex.fromString(value)\n const partsLength = Math.ceil(Hex.size(hexValue) / 32)\n const parts: Hex.Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(Hex.padRight(Hex.slice(hexValue, i * 32, (i + 1) * 32)))\n }\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padRight(Hex.fromNumber(Hex.size(hexValue), { size: 32 })),\n ...parts,\n ),\n }\n}\n\n/** @internal */\nexport declare namespace encodeString {\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Hex.padRight.ErrorType\n | Hex.slice.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeTuple<\n const parameter extends AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n },\n>(\n value: ParameterToPrimitiveType,\n options: {\n checksumAddress?: boolean | undefined\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, parameter } = options\n\n let dynamic = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameter.components.length; i++) {\n const param_ = parameter.components[i]!\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParameters.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encode(preparedParameters)\n : Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeTuple {\n type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\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\n/** @internal */\nexport function hasDynamicChild(param: AbiParameters.Parameter) {\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({\n ...param,\n type: arrayComponents[1],\n } as AbiParameters.Parameter)\n )\n return true\n\n return false\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\nexport 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 type { Bytes } from '../Bytes.js'\nimport * as Errors from '../Errors.js'\n\n/** @internal */\nexport type Cursor = {\n bytes: Bytes\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): Bytes[number]\n inspectBytes(length: number, position?: number): Bytes\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: Bytes[number]): void\n pushBytes(bytes: Bytes): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): Bytes[number]\n readBytes(length: number, size?: number): Bytes\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\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: Bytes[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: Bytes) {\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\n/** @internal */\nexport function create(\n bytes: Bytes,\n { recursiveReadLimit = 8_192 }: create.Config = {},\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\n/** @internal */\nexport declare namespace create {\n type Config = { recursiveReadLimit?: number | undefined }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport class NegativeOffsetError extends Errors.BaseError {\n override readonly name = 'Cursor.NegativeOffsetError'\n\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`)\n }\n}\n\n/** @internal */\nexport class PositionOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Cursor.PositionOutOfBoundsError'\n\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n )\n }\n}\n\n/** @internal */\nexport class RecursiveReadLimitExceededError extends Errors.BaseError {\n override readonly name = 'Cursor.RecursiveReadLimitExceededError'\n\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n )\n }\n}\n","import type * as Address from './Address.js'\nimport type * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, Mutable, Undefined } from './internal/types.js'\nimport * as Rlp from './Rlp.js'\nimport * as Signature from './Signature.js'\n\n/** Root type for an EIP-7702 Authorization. */\nexport type Authorization<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** Address of the contract to set as code for the Authority. */\n address: Address.Address\n /** Chain ID to authorize. */\n chainId: numberType\n /** Nonce of the Authority to authorize. */\n nonce: bigintType\n } & (signed extends true\n ? Signature.Signature\n : Undefined)\n>\n\n/** RPC representation of an {@link ox#Authorization.Authorization}. */\nexport type Rpc = Authorization\n\n/** List of {@link ox#Authorization.Authorization}. */\nexport type List<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute[]>\n\n/** RPC representation of an {@link ox#Authorization.List}. */\nexport type ListRpc = List\n\n/** Signed representation of a list of {@link ox#Authorization.Authorization}. */\nexport type ListSigned = List<\n true,\n bigintType,\n numberType\n>\n\n/** Signed representation of an {@link ox#Authorization.Authorization}. */\nexport type Signed = Authorization<\n true,\n bigintType,\n numberType\n>\n\n/** Tuple representation of an {@link ox#Authorization.Authorization}. */\nexport type Tuple = signed extends true\n ? readonly [\n chainId: Hex.Hex,\n address: Hex.Hex,\n nonce: Hex.Hex,\n yParity: Hex.Hex,\n r: Hex.Hex,\n s: Hex.Hex,\n ]\n : readonly [chainId: Hex.Hex, address: Hex.Hex, nonce: Hex.Hex]\n\n/** Tuple representation of a signed {@link ox#Authorization.Authorization}. */\nexport type TupleSigned = Tuple\n\n/** Tuple representation of a list of {@link ox#Authorization.Authorization}. */\nexport type TupleList =\n readonly Tuple[]\n\n/** Tuple representation of a list of signed {@link ox#Authorization.Authorization}. */\nexport type TupleListSigned = TupleList\n\n/**\n * Converts an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization object into a typed {@link ox#Authorization.Authorization}.\n *\n * @example\n * An Authorization can be instantiated from an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * A {@link ox#Signature.Signature} can be attached with the `signature` option. The example below demonstrates signing\n * an Authorization with {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: Authorization.getSignPayload(authorization),\n * privateKey: '0x...',\n * })\n *\n * const authorization_signed = Authorization.from(authorization, { signature }) // [!code focus]\n * ```\n *\n * @param authorization - An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n * @param options - Authorization options.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function from<\n const authorization extends Authorization | Rpc,\n const signature extends Signature.Signature | undefined = undefined,\n>(\n authorization: authorization | Authorization,\n options: from.Options = {},\n): from.ReturnType {\n if (typeof authorization.chainId === 'string')\n return fromRpc(authorization) as never\n return { ...authorization, ...options.signature } as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = {\n /** The {@link ox#Signature.Signature} to attach to the Authorization. */\n signature?: signature | Signature.Signature | undefined\n }\n\n type ReturnType<\n authorization extends Authorization | Rpc = Authorization,\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends Signature.Signature ? Readonly : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Rpc} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param authorization - The RPC-formatted Authorization.\n * @returns A signed {@link ox#Authorization.Authorization}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)!\n\n return {\n address,\n chainId: Number(chainId),\n nonce: BigInt(nonce),\n ...signature,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.ListRpc} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * }])\n * ```\n *\n * @param authorizationList - The RPC-formatted Authorization list.\n * @returns A signed {@link ox#Authorization.List}.\n */\nexport function fromRpcList(authorizationList: ListRpc): ListSigned {\n return authorizationList.map(fromRpc)\n}\n\nexport declare namespace fromRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Tuple} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3'\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: }\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3',\n * '0x1',\n * '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90',\n * '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: }\n * ```\n *\n * @param tuple - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function fromTuple(\n tuple: tuple,\n): fromTuple.ReturnType {\n const [chainId, address, nonce, yParity, r, s] = tuple\n let args = {\n address,\n chainId: chainId === '0x' ? 0 : Number(chainId),\n nonce: nonce === '0x' ? 0n : BigInt(nonce),\n }\n if (yParity && r && s)\n args = { ...args, ...Signature.fromTuple([yParity, r, s]) }\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType = Compute<\n Authorization ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.TupleList} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param tupleList - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n * @returns An {@link ox#Authorization.List}.\n */\nexport function fromTupleList(\n tupleList: tupleList,\n): fromTupleList.ReturnType {\n const list: Mutable = []\n for (const tuple of tupleList) list.push(fromTuple(tuple))\n return list as never\n}\n\nexport declare namespace fromTupleList {\n type ReturnType = Compute<\n TupleList ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * The example below demonstrates computing the sign payload for an {@link ox#Authorization.Authorization}. This payload\n * can then be passed to signing functions like {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = Authorization.getSignPayload(authorization) // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload,\n * privateKey: '0x...',\n * })\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: Authorization): Hex.Hex {\n return hash(authorization, { presign: true })\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const hash = Authorization.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The hash.\n */\nexport function hash(\n authorization: Authorization,\n options: hash.Options = {},\n): Hex.Hex {\n const { presign } = options\n return Hash.keccak256(\n Hex.concat(\n '0x05',\n Rlp.fromHex(\n toTuple(\n presign\n ? {\n address: authorization.address,\n chainId: authorization.chainId,\n nonce: authorization.nonce,\n }\n : authorization,\n ),\n ),\n ),\n )\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /** Whether to hash this authorization for signing. @default false */\n presign?: boolean | undefined\n }\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * })\n * ```\n *\n * @param authorization - An Authorization.\n * @returns An RPC-formatted Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, nonce, ...signature } = authorization\n\n return {\n address,\n chainId: Hex.fromNumber(chainId),\n nonce: Hex.fromNumber(nonce),\n ...Signature.toRpc(signature),\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.ListRpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * }])\n * ```\n *\n * @param authorizationList - An Authorization List.\n * @returns An RPC-formatted Authorization List.\n */\nexport function toRpcList(authorizationList: ListSigned): ListRpc {\n return authorizationList.map(toRpc)\n}\n\nexport declare namespace toRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const tuple = Authorization.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n */\nexport function toTuple(\n authorization: authorization,\n): toTuple.ReturnType {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)\n return [\n chainId ? Hex.fromNumber(chainId) : '0x',\n address,\n nonce ? Hex.fromNumber(nonce) : '0x',\n ...(signature ? Signature.toTuple(signature) : []),\n ] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType =\n Compute>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.TupleList}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization_1 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * const authorization_2 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 3,\n * nonce: 20n,\n * })\n *\n * const tuple = Authorization.toTupleList([authorization_1, authorization_2]) // [!code focus]\n * // @log: [\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ],\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param list - An {@link ox#Authorization.List}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n */\nexport function toTupleList<\n const list extends\n | readonly Authorization[]\n | readonly Authorization[],\n>(list?: list | undefined): toTupleList.ReturnType {\n if (!list || list.length === 0) return []\n\n const tupleList: Mutable = []\n for (const authorization of list) tupleList.push(toTuple(authorization))\n\n return tupleList as never\n}\n\nexport declare namespace toTupleList {\n type ReturnType<\n list extends\n | readonly Authorization[]\n | readonly Authorization[],\n > = Compute<\n TupleList[] ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Cursor from './internal/cursor.js'\nimport type { ExactPartial, RecursiveArray } from './internal/types.js'\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toBytes('0x8b68656c6c6f20776f726c64')\n * // Uint8Array([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Bytes.Bytes} value.\n */\nexport function toBytes(\n value: Bytes.Bytes | Hex.Hex,\n): RecursiveArray {\n return to(value, 'Bytes')\n}\n\nexport declare namespace toBytes {\n type ErrorType = to.ErrorType\n}\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toHex('0x8b68656c6c6f20776f726c64')\n * // 0x68656c6c6f20776f726c64\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes.Bytes | Hex.Hex): RecursiveArray {\n return to(value, 'Hex')\n}\n\nexport declare namespace toHex {\n type ErrorType = to.ErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\n/////////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport function to<\n value extends Bytes.Bytes | Hex.Hex,\n to extends 'Hex' | 'Bytes',\n>(value: value, to: to | 'Hex' | 'Bytes'): to.ReturnType {\n const to_ = to ?? (typeof value === 'string' ? 'Hex' : 'Bytes')\n\n const bytes = (() => {\n if (typeof value === 'string') {\n if (value.length > 3 && value.length % 2 !== 0)\n throw new Hex.InvalidLengthError(value)\n return Bytes.fromHex(value)\n }\n return value as Bytes.Bytes\n })()\n\n const cursor = Cursor.create(bytes, {\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n })\n const result = decodeRlpCursor(cursor, to_)\n\n return result as to.ReturnType\n}\n\n/** @internal */\nexport declare namespace to {\n type ReturnType =\n | (to extends 'Bytes' ? RecursiveArray : never)\n | (to extends 'Hex' ? RecursiveArray : never)\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | decodeRlpCursor.ErrorType\n | Cursor.create.ErrorType\n | Hex.InvalidLengthError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\n\n/** @internal */\nexport function decodeRlpCursor(\n cursor: Cursor.Cursor,\n to: to | 'Hex' | 'Bytes' | undefined = 'Hex',\n): decodeRlpCursor.ReturnType {\n if (cursor.bytes.length === 0)\n return (\n to === 'Hex' ? Hex.fromBytes(cursor.bytes) : cursor.bytes\n ) as decodeRlpCursor.ReturnType\n\n const prefix = cursor.readByte()\n if (prefix < 0x80) cursor.decrementPosition(1)\n\n // bytes\n if (prefix < 0xc0) {\n const length = readLength(cursor, prefix, 0x80)\n const bytes = cursor.readBytes(length)\n return (\n to === 'Hex' ? Hex.fromBytes(bytes) : bytes\n ) as decodeRlpCursor.ReturnType\n }\n\n // list\n const length = readLength(cursor, prefix, 0xc0)\n return readList(cursor, length, to) as {} as decodeRlpCursor.ReturnType\n}\n\n/** @internal */\nexport declare namespace decodeRlpCursor {\n type ReturnType = to.ReturnType\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | readLength.ErrorType\n | readList.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readLength(\n cursor: Cursor.Cursor,\n prefix: number,\n offset: number,\n) {\n if (offset === 0x80 && prefix < 0x80) return 1\n if (prefix <= offset + 55) return prefix - offset\n if (prefix === offset + 55 + 1) return cursor.readUint8()\n if (prefix === offset + 55 + 2) return cursor.readUint16()\n if (prefix === offset + 55 + 3) return cursor.readUint24()\n if (prefix === offset + 55 + 4) return cursor.readUint32()\n throw new Errors.BaseError('Invalid RLP prefix')\n}\n\n/** @internal */\nexport declare namespace readLength {\n type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readList(\n cursor: Cursor.Cursor,\n length: number,\n to: to | 'Hex' | 'Bytes',\n) {\n const position = cursor.position\n const value: decodeRlpCursor.ReturnType[] = []\n while (cursor.position - position < length)\n value.push(decodeRlpCursor(cursor, to))\n return value\n}\n\n/** @internal */\nexport declare namespace readList {\n type ErrorType = Errors.GlobalErrorType\n}\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor.Cursor): void\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.from('0x68656c6c6f20776f726c64', { as: 'Hex' })\n * // @log: 0x8b68656c6c6f20776f726c64\n *\n * Rlp.from(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), { as: 'Bytes' })\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function from(\n value: RecursiveArray | RecursiveArray,\n options: from.Options,\n): from.ReturnType {\n const { as } = options\n\n const encodable = getEncodable(value)\n const cursor = Cursor.create(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (as === 'Hex') return Hex.fromBytes(cursor.bytes) as from.ReturnType\n return cursor.bytes as from.ReturnType\n}\n\nexport declare namespace from {\n type Options = {\n /** The type to convert the RLP value to. */\n as: as | 'Hex' | 'Bytes'\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Cursor.create.ErrorType\n | Hex.fromBytes.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.fromBytes(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]))\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromBytes(\n bytes: RecursiveArray,\n options: fromBytes.Options = {},\n): fromBytes.ReturnType {\n const { as = 'Bytes' } = options\n return from(bytes, { as }) as never\n}\n\nexport declare namespace fromBytes {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n *\n * Rlp.fromHex('0x68656c6c6f20776f726c64')\n * // @log: 0x8b68656c6c6f20776f726c64\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromHex(\n hex: RecursiveArray,\n options: fromHex.Options = {},\n): fromHex.ReturnType {\n const { as = 'Hex' } = options\n return from(hex, { as }) as never\n}\n\nexport declare namespace fromHex {\n type Options = ExactPartial<\n from.Options\n >\n\n type ReturnType = from.ReturnType\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\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.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: Bytes.Bytes | Hex.Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? Bytes.fromHex(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.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 <= 0xff) return 1\n if (length <= 0xff_ff) return 2\n if (length <= 0xff_ff_ff) return 3\n if (length <= 0xff_ff_ff_ff) return 4\n throw new Errors.BaseError('Length is too large.')\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher = /* @__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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\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\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\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 // 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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16(Fp: IField, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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/**\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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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): 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(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\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 */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security 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're 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 isLE,\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 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 // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T): 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): 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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\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.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF> = {\n constTimeNegate: >(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group[];\n getPrecomputes(W: number, P: T, transform: Mapper): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF>(c: GroupConstructor, bits: number): IWNAF {\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\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 than 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 const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(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 < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & 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): (scalars: bigint[]) => T {\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 = bitMask(windowSize);\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/**\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).\n */\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(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type 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// 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 toAffine(iz?: T): AffinePoint;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\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\nexport type CurvePointsTypeWithLength = Readonly<\n CurvePointsType & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts(curve: CurvePointsType): CurvePointsTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: 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\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\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): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): 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 = 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 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = 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): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = 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 bytesToNumberBE(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 = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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 = 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 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return 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 (isBytes(key)) key = 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 : 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(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(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 if (!isValidXY(x, y)) 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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 aprjpoint(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 aprjpoint(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\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 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 /** See docs for {@link EndomorphismOpts} */\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 aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\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 bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly {\n const opts = validateBasic(curve);\n 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, nByteLength, nBitLength } = 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(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = 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 = bytesToNumberBE(tail);\n if (!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\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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\", for protection against DoS\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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 = 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 = 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' || 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(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial, OneOf } from './internal/types.js'\nimport * as Json from './Json.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for an ECDSA signature. */\nexport type Signature<\n recovered extends boolean = true,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n recovered extends true\n ? {\n r: bigintType\n s: bigintType\n yParity: numberType\n }\n : {\n r: bigintType\n s: bigintType\n yParity?: numberType | undefined\n }\n>\n\n/** RPC-formatted ECDSA signature. */\nexport type Rpc = Signature<\n recovered,\n Hex.Hex,\n Hex.Hex\n>\n\n/** (Legacy) ECDSA signature. */\nexport type Legacy = {\n r: bigintType\n s: bigintType\n v: numberType\n}\n\n/** RPC-formatted (Legacy) ECDSA signature. */\nexport type LegacyRpc = Legacy\n\nexport type Tuple = readonly [yParity: Hex.Hex, r: Hex.Hex, s: Hex.Hex]\n\n/**\n * Asserts that a Signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.assert({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @error: InvalidSignatureRError:\n * // @error: Value `-549...n` is an invalid r value.\n * // @error: r must be a positive integer less than 2^256.\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function assert(\n signature: ExactPartial,\n options: assert.Options = {},\n): asserts signature is Signature {\n const { recovered } = options\n if (typeof signature.r === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (typeof signature.s === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (recovered && typeof signature.yParity === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (signature.r < 0n || signature.r > Solidity.maxUint256)\n throw new InvalidRError({ value: signature.r })\n if (signature.s < 0n || signature.s > Solidity.maxUint256)\n throw new InvalidSError({ value: signature.s })\n if (\n typeof signature.yParity === 'number' &&\n signature.yParity !== 0 &&\n signature.yParity !== 1\n )\n throw new InvalidYParityError({ value: signature.yParity })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType =\n | MissingPropertiesError\n | InvalidRError\n | InvalidSError\n | InvalidYParityError\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Bytes.Bytes} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param signature - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromBytes(signature: Bytes.Bytes): Signature {\n return fromHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Hex.Hex} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.fromHex('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c')\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param serialized - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromHex(signature: Hex.Hex): Signature {\n if (signature.length !== 130 && signature.length !== 132)\n throw new InvalidSerializedSizeError({ signature })\n\n const r = BigInt(Hex.slice(signature, 0, 32))\n const s = BigInt(Hex.slice(signature, 32, 64))\n\n const yParity = (() => {\n const yParity = Number(`0x${signature.slice(130)}`)\n if (Number.isNaN(yParity)) return undefined\n try {\n return vToYParity(yParity)\n } catch {\n throw new InvalidYParityError({ value: yParity })\n }\n })()\n\n if (typeof yParity === 'undefined')\n return {\n r,\n s,\n } as never\n return {\n r,\n s,\n yParity,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType =\n | Hex.from.ErrorType\n | InvalidSerializedSizeError\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts a {@link ox#Signature.Signature} from an arbitrary object that may include signature properties.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.extract({\n * baz: 'barry',\n * foo: 'bar',\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * zebra: 'stripes',\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @param value - The arbitrary object to extract the signature from.\n * @returns The extracted {@link ox#Signature.Signature}.\n */\nexport function extract(value: extract.Value): Signature | undefined {\n if (typeof value.r === 'undefined') return undefined\n if (typeof value.s === 'undefined') return undefined\n return from(value as any)\n}\n\nexport declare namespace extract {\n type Value = {\n r?: bigint | Hex.Hex | undefined\n s?: bigint | Hex.Hex | undefined\n yParity?: number | Hex.Hex | undefined\n v?: number | Hex.Hex | undefined\n }\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#Signature.Signature} object from a {@link ox#Signature.Signature}, {@link ox#Signature.Legacy}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db801')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @example\n * ### From Legacy\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * v: 27,\n * })\n * // @log: {\n * // @log: r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * // @log: s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * // @log: yParity: 0\n * // @log: }\n * ```\n *\n * @param signature - The signature value to instantiate.\n * @returns The instantiated {@link ox#Signature.Signature}.\n */\nexport function from<\n const signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n>(\n signature:\n | signature\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n): from.ReturnType {\n const signature_ = (() => {\n if (typeof signature === 'string') return fromHex(signature)\n if (signature instanceof Uint8Array) return fromBytes(signature)\n if (typeof signature.r === 'string') return fromRpc(signature)\n if (signature.v) return fromLegacy(signature)\n return {\n r: signature.r,\n s: signature.s,\n ...(typeof signature.yParity !== 'undefined'\n ? { yParity: signature.yParity }\n : {}),\n }\n })()\n assert(signature_)\n return signature_ as never\n}\n\nexport declare namespace from {\n type ReturnType<\n signature extends\n | OneOf | Rpc | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n > = signature extends Signature & { v?: undefined }\n ? signature\n : Signature\n\n type ErrorType =\n | assert.ErrorType\n | fromBytes.ErrorType\n | fromHex.ErrorType\n | vToYParity.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerBytes(new Uint8Array([132, 51, 23, ...]))\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerBytes(signature: Bytes.Bytes): Signature {\n return fromDerHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerHex('0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerHex(signature: Hex.Hex): Signature {\n const { r, s } = secp256k1.Signature.fromDER(Hex.from(signature).slice(2))\n return { r, s }\n}\n\nexport declare namespace fromDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Legacy} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.fromLegacy({ r: 1n, s: 2n, v: 28 })\n * // @log: { r: 1n, s: 2n, yParity: 1 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Legacy} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromLegacy(signature: Legacy): Signature {\n return {\n r: signature.r,\n s: signature.s,\n yParity: vToYParity(signature.v),\n }\n}\n\nexport declare namespace fromLegacy {\n type ErrorType = vToYParity.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Rpc} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromRpc({\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Rpc} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromRpc(signature: {\n r: Hex.Hex\n s: Hex.Hex\n yParity?: Hex.Hex | undefined\n v?: Hex.Hex | undefined\n}): Signature {\n const yParity = (() => {\n const v = signature.v ? Number(signature.v) : undefined\n let yParity = signature.yParity ? Number(signature.yParity) : undefined\n if (typeof v === 'number' && typeof yParity !== 'number')\n yParity = vToYParity(v)\n if (typeof yParity !== 'number')\n throw new InvalidYParityError({ value: signature.yParity })\n return yParity\n })()\n\n return {\n r: BigInt(signature.r),\n s: BigInt(signature.s),\n yParity,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Tuple} to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromTuple(['0x01', '0x7b', '0x1c8'])\n * // @log: {\n * // @log: r: 123n,\n * // @log: s: 456n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @param tuple - The {@link ox#Signature.Tuple} to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromTuple(tuple: Tuple): Signature {\n const [yParity, r, s] = tuple\n return from({\n r: r === '0x' ? 0n : BigInt(r),\n s: s === '0x' ? 0n : BigInt(s),\n yParity: yParity === '0x' ? 0 : Number(yParity),\n })\n}\n\nexport declare namespace fromTuple {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toBytes({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: Uint8Array [102, 16, 10, ...]\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toBytes(signature: Signature): Bytes.Bytes {\n return Bytes.fromHex(toHex(signature))\n}\n\nexport declare namespace toBytes {\n type ErrorType =\n | toHex.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toHex({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c'\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toHex(signature: Signature): Hex.Hex {\n assert(signature)\n\n const r = signature.r\n const s = signature.s\n\n const signature_ = Hex.concat(\n Hex.fromNumber(r, { size: 32 }),\n Hex.fromNumber(s, { size: 32 }),\n // If the signature is recovered, add the recovery byte to the signature.\n typeof signature.yParity === 'number'\n ? Hex.fromNumber(yParityToV(signature.yParity), { size: 1 })\n : '0x',\n )\n\n return signature_\n}\n\nexport declare namespace toHex {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerBytes(signature)\n * // @log: Uint8Array [132, 51, 23, ...]\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerBytes(signature: Signature): Bytes.Bytes {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return sig.toDERRawBytes()\n}\n\nexport declare namespace toDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerHex(signature)\n * // @log: '0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8'\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerHex(signature: Signature): Hex.Hex {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return `0x${sig.toDERHex()}`\n}\n\nexport declare namespace toDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Legacy}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.toLegacy({ r: 1n, s: 2n, yParity: 1 })\n * // @log: { r: 1n, s: 2n, v: 28 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Legacy}.\n */\nexport function toLegacy(signature: Signature): Legacy {\n return {\n r: signature.r,\n s: signature.s,\n v: yParityToV(signature.yParity),\n }\n}\n\nexport declare namespace toLegacy {\n type ErrorType = yParityToV.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toRpc({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Rpc}.\n */\nexport function toRpc(signature: Signature): Rpc {\n const { r, s, yParity } = signature\n return {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity: yParity === 0 ? '0x0' : '0x1',\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to a serialized {@link ox#Signature.Tuple} to be used for signatures in Transaction Envelopes, EIP-7702 Authorization Lists, etc.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signatureTuple = Signature.toTuple({\n * r: 123n,\n * s: 456n,\n * yParity: 1,\n * })\n * // @log: [yParity: '0x01', r: '0x7b', s: '0x1c8']\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The {@link ox#Signature.Tuple}.\n */\nexport function toTuple(signature: Signature): Tuple {\n const { r, s, yParity } = signature\n\n return [\n yParity ? '0x01' : '0x',\n r === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(r!)),\n s === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(s!)),\n ] as const\n}\n\nexport declare namespace toTuple {\n type ErrorType =\n | Hex.trimLeft.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a Signature. Returns `true` if the signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const valid = Signature.validate({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: false\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function validate(\n signature: ExactPartial,\n options: validate.Options = {},\n): boolean {\n try {\n assert(signature, options)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const yParity = Signature.vToYParity(28)\n * // @log: 1\n * ```\n *\n * @param v - The ECDSA `v` value to convert.\n * @returns The `yParity` value.\n */\nexport function vToYParity(v: number): Signature['yParity'] {\n if (v === 0 || v === 27) return 0\n if (v === 1 || v === 28) return 1\n if (v >= 35) return v % 2 === 0 ? 1 : 0\n throw new InvalidVError({ value: v })\n}\n\nexport declare namespace vToYParity {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const v = Signature.yParityToV(1)\n * // @log: 28\n * ```\n *\n * @param yParity - The ECDSA `yParity` value to convert.\n * @returns The `v` value.\n */\nexport function yParityToV(yParity: number): number {\n if (yParity === 0) return 27\n if (yParity === 1) return 28\n throw new InvalidYParityError({ value: yParity })\n}\n\nexport declare namespace yParityToV {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/** Thrown when the serialized signature is of an invalid size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSerializedSizeError'\n\n constructor({ signature }: { signature: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${signature}\\` is an invalid signature size.`, {\n metaMessages: [\n 'Expected: 64 bytes or 65 bytes.',\n `Received ${Hex.size(Hex.from(signature))} bytes.`,\n ],\n })\n }\n}\n\n/** Thrown when the signature is missing either an `r`, `s`, or `yParity` property. */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'Signature.MissingPropertiesError'\n\n constructor({ signature }: { signature: unknown }) {\n super(\n `Signature \\`${Json.stringify(signature)}\\` is missing either an \\`r\\`, \\`s\\`, or \\`yParity\\` property.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `r` value. */\nexport class InvalidRError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidRError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid r value. r must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `s` value. */\nexport class InvalidSError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid s value. s must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `yParity` value. */\nexport class InvalidYParityError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidYParityError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid y-parity value. Y-parity must be 0 or 1.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `v` value. */\nexport class InvalidVError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidVError'\n\n constructor({ value }: { value: number }) {\n super(`Value \\`${value}\\` is an invalid v value. v must be 27, 28 or >=35.`)\n }\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Entropy from './internal/entropy.js'\nimport type { OneOf } from './internal/types.js'\nimport * as PublicKey from './PublicKey.js'\nimport type * as Signature from './Signature.js'\n\n/** Re-export of noble/curves secp256k1 utilities. */\nexport const noble = secp256k1\n\n/**\n * Creates a new secp256k1 ECDSA key pair consisting of a private key and its corresponding public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey, publicKey } = Secp256k1.createKeyPair()\n * ```\n *\n * @param options - The options to generate the key pair.\n * @returns The generated key pair containing both private and public keys.\n */\nexport function createKeyPair(\n options: createKeyPair.Options = {},\n): createKeyPair.ReturnType {\n const { as = 'Hex' } = options\n const privateKey = randomPrivateKey({ as })\n const publicKey = getPublicKey({ privateKey })\n\n return {\n privateKey: privateKey as never,\n publicKey,\n }\n}\n\nexport declare namespace createKeyPair {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType = {\n privateKey:\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n publicKey: PublicKey.PublicKey\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the secp256k1 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const publicKey = Secp256k1.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(\n options: getPublicKey.Options,\n): PublicKey.PublicKey {\n const { privateKey } = options\n const point = secp256k1.ProjectivePoint.fromPrivateKey(\n Hex.from(privateKey).slice(2),\n )\n return PublicKey.from(point)\n}\n\nexport declare namespace getPublicKey {\n type Options = {\n /**\n * Private key to compute the public key from.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes a shared secret using ECDH (Elliptic Curve Diffie-Hellman) between a private key and a public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey: privateKeyA } = Secp256k1.createKeyPair()\n * const { publicKey: publicKeyB } = Secp256k1.createKeyPair()\n *\n * const sharedSecret = Secp256k1.getSharedSecret({\n * privateKey: privateKeyA,\n * publicKey: publicKeyB\n * })\n * ```\n *\n * @param options - The options to compute the shared secret.\n * @returns The computed shared secret.\n */\nexport function getSharedSecret(\n options: getSharedSecret.Options,\n): getSharedSecret.ReturnType {\n const { as = 'Hex', privateKey, publicKey } = options\n const point = secp256k1.ProjectivePoint.fromHex(\n PublicKey.toHex(publicKey).slice(2),\n )\n const sharedPoint = point.multiply(\n secp256k1.utils.normPrivateKeyToScalar(Hex.from(privateKey).slice(2)),\n )\n const sharedSecret = sharedPoint.toRawBytes(true) // compressed format\n if (as === 'Hex') return Hex.fromBytes(sharedSecret) as never\n return sharedSecret as never\n}\n\nexport declare namespace getSharedSecret {\n type Options = {\n /**\n * Format of the returned shared secret.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n /**\n * Private key to use for the shared secret computation.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n /**\n * Public key to use for the shared secret computation.\n */\n publicKey: PublicKey.PublicKey\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.toHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random ECDSA private key on the secp256k1 curve.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey(\n options: randomPrivateKey.Options = {},\n): randomPrivateKey.ReturnType {\n const { as = 'Hex' } = options\n const bytes = secp256k1.utils.randomPrivateKey()\n if (as === 'Hex') return Hex.fromBytes(bytes) as never\n return bytes as never\n}\n\nexport declare namespace randomPrivateKey {\n type Options = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing address from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const address = Secp256k1.recoverAddress({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered address.\n */\nexport function recoverAddress(\n options: recoverAddress.Options,\n): recoverAddress.ReturnType {\n return Address.fromPublicKey(recoverPublicKey(options))\n}\n\nexport declare namespace recoverAddress {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = Secp256k1.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(\n options: recoverPublicKey.Options,\n): PublicKey.PublicKey {\n const { payload, signature } = options\n const { r, s, yParity } = signature\n const signature_ = new secp256k1.Signature(\n BigInt(r),\n BigInt(s),\n ).addRecoveryBit(yParity)\n const point = signature_.recoverPublicKey(Hex.from(payload).substring(2))\n return PublicKey.from(point)\n}\n\nexport declare namespace recoverPublicKey {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ErrorType =\n | PublicKey.from.ErrorType\n | Hex.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs the payload with the provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options: sign.Options): Signature.Signature {\n const {\n extraEntropy = Entropy.extraEntropy,\n hash,\n payload,\n privateKey,\n } = options\n const { r, s, recovery } = secp256k1.sign(\n Bytes.from(payload),\n Bytes.from(privateKey),\n {\n extraEntropy:\n typeof extraEntropy === 'boolean'\n ? extraEntropy\n : Hex.from(extraEntropy).slice(2),\n lowS: true,\n ...(hash ? { prehash: true } : {}),\n },\n )\n return {\n r,\n s,\n yParity: recovery,\n }\n}\n\nexport declare namespace sign {\n type Options = {\n /**\n * Extra entropy to add to the signing process. Setting to `false` will disable it.\n * @default true\n */\n extraEntropy?: boolean | Hex.Hex | Bytes.Bytes | undefined\n /**\n * If set to `true`, the payload will be hashed (sha256) before being signed.\n */\n hash?: boolean | undefined\n /**\n * Payload to sign.\n */\n payload: Hex.Hex | Bytes.Bytes\n /**\n * ECDSA private key.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Bytes.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Verifies a payload was signed by the provided address.\n *\n * @example\n * ### Verify with Ethereum Address\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Verify with Public Key\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = '0x...'\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided address.\n */\nexport function verify(options: verify.Options): boolean {\n const { address, hash, payload, publicKey, signature } = options\n if (address)\n return Address.isEqual(address, recoverAddress({ payload, signature }))\n return secp256k1.verify(\n signature,\n Bytes.from(payload),\n PublicKey.toBytes(publicKey),\n ...(hash ? [{ prehash: true, lowS: true }] : []),\n )\n}\n\nexport declare namespace verify {\n type Options = {\n /** If set to `true`, the payload will be hashed (sha256) before being verified. */\n hash?: boolean | undefined\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Address that signed the payload. */\n address: Address.Address\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RpcProof } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../index.js'\n\nexport type FormatProofErrorType = ErrorType\n\nfunction formatStorageProof(storageProof: RpcProof['storageProof']) {\n return storageProof.map((proof) => ({\n ...proof,\n value: BigInt(proof.value),\n }))\n}\n\nexport function formatProof(proof: ExactPartial) {\n return {\n ...proof,\n balance: proof.balance ? BigInt(proof.balance) : undefined,\n nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined,\n storageProof: proof.storageProof\n ? formatStorageProof(proof.storageProof)\n : undefined,\n } as Proof\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.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 { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetStorageAtParameters = {\n address: Address\n slot: Hex\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetStorageAtReturnType = Hex | undefined\n\nexport type GetStorageAtErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param client - Client to use\n * @param parameters - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getStorageAt(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\nexport async function getStorageAt(\n client: Client,\n { address, blockNumber, blockTag = 'latest', slot }: GetStorageAtParameters,\n): Promise {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const data = await client.request({\n method: 'eth_getStorageAt',\n params: [address, slot, blockNumberHex || blockTag],\n })\n return data\n}\n","import type { Address } from '../../accounts/index.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { OneOf, Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters =\n OneOf<\n // eth_getTransactionByBlockHashAndIndex\n | {\n /** The block hash */\n blockHash: Hash\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block number */\n blockNumber: bigint\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block tag. */\n blockTag: blockTag | BlockTag\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByHash\n | {\n /** The hash of the transaction. */\n hash: Hash\n }\n // eth_getTransactionBySenderAndNonce\n | {\n /** The sender of the transaction. */\n sender: Address\n /** The nonce of the transaction on the sender. */\n nonce: number\n }\n >\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetTransactionErrorType =\n | TransactionNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n sender,\n nonce,\n }: GetTransactionParameters,\n): Promise> {\n const blockTag = blockTag_ || 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let transaction: RpcTransaction | null = null\n if (hash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if ((blockNumberHex || blockTag) && typeof index === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n } else if (sender && typeof nonce === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionBySenderAndNonce',\n params: [sender, numberToHex(nonce)],\n },\n { dedupe: true },\n )\n }\n\n if (!transaction)\n throw new TransactionNotFoundError({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n })\n\n const format =\n client.chain?.formatters?.transaction?.format || formatTransaction\n return format(transaction, 'getTransaction')\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { FormattedTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetBlockNumberErrorType,\n getBlockNumber,\n} from './getBlockNumber.js'\nimport {\n type GetTransactionErrorType,\n getTransaction,\n} from './getTransaction.js'\n\nexport type GetTransactionConfirmationsParameters<\n chain extends Chain | undefined = Chain,\n> =\n | {\n /** The transaction hash. */\n hash: Hash\n transactionReceipt?: undefined\n }\n | {\n hash?: undefined\n /** The transaction receipt. */\n transactionReceipt: FormattedTransactionReceipt\n }\n\nexport type GetTransactionConfirmationsReturnType = bigint\n\nexport type GetTransactionConfirmationsErrorType =\n | GetBlockNumberErrorType\n | GetTransactionErrorType\n | ErrorType\n\n/**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionConfirmations } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await getTransactionConfirmations(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionConfirmations<\n chain extends Chain | undefined,\n>(\n client: Client,\n { hash, transactionReceipt }: GetTransactionConfirmationsParameters,\n): Promise {\n const [blockNumber, transaction] = await Promise.all([\n getAction(client, getBlockNumber, 'getBlockNumber')({}),\n hash\n ? getAction(client, getTransaction, 'getTransaction')({ hash })\n : undefined,\n ])\n const transactionBlockNumber =\n transactionReceipt?.blockNumber || transaction?.blockNumber\n if (!transactionBlockNumber) return 0n\n return blockNumber - transactionBlockNumber! + 1n\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n /** The hash of the transaction. */\n hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt(\n client: Client,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(\n receipt,\n 'getTransactionReceipt',\n ) as GetTransactionReceiptReturnType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { multicall3Bytecode } from '../../constants/contracts.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record\n } = {},\n> = Pick<\n CallParameters,\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'stateOverride'\n> & {\n /** The account to use for the multicall. */\n account?: Address | undefined\n /** Whether to allow failures. */\n allowFailure?: allowFailure | boolean | undefined\n /** The size of each batch of calls. */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The contracts to call. */\n contracts: MulticallContracts<\n Narrow,\n { mutability: AbiStateMutability } & options\n >\n /** The address of the multicall3 contract to use. */\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client,\n parameters: MulticallParameters,\n): Promise> {\n const {\n account,\n authorizationList,\n allowFailure = true,\n blockNumber,\n blockOverrides,\n blockTag,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const {\n batchSize = parameters.batchSize ?? 1024,\n deployless = parameters.deployless ?? false,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n\n const multicallAddress = (() => {\n if (parameters.multicallAddress) return parameters.multicallAddress\n if (deployless) return null\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n })()\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n sender: account,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress === null\n ? { code: multicall3Bytecode }\n : { address: multicallAddress }),\n abi: multicall3Abi,\n account,\n args: [calls],\n authorizationList,\n blockNumber,\n blockOverrides,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType\n}\n","import type { Abi, AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\n\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 { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.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 EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { concat } from '../../utils/data/concat.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getContractError } from '../../utils/errors/getContractError.js'\nimport {\n type GetNodeErrorReturnType,\n getNodeError,\n} from '../../utils/errors/getNodeError.js'\nimport {\n type FormatBlockErrorType,\n formatBlock,\n} from '../../utils/formatters/block.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport {\n type FormatTransactionRequestErrorType,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\n\ntype CallExtraProperties = ExactPartial<\n UnionOmit<\n TransactionRequest,\n 'blobs' | 'data' | 'kzg' | 'to' | 'sidecars' | 'value'\n >\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Recipient. `null` if contract deployment. */\n to?: Address | null | undefined\n}\n\nexport type SimulateBlocksParameters<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Blocks to simulate. */\n blocks: readonly {\n /** Block overrides. */\n blockOverrides?: BlockOverrides.BlockOverrides | undefined\n /** Calls to execute. */\n calls: Calls, CallExtraProperties>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n }[]\n /** Whether to return the full transactions. */\n returnFullTransactions?: boolean | undefined\n /** Whether to trace transfers. */\n traceTransfers?: boolean | undefined\n /** Whether to enable validation mode. */\n validation?: boolean | 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)\n\nexport type SimulateBlocksReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = readonly (Block & {\n calls: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n})[]\n\nexport type SimulateBlocksErrorType =\n | AssertRequestErrorType\n | DecodeFunctionResultErrorType\n | EncodeFunctionDataErrorType\n | FormatBlockErrorType\n | FormatTransactionRequestErrorType\n | GetNodeErrorReturnType\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createClient, http, parseEther } from 'viem'\n * import { simulate } from 'viem/actions'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulate(client, {\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateBlocksParameters}\n * @returns Simulated blocks. {@link SimulateBlocksReturnType}\n */\nexport async function simulateBlocks<\n chain extends Chain | undefined,\n const calls extends readonly unknown[],\n>(\n client: Client,\n parameters: SimulateBlocksParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n blocks,\n returnFullTransactions,\n traceTransfers,\n validation,\n } = parameters\n\n try {\n const blockStateCalls = []\n for (const block of blocks) {\n const blockOverrides = block.blockOverrides\n ? BlockOverrides.toRpc(block.blockOverrides)\n : undefined\n const calls = block.calls.map((call_) => {\n const call = call_ as Call\n const account = call.account ? parseAccount(call.account) : undefined\n const data = call.abi ? encodeFunctionData(call) : call.data\n const request = {\n ...call,\n account,\n data: call.dataSuffix\n ? concat([data || '0x', call.dataSuffix])\n : data,\n from: call.from ?? account?.address,\n } as const\n assertRequest(request)\n return formatTransactionRequest(request)\n })\n const stateOverrides = block.stateOverrides\n ? serializeStateOverride(block.stateOverrides)\n : undefined\n\n blockStateCalls.push({\n blockOverrides,\n calls,\n stateOverrides,\n })\n }\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const result = await client.request({\n method: 'eth_simulateV1',\n params: [\n { blockStateCalls, returnFullTransactions, traceTransfers, validation },\n block,\n ],\n })\n\n return result.map((block, i) => ({\n ...formatBlock(block),\n calls: block.calls.map((call, j) => {\n const { abi, args, functionName, to } = blocks[i].calls[j] as Call<\n unknown,\n CallExtraProperties\n >\n\n const data = call.error?.data ?? call.returnData\n const gasUsed = BigInt(call.gasUsed)\n const logs = call.logs?.map((log) => formatLog(log))\n const status = call.status === '0x1' ? 'success' : 'failure'\n\n const result =\n abi && status === 'success' && data !== '0x'\n ? decodeFunctionResult({\n abi,\n data,\n functionName,\n })\n : null\n\n const error = (() => {\n if (status === 'success') return undefined\n\n let error: Error | undefined\n if (data === '0x') error = new AbiDecodingZeroDataError()\n else if (data) error = new RawContractError({ data })\n\n if (!error) return undefined\n return getContractError(error, {\n abi: (abi ?? []) as Abi,\n address: to ?? '0x',\n args,\n functionName: functionName ?? '',\n })\n })()\n\n return {\n data,\n gasUsed,\n logs,\n status,\n ...(status === 'success'\n ? {\n result,\n }\n : {\n error,\n }),\n }\n }),\n })) as unknown as SimulateBlocksReturnType\n } catch (e) {\n const cause = e as BaseError\n const error = getNodeError(cause, {})\n if (error instanceof UnknownNodeError) throw cause\n throw error\n }\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiItem.js'\nimport type { UnionCompute } from './internal/types.js'\n\n/** Root type for an item on an {@link ox#Abi.Abi}. */\nexport type AbiItem = Abi.Abi[number]\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type Foo = AbiItem.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = Extract\n\n/**\n * Extracts the names of all {@link ox#AbiItem.AbiItem} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type names = AbiItem.Name\n * // ^?\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames = Extract<\n abi[number],\n { name: string }\n>['name']\n\n/**\n * Formats an {@link ox#AbiItem.AbiItem} into a **Human Readable ABI Item**.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const formatted = AbiItem.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiItem - The ABI Item to format.\n * @returns The formatted ABI Item .\n */\nexport function format(\n abiItem: abiItem | AbiItem,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiItem) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Item** or **Human Readable ABI Item** into a typed {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from({\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: [{ type: 'bool' }],\n * })\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiItem - The ABI Item to parse.\n * @returns The typed ABI Item.\n */\nexport function from<\n const abiItem extends AbiItem | string | readonly string[],\n>(\n abiItem: (abiItem | AbiItem | string | readonly string[]) &\n (\n | (abiItem extends string ? internal.Signature : never)\n | (abiItem extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiItem\n ),\n options: from.Options = {},\n): from.ReturnType {\n const { prepare = true } = options\n const item = (() => {\n if (Array.isArray(abiItem)) return abitype.parseAbiItem(abiItem)\n if (typeof abiItem === 'string')\n return abitype.parseAbiItem(abiItem as never)\n return abiItem\n })() as AbiItem\n return {\n ...item,\n ...(prepare ? { hash: getSignatureHash(item) } : {}),\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType =\n abiItem extends string\n ? abitype.ParseAbiItem\n : abiItem extends readonly string[]\n ? abitype.ParseAbiItem\n : abiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ABI Items can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiItem.fromAbi(abi, 'Transfer') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Items can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiItem.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Item from an `eth_call` RPC response,\n * a Transaction `input`, or from Event Log `topics`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends internal.ExtractArgs | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: fromAbi.Options,\n): fromAbi.ReturnType {\n const { args = [], prepare = true } = (options ??\n {}) as unknown as fromAbi.Options\n\n const isSelector = Hex.validate(name, { strict: false })\n const abiItems = (abi as Abi.Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function' || abiItem.type === 'error')\n return getSelector(abiItem) === Hex.slice(name, 0, 4)\n if (abiItem.type === 'event') return getSignatureHash(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0) throw new NotFoundError({ name: name as string })\n if (abiItems.length === 1)\n return {\n ...abiItems[0],\n ...(prepare ? { hash: getSignatureHash(abiItems[0]!) } : {}),\n } as never\n\n let matchedAbiItem: AbiItem | 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 {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\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 internal.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 = internal.getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AmbiguityError(\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 const abiItem = (() => {\n if (matchedAbiItem) return matchedAbiItem\n const [abiItem, ...overloads] = abiItems\n return { ...abiItem!, overloads }\n })()\n\n if (!abiItem) throw new NotFoundError({ name: name as string })\n return {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\n}\n\nexport declare namespace fromAbi {\n type Options<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n ///\n allArgs = internal.ExtractArgs,\n > = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n } & UnionCompute<\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.Abi\n ? args extends allArgs\n ? internal.Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (internal.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\n type ReturnType<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name = Name,\n args extends\n | internal.ExtractArgs\n | undefined = internal.ExtractArgs,\n fallback = AbiItem,\n > = abi extends Abi.Abi\n ? Abi.Abi extends abi\n ? fallback\n : internal.ExtractForArgs<\n abi,\n name,\n args extends internal.ExtractArgs\n ? args\n : internal.ExtractArgs\n >\n : fallback\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const selector = AbiItem.getSelector(erc20Abi, 'ownerOf')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for. Can be a signature or an ABI item for an error, event, function, etc.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSelector(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSelector(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n return Hex.slice(getSignatureHash(abiItem), 0, 4)\n}\n\nexport declare namespace getSelector {\n type ErrorType =\n | getSignatureHash.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the stringified signature for a given {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature('function ownerOf(uint256 tokenId)')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const signature = AbiItem.getSignature(erc20Abi, 'ownerOf')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature for.\n * @returns The stringified signature of the ABI Item.\n */\nexport function getSignature<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): string\nexport function getSignature(abiItem: string | AbiItem): string\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignature(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): string {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n const signature = (() => {\n if (typeof abiItem === 'string') return abiItem\n return abitype.formatAbiItem(abiItem)\n })()\n return internal.normalizeSignature(signature)\n}\n\nexport declare namespace getSignature {\n type ErrorType =\n | internal.normalizeSignature.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the signature hash for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing Event Topic values.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash('event Transfer(address indexed from, address indexed to, uint256 amount)')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiItem } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const hash = AbiItem.getSignatureHash(erc20Abi, 'Transfer')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash({\n * name: 'Transfer',\n * type: 'event',\n * inputs: [\n * { name: 'from', type: 'address', indexed: true },\n * { name: 'to', type: 'address', indexed: true },\n * { name: 'amount', type: 'uint256', indexed: false },\n * ],\n * })\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature hash for.\n * @returns The {@link ox#Hash.(keccak256:function)} hash of the ABI item's signature.\n */\nexport function getSignatureHash<\n abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n>(abi: abi | Abi.Abi | readonly unknown[], name: name): Hex.Hex\nexport function getSignatureHash(abiItem: string | AbiItem): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function getSignatureHash(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: string]\n | [string | AbiItem]\n): Hex.Hex {\n const abiItem = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name] = parameters as [Abi.Abi | readonly unknown[], string]\n return fromAbi(abi, name)\n }\n return parameters[0] as string | AbiItem\n })()\n if (typeof abiItem !== 'string' && 'hash' in abiItem && abiItem.hash)\n return abiItem.hash as Hex.Hex\n return Hash.keccak256(Hex.fromString(getSignature(abiItem)))\n}\n\nexport declare namespace getSignatureHash {\n type ErrorType =\n | getSignature.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Throws when ambiguous types are found on overloaded ABI items.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from(['function foo(address)', 'function foo(bytes20)'])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n *\n * ### Solution\n *\n * Remove one of the ambiguous types from the ABI.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function foo(bytes20)' // [!code --]\n * ])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n */\nexport class AmbiguityError extends Errors.BaseError {\n override readonly name = 'AbiItem.AmbiguityError'\n constructor(\n x: { abiItem: Abi.Abi[number]; type: string },\n y: { abiItem: Abi.Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI Items.', {\n metaMessages: [\n // TODO: abitype to add support for signature-formatted ABI items.\n `\\`${x.type}\\` in \\`${internal.normalizeSignature(abitype.formatAbiItem(x.abiItem))}\\`, and`,\n `\\`${y.type}\\` in \\`${internal.normalizeSignature(abitype.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 })\n }\n}\n\n/**\n * Throws when an ABI item is not found in the ABI.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * // @error: AbiItem.NotFoundError: ABI function with name \"baz\" not found.\n * ```\n *\n * ### Solution\n *\n * Ensure the ABI item exists on the ABI.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)',\n * 'function baz(bool)' // [!code ++]\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * ```\n */\nexport class NotFoundError extends Errors.BaseError {\n override readonly name = 'AbiItem.NotFoundError'\n constructor({\n name,\n data,\n type = 'item',\n }: {\n name?: string | undefined\n data?: Hex.Hex | undefined\n type?: string | undefined\n }) {\n const selector = (() => {\n if (name) return ` with name \"${name}\"`\n if (data) return ` with data \"${data}\"`\n return ''\n })()\n super(`ABI ${type}${selector} not found.`)\n }\n}\n\n/**\n * Throws when the selector size is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0xaaa')\n * // @error: AbiItem.InvalidSelectorSizeError: Selector size is invalid. Expected 4 bytes. Received 2 bytes (\"0xaaa\").\n * ```\n *\n * ### Solution\n *\n * Ensure the selector size is 4 bytes.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0x7af82b1a')\n * ```\n */\nexport class InvalidSelectorSizeError extends Errors.BaseError {\n override readonly name = 'AbiItem.InvalidSelectorSizeError'\n constructor({ data }: { data: Hex.Hex }) {\n super(\n `Selector size is invalid. Expected 4 bytes. Received ${Hex.size(data)} bytes (\"${data}\").`,\n )\n }\n}\n","import type * as abitype from 'abitype'\nimport type * as Abi from '../Abi.js'\nimport type * as AbiItem from '../AbiItem.js'\nimport type * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Errors from '../Errors.js'\nimport type {\n Compute,\n IsNever,\n IsUnion,\n TypeErrorMessage,\n UnionToTuple,\n} from './types.js'\n\n/** @internal */\nexport type ExtractArgs<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends AbiItem.Name = AbiItem.Name,\n> = abitype.AbiParametersToPrimitiveTypes<\n AbiItem.FromAbi['inputs'],\n 'inputs'\n> extends infer args\n ? [args] extends [never]\n ? readonly unknown[]\n : args\n : readonly unknown[]\n\n/** @internal */\nexport type ExtractForArgs<\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = IsUnion extends true\n ? {\n [key in keyof abi]: abi[key] extends { name: name } ? abi[key] : never\n }[number]\n : AbiItem.FromAbi extends infer abiItem extends AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n }\n ? IsUnion extends true // narrow overloads using `args` by converting to tuple and filtering out overloads that don't match\n ? UnionToTuple extends infer abiItems extends\n readonly (AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n })[]\n ? IsNever> extends true\n ? Compute<\n abiItems[0] & {\n readonly overloads: UnionToTuple<\n Exclude\n >\n }\n >\n : TupleToUnion // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)\n : never\n : abiItem\n : never\n\n/** @internal */\nexport type TupleToUnion<\n abiItems extends readonly {\n inputs: readonly abitype.AbiParameter[]\n }[],\n abi extends Abi.Abi,\n name extends AbiItem.Name,\n args extends ExtractArgs,\n> = {\n [k in keyof abiItems]: (\n readonly [] extends args\n ? readonly [] // fallback to `readonly []` if `args` has no value (e.g. `args` property not provided)\n : args\n ) extends abitype.AbiParametersToPrimitiveTypes<\n abiItems[k]['inputs'],\n 'inputs'\n >\n ? abiItems[k]\n : never\n}[number]\n\n/** @internal */\nexport type ErrorSignature<\n name extends string = string,\n parameters extends string = string,\n> = `error ${name}(${parameters})`\n\n/** @internal */\nexport type IsErrorSignature =\n signature extends ErrorSignature ? IsName : false\n\n/** @internal */\nexport type EventSignature<\n name extends string = string,\n parameters extends string = string,\n> = `event ${name}(${parameters})`\n\n/** @internal */\nexport type IsEventSignature =\n signature extends EventSignature ? IsName : false\n\n/** @internal */\nexport type FunctionSignature<\n name extends string = string,\n tail extends string = string,\n> = `function ${name}(${tail}`\nexport type IsFunctionSignature =\n signature extends FunctionSignature\n ? IsName extends true\n ? signature extends ValidFunctionSignatures\n ? true\n : // Check that `Parameters` is not absorbing other types (e.g. `returns`)\n signature extends `function ${string}(${infer parameters})`\n ? parameters extends InvalidFunctionParameters\n ? false\n : true\n : false\n : false\n : false\n/** @internal */\nexport type Scope = 'public' | 'external' // `internal` or `private` functions wouldn't make it to ABI so can ignore\n\n/** @internal */\nexport type Returns = `returns (${string})` | `returns(${string})`\n\n// Almost all valid function signatures, except `function ${string}(${infer parameters})` since `parameters` can absorb returns\n/** @internal */\nexport type ValidFunctionSignatures =\n | `function ${string}()`\n // basic\n | `function ${string}() ${Returns}`\n | `function ${string}() ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope}`\n // combinations\n | `function ${string}() ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}() ${Scope} ${Returns}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n // Parameters\n | `function ${string}(${string}) ${Returns}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n\n/** @internal */\nexport type StructSignature<\n name extends string = string,\n properties extends string = string,\n> = `struct ${name} {${properties}}`\n\n/** @internal */\nexport type IsStructSignature =\n signature extends StructSignature ? IsName : false\n\n/** @internal */\nexport type ConstructorSignature =\n `constructor(${tail}`\n\n/** @internal */\nexport type IsConstructorSignature =\n signature extends ConstructorSignature\n ? signature extends ValidConstructorSignatures\n ? true\n : false\n : false\n\n/** @internal */\nexport type ValidConstructorSignatures =\n | `constructor(${string})`\n | `constructor(${string}) payable`\n\n/** @internal */\nexport type FallbackSignature =\n `fallback() external${abiStateMutability}`\n\n/** @internal */\nexport type ReceiveSignature = 'receive() external payable'\n\n// TODO: Maybe use this for signature validation one day\n// https://twitter.com/devanshj__/status/1610423724708343808\n/** @internal */\nexport type IsSignature =\n | (IsErrorSignature extends true ? true : never)\n | (IsEventSignature extends true ? true : never)\n | (IsFunctionSignature extends true ? true : never)\n | (IsStructSignature extends true ? true : never)\n | (IsConstructorSignature extends true ? true : never)\n | (type extends FallbackSignature ? true : never)\n | (type extends ReceiveSignature ? true : never) extends infer condition\n ? [condition] extends [never]\n ? false\n : true\n : false\n\n/** @internal */\nexport type Signature<\n string1 extends string,\n string2 extends string | unknown = unknown,\n> = IsSignature extends true\n ? string1\n : string extends string1 // if exactly `string` (not narrowed), then pass through as valid\n ? string1\n : TypeErrorMessage<`Signature \"${string1}\" is invalid${string2 extends string\n ? ` at position ${string2}`\n : ''}.`>\n\n/** @internal */\nexport type Signatures = {\n [key in keyof signatures]: Signature\n}\n\n/** @internal */\nexport type IsName = name extends ''\n ? false\n : ValidateName extends name\n ? true\n : false\n\n/** @internal */\nexport type ValidateName<\n name extends string,\n checkCharacters extends boolean = false,\n> = name extends `${string}${' '}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot contain whitespace.`>\n : IsSolidityKeyword extends true\n ? TypeErrorMessage<`\"${name}\" is a protected Solidity keyword.`>\n : name extends `${number}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot be a number string.`>\n : name extends `${number}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot start with a number.`>\n : checkCharacters extends true\n ? IsValidCharacter extends true\n ? name\n : TypeErrorMessage<`\"${name}\" contains invalid character.`>\n : name\n\n/** @internal */\nexport type IsSolidityKeyword =\n type extends SolidityKeywords ? true : false\n\n/** @internal */\nexport type SolidityKeywords =\n | 'after'\n | 'alias'\n | 'anonymous'\n | 'apply'\n | 'auto'\n | 'byte'\n | 'calldata'\n | 'case'\n | 'catch'\n | 'constant'\n | 'copyof'\n | 'default'\n | 'defined'\n | 'error'\n | 'event'\n | 'external'\n | 'false'\n | 'final'\n | 'function'\n | 'immutable'\n | 'implements'\n | 'in'\n | 'indexed'\n | 'inline'\n | 'internal'\n | 'let'\n | 'mapping'\n | 'match'\n | 'memory'\n | 'mutable'\n | 'null'\n | 'of'\n | 'override'\n | 'partial'\n | 'private'\n | 'promise'\n | 'public'\n | 'pure'\n | 'reference'\n | 'relocatable'\n | 'return'\n | 'returns'\n | 'sizeof'\n | 'static'\n | 'storage'\n | 'struct'\n | 'super'\n | 'supports'\n | 'switch'\n | 'this'\n | 'true'\n | 'try'\n | 'typedef'\n | 'typeof'\n | 'var'\n | 'view'\n | 'virtual'\n | `address${`[${string}]` | ''}`\n | `bool${`[${string}]` | ''}`\n | `string${`[${string}]` | ''}`\n | `tuple${`[${string}]` | ''}`\n | `bytes${number | ''}${`[${string}]` | ''}`\n | `${'u' | ''}int${number | ''}${`[${string}]` | ''}`\n\n/** @internal */\nexport type IsValidCharacter =\n character extends `${ValidCharacters}${infer tail}`\n ? tail extends ''\n ? true\n : IsValidCharacter\n : false\n\n// biome-ignore format: no formatting\n/** @internal */\nexport type ValidCharacters =\n // uppercase letters\n | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'\n // lowercase letters\n | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'\n // numbers\n | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n // special characters\n | '_' | '$'\n\n// Template string inference can absorb `returns`:\n// type Result = `function foo(string) return s (uint256)` extends `function ${string}(${infer Parameters})` ? Parameters : never\n// // ^? type Result = \"string ) return s (uint256\"\n// So we need to validate against `returns` keyword with all combinations of whitespace\n/** @internal */\nexport type InvalidFunctionParameters =\n | `${string}${MangledReturns} (${string}`\n | `${string}) ${MangledReturns}${string}`\n | `${string})${string}${MangledReturns}${string}(${string}`\n\n// r_e_t_u_r_n_s\n/** @internal */\nexport type MangledReturns =\n // Single\n | `r${string}eturns`\n | `re${string}turns`\n | `ret${string}urns`\n | `retu${string}rns`\n | `retur${string}ns`\n | `return${string}s`\n // Double\n // `r_e*`\n | `r${string}e${string}turns`\n | `r${string}et${string}urns`\n | `r${string}etu${string}rns`\n | `r${string}etur${string}ns`\n | `r${string}eturn${string}s`\n // `re_t*`\n | `re${string}t${string}urns`\n | `re${string}tu${string}rns`\n | `re${string}tur${string}ns`\n | `re${string}turn${string}s`\n // `ret_u*`\n | `ret${string}u${string}rns`\n | `ret${string}ur${string}ns`\n | `ret${string}urn${string}s`\n // `retu_r*`\n | `retu${string}r${string}ns`\n | `retu${string}rn${string}s`\n // `retur_n*`\n | `retur${string}n${string}s`\n // Triple\n // `r_e_t*`\n | `r${string}e${string}t${string}urns`\n | `r${string}e${string}tu${string}rns`\n | `r${string}e${string}tur${string}ns`\n | `r${string}e${string}turn${string}s`\n // `re_t_u*`\n | `re${string}t${string}u${string}rns`\n | `re${string}t${string}ur${string}ns`\n | `re${string}t${string}urn${string}s`\n // `ret_u_r*`\n | `ret${string}u${string}r${string}ns`\n | `ret${string}u${string}rn${string}s`\n // `retu_r_n*`\n | `retu${string}r${string}n${string}s`\n // Quadruple\n // `r_e_t_u*`\n | `r${string}e${string}t${string}u${string}rns`\n | `r${string}e${string}t${string}ur${string}ns`\n | `r${string}e${string}t${string}urn${string}s`\n // `re_t_u_r*`\n | `re${string}t${string}u${string}r${string}ns`\n | `re${string}t${string}u${string}rn${string}s`\n // `ret_u_r_n*`\n | `ret${string}u${string}r${string}n${string}s`\n // Quintuple\n // `r_e_t_u_r*`\n | `r${string}e${string}t${string}u${string}r${string}ns`\n | `r${string}e${string}t${string}u${string}rn${string}s`\n // `re_t_u_r_n*`\n | `re${string}t${string}u${string}r${string}n${string}s`\n // Sextuple\n // `r_e_t_u_r_n_s`\n | `r${string}e${string}t${string}u${string}r${string}n${string}s`\n\n/** @internal */\nexport type Widen =\n | ([unknown] extends [type] ? unknown : never)\n | (type extends Function ? type : never)\n | (type extends abitype.ResolvedRegister['bigIntType'] ? bigint : never)\n | (type extends boolean ? boolean : never)\n | (type extends abitype.ResolvedRegister['intType'] ? number : never)\n | (type extends string\n ? type extends abitype.ResolvedRegister['addressType']\n ? abitype.ResolvedRegister['addressType']\n : type extends abitype.ResolvedRegister['bytesType']['inputs']\n ? abitype.ResolvedRegister['bytesType']\n : string\n : never)\n | (type extends readonly [] ? readonly [] : never)\n | (type extends Record\n ? { [K in keyof type]: Widen }\n : never)\n | (type extends { length: number }\n ? {\n [K in keyof type]: Widen\n } extends infer Val extends readonly unknown[]\n ? readonly [...Val]\n : never\n : never)\n\n/** @internal */\nexport function normalizeSignature(signature: string): string {\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', 'error', ''].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 Errors.BaseError('Unable to normalize signature.')\n\n return result\n}\n\n/** @internal */\nexport declare namespace normalizeSignature {\n export type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function isArgOfType(\n arg: unknown,\n abiParameter: AbiParameters.Parameter,\n): boolean {\n const argType = typeof arg\n const abiParameterType = abiParameter.type\n switch (abiParameterType) {\n case 'address':\n return Address.validate(arg as Address.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 AbiParameters.Parameter,\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 AbiParameters.Parameter),\n )\n )\n }\n\n return false\n }\n }\n}\n\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameters.Parameter[],\n targetParameters: readonly AbiParameters.Parameter[],\n args: ExtractArgs,\n): AbiParameters.Parameter['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 Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n if (types.includes('address') && types.includes('bytes'))\n return Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiConstructor.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `constructor` type. */\nexport type AbiConstructor = abitype.AbiConstructor\n\n/**\n * ABI-decodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const bytecode = '0x...'\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode,\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(constructor, { // [!code focus]\n * bytecode, // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.decode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param abiConstructor - The ABI Constructor to decode.\n * @param options - Decoding options.\n * @returns The decoded constructor inputs.\n */\nexport function decode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: decode.Options,\n): decode.ReturnType\nexport function decode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: decode.Options,\n): decode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: decode.Options]\n | [abiConstructor: AbiConstructor, options: decode.Options]\n): decode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n decode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, decode.Options]\n }\n return parameters as [AbiConstructor, decode.Options]\n })()\n\n const { bytecode } = options\n if (abiConstructor.inputs?.length === 0) return undefined\n const data = options.data.replace(bytecode, '0x') as Hex.Hex\n return AbiParameters.decode(abiConstructor.inputs, data)\n}\n\nexport declare namespace decode {\n interface Options {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The encoded constructor. */\n data: Hex.Hex\n }\n\n type ReturnType =\n | (abiConstructor['inputs']['length'] extends 0\n ? undefined\n : abitype.AbiParametersToPrimitiveTypes)\n | (IsNarrowable extends true\n ? never\n : undefined)\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object as a parameter to `AbiConstructor.encode`.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiConstructor.encode(abi, { // [!code focus]\n * bytecode: '0x...', // [!code focus]\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n], // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiConstructor.encode` to encode the constructor of a contract and deploy it.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { AbiConstructor, Hex } from 'ox'\n *\n * // 1. Instantiate the ABI Constructor.\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner, uint256 amount)',\n * )\n *\n * // 2. Encode the ABI Constructor.\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * // 3. Deploy the contract.\n * const hash = await window.ethereum!.request({\n * method: 'eth_sendTransaction',\n * params: [{ data }],\n * })\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiConstructor - The ABI Constructor to encode.\n * @param options - Encoding options.\n * @returns The encoded constructor.\n */\nexport function encode<\n const abi extends Abi.Abi | readonly unknown[],\n abiConstructor extends\n AbiConstructor = fromAbi.ReturnType extends AbiConstructor\n ? fromAbi.ReturnType\n : never,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n options: encode.Options,\n): encode.ReturnType\nexport function encode(\n abiConstructor: abiConstructor | AbiConstructor,\n options: encode.Options,\n): encode.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encode(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], options: encode.Options]\n | [abiConstructor: AbiConstructor, options: encode.Options]\n): encode.ReturnType {\n const [abiConstructor, options] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, options] = parameters as [\n Abi.Abi | readonly unknown[],\n encode.Options,\n ]\n return [fromAbi(abi), options] as [AbiConstructor, encode.Options]\n }\n\n return parameters as [AbiConstructor, encode.Options]\n })()\n\n const { bytecode, args } = options\n return Hex.concat(\n bytecode,\n abiConstructor.inputs?.length && args?.length\n ? AbiParameters.encode(abiConstructor.inputs, args as readonly unknown[])\n : '0x',\n )\n}\n\nexport declare namespace encode {\n type Options<\n abiConstructor extends AbiConstructor = AbiConstructor,\n ///\n args extends abitype.AbiParametersToPrimitiveTypes<\n abiConstructor['inputs']\n > = abitype.AbiParametersToPrimitiveTypes,\n > = {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The constructor arguments to encode. */\n args?: args | undefined\n } & (readonly [] extends args\n ? {}\n : {\n /** The constructor arguments to encode. */\n args: args\n })\n\n type ReturnType = Hex.Hex\n\n type ErrorType =\n | Hex.concat.ErrorType\n | AbiParameters.encode.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function format(\n abiConstructor: abiConstructor,\n): format.ReturnType\n/**\n * Formats an {@link ox#AbiConstructor.AbiConstructor} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const formatted = AbiConstructor.format({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiConstructor - The ABI Constructor to format.\n * @returns The formatted ABI Constructor.\n */\nexport function format(abiConstructor: AbiConstructor): string\n/** @internal */\nexport function format(abiConstructor: AbiConstructor): format.ReturnType {\n return abitype.formatAbiItem(abiConstructor)\n}\n\nexport declare namespace format {\n type ReturnType =\n abitype.FormatAbiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function from<\n const abiConstructor extends AbiConstructor | string | readonly string[],\n>(\n abiConstructor: (abiConstructor | string | readonly string[]) &\n (\n | (abiConstructor extends string\n ? internal.Signature\n : never)\n | (abiConstructor extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiConstructor\n ),\n): from.ReturnType\n/**\n * Parses an arbitrary **JSON ABI Constructor** or **Human Readable ABI Constructor** into a typed {@link ox#AbiConstructor.AbiConstructor}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner)' // [!code hl]\n * )\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from([\n * 'struct Foo { address owner; uint256 amount; }', // [!code hl]\n * 'constructor(Foo foo)',\n * ])\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiConstructor - The ABI Constructor to parse.\n * @returns Typed ABI Constructor.\n */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): AbiConstructor\n/** @internal */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): from.ReturnType {\n return AbiItem.from(abiConstructor as AbiConstructor)\n}\n\nexport declare namespace from {\n type ReturnType<\n abiConstructor extends\n | AbiConstructor\n | string\n | readonly string[] = AbiConstructor,\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function fromAbi(\n abi: abi | Abi.Abi | readonly unknown[],\n): fromAbi.ReturnType\n/**\n * Extracts an {@link ox#AbiConstructor.AbiConstructor} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Events can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([\n * 'constructor(address owner)',\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiConstructor.fromAbi(abi) // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @returns The ABI constructor.\n */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): AbiConstructor\n/** @internal */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): fromAbi.ReturnType {\n const item = (abi as Abi.Abi).find((item) => item.type === 'constructor')\n if (!item) throw new AbiItem.NotFoundError({ name: 'constructor' })\n return item\n}\n\nexport declare namespace fromAbi {\n type ReturnType = Extract<\n abi[number],\n { type: 'constructor' }\n >\n\n type ErrorType = AbiItem.NotFoundError | Errors.GlobalErrorType\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiFunction.js'\nimport type * as AbiItem_internal from './internal/abiItem.js'\nimport type * as AbiParameters_internal from './internal/abiParameters.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `function` type. */\nexport type AbiFunction = abitype.AbiFunction & {\n hash?: Hex.Hex | undefined\n overloads?: readonly AbiFunction[] | undefined\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type Foo = AbiFunction.FromAbi\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames,\n> = abitype.ExtractAbiFunction\n\n/**\n * Extracts the names of all {@link ox#AbiFunction.AbiFunction} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type names = AbiFunction.Name\n * // ^?\n *\n *\n * ```\n */\nexport type Name =\n abi extends Abi.Abi ? ExtractNames : string\n\nexport type ExtractNames<\n abi extends Abi.Abi,\n abiStateMutability extends\n abitype.AbiStateMutability = abitype.AbiStateMutability,\n> = abitype.ExtractAbiFunctionNames\n\n/**\n * ABI-decodes function arguments according to the ABI Item's input types (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n *\n * const input = AbiFunction.decodeData(approve, data) // [!code focus]\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n * const data = '0x...\n *\n * const input = AbiFunction.decodeData(\n * abi, // [!code focus]\n * 'approve', // [!code focus]\n * data\n * )\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @param abiFunction - The ABI Item to decode.\n * @param data - The data to decode.\n */\nexport function decodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n): decodeData.ReturnType\nexport function decodeData(\n abiFunction: abiItem | AbiFunction,\n data: Hex.Hex,\n): decodeData.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeData(\n ...parameters:\n | [abi: Abi.Abi | readonly unknown[], name: Hex.Hex | string, data: Hex.Hex]\n | [abiFunction: AbiFunction, data: Hex.Hex]\n) {\n const [abiFunction, data] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n ]\n return [fromAbi(abi, name), data]\n }\n return parameters as [AbiFunction, Hex.Hex]\n })()\n\n const { overloads } = abiFunction\n\n if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })\n if (abiFunction.inputs?.length === 0) return undefined\n\n const item = overloads\n ? fromAbi([abiFunction, ...overloads], data as never)\n : abiFunction\n\n if (Hex.size(data) <= 4) return undefined\n return AbiParameters.decode(item.inputs, Hex.slice(data, 4))\n}\n\nexport declare namespace decodeData {\n type ReturnType = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ? abiFunction['inputs'] extends readonly []\n ? undefined\n :\n | AbiParameters_internal.ToPrimitiveTypes\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? AbiParameters_internal.ToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >\n : never)\n : unknown\n\n type ErrorType =\n | fromAbi.ErrorType\n | AbiParameters.decode.ErrorType\n | Hex.size.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * ABI-decodes a function's result according to the ABI Item's output types (`outputs`).\n *\n * :::tip\n *\n * This function is typically used to decode contract function return values (e.g. the response of an `eth_call` or the `input` property of a Transaction).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply') // [!code hl]\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(decodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const output = AbiFunction.decodeResult(\n * erc20Abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * data\n * )\n * // @log: 42n\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.decodeResult` to decode the result of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input.\n * const data = AbiFunction.encodeData(\n * balanceOf,\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B']\n * )\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output. // [!code focus]\n * const balance = AbiFunction.decodeResult(balanceOf, response) // [!code focus]\n * // @log: 42n\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to decode\n * @param data - ABI-encoded function output\n * @param options - Decoding options\n * @returns Decoded function output\n */\nexport function decodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\nexport function decodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n): decodeResult.ReturnType\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n data: Hex.Hex,\n options?: decodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, data, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, data, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), data, options]\n }\n return parameters as [\n AbiFunction,\n Hex.Hex,\n decodeResult.Options | undefined,\n ]\n })()\n\n const values = AbiParameters.decode(abiFunction.outputs, data, options)\n if (values && Object.keys(values).length === 0) return undefined\n if (values && Object.keys(values).length === 1) {\n if (Array.isArray(values)) return values[0]\n return Object.values(values)[0]\n }\n return values\n}\n\nexport declare namespace decodeResult {\n type Options = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Array' | 'Object' | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = IsNarrowable extends true\n ? abiFunction['outputs'] extends readonly []\n ? undefined\n : abiFunction['outputs'] extends readonly [\n infer type extends abitype.AbiParameter,\n ]\n ? abitype.AbiParameterToPrimitiveType\n : AbiParameters.decode.ReturnType<\n abiFunction['outputs'],\n as\n > extends infer types\n ? types extends readonly []\n ? undefined\n : types extends readonly [infer type]\n ? type\n : types\n : never\n : unknown\n\n type ErrorType = AbiParameters.decode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes function arguments (`inputs`), prefixed with the 4 byte function selector.\n *\n * :::tip\n *\n * This function is typically used to encode a contract function and its arguments for contract calls (e.g. `data` parameter of an `eth_call` or `eth_sendTransaction`).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData( // [!code focus]\n * approve, // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] // [!code focus]\n * ) // [!code focus]\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const approve = AbiFunction.fromAbi(erc20Abi, 'approve') // [!code hl]\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeData:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeData(\n * erc20Abi, // [!code focus]\n * 'approve', // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.encodeData` to encode the input of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input. // [!code focus]\n * const data = AbiFunction.encodeData( // [!code focus]\n * balanceOf, // [!code focus]\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] // [!code focus]\n * ) // [!code focus]\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output.\n * const balance = AbiFunction.decodeResult(balanceOf, response)\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to encode\n * @param args - Function arguments\n * @returns ABI-encoded function name and arguments\n */\nexport function encodeData<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n ...args: encodeData.Args\n): Hex.Hex\nexport function encodeData(\n abiFunction: abiFunction | AbiFunction,\n ...args: encodeData.Args\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeData(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n ...args: readonly unknown[],\n ]\n | [abiFunction: AbiFunction, ...args: readonly unknown[]]\n) {\n const [abiFunction, args = []] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, args] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n readonly unknown[],\n ]\n return [fromAbi(abi, name, { args }), args]\n }\n const [abiFunction, args] = parameters as [AbiFunction, readonly unknown[]]\n return [abiFunction, args]\n })()\n\n const { overloads } = abiFunction\n\n const item = overloads\n ? (fromAbi([abiFunction as AbiFunction, ...overloads], abiFunction.name, {\n args,\n }) as AbiFunction)\n : abiFunction\n\n const selector = getSelector(item)\n\n const data =\n args.length > 0 ? AbiParameters.encode(item.inputs, args) : undefined\n\n return data ? Hex.concat(selector, data) : selector\n}\n\nexport declare namespace encodeData {\n type Args = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ?\n | (abitype.AbiParametersToPrimitiveTypes<\n abiFunction['inputs']\n > extends readonly []\n ? []\n : [abitype.AbiParametersToPrimitiveTypes])\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? [\n abitype.AbiParametersToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >,\n ]\n : [])\n : readonly unknown[]\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes a function's result (`outputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n * const output = AbiFunction.decodeResult(totalSupply, '0x000000000000000000000000000000000000000000000000000000000000002a')\n * // 42n\n *\n * const data = AbiFunction.encodeResult(totalSupply, 42n) // [!code focus]\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @example\n * ### ABI-shorthand\n *\n * You can also specify an entire ABI object and a function name as parameters to {@link ox#AbiFunction.(encodeResult:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([...])\n *\n * const data = AbiFunction.encodeResult(\n * abi, // [!code focus]\n * 'totalSupply', // [!code focus]\n * 42n\n * )\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @param abiFunction - The ABI item to encode the function output for.\n * @param output - The function output to encode.\n * @param options - Encoding options.\n * @returns The encoded function output.\n */\nexport function encodeResult<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n as extends 'Object' | 'Array' = 'Array',\n //\n abiFunction extends AbiFunction = AbiItem.fromAbi.ReturnType<\n abi,\n name,\n args,\n AbiFunction\n >,\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\nexport function encodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n output: encodeResult.Output,\n options?: encodeResult.Options,\n): Hex.Hex\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function encodeResult(\n ...parameters:\n | [\n abi: Abi.Abi | readonly unknown[],\n name: Hex.Hex | string,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n | [\n abiFunction: AbiFunction,\n output: any,\n options?: encodeResult.Options | undefined,\n ]\n) {\n const [abiFunction, output, options = {}] = (() => {\n if (Array.isArray(parameters[0])) {\n const [abi, name, output, options] = parameters as [\n Abi.Abi | readonly unknown[],\n Hex.Hex | string,\n any,\n encodeResult.Options | undefined,\n ]\n return [fromAbi(abi, name), output, options]\n }\n return parameters as [\n AbiFunction,\n any,\n encodeResult.Options | undefined,\n ]\n })()\n\n const { as = 'Array' } = options\n\n const values = (() => {\n if (abiFunction.outputs.length === 1) return [output]\n if (Array.isArray(output)) return output\n if (as === 'Object') return Object.values(output as any)\n return [output]\n })()\n\n return AbiParameters.encode(abiFunction.outputs, values)\n}\n\nexport declare namespace encodeResult {\n type Output<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = abiFunction['outputs'] extends readonly []\n ? never\n : abiFunction['outputs']['length'] extends 1\n ? AbiParameters_internal.ToPrimitiveTypes[0]\n : as extends 'Object'\n ? AbiParameters_internal.ToObject\n : AbiParameters_internal.ToPrimitiveTypes\n\n type Options = {\n as?: as | 'Object' | 'Array' | undefined\n }\n\n type ErrorType = AbiParameters.encode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Formats an {@link ox#AbiFunction.AbiFunction} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const formatted = AbiFunction.format({\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: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiFunction - The ABI Function to format.\n * @returns The formatted ABI Function.\n */\nexport function format(\n abiFunction: abiFunction | AbiFunction,\n): abitype.FormatAbiItem {\n return abitype.formatAbiItem(abiFunction) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Function** or **Human Readable ABI Function** into a typed {@link ox#AbiFunction.AbiFunction}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from({\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: [{ type: 'bool' }],\n * })\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiFunction - The ABI Function to parse.\n * @returns Typed ABI Function.\n */\nexport function from<\n const abiFunction extends AbiFunction | string | readonly string[],\n>(\n abiFunction: (abiFunction | AbiFunction | string | readonly string[]) &\n (\n | (abiFunction extends string ? internal.Signature : never)\n | (abiFunction extends readonly string[]\n ? internal.Signatures\n : never)\n | AbiFunction\n ),\n options: from.Options = {},\n): from.ReturnType {\n return AbiItem.from(abiFunction as AbiFunction, options) as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted function (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction | string | readonly string[],\n > = AbiItem.from.ReturnType\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Functions can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiFunction.fromAbi(abi, 'foo') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Functions can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiFunction.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Function from an `eth_call` RPC response or\n * from a Transaction `input`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name,\n const args extends\n | AbiItem_internal.ExtractArgs\n | undefined = undefined,\n //\n allNames = Name,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: AbiItem.fromAbi.Options<\n abi,\n name,\n args,\n AbiItem_internal.ExtractArgs\n >,\n): AbiItem.fromAbi.ReturnType {\n const item = AbiItem.fromAbi(abi, name, options as any)\n if (item.type !== 'function')\n throw new AbiItem.NotFoundError({ name, type: 'function' })\n return item as never\n}\n\nexport declare namespace fromAbi {\n type ErrorType = AbiItem.fromAbi.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiFunction.AbiFunction}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector(abiItem: string | AbiFunction): Hex.Hex {\n return AbiItem.getSelector(abiItem)\n}\n\nexport declare namespace getSelector {\n type ErrorType = AbiItem.getSelector.ErrorType | Errors.GlobalErrorType\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as AbiConstructor from 'ox/AbiConstructor'\nimport * as AbiFunction from 'ox/AbiFunction'\n\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { ethAddress, zeroAddress } from '../../constants/address.js'\nimport { deploylessCallViaBytecodeBytecode } from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { Mutable } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { hexToBigInt } from '../../utils/index.js'\nimport {\n type CreateAccessListErrorType,\n createAccessList,\n} from './createAccessList.js'\nimport {\n type SimulateBlocksErrorType,\n type SimulateBlocksParameters,\n simulateBlocks,\n} from './simulateBlocks.js'\n\nconst getBalanceCode =\n '0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033'\n\nexport type SimulateCallsParameters<\n calls extends readonly unknown[] = readonly unknown[],\n account extends Account | Address | undefined = Account | Address | undefined,\n> = Omit & {\n /** Account attached to the calls (msg.sender). */\n account?: account | undefined\n /** Calls to simulate. */\n calls: Calls>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n /** Whether to trace asset changes. */\n traceAssetChanges?: boolean | undefined\n}\n\nexport type SimulateCallsReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Asset changes. */\n assetChanges: readonly {\n token: {\n address: Address\n decimals?: number | undefined\n symbol?: string | undefined\n }\n value: { pre: bigint; post: bigint; diff: bigint }\n }[]\n /** Block results. */\n block: Block\n /** Call results. */\n results: MulticallResults<\n Narrow,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n}\n\nexport type SimulateCallsErrorType =\n | AbiFunction.encodeData.ErrorType\n | AbiFunction.from.ErrorType\n | CreateAccessListErrorType\n | EncodeFunctionDataErrorType\n | SimulateBlocksErrorType\n | ErrorType\n\n/**\n * Simulates execution of a batch of calls.\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateCalls } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulateCalls(client, {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n */\nexport async function simulateCalls<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | Address | undefined = undefined,\n>(\n client: Client,\n parameters: SimulateCallsParameters,\n): Promise> {\n const {\n blockNumber,\n blockTag,\n calls,\n stateOverrides,\n traceAssetChanges,\n traceTransfers,\n validation,\n } = parameters\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n\n if (traceAssetChanges && !account)\n throw new BaseError(\n '`account` is required when `traceAssetChanges` is true',\n )\n\n // Derive bytecode to extract ETH balance via a contract call.\n const getBalanceData = account\n ? AbiConstructor.encode(AbiConstructor.from('constructor(bytes, bytes)'), {\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [\n getBalanceCode,\n AbiFunction.encodeData(\n AbiFunction.from('function getBalance(address)'),\n [account.address],\n ),\n ],\n })\n : undefined\n\n // Fetch ERC20/721 addresses that were \"touched\" from the calls.\n const assetAddresses = traceAssetChanges\n ? await Promise.all(\n parameters.calls.map(async (call: any) => {\n if (!call.data && !call.abi) return\n const { accessList } = await createAccessList(client, {\n account: account!.address,\n ...call,\n data: call.abi ? encodeFunctionData(call) : call.data,\n })\n return accessList.map(({ address, storageKeys }) =>\n storageKeys.length > 0 ? address : null,\n )\n }),\n ).then((x) => x.flat().filter(Boolean))\n : []\n\n const blocks = await simulateBlocks(client, {\n blockNumber,\n blockTag: blockTag as undefined,\n blocks: [\n ...(traceAssetChanges\n ? [\n // ETH pre balances\n {\n calls: [{ data: getBalanceData }],\n stateOverrides,\n },\n\n // Asset pre balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n\n {\n calls: [...calls, {}].map((call) => ({\n ...(call as Call),\n from: account?.address,\n })) as any,\n stateOverrides,\n },\n\n ...(traceAssetChanges\n ? [\n // ETH post balances\n {\n calls: [{ data: getBalanceData }],\n },\n\n // Asset post balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Decimals\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from('function decimals() returns (uint256)'),\n ],\n functionName: 'decimals',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Token URI\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from(\n 'function tokenURI(uint256) returns (string)',\n ),\n ],\n functionName: 'tokenURI',\n args: [0n],\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Symbols\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [AbiFunction.from('function symbol() returns (string)')],\n functionName: 'symbol',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n ],\n traceTransfers,\n validation,\n })\n\n const block_results = traceAssetChanges ? blocks[2] : blocks[0]\n const [\n block_ethPre,\n block_assetsPre,\n ,\n block_ethPost,\n block_assetsPost,\n block_decimals,\n block_tokenURI,\n block_symbols,\n ] = traceAssetChanges ? blocks : []\n\n // Extract call results from the simulation.\n const { calls: block_calls, ...block } = block_results\n const results = block_calls.slice(0, -1) ?? []\n\n // Extract pre-execution ETH and asset balances.\n const ethPre = block_ethPre?.calls ?? []\n const assetsPre = block_assetsPre?.calls ?? []\n const balancesPre = [...ethPre, ...assetsPre].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract post-execution ETH and asset balances.\n const ethPost = block_ethPost?.calls ?? []\n const assetsPost = block_assetsPost?.calls ?? []\n const balancesPost = [...ethPost, ...assetsPost].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract asset symbols & decimals.\n const decimals = (block_decimals?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (number | null)[]\n const symbols = (block_symbols?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n const tokenURI = (block_tokenURI?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n\n const changes: Mutable['assetChanges']> = []\n for (const [i, balancePost] of balancesPost.entries()) {\n const balancePre = balancesPre[i]\n\n if (typeof balancePost !== 'bigint') continue\n if (typeof balancePre !== 'bigint') continue\n\n const decimals_ = decimals[i - 1]\n const symbol_ = symbols[i - 1]\n const tokenURI_ = tokenURI[i - 1]\n\n const token = (() => {\n if (i === 0)\n return {\n address: ethAddress,\n decimals: 18,\n symbol: 'ETH',\n }\n\n return {\n address: assetAddresses[i - 1]! as Address,\n decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined,\n symbol: symbol_ ?? undefined,\n }\n })()\n\n if (changes.some((change) => change.token.address === token.address))\n continue\n\n changes.push({\n token,\n value: {\n pre: balancePre,\n post: balancePost,\n diff: balancePost - balancePre,\n },\n })\n }\n\n return {\n assetChanges: changes,\n block,\n results,\n } as unknown as SimulateCallsReturnType\n}\n","export const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const\n\nexport const zeroAddress = '0x0000000000000000000000000000000000000000' as const\n","import type * as Abi from '../core/Abi.js'\nimport * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-6492 signature. */\nexport type Unwrapped = {\n /** Calldata to pass to the target address for counterfactual verification. */\n data: Hex.Hex\n /** The original signature. */\n signature: Hex.Hex\n /** The target address to use for counterfactual verification. */\n to: Address.Address\n}\n\n/** Wrapped ERC-6492 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-6492 wrapped signatures.\n */\nexport const magicBytes =\n '0x6492649264926492649264926492649264926492649264926492649264926492' as const\n\n/**\n * Deployless ERC-6492 signature verification bytecode.\n */\nexport const universalSignatureValidatorBytecode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\n/**\n * ABI for the ERC-6492 universal deployless signature validator contract.\n *\n * Constructor return value is `0x1` (valid) or `0x0` (invalid).\n */\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 satisfies Abi.Abi\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * SignatureErc6492.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-6492 wrapped signature.\n * ```\n *\n * @param wrapped - The wrapped signature to assert.\n */\nexport function assert(wrapped: Wrapped) {\n if (Hex.slice(wrapped, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(wrapped)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc6492.from('0x...') // [!code focus]\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc6492.from({ // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * to: '0x...', // [!code focus]\n * })\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', }\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function from(wrapped: Unwrapped | Wrapped): Unwrapped {\n if (typeof wrapped === 'string') return unwrap(wrapped)\n return wrapped\n}\n\nexport declare namespace from {\n type ReturnType = Unwrapped\n\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const { data, signature, to } = SignatureErc6492.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const [to, data, signature] = AbiParameters.decode(\n AbiParameters.from('address, bytes, bytes'),\n wrapped,\n )\n\n return { data, signature, to }\n}\n\nexport declare namespace unwrap {\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc6492.wrap({ // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * to: '0x00000000219ab540356cBB839Cbe05303d7705Fa', // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Wrapped signature to serialize.\n * @returns Serialized wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature, to } = value\n\n return Hex.concat(\n AbiParameters.encode(AbiParameters.from('address, bytes, bytes'), [\n to,\n data,\n signature,\n ]),\n magicBytes,\n )\n}\n\nexport declare namespace wrap {\n type ErrorType =\n | AbiParameters.encode.ErrorType\n | Hex.concat.ErrorType\n | Signature.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const valid = SignatureErc6492.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param wrapped - The wrapped signature to validate.\n * @returns `true` if the wrapped signature is valid, `false` otherwise.\n */\nexport function validate(wrapped: Wrapped): boolean {\n try {\n assert(wrapped)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-6492 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc6492.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-6492 wrapped signature.`)\n }\n}\n","import type { Address } from 'abitype'\nimport { SignatureErc6492 } from 'ox/erc6492'\nimport { SignatureErc8010 } from 'ox/erc8010'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n erc1271Abi,\n erc6492SignatureValidatorAbi,\n multicall3Abi,\n} from '../../constants/abis.js'\nimport {\n erc6492SignatureValidatorByteCode,\n multicall3Bytecode,\n} from '../../constants/contracts.js'\nimport {\n CallExecutionError,\n ContractFunctionExecutionError,\n} from '../../errors/contract.js'\nimport type { InvalidHexBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.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 {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../../utils/address/isAddressEqual.js'\nimport { verifyAuthorization } from '../../utils/authorization/verifyAuthorization.js'\nimport { type ConcatHexErrorType, concatHex } from '../../utils/data/concat.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { hexToBool } from '../../utils/encoding/fromHex.js'\nimport {\n type BytesToHexErrorType,\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../utils/signature/recoverAddress.js'\nimport {\n type SerializeSignatureErrorType,\n serializeSignature,\n} from '../../utils/signature/serializeSignature.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type VerifyHashParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n /** The address that signed the original message. */\n address: Address\n /** The chain to use. */\n chain?: Chain | null | undefined\n /** The address of the ERC-6492 signature verifier contract. */\n erc6492VerifierAddress?: Address | undefined\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n /** @deprecated use `erc6492VerifierAddress` instead. */\n universalSignatureVerifierAddress?: Address | undefined\n} & OneOf<{ factory: Address; factoryData: Hex } | {}>\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n | BytesToHexErrorType\n | CallErrorType\n | ConcatHexErrorType\n | EncodeDeployDataErrorType\n | EncodeFunctionDataErrorType\n | ErrorType\n | GetAddressErrorType\n | GetCodeErrorType\n | InvalidHexBooleanError\n | IsAddressEqualErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ReadContractErrorType\n | RecoverAddressErrorType\n | SerializeSignatureErrorType\n\n/**\n * Verifies a message hash onchain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash(\n client: Client,\n parameters: VerifyHashParameters,\n): Promise {\n const {\n address,\n chain = client.chain,\n hash,\n erc6492VerifierAddress:\n verifierAddress = parameters.universalSignatureVerifierAddress ??\n chain?.contracts?.erc6492Verifier?.address,\n multicallAddress = parameters.multicallAddress ??\n chain?.contracts?.multicall3?.address,\n } = parameters\n\n if (chain?.verifyHash) return await chain.verifyHash(client, parameters)\n\n const signature = (() => {\n const signature = parameters.signature\n if (isHex(signature)) return signature\n if (typeof signature === 'object' && 'r' in signature && 's' in signature)\n return serializeSignature(signature)\n return bytesToHex(signature)\n })()\n\n try {\n if (SignatureErc8010.validate(signature))\n return await verifyErc8010(client, {\n ...parameters,\n multicallAddress,\n signature,\n })\n return await verifyErc6492(client, {\n ...parameters,\n verifierAddress,\n signature,\n })\n } catch (error) {\n // Fallback attempt to verify the signature via ECDSA recovery.\n try {\n const verified = isAddressEqual(\n getAddress(address),\n await recoverAddress({ hash, signature }),\n )\n if (verified) return true\n } catch {}\n\n if (error instanceof VerificationError) {\n // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n // this can happen for many reasons, for example if signer can not be recovered from the signature\n // or if the signature has no valid format\n return false\n }\n\n throw error\n }\n}\n\n/** @internal */\nexport async function verifyErc8010(\n client: Client,\n parameters: verifyErc8010.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, multicallAddress } = parameters\n\n const {\n authorization: authorization_ox,\n data: initData,\n signature,\n to,\n } = SignatureErc8010.unwrap(parameters.signature)\n\n // Check if already delegated\n const code = await getCode(client, {\n address,\n blockNumber,\n blockTag,\n } as never)\n\n // If already delegated, perform standard ERC-1271 verification.\n if (code === concatHex(['0xef0100', authorization_ox.address]))\n return await verifyErc1271(client, {\n address,\n blockNumber,\n blockTag,\n hash,\n signature,\n })\n\n const authorization = {\n address: authorization_ox.address,\n chainId: Number(authorization_ox.chainId),\n nonce: Number(authorization_ox.nonce),\n r: numberToHex(authorization_ox.r, { size: 32 }),\n s: numberToHex(authorization_ox.s, { size: 32 }),\n yParity: authorization_ox.yParity,\n } as const\n\n const valid = await verifyAuthorization({\n address,\n authorization,\n })\n if (!valid) throw new VerificationError()\n\n // Deployless verification.\n const results = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress\n ? { address: multicallAddress }\n : { code: multicall3Bytecode }),\n authorizationList: [authorization],\n abi: multicall3Abi,\n blockNumber,\n blockTag: 'pending',\n functionName: 'aggregate3',\n args: [\n [\n ...(initData\n ? ([\n {\n allowFailure: true,\n target: to ?? address,\n callData: initData,\n },\n ] as const)\n : []),\n {\n allowFailure: true,\n target: address,\n callData: encodeFunctionData({\n abi: erc1271Abi,\n functionName: 'isValidSignature',\n args: [hash, signature],\n }),\n },\n ],\n ],\n })\n\n const data = results[results.length - 1]?.returnData\n\n if (data?.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc8010 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nasync function verifyErc6492(\n client: Client,\n parameters: verifyErc6492.Parameters,\n) {\n const {\n address,\n factory,\n factoryData,\n hash,\n signature,\n verifierAddress,\n ...rest\n } = parameters\n\n const wrappedSignature = await (async () => {\n // If no `factory` or `factoryData` is provided, it is assumed that the\n // address is not a Smart Account, or the Smart Account is already deployed.\n if (!factory && !factoryData) return signature\n\n // If the signature is already wrapped, return the signature.\n if (SignatureErc6492.validate(signature)) return signature\n\n // If the Smart Account is not deployed, wrap the signature with a 6492 wrapper\n // to perform counterfactual validation.\n return SignatureErc6492.wrap({\n data: factoryData!,\n signature,\n to: factory!,\n })\n })()\n\n const args = verifierAddress\n ? ({\n to: verifierAddress,\n data: encodeFunctionData({\n abi: erc6492SignatureValidatorAbi,\n functionName: 'isValidSig',\n args: [address, hash, wrappedSignature],\n }),\n ...rest,\n } as unknown as CallParameters)\n : ({\n data: encodeDeployData({\n abi: erc6492SignatureValidatorAbi,\n args: [address, hash, wrappedSignature],\n bytecode: erc6492SignatureValidatorByteCode,\n }),\n ...rest,\n } as unknown as CallParameters)\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )(args).catch((error) => {\n if (error instanceof CallExecutionError) throw new VerificationError()\n throw error\n })\n\n if (hexToBool(data ?? '0x0')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc6492 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n /** The address of the ERC-6492 signature verifier contract. */\n verifierAddress?: Address | undefined\n } & OneOf<{ factory: Address; factoryData: Hex } | {}>\n}\n\n/** @internal */\nexport async function verifyErc1271(\n client: Client,\n parameters: verifyErc1271.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, signature } = parameters\n\n const result = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address,\n abi: erc1271Abi,\n args: [hash, signature],\n blockNumber,\n blockTag,\n functionName: 'isValidSignature',\n }).catch((error) => {\n if (error instanceof ContractFunctionExecutionError)\n throw new VerificationError()\n throw error\n })\n\n if (result.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc1271 {\n export type Parameters = Pick & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\nclass VerificationError extends Error {}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ByteArray,\n Hex,\n SignableMessage,\n Signature,\n} from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyMessageParameters = Prettify<\n Omit & {\n /** The address that signed the original message. */\n address: Address\n /** The message to be verified. */\n message: SignableMessage\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n }\n>\n\nexport type VerifyMessageReturnType = boolean\n\nexport type VerifyMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\nexport async function verifyMessage(\n client: Client,\n {\n address,\n message,\n factory,\n factoryData,\n signature,\n ...callRequest\n }: VerifyMessageParameters,\n): Promise {\n const hash = hashMessage(message)\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address, TypedData } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = Omit &\n TypedDataDefinition & {\n /** The address to verify the typed data for. */\n address: Address\n /** The signature to verify */\n signature: Hex | ByteArray | Signature\n }\n\nexport type VerifyTypedDataReturnType = boolean\n\nexport type VerifyTypedDataErrorType =\n | HashTypedDataErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\nexport async function verifyTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: VerifyTypedDataParameters,\n): Promise {\n const {\n address,\n factory,\n factoryData,\n signature,\n message,\n primaryType,\n types,\n domain,\n ...callRequest\n } = parameters as VerifyTypedDataParameters\n const hash = hashTypedData({ message, primaryType, types, domain })\n return getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n TransactionNotFoundError,\n TransactionReceiptNotFoundError,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n type GetTransactionErrorType,\n type GetTransactionReturnType,\n getTransaction,\n} from './getTransaction.js'\nimport {\n type GetTransactionReceiptErrorType,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n type WatchBlockNumberErrorType,\n watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * Whether to check for transaction replacements.\n * @default true\n */\n checkReplacement?: boolean | undefined\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | WaitForTransactionReceiptTimeoutErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n chain extends Chain | undefined,\n>(\n client: Client,\n parameters: WaitForTransactionReceiptParameters,\n): Promise> {\n const {\n checkReplacement = true,\n confirmations = 1,\n hash,\n onReplaced,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n } = parameters\n\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n const pollingInterval = (() => {\n if (parameters.pollingInterval) return parameters.pollingInterval\n if (client.chain?.experimental_preconfirmationTime)\n return client.chain.experimental_preconfirmationTime\n return client.pollingInterval\n })()\n\n let transaction: GetTransactionReturnType | undefined\n let replacedTransaction: GetTransactionReturnType | undefined\n let receipt: GetTransactionReceiptReturnType | undefined\n let retrying = false\n\n let _unobserve: () => void\n let _unwatch: () => void\n\n const { promise, resolve, reject } =\n withResolvers>()\n\n const timer = timeout\n ? setTimeout(() => {\n _unwatch?.()\n _unobserve?.()\n reject(new WaitForTransactionReceiptTimeoutError({ hash }))\n }, timeout)\n : undefined\n\n _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n async (emit) => {\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash }).catch(() => undefined)\n\n if (receipt && confirmations <= 1) {\n clearTimeout(timer)\n emit.resolve(receipt)\n _unobserve?.()\n return\n }\n\n _unwatch = getAction(\n client,\n watchBlockNumber,\n 'watchBlockNumber',\n )({\n emitMissed: true,\n emitOnBegin: true,\n poll: true,\n pollingInterval,\n async onBlockNumber(blockNumber_) {\n const done = (fn: () => void) => {\n clearTimeout(timer)\n _unwatch?.()\n fn()\n _unobserve?.()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\n\n try {\n // If we already have a valid receipt, let's check if we have enough\n // confirmations. If we do, then we can resolve.\n if (receipt) {\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n return\n }\n\n // Get the transaction to check if it's been replaced.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined transactions.\n if (checkReplacement && !transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\n },\n )\n retrying = false\n }\n\n // Get the receipt to check if it's been processed.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt!))\n } catch (err) {\n // If the receipt is not found, the transaction will be pending.\n // We need to check if it has potentially been replaced.\n if (\n err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\n\n try {\n replacedTransaction = transaction\n\n // Let's retrieve the transactions from the current block.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined blocks.\n retrying = true\n const block = await withRetry(\n () =>\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber,\n includeTransactions: true,\n }),\n {\n delay: retryDelay,\n retryCount,\n shouldRetry: ({ error }) =>\n error instanceof BlockNotFoundError,\n },\n )\n retrying = false\n\n const replacementTransaction = (\n block.transactions as {} as Transaction[]\n ).find(\n ({ from, nonce }) =>\n from === replacedTransaction!.from &&\n nonce === replacedTransaction!.nonce,\n )\n\n // If we couldn't find a replacement transaction, continue polling.\n if (!replacementTransaction) return\n\n // If we found a replacement transaction, return it's receipt.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({\n hash: replacementTransaction.hash,\n })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n let reason: ReplacementReason = 'replaced'\n if (\n replacementTransaction.to === replacedTransaction.to &&\n replacementTransaction.value === replacedTransaction.value &&\n replacementTransaction.input === replacedTransaction.input\n ) {\n reason = 'repriced'\n } else if (\n replacementTransaction.from === replacementTransaction.to &&\n replacementTransaction.value === 0n\n ) {\n reason = 'cancelled'\n }\n\n done(() => {\n emit.onReplaced?.({\n reason,\n replacedTransaction: replacedTransaction! as any,\n transaction: replacementTransaction,\n transactionReceipt: receipt!,\n })\n emit.resolve(receipt!)\n })\n } catch (err_) {\n done(() => emit.reject(err_))\n }\n } else {\n done(() => emit.reject(err))\n }\n }\n },\n })\n },\n )\n\n return promise\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n blockNumber: OnBlockNumberParameter,\n prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type WatchBlockNumberParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when a new block number is received. */\n onBlockNumber: OnBlockNumberFn\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n\n let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n const pollBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) =>\n poll(\n async () => {\n try {\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({ cacheTime: 0 })\n\n if (prevBlockNumber !== undefined) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (blockNumber === prevBlockNumber) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n emit.onBlockNumber(i, prevBlockNumber)\n prevBlockNumber = i\n }\n }\n }\n\n // If the next block number is greater than the previous,\n // it is not in the past, and we can emit the new block number.\n if (\n prevBlockNumber === undefined ||\n blockNumber > prevBlockNumber\n ) {\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockReturnType, getBlock } from './getBlock.js'\n\nexport type OnBlockParameter<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = GetBlockReturnType\n\nexport type OnBlock<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = (\n block: OnBlockParameter,\n prevBlock: OnBlockParameter | undefined,\n) => void\n\nexport type WatchBlocksParameters<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** The callback to call when a new block is received. */\n onBlock: OnBlock\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n blockTag?: undefined\n emitMissed?: undefined\n emitOnBegin?: undefined\n includeTransactions?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** The block tag. Defaults to \"latest\". */\n blockTag?: blockTag | BlockTag | undefined\n /** Whether or not to emit the missed blocks to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the block to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to the client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlocksReturnType = () => void\n\nexport type WatchBlocksErrorType =\n | StringifyErrorType\n | PollErrorType\n | ErrorType\n\n/**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, watchBlocks, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlocks(client, {\n * onBlock: (block) => console.log(block),\n * })\n */\nexport function watchBlocks<\n transport extends Transport,\n chain extends Chain | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockTag = client.experimental_blockTag ?? 'latest',\n emitMissed = false,\n emitOnBegin = false,\n onBlock,\n onError,\n includeTransactions: includeTransactions_,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlocksParameters,\n): WatchBlocksReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const includeTransactions = includeTransactions_ ?? false\n\n let prevBlock:\n | GetBlockReturnType\n | undefined\n\n const pollBlocks = () => {\n const observerId = stringify([\n 'watchBlocks',\n client.uid,\n blockTag,\n emitMissed,\n emitOnBegin,\n includeTransactions,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlock, onError }, (emit) =>\n poll(\n async () => {\n try {\n const block = await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n if (block.number !== null && prevBlock?.number != null) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (block.number === prevBlock.number) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (block.number - prevBlock.number > 1 && emitMissed) {\n for (let i = prevBlock?.number + 1n; i < block.number; i++) {\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: i,\n includeTransactions,\n })) as GetBlockReturnType\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block\n }\n }\n }\n\n if (\n // If no previous block exists, emit.\n prevBlock?.number == null ||\n // If the block tag is \"pending\" with no block number, emit.\n (blockTag === 'pending' && block?.number == null) ||\n // If the next block number is greater than the previous block number, emit.\n // We don't want to emit blocks in the past.\n (block.number !== null && block.number > prevBlock.number)\n ) {\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block as any\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlocks = () => {\n let active = true\n let emitFetched = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n if (emitOnBegin) {\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n .then((block) => {\n if (!active) return\n if (!emitFetched) return\n onBlock(block as any, undefined)\n emitFetched = false\n })\n .catch(onError)\n }\n\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n async onData(data: any) {\n if (!active) return\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: data.result?.number,\n includeTransactions,\n }).catch(() => {})) as GetBlockReturnType\n if (!active) return\n onBlock(block as any, prevBlock as any)\n emitFetched = false\n prevBlock = block\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollBlocks() : subscribeBlocks()\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport {\n type CreateEventFilterParameters,\n createEventFilter,\n} from './createEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { type GetLogsParameters, getLogs } from './getLogs.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchEventOnLogsParameter<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n eventName extends string | undefined = MaybeAbiEventName,\n> = Log[]\nexport type WatchEventOnLogsFn<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = (\n logs: WatchEventOnLogsParameter,\n) => void\n\nexport type WatchEventParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n //\n _eventName extends string | undefined = MaybeAbiEventName,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchEventOnLogsFn\n} & GetPollOptions &\n (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: abiEvents | undefined\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n )\n\nexport type WatchEventReturnType = () => void\n\nexport type WatchEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchEvent } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchEvent(client, {\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchEvent<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n _eventName extends string | undefined = undefined,\n>(\n client: Client,\n {\n address,\n args,\n batch = true,\n event,\n events,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n }: WatchEventParameters,\n): WatchEventReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\n const strict = strict_ ?? false\n\n const pollEvent = () => {\n const observerId = stringify([\n 'watchEvent',\n address,\n args,\n batch,\n client.uid,\n event,\n pollingInterval,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abiEvents, _eventName, any>\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createEventFilter as any,\n 'createEventFilter',\n )({\n address,\n args,\n event: event!,\n events,\n strict,\n fromBlock,\n } as unknown as CreateEventFilterParameters)) as unknown as Filter<\n 'event',\n abiEvents,\n _eventName\n >\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n logs = await getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n event: event!,\n events,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n } as unknown as GetLogsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeEvent = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const events_ = events ?? (event ? [event] : undefined)\n let topics: LogTopic[] = []\n if (events_) {\n const encoded = (events_ as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: events_ ?? [],\n data: log.data,\n topics: log.topics,\n strict,\n })\n const formatted = formatLog(log, { args, eventName })\n onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollEvent() : subscribeEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { createPendingTransactionFilter } from './createPendingTransactionFilter.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type OnTransactionsParameter = Hash[]\nexport type OnTransactionsFn = (transactions: OnTransactionsParameter) => void\n\nexport type WatchPendingTransactionsParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new transactions are received. */\n onTransactions: OnTransactionsFn\n} & GetPollOptions\n\nexport type WatchPendingTransactionsReturnType = () => void\n\nexport type WatchPendingTransactionsErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param client - Client to use\n * @param parameters - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchPendingTransactions } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await watchPendingTransactions(client, {\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\nexport function watchPendingTransactions<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client,\n {\n batch = true,\n onError,\n onTransactions,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchPendingTransactionsParameters,\n) {\n const enablePolling =\n typeof poll_ !== 'undefined'\n ? poll_\n : client.transport.type !== 'webSocket' && client.transport.type !== 'ipc'\n\n const pollPendingTransactions = () => {\n const observerId = stringify([\n 'watchPendingTransactions',\n client.uid,\n batch,\n pollingInterval,\n ])\n return observe(observerId, { onTransactions, onError }, (emit) => {\n let filter: Filter<'transaction'>\n\n const unwatch = poll(\n async () => {\n try {\n if (!filter) {\n try {\n filter = await getAction(\n client,\n createPendingTransactionFilter,\n 'createPendingTransactionFilter',\n )({})\n return\n } catch (err) {\n unwatch()\n throw err\n }\n }\n\n const hashes = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n if (hashes.length === 0) return\n if (batch) emit.onTransactions(hashes)\n else for (const hash of hashes) emit.onTransactions([hash])\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribePendingTransactions = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n params: ['newPendingTransactions'],\n onData(data: any) {\n if (!active) return\n const transaction = data.result\n onTransactions([transaction])\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling\n ? pollPendingTransactions()\n : subscribePendingTransactions()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport { parseSiweMessage } from '../../utils/siwe/parseSiweMessage.js'\nimport {\n type ValidateSiweMessageParameters,\n validateSiweMessage,\n} from '../../utils/siwe/validateSiweMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from '../public/verifyHash.js'\n\nexport type VerifySiweMessageParameters = Prettify<\n Pick &\n Pick<\n ValidateSiweMessageParameters,\n 'address' | 'domain' | 'nonce' | 'scheme' | 'time'\n > & {\n /**\n * EIP-4361 formatted message.\n */\n message: string\n /**\n * Signature to check against.\n */\n signature: Hex\n }\n>\n\nexport type VerifySiweMessageReturnType = boolean\n\nexport type VerifySiweMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\nexport async function verifySiweMessage(\n client: Client,\n parameters: VerifySiweMessageParameters,\n): Promise {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n ...callRequest\n } = parameters\n\n const parsed = parseSiweMessage(message)\n if (!parsed.address) return false\n\n const isValid = validateSiweMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n })\n if (!isValid) return false\n\n const hash = hashMessage(message)\n return verifyHash(client, {\n address: parsed.address,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\nimport type { SiweMessage } from './types.js'\n\n/**\n * @description Parses EIP-4361 formatted message into message fields object.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n *\n * @returns EIP-4361 fields object\n */\nexport function parseSiweMessage(\n message: string,\n): Prettify> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: Address\n domain: string\n scheme?: string\n statement?: string\n }\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string\n expirationTime?: string\n issuedAt?: string\n nonce: string\n notBefore?: string\n requestId?: string\n uri: string\n version: '1'\n }\n const resources = message.split('Resources:')[1]?.split('\\n- ').slice(1)\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n }\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\\n)(?
0x[a-fA-F0-9]{40})\\n\\n(?:(?.*)\\n\\n)?/\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?.+))\\n(?:Version: (?.+))\\n(?:Chain ID: (?\\d+))\\n(?:Nonce: (?[a-zA-Z0-9]+))\\n(?:Issued At: (?.+))(?:\\nExpiration Time: (?.+))?(?:\\nNot Before: (?.+))?(?:\\nRequest ID: (?.+))?/\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport type { SiweMessage } from './types.js'\n\nexport type ValidateSiweMessageParameters = {\n /**\n * Ethereum address to check against.\n */\n address?: Address | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined\n /**\n * EIP-4361 message fields.\n */\n message: ExactPartial\n /**\n * Random string to check against.\n */\n nonce?: string | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined\n}\n\nexport type ValidateSiweMessageReturnType = boolean\n\n/**\n * @description Validates EIP-4361 message.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n */\nexport function validateSiweMessage(\n parameters: ValidateSiweMessageParameters,\n): ValidateSiweMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters\n\n if (domain && message.domain !== domain) return false\n if (nonce && message.nonce !== nonce) return false\n if (scheme && message.scheme !== scheme) return false\n\n if (message.expirationTime && time >= message.expirationTime) return false\n if (message.notBefore && time < message.notBefore) return false\n\n try {\n if (!message.address) return false\n if (!isAddress(message.address, { strict: false })) return false\n if (address && !isAddressEqual(message.address, address)) return false\n } catch {\n return false\n }\n\n return true\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionReceiptRevertedError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { formatTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport type { FormattedTransactionReceipt } from '../../utils/index.js'\n\nexport type SendRawTransactionSyncParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n /** Whether to throw an error if the transaction was detected as reverted. @default true */\n throwOnReceiptRevert?: boolean | undefined\n /** The timeout for the transaction. */\n timeout?: number | undefined\n}\n\nexport type SendRawTransactionSyncReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type SendRawTransactionSyncErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network synchronously,\n * and waits for the transaction to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await sendRawTransactionSync(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransactionSync(\n client: Client,\n {\n serializedTransaction,\n throwOnReceiptRevert,\n timeout,\n }: SendRawTransactionSyncParameters,\n): Promise> {\n const receipt = await client.request(\n {\n method: 'eth_sendRawTransactionSync',\n params: timeout\n ? [serializedTransaction, timeout]\n : [serializedTransaction],\n },\n { retryCount: 0 },\n )\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n\n const formatted = format(receipt) as SendRawTransactionSyncReturnType\n if (formatted.status === 'reverted' && throwOnReceiptRevert)\n throw new TransactionReceiptRevertedError({ receipt: formatted })\n return formatted\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account, ParseAccount } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { PublicRpcSchema, RpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n} from './createClient.js'\nimport { type PublicActions, publicActions } from './decorators/public.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type PublicClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Pick<\n ClientConfig,\n | 'batch'\n | 'cacheTime'\n | 'ccipRead'\n | 'chain'\n | 'experimental_blockTag'\n | 'key'\n | 'name'\n | 'pollingInterval'\n | 'rpcSchema'\n | 'transport'\n >\n>\n\nexport type PublicClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Client<\n transport,\n chain,\n accountOrAddress,\n rpcSchema extends RpcSchema\n ? [...PublicRpcSchema, ...rpcSchema]\n : PublicRpcSchema,\n PublicActions\n >\n>\n\nexport type CreatePublicClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://viem.sh/docs/clients/public\n *\n * A Public Client is an interface to \"public\" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param config - {@link PublicClientConfig}\n * @returns A Public Client. {@link PublicClient}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: PublicClientConfig,\n): PublicClient, rpcSchema> {\n const { key = 'public', name = 'Public Client' } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n type: 'publicClient',\n })\n return client.extend(publicActions) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { OneOf } from '../../types/utils.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** Methods to include or exclude from executing RPC requests. */\n methods?:\n | OneOf<\n | {\n include?: string[] | undefined\n }\n | {\n exclude?: string[] | undefined\n }\n >\n | undefined\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = ({\n chain,\n}: {\n account?: Account | undefined\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record,\n>(\n {\n key,\n methods,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig,\n value?: rpcAttributes | undefined,\n): ReturnType> {\n const uid = uid_()\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\n value,\n }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { EIP1193RequestFn, RpcSchema } from '../../types/eip1193.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n getHttpRpcClient,\n type HttpRpcClientOptions,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './createTransport.js'\n\nexport type HttpTransportConfig<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** Methods to include or exclude from executing RPC requests. */\n methods?: TransportConfig['methods'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** Whether to return JSON RPC errors as responses instead of throwing. */\n raw?: raw | boolean | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** Typed JSON-RPC schema for the transport. */\n rpcSchema?: rpcSchema | RpcSchema | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n },\n EIP1193RequestFn\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n>(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig = {},\n): HttpTransport {\n const {\n batch,\n fetchFn,\n fetchOptions,\n key = 'http',\n methods,\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n raw,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchFn,\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n methods,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n\n if (raw) return { error, result }\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type AbiParameter,\n type AbiParameterKind,\n type AbiParameterToPrimitiveType,\n type AbiStateMutability,\n type Address,\n CircularReferenceError,\n InvalidAbiItemError,\n InvalidAbiParameterError,\n InvalidAbiParametersError,\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n InvalidParenthesisError,\n InvalidSignatureError,\n InvalidStructSignatureError,\n type Narrow,\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n SolidityProtectedKeywordError,\n type TypedData,\n type TypedDataDomain,\n type TypedDataParameter,\n UnknownSignatureError,\n UnknownTypeError,\n} from 'abitype'\nexport type {\n BlockOverrides,\n Rpc as RpcBlockOverrides,\n} from 'ox/BlockOverrides'\nexport type { EntryPointVersion } from './account-abstraction/types/entryPointVersion.js'\nexport type {\n RpcEstimateUserOperationGasReturnType,\n RpcGetUserOperationByHashReturnType,\n RpcUserOperation,\n RpcUserOperationReceipt,\n RpcUserOperationRequest,\n} from './account-abstraction/types/rpc.js'\nexport type {\n EstimateUserOperationGasReturnType,\n GetUserOperationByHashReturnType,\n PackedUserOperation,\n UserOperation,\n UserOperationReceipt,\n UserOperationRequest,\n} from './account-abstraction/types/userOperation.js'\nexport type {\n Account,\n AccountSource,\n CustomSource,\n HDAccount,\n HDOptions,\n JsonRpcAccount,\n LocalAccount,\n PrivateKeyAccount,\n} from './accounts/types.js'\nexport type {\n GetEnsAddressErrorType,\n GetEnsAddressParameters,\n GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n GetEnsAvatarErrorType,\n GetEnsAvatarParameters,\n GetEnsAvatarReturnType,\n} from './actions/ens/getEnsAvatar.js'\nexport type {\n GetEnsNameErrorType,\n GetEnsNameParameters,\n GetEnsNameReturnType,\n} from './actions/ens/getEnsName.js'\nexport type {\n GetEnsResolverErrorType,\n GetEnsResolverParameters,\n GetEnsResolverReturnType,\n} from './actions/ens/getEnsResolver.js'\nexport type {\n GetEnsTextErrorType,\n GetEnsTextParameters,\n GetEnsTextReturnType,\n} from './actions/ens/getEnsText.js'\nexport {\n type GetContractErrorType,\n type GetContractParameters,\n type GetContractReturnType,\n getContract,\n} from './actions/getContract.js'\nexport type {\n CallErrorType,\n CallParameters,\n CallReturnType,\n} from './actions/public/call.js'\nexport type {\n CreateAccessListErrorType,\n CreateAccessListParameters,\n CreateAccessListReturnType,\n} from './actions/public/createAccessList.js'\nexport type {\n CreateBlockFilterErrorType,\n CreateBlockFilterReturnType,\n} from './actions/public/createBlockFilter.js'\nexport type {\n CreateContractEventFilterErrorType,\n CreateContractEventFilterParameters,\n CreateContractEventFilterReturnType,\n} from './actions/public/createContractEventFilter.js'\nexport type {\n CreateEventFilterErrorType,\n CreateEventFilterParameters,\n CreateEventFilterReturnType,\n} from './actions/public/createEventFilter.js'\nexport type {\n CreatePendingTransactionFilterErrorType,\n CreatePendingTransactionFilterReturnType,\n} from './actions/public/createPendingTransactionFilter.js'\nexport type {\n EstimateContractGasErrorType,\n EstimateContractGasParameters,\n EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n EstimateFeesPerGasErrorType,\n EstimateFeesPerGasParameters,\n EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n EstimateGasErrorType,\n EstimateGasParameters,\n EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n EstimateMaxPriorityFeePerGasErrorType,\n EstimateMaxPriorityFeePerGasParameters,\n EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n FillTransactionErrorType,\n FillTransactionParameters,\n FillTransactionReturnType,\n} from './actions/public/fillTransaction.js'\nexport type {\n GetBalanceErrorType,\n GetBalanceParameters,\n GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n GetBlobBaseFeeErrorType,\n GetBlobBaseFeeReturnType,\n} from './actions/public/getBlobBaseFee.js'\nexport type {\n GetBlockErrorType,\n GetBlockParameters,\n GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n GetBlockNumberErrorType,\n GetBlockNumberParameters,\n GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n GetBlockTransactionCountErrorType,\n GetBlockTransactionCountParameters,\n GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n GetChainIdErrorType,\n GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n /** @deprecated Use `GetCodeErrorType` instead */\n GetCodeErrorType as GetBytecodeErrorType,\n GetCodeErrorType,\n /** @deprecated Use `GetCodeParameters` instead */\n GetCodeParameters as GetBytecodeParameters,\n GetCodeParameters,\n /** @deprecated Use `GetCodeReturnType` instead */\n GetCodeReturnType as GetBytecodeReturnType,\n GetCodeReturnType,\n} from './actions/public/getCode.js'\nexport type {\n GetContractEventsErrorType,\n GetContractEventsParameters,\n GetContractEventsReturnType,\n} from './actions/public/getContractEvents.js'\nexport type {\n GetDelegationErrorType,\n GetDelegationParameters,\n GetDelegationReturnType,\n} from './actions/public/getDelegation.js'\nexport type {\n GetEip712DomainErrorType,\n GetEip712DomainParameters,\n GetEip712DomainReturnType,\n} from './actions/public/getEip712Domain.js'\nexport type {\n GetFeeHistoryErrorType,\n GetFeeHistoryParameters,\n GetFeeHistoryReturnType,\n} from './actions/public/getFeeHistory.js'\nexport type {\n GetFilterChangesErrorType,\n GetFilterChangesParameters,\n GetFilterChangesReturnType,\n} from './actions/public/getFilterChanges.js'\nexport type {\n GetFilterLogsErrorType,\n GetFilterLogsParameters,\n GetFilterLogsReturnType,\n} from './actions/public/getFilterLogs.js'\nexport type {\n GetGasPriceErrorType,\n GetGasPriceReturnType,\n} from './actions/public/getGasPrice.js'\nexport type {\n GetLogsErrorType,\n GetLogsParameters,\n GetLogsReturnType,\n} from './actions/public/getLogs.js'\nexport type {\n GetProofErrorType,\n GetProofParameters,\n GetProofReturnType,\n} from './actions/public/getProof.js'\nexport type {\n GetStorageAtErrorType,\n GetStorageAtParameters,\n GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n GetTransactionErrorType,\n GetTransactionParameters,\n GetTransactionReturnType,\n} from './actions/public/getTransaction.js'\nexport type {\n GetTransactionConfirmationsErrorType,\n GetTransactionConfirmationsParameters,\n GetTransactionConfirmationsReturnType,\n} from './actions/public/getTransactionConfirmations.js'\nexport type {\n GetTransactionCountErrorType,\n GetTransactionCountParameters,\n GetTransactionCountReturnType,\n} from './actions/public/getTransactionCount.js'\nexport type {\n GetTransactionReceiptErrorType,\n GetTransactionReceiptParameters,\n GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n MulticallErrorType,\n MulticallParameters,\n MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n ReadContractErrorType,\n ReadContractParameters,\n ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n SimulateBlocksErrorType,\n SimulateBlocksParameters,\n SimulateBlocksReturnType,\n} from './actions/public/simulateBlocks.js'\nexport type {\n SimulateCallsErrorType,\n SimulateCallsParameters,\n SimulateCallsReturnType,\n} from './actions/public/simulateCalls.js'\nexport type {\n GetMutabilityAwareValue,\n SimulateContractErrorType,\n SimulateContractParameters,\n SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n UninstallFilterErrorType,\n UninstallFilterParameters,\n UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n VerifyHashErrorType as VerifyHashActionErrorType,\n VerifyHashParameters as VerifyHashActionParameters,\n VerifyHashReturnType as VerifyHashActionReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n VerifyMessageErrorType as VerifyMessageActionErrorType,\n VerifyMessageParameters as VerifyMessageActionParameters,\n VerifyMessageReturnType as VerifyMessageActionReturnType,\n} from './actions/public/verifyMessage.js'\nexport type {\n VerifyTypedDataErrorType as VerifyTypedDataActionErrorType,\n VerifyTypedDataParameters as VerifyTypedDataActionParameters,\n VerifyTypedDataReturnType as VerifyTypedDataActionReturnType,\n} from './actions/public/verifyTypedData.js'\nexport type {\n ReplacementReason,\n ReplacementReturnType,\n WaitForTransactionReceiptErrorType,\n WaitForTransactionReceiptParameters,\n WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n OnBlockNumberFn,\n OnBlockNumberParameter,\n WatchBlockNumberErrorType,\n WatchBlockNumberParameters,\n WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n OnBlock,\n OnBlockParameter,\n WatchBlocksErrorType,\n WatchBlocksParameters,\n WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n WatchContractEventErrorType,\n WatchContractEventOnLogsFn,\n WatchContractEventOnLogsParameter,\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n WatchEventErrorType,\n WatchEventOnLogsFn,\n WatchEventOnLogsParameter,\n WatchEventParameters,\n WatchEventReturnType,\n} from './actions/public/watchEvent.js'\nexport type {\n OnTransactionsFn,\n OnTransactionsParameter,\n WatchPendingTransactionsErrorType,\n WatchPendingTransactionsParameters,\n WatchPendingTransactionsReturnType,\n} from './actions/public/watchPendingTransactions.js'\nexport type {\n DropTransactionErrorType,\n DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n DumpStateErrorType,\n DumpStateReturnType,\n} from './actions/test/dumpState.js'\nexport type {\n GetAutomineErrorType,\n GetAutomineReturnType,\n} from './actions/test/getAutomine.js'\nexport type {\n GetTxpoolContentErrorType,\n GetTxpoolContentReturnType,\n} from './actions/test/getTxpoolContent.js'\nexport type {\n GetTxpoolStatusErrorType,\n GetTxpoolStatusReturnType,\n} from './actions/test/getTxpoolStatus.js'\nexport type {\n ImpersonateAccountErrorType,\n ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n IncreaseTimeErrorType,\n IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type {\n InspectTxpoolErrorType,\n InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type {\n LoadStateErrorType,\n LoadStateParameters,\n LoadStateReturnType,\n} from './actions/test/loadState.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type { RemoveBlockTimestampIntervalErrorType } from './actions/test/removeBlockTimestampInterval.js'\nexport type { ResetErrorType, ResetParameters } from './actions/test/reset.js'\nexport type {\n RevertErrorType,\n RevertParameters,\n} from './actions/test/revert.js'\nexport type {\n SendUnsignedTransactionErrorType,\n SendUnsignedTransactionParameters,\n SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type { SetAutomineErrorType } from './actions/test/setAutomine.js'\nexport type {\n SetBalanceErrorType,\n SetBalanceParameters,\n} from './actions/test/setBalance.js'\nexport type {\n SetBlockGasLimitErrorType,\n SetBlockGasLimitParameters,\n} from './actions/test/setBlockGasLimit.js'\nexport type {\n SetBlockTimestampIntervalErrorType,\n SetBlockTimestampIntervalParameters,\n} from './actions/test/setBlockTimestampInterval.js'\nexport type {\n SetCodeErrorType,\n SetCodeParameters,\n} from './actions/test/setCode.js'\nexport type {\n SetCoinbaseErrorType,\n SetCoinbaseParameters,\n} from './actions/test/setCoinbase.js'\nexport type {\n SetIntervalMiningErrorType,\n SetIntervalMiningParameters,\n} from './actions/test/setIntervalMining.js'\nexport type { SetLoggingEnabledErrorType } from './actions/test/setLoggingEnabled.js'\nexport type {\n SetMinGasPriceErrorType,\n SetMinGasPriceParameters,\n} from './actions/test/setMinGasPrice.js'\nexport type {\n SetNextBlockBaseFeePerGasErrorType,\n SetNextBlockBaseFeePerGasParameters,\n} from './actions/test/setNextBlockBaseFeePerGas.js'\nexport type {\n SetNextBlockTimestampErrorType,\n SetNextBlockTimestampParameters,\n} from './actions/test/setNextBlockTimestamp.js'\nexport type {\n SetNonceErrorType,\n SetNonceParameters,\n} from './actions/test/setNonce.js'\nexport type { SetRpcUrlErrorType } from './actions/test/setRpcUrl.js'\nexport type {\n SetStorageAtErrorType,\n SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type { SnapshotErrorType } from './actions/test/snapshot.js'\nexport type {\n StopImpersonatingAccountErrorType,\n StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n AddChainErrorType,\n AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport type {\n DeployContractErrorType,\n DeployContractParameters,\n DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n GetAddressesErrorType,\n GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n GetCallsStatusErrorType,\n GetCallsStatusParameters,\n GetCallsStatusReturnType,\n} from './actions/wallet/getCallsStatus.js'\nexport type {\n GetCapabilitiesErrorType,\n GetCapabilitiesParameters,\n GetCapabilitiesReturnType,\n} from './actions/wallet/getCapabilities.js'\nexport type {\n GetPermissionsErrorType,\n GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n PrepareAuthorizationErrorType,\n PrepareAuthorizationParameters,\n PrepareAuthorizationReturnType,\n} from './actions/wallet/prepareAuthorization.js'\nexport type {\n PrepareTransactionRequestErrorType,\n PrepareTransactionRequestParameters,\n PrepareTransactionRequestParameterType,\n PrepareTransactionRequestRequest,\n PrepareTransactionRequestReturnType,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n RequestAddressesErrorType,\n RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n RequestPermissionsErrorType,\n RequestPermissionsParameters,\n RequestPermissionsReturnType,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n SendCallsErrorType,\n SendCallsParameters,\n SendCallsReturnType,\n} from './actions/wallet/sendCalls.js'\nexport type {\n SendCallsSyncErrorType,\n SendCallsSyncParameters,\n SendCallsSyncReturnType,\n} from './actions/wallet/sendCallsSync.js'\nexport type {\n SendRawTransactionErrorType,\n SendRawTransactionParameters,\n SendRawTransactionReturnType,\n} from './actions/wallet/sendRawTransaction.js'\nexport type {\n SendRawTransactionSyncErrorType,\n SendRawTransactionSyncParameters,\n SendRawTransactionSyncReturnType,\n} from './actions/wallet/sendRawTransactionSync.js'\nexport type {\n SendTransactionErrorType,\n SendTransactionParameters,\n SendTransactionRequest,\n SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n SendTransactionSyncErrorType,\n SendTransactionSyncParameters,\n SendTransactionSyncRequest,\n SendTransactionSyncReturnType,\n} from './actions/wallet/sendTransactionSync.js'\nexport type {\n ShowCallsStatusErrorType,\n ShowCallsStatusParameters,\n ShowCallsStatusReturnType,\n} from './actions/wallet/showCallsStatus.js'\nexport type {\n SignAuthorizationErrorType,\n SignAuthorizationParameters,\n SignAuthorizationReturnType,\n} from './actions/wallet/signAuthorization.js'\nexport type {\n SignMessageErrorType,\n SignMessageParameters,\n SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n SignTransactionErrorType,\n SignTransactionParameters,\n SignTransactionRequest,\n SignTransactionReturnType,\n} from './actions/wallet/signTransaction.js'\nexport type {\n SignTypedDataErrorType,\n SignTypedDataParameters,\n SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n SwitchChainErrorType,\n SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n WaitForCallsStatusErrorType,\n WaitForCallsStatusParameters,\n WaitForCallsStatusReturnType,\n WaitForCallsStatusTimeoutErrorType,\n} from './actions/wallet/waitForCallsStatus.js'\nexport { WaitForCallsStatusTimeoutError } from './actions/wallet/waitForCallsStatus.js'\nexport type {\n WatchAssetErrorType,\n WatchAssetParameters,\n WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n WriteContractErrorType,\n WriteContractParameters,\n WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n WriteContractSyncErrorType,\n WriteContractSyncParameters,\n WriteContractSyncReturnType,\n} from './actions/wallet/writeContractSync.js'\nexport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n type MulticallBatchOptions,\n rpcSchema,\n} from './clients/createClient.js'\nexport {\n type CreatePublicClientErrorType,\n createPublicClient,\n type PublicClient,\n type PublicClientConfig,\n} from './clients/createPublicClient.js'\nexport {\n type CreateTestClientErrorType,\n createTestClient,\n type TestClient,\n type TestClientConfig,\n} from './clients/createTestClient.js'\nexport {\n type CreateWalletClientErrorType,\n createWalletClient,\n type WalletClient,\n type WalletClientConfig,\n} from './clients/createWalletClient.js'\nexport {\n type PublicActions,\n publicActions,\n} from './clients/decorators/public.js'\nexport {\n type TestActions,\n testActions,\n} from './clients/decorators/test.js'\nexport {\n type WalletActions,\n walletActions,\n} from './clients/decorators/wallet.js'\nexport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './clients/transports/createTransport.js'\nexport {\n type CustomTransport,\n type CustomTransportConfig,\n type CustomTransportErrorType,\n custom,\n} from './clients/transports/custom.js'\nexport {\n type FallbackTransport,\n type FallbackTransportConfig,\n type FallbackTransportErrorType,\n fallback,\n shouldThrow,\n} from './clients/transports/fallback.js'\nexport {\n type HttpTransport,\n type HttpTransportConfig,\n type HttpTransportErrorType,\n http,\n} from './clients/transports/http.js'\nexport {\n type WebSocketTransport,\n type WebSocketTransportConfig,\n type WebSocketTransportErrorType,\n webSocket,\n} from './clients/transports/webSocket.js'\nexport {\n erc20Abi,\n erc20Abi_bytes32,\n erc721Abi,\n erc1155Abi,\n erc4626Abi,\n erc6492SignatureValidatorAbi,\n /** @deprecated use `erc6492SignatureValidatorAbi` instead. */\n erc6492SignatureValidatorAbi as universalSignatureValidatorAbi,\n multicall3Abi,\n} from './constants/abis.js'\nexport { ethAddress, zeroAddress } from './constants/address.js'\nexport { zeroHash } from './constants/bytes.js'\nexport {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n erc6492SignatureValidatorByteCode,\n /** @deprecated use `erc6492SignatureValidatorByteCode` instead. */\n erc6492SignatureValidatorByteCode as universalSignatureValidatorByteCode,\n} from './constants/contracts.js'\nexport {\n maxInt8,\n maxInt16,\n maxInt24,\n maxInt32,\n maxInt40,\n maxInt48,\n maxInt56,\n maxInt64,\n maxInt72,\n maxInt80,\n maxInt88,\n maxInt96,\n maxInt104,\n maxInt112,\n maxInt120,\n maxInt128,\n maxInt136,\n maxInt144,\n maxInt152,\n maxInt160,\n maxInt168,\n maxInt176,\n maxInt184,\n maxInt192,\n maxInt200,\n maxInt208,\n maxInt216,\n maxInt224,\n maxInt232,\n maxInt240,\n maxInt248,\n maxInt256,\n maxUint8,\n maxUint16,\n maxUint24,\n maxUint32,\n maxUint40,\n maxUint48,\n maxUint56,\n maxUint64,\n maxUint72,\n maxUint80,\n maxUint88,\n maxUint96,\n maxUint104,\n maxUint112,\n maxUint120,\n maxUint128,\n maxUint136,\n maxUint144,\n maxUint152,\n maxUint160,\n maxUint168,\n maxUint176,\n maxUint184,\n maxUint192,\n maxUint200,\n maxUint208,\n maxUint216,\n maxUint224,\n maxUint232,\n maxUint240,\n maxUint248,\n maxUint256,\n minInt8,\n minInt16,\n minInt24,\n minInt32,\n minInt40,\n minInt48,\n minInt56,\n minInt64,\n minInt72,\n minInt80,\n minInt88,\n minInt96,\n minInt104,\n minInt112,\n minInt120,\n minInt128,\n minInt136,\n minInt144,\n minInt152,\n minInt160,\n minInt168,\n minInt176,\n minInt184,\n minInt192,\n minInt200,\n minInt208,\n minInt216,\n minInt224,\n minInt232,\n minInt240,\n minInt248,\n minInt256,\n} from './constants/number.js'\nexport { presignMessagePrefix } from './constants/strings.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.js'\nexport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n type AbiConstructorParamsNotFoundErrorType,\n AbiDecodingDataSizeInvalidError,\n type AbiDecodingDataSizeInvalidErrorType,\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiDecodingZeroDataError,\n type AbiDecodingZeroDataErrorType,\n AbiEncodingArrayLengthMismatchError,\n type AbiEncodingArrayLengthMismatchErrorType,\n AbiEncodingBytesSizeMismatchError,\n type AbiEncodingBytesSizeMismatchErrorType,\n AbiEncodingLengthMismatchError,\n type AbiEncodingLengthMismatchErrorType,\n AbiErrorInputsNotFoundError,\n type AbiErrorInputsNotFoundErrorType,\n AbiErrorNotFoundError,\n type AbiErrorNotFoundErrorType,\n AbiErrorSignatureNotFoundError,\n type AbiErrorSignatureNotFoundErrorType,\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n AbiFunctionSignatureNotFoundError,\n type AbiFunctionSignatureNotFoundErrorType,\n BytesSizeMismatchError,\n type BytesSizeMismatchErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n InvalidAbiEncodingTypeError,\n type InvalidAbiEncodingTypeErrorType,\n InvalidArrayError,\n type InvalidArrayErrorType,\n InvalidDefinitionTypeError,\n type InvalidDefinitionTypeErrorType,\n UnsupportedPackedAbiType,\n type UnsupportedPackedAbiTypeErrorType,\n} from './errors/abi.js'\nexport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from './errors/address.js'\nexport { BaseError, type BaseErrorType, setErrorConfig } from './errors/base.js'\nexport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n BundleFailedError,\n type BundleFailedErrorType,\n} from './errors/calls.js'\nexport {\n ChainDoesNotSupportContract,\n type ChainDoesNotSupportContractErrorType,\n ChainMismatchError,\n type ChainMismatchErrorType,\n ChainNotFoundError,\n type ChainNotFoundErrorType,\n ClientChainNotConfiguredError,\n type ClientChainNotConfiguredErrorType,\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from './errors/chain.js'\nexport {\n CallExecutionError,\n type CallExecutionErrorType,\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n CounterfactualDeploymentFailedError,\n type CounterfactualDeploymentFailedErrorType,\n RawContractError,\n type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n SliceOffsetOutOfBoundsError,\n type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n InvalidBytesBooleanError,\n type InvalidBytesBooleanErrorType,\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n InvalidHexValueError,\n type InvalidHexValueErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n type EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n EnsInvalidChainIdError,\n type EnsInvalidChainIdErrorType,\n} from './errors/ens.js'\nexport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n MaxFeePerGasTooLowError,\n type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from './errors/log.js'\nexport {\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'\nexport {\n HttpRequestError,\n type HttpRequestErrorType,\n RpcRequestError,\n type RpcRequestErrorType,\n SocketClosedError,\n type SocketClosedErrorType,\n TimeoutError,\n type TimeoutErrorType,\n WebSocketRequestError,\n type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n ProviderRpcError,\n type ProviderRpcErrorCode,\n type ProviderRpcErrorType,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from './errors/stateOverride.js'\nexport {\n FeeConflictError,\n type FeeConflictErrorType,\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n InvalidSerializedTransactionError,\n type InvalidSerializedTransactionErrorType,\n InvalidSerializedTransactionTypeError,\n type InvalidSerializedTransactionTypeErrorType,\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from './errors/transaction.js'\nexport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport {\n InvalidDomainError,\n type InvalidDomainErrorType,\n InvalidPrimaryTypeError,\n type InvalidPrimaryTypeErrorType,\n InvalidStructTypeError,\n type InvalidStructTypeErrorType,\n} from './errors/typedData.js'\nexport {\n InvalidDecimalNumberError,\n type InvalidDecimalNumberErrorType,\n} from './errors/unit.js'\nexport type {\n DeriveAccount,\n HDKey,\n ParseAccount,\n} from './types/account.js'\nexport type {\n Authorization,\n AuthorizationList,\n AuthorizationRequest,\n SerializedAuthorization,\n SerializedAuthorizationList,\n SignedAuthorization,\n SignedAuthorizationList,\n} from './types/authorization.js'\nexport type {\n Block,\n BlockIdentifier,\n BlockNumber,\n BlockTag,\n Uncle,\n} from './types/block.js'\nexport type { Call, Calls } from './types/calls.js'\nexport type {\n Capabilities,\n /** @deprecated Use `Capabilities` instead. */\n Capabilities as WalletCapabilities,\n CapabilitiesSchema,\n /** @deprecated Use `ChainIdToCapabilities` instead. */\n ChainIdToCapabilities as WalletCapabilitiesRecord,\n ChainIdToCapabilities,\n ExtractCapabilities,\n} from './types/capabilities.js'\nexport type {\n Chain,\n ChainConfig,\n ChainContract,\n ChainEstimateFeesPerGasFn,\n ChainEstimateFeesPerGasFnParameters,\n ChainFees,\n ChainFeesFnParameters,\n ChainFormatter,\n ChainFormatters,\n ChainMaxPriorityFeePerGasFn,\n ChainSerializers,\n DeriveChain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterParameters,\n ExtractChainFormatterReturnType,\n GetChainParameter,\n} from './types/chain.js'\nexport type {\n AbiEventParametersToPrimitiveTypes,\n AbiEventParameterToPrimitiveType,\n AbiEventTopicToPrimitiveType,\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ContractConstructorArgs,\n ContractErrorArgs,\n ContractErrorName,\n ContractEventArgs,\n ContractEventArgsFromTopics,\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n EventDefinition,\n ExtractAbiFunctionForArgs,\n ExtractAbiItem,\n ExtractAbiItemForArgs,\n ExtractAbiItemNames,\n GetEventArgs,\n GetValue,\n LogTopicType,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n UnionWiden,\n Widen,\n} from './types/contract.js'\nexport type { DataSuffix } from './types/dataSuffix.js'\nexport type {\n AddEthereumChainParameter,\n BundlerRpcSchema,\n DebugBundlerRpcSchema,\n EIP1193EventMap,\n EIP1193Events,\n EIP1193Parameters,\n EIP1193Provider,\n EIP1193RequestFn,\n EIP1474Methods,\n NetworkSync,\n PaymasterRpcSchema,\n ProviderConnectInfo,\n ProviderMessage,\n ProviderRpcErrorType as EIP1193ProviderRpcErrorType,\n PublicRpcSchema,\n RpcSchema,\n RpcSchemaOverride,\n TestRpcSchema,\n WalletCallReceipt,\n WalletGetAssetsParameters,\n WalletGetAssetsReturnType,\n WalletGetCallsStatusReturnType,\n WalletGrantPermissionsParameters,\n WalletGrantPermissionsReturnType,\n WalletPermission,\n WalletPermissionCaveat,\n WalletRpcSchema,\n WalletSendCallsParameters,\n WalletSendCallsReturnType,\n WatchAssetParams,\n} from './types/eip1193.js'\nexport { ProviderRpcError as EIP1193ProviderRpcError } from './types/eip1193.js'\nexport type { BlobSidecar, BlobSidecars } from './types/eip4844.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n FeeHistory,\n FeeValues,\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n FeeValuesType,\n} from './types/fee.js'\nexport type { Filter, FilterType } from './types/filter.js'\nexport type { GetTransactionRequestKzgParameter, Kzg } from './types/kzg.js'\nexport type { Log } from './types/log.js'\nexport type {\n ByteArray,\n CompactSignature,\n Hash,\n Hex,\n LogTopic,\n SignableMessage,\n Signature,\n} from './types/misc.js'\nexport type {\n MulticallContracts,\n MulticallResponse,\n MulticallResults,\n} from './types/multicall.js'\nexport type { Register, ResolvedRegister } from './types/register.js'\nexport type {\n Index,\n Quantity,\n RpcAccountStateOverride,\n RpcAuthorization,\n RpcAuthorizationList,\n RpcBlock,\n RpcBlockIdentifier,\n RpcBlockNumber,\n RpcFeeHistory,\n RpcFeeValues,\n RpcLog,\n RpcProof,\n RpcStateMapping,\n RpcStateOverride,\n RpcTransaction,\n RpcTransactionReceipt,\n RpcTransactionRequest,\n RpcUncle,\n Status,\n} from './types/rpc.js'\nexport type {\n StateMapping,\n StateOverride,\n} from './types/stateOverride.js'\nexport type {\n AccessList,\n Transaction,\n TransactionBase,\n TransactionEIP1559,\n TransactionEIP2930,\n TransactionEIP4844,\n TransactionEIP7702,\n TransactionLegacy,\n TransactionReceipt,\n TransactionRequest,\n TransactionRequestBase,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestGeneric,\n TransactionRequestLegacy,\n TransactionSerializable,\n TransactionSerializableBase,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionSerializedLegacy,\n TransactionType,\n} from './types/transaction.js'\nexport type { GetPollOptions, GetTransportConfig } from './types/transport.js'\nexport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from './types/typedData.js'\nexport type {\n Assign,\n Branded,\n Evaluate,\n ExactPartial,\n ExactRequired,\n IsNarrowable,\n IsNever,\n IsUndefined,\n IsUnion,\n LooseOmit,\n MaybePartial,\n MaybePromise,\n MaybeRequired,\n Mutable,\n NoInfer,\n NoUndefined,\n Omit,\n OneOf,\n Or,\n PartialBy,\n Prettify,\n RequiredBy,\n Some,\n UnionEvaluate,\n UnionLooseOmit,\n UnionOmit,\n UnionPartialBy,\n UnionPick,\n UnionRequiredBy,\n UnionToTuple,\n ValueOf,\n} from './types/utils.js'\nexport type { Withdrawal } from './types/withdrawal.js'\nexport {\n type DecodeAbiParametersErrorType,\n type DecodeAbiParametersReturnType,\n decodeAbiParameters,\n} from './utils/abi/decodeAbiParameters.js'\nexport {\n type DecodeDeployDataErrorType,\n type DecodeDeployDataParameters,\n type DecodeDeployDataReturnType,\n decodeDeployData,\n} from './utils/abi/decodeDeployData.js'\nexport {\n type DecodeErrorResultErrorType,\n type DecodeErrorResultParameters,\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from './utils/abi/decodeErrorResult.js'\nexport {\n type DecodeEventLogErrorType,\n type DecodeEventLogParameters,\n type DecodeEventLogReturnType,\n decodeEventLog,\n} from './utils/abi/decodeEventLog.js'\nexport {\n type DecodeFunctionDataErrorType,\n type DecodeFunctionDataParameters,\n type DecodeFunctionDataReturnType,\n decodeFunctionData,\n} from './utils/abi/decodeFunctionData.js'\nexport {\n type DecodeFunctionResultErrorType,\n type DecodeFunctionResultParameters,\n type DecodeFunctionResultReturnType,\n decodeFunctionResult,\n} from './utils/abi/decodeFunctionResult.js'\nexport {\n type EncodeAbiParametersErrorType,\n type EncodeAbiParametersReturnType,\n encodeAbiParameters,\n} from './utils/abi/encodeAbiParameters.js'\nexport {\n type EncodeDeployDataErrorType,\n type EncodeDeployDataParameters,\n type EncodeDeployDataReturnType,\n encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n type EncodeErrorResultReturnType,\n encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n type EncodeFunctionDataReturnType,\n encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n type EncodeFunctionResultReturnType,\n encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n type EncodePackedErrorType,\n encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n type GetAbiItemReturnType,\n getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './utils/abi/parseEventLogs.js'\nexport {\n type PrepareEncodeFunctionDataErrorType,\n type PrepareEncodeFunctionDataParameters,\n type PrepareEncodeFunctionDataReturnType,\n prepareEncodeFunctionData,\n} from './utils/abi/prepareEncodeFunctionData.js'\nexport {\n type ChecksumAddressErrorType,\n checksumAddress,\n type GetAddressErrorType,\n getAddress,\n} from './utils/address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n type IsAddressErrorType,\n type IsAddressOptions,\n isAddress,\n} from './utils/address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n type IsAddressEqualReturnType,\n isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport {\n type BlobsToCommitmentsErrorType,\n type BlobsToCommitmentsParameters,\n type BlobsToCommitmentsReturnType,\n blobsToCommitments,\n} from './utils/blob/blobsToCommitments.js'\nexport {\n blobsToProofs,\n type blobsToProofsErrorType,\n type blobsToProofsParameters,\n type blobsToProofsReturnType,\n} from './utils/blob/blobsToProofs.js'\nexport {\n type CommitmentsToVersionedHashesErrorType,\n type CommitmentsToVersionedHashesParameters,\n type CommitmentsToVersionedHashesReturnType,\n commitmentsToVersionedHashes,\n} from './utils/blob/commitmentsToVersionedHashes.js'\nexport {\n type CommitmentToVersionedHashErrorType,\n type CommitmentToVersionedHashParameters,\n type CommitmentToVersionedHashReturnType,\n commitmentToVersionedHash,\n} from './utils/blob/commitmentToVersionedHash.js'\nexport {\n type FromBlobsErrorType,\n type FromBlobsParameters,\n type FromBlobsReturnType,\n fromBlobs,\n} from './utils/blob/fromBlobs.js'\nexport {\n type SidecarsToVersionedHashesErrorType,\n type SidecarsToVersionedHashesParameters,\n type SidecarsToVersionedHashesReturnType,\n sidecarsToVersionedHashes,\n} from './utils/blob/sidecarsToVersionedHashes.js'\nexport {\n type ToBlobSidecarsErrorType,\n type ToBlobSidecarsParameters,\n type ToBlobSidecarsReturnType,\n toBlobSidecars,\n} from './utils/blob/toBlobSidecars.js'\nexport {\n type ToBlobsErrorType,\n type ToBlobsParameters,\n type ToBlobsReturnType,\n toBlobs,\n} from './utils/blob/toBlobs.js'\nexport {\n type CcipRequestErrorType,\n type CcipRequestParameters,\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport {\n type DefineChainReturnType,\n defineChain,\n extendSchema,\n} from './utils/chain/defineChain.js'\nexport {\n type ExtractChainErrorType,\n type ExtractChainParameters,\n type ExtractChainReturnType,\n extractChain,\n} from './utils/chain/extractChain.js'\nexport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from './utils/chain/getChainContractAddress.js'\nexport {\n type ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n type ConcatReturnType,\n concat,\n concatBytes,\n concatHex,\n} from './utils/data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.js'\nexport {\n type PadBytesErrorType,\n type PadErrorType,\n type PadHexErrorType,\n type PadReturnType,\n pad,\n padBytes,\n padHex,\n} from './utils/data/pad.js'\nexport { type SizeErrorType, size } from './utils/data/size.js'\nexport {\n type SliceBytesErrorType,\n type SliceErrorType,\n type SliceHexErrorType,\n slice,\n sliceBytes,\n sliceHex,\n} from './utils/data/slice.js'\nexport {\n type TrimErrorType,\n type TrimReturnType,\n trim,\n} from './utils/data/trim.js'\nexport {\n type BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n type FromHexErrorType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBoolErrorType,\n type HexToNumberErrorType,\n type HexToStringErrorType,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './utils/encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n type FromRlpReturnType,\n fromRlp,\n} from './utils/encoding/fromRlp.js'\nexport {\n type BoolToBytesErrorType,\n type BoolToBytesOpts,\n boolToBytes,\n type HexToBytesErrorType,\n type HexToBytesOpts,\n hexToBytes,\n type NumberToBytesErrorType,\n numberToBytes,\n type StringToBytesErrorType,\n type StringToBytesOpts,\n stringToBytes,\n type ToBytesErrorType,\n type ToBytesParameters,\n toBytes,\n} from './utils/encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\n bytesToHex,\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n type StringToHexErrorType,\n type StringToHexOpts,\n stringToHex,\n type ToHexErrorType,\n type ToHexParameters,\n toHex,\n} from './utils/encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n bytesToRlp,\n type HexToRlpErrorType,\n hexToRlp,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './utils/encoding/toRlp.js'\nexport { type LabelhashErrorType, labelhash } from './utils/ens/labelhash.js'\nexport { type NamehashErrorType, namehash } from './utils/ens/namehash.js'\nexport {\n type ToCoinTypeError,\n toCoinType,\n} from './utils/ens/toCoinType.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './utils/formatters/block.js'\nexport { type FormatLogErrorType, formatLog } from './utils/formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport {\n type Keccak256ErrorType,\n type Keccak256Hash,\n keccak256,\n} from './utils/hash/keccak256.js'\nexport {\n type Ripemd160ErrorType,\n type Ripemd160Hash,\n ripemd160,\n} from './utils/hash/ripemd160.js'\nexport {\n type Sha256ErrorType,\n type Sha256Hash,\n sha256,\n} from './utils/hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './utils/hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './utils/hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './utils/hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './utils/hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './utils/hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './utils/hash/toFunctionSignature.js'\nexport {\n type DefineKzgErrorType,\n type DefineKzgParameters,\n type DefineKzgReturnType,\n defineKzg,\n} from './utils/kzg/defineKzg.js'\nexport {\n type SetupKzgErrorType,\n type SetupKzgParameters,\n type SetupKzgReturnType,\n setupKzg,\n} from './utils/kzg/setupKzg.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './utils/nonceManager.js'\nexport { withCache } from './utils/promise/withCache.js'\nexport {\n type WithRetryErrorType,\n withRetry,\n} from './utils/promise/withRetry.js'\nexport {\n type WithTimeoutErrorType,\n withTimeout,\n} from './utils/promise/withTimeout.js'\nexport {\n type CompactSignatureToSignatureErrorType,\n compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n type HashMessageErrorType,\n hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashDomain,\n hashStruct,\n hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './utils/signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './utils/signature/isErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseCompactSignatureErrorType`. */\n type ParseCompactSignatureErrorType as HexToCompactSignatureErrorType,\n type ParseCompactSignatureErrorType,\n /** @deprecated Use `parseCompactSignature`. */\n parseCompactSignature as hexToCompactSignature,\n parseCompactSignature,\n} from './utils/signature/parseCompactSignature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './utils/signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './utils/signature/parseErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseSignatureErrorType`. */\n type ParseSignatureErrorType as HexToSignatureErrorType,\n type ParseSignatureErrorType,\n /** @deprecated Use `parseSignature`. */\n parseSignature as hexToSignature,\n parseSignature,\n} from './utils/signature/parseSignature.js'\nexport {\n type RecoverAddressErrorType,\n type RecoverAddressParameters,\n type RecoverAddressReturnType,\n recoverAddress,\n} from './utils/signature/recoverAddress.js'\nexport {\n type RecoverMessageAddressErrorType,\n type RecoverMessageAddressParameters,\n type RecoverMessageAddressReturnType,\n recoverMessageAddress,\n} from './utils/signature/recoverMessageAddress.js'\nexport {\n type RecoverPublicKeyErrorType,\n type RecoverPublicKeyParameters,\n type RecoverPublicKeyReturnType,\n recoverPublicKey,\n} from './utils/signature/recoverPublicKey.js'\nexport {\n type RecoverTransactionAddressErrorType,\n type RecoverTransactionAddressParameters,\n type RecoverTransactionAddressReturnType,\n recoverTransactionAddress,\n} from './utils/signature/recoverTransactionAddress.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeCompactSignatureErrorType as CompactSignatureToHexErrorType,\n type SerializeCompactSignatureErrorType,\n /** @deprecated Use `serializeCompactSignature` instead. */\n serializeCompactSignature as compactSignatureToHex,\n serializeCompactSignature,\n} from './utils/signature/serializeCompactSignature.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './utils/signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './utils/signature/serializeErc8010Signature.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n type SerializeSignatureParameters,\n type SerializeSignatureReturnType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from './utils/signature/serializeSignature.js'\nexport {\n type SignatureToCompactSignatureErrorType,\n signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n type ToPrefixedMessageErrorType,\n toPrefixedMessage,\n} from './utils/signature/toPrefixedMessage.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './utils/signature/verifyHash.js'\nexport {\n type VerifyMessageErrorType,\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from './utils/signature/verifyMessage.js'\nexport {\n type VerifyTypedDataErrorType,\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from './utils/signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n type ParseTransactionReturnType,\n parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n type SerializedTransactionReturnType,\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './utils/transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n domainSeparator,\n type GetTypesForEIP712DomainErrorType,\n getTypesForEIP712Domain,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './utils/typedData.js'\nexport {\n type FormatEtherErrorType,\n formatEther,\n} from './utils/unit/formatEther.js'\nexport {\n type FormatGweiErrorType,\n formatGwei,\n} from './utils/unit/formatGwei.js'\nexport {\n type FormatUnitsErrorType,\n formatUnits,\n} from './utils/unit/formatUnits.js'\nexport {\n type ParseEtherErrorType,\n parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n type ParseUnitsErrorType,\n parseUnits,\n} from './utils/unit/parseUnits.js'\n","import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","export const x402Version = 2;\n","import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData {\n facilitator: T;\n networks: Set;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = (\n map: Map>,\n network: Network,\n): Map | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = (\n map: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = (\n schemeMap: Map>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record = {};\n Object.keys(obj as Record)\n .sort()\n .forEach(key => {\n const value = (obj as Record)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n","import { x402ResourceServer } from \"../server\";\nimport {\n decodePaymentSignatureHeader,\n encodePaymentRequiredHeader,\n encodePaymentResponseHeader,\n} from \".\";\nimport {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n SettleError,\n Price,\n Network,\n PaymentRequirements,\n} from \"../types\";\nimport { x402Version } from \"..\";\n\n/**\n * Framework-agnostic HTTP adapter interface\n * Implementations provide framework-specific HTTP operations\n */\nexport interface HTTPAdapter {\n getHeader(name: string): string | undefined;\n getMethod(): string;\n getPath(): string;\n getUrl(): string;\n getAcceptHeader(): string;\n getUserAgent(): string;\n\n /**\n * Get query parameters from the request URL\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams?(): Record;\n\n /**\n * Get a specific query parameter by name\n *\n * @param name - The query parameter name\n * @returns The query parameter value(s) or undefined\n */\n getQueryParam?(name: string): string | string[] | undefined;\n\n /**\n * Get the parsed request body\n * Framework adapters should parse JSON/form data appropriately\n *\n * @returns The parsed request body\n */\n getBody?(): unknown;\n}\n\n/**\n * Paywall configuration for HTML responses\n */\nexport interface PaywallConfig {\n appName?: string;\n appLogo?: string;\n sessionTokenEndpoint?: string;\n currentUrl?: string;\n testnet?: boolean;\n}\n\n/**\n * Paywall provider interface for generating HTML\n */\nexport interface PaywallProvider {\n generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;\n}\n\n/**\n * Dynamic payTo function that receives HTTP request context\n */\nexport type DynamicPayTo = (context: HTTPRequestContext) => string | Promise;\n\n/**\n * Dynamic price function that receives HTTP request context\n */\nexport type DynamicPrice = (context: HTTPRequestContext) => Price | Promise;\n\n/**\n * Result of response body callbacks containing content type and body.\n */\nexport interface HTTPResponseBody {\n /**\n * The content type for the response (e.g., 'application/json', 'text/plain').\n */\n contentType: string;\n\n /**\n * The response body to include in the 402 response.\n */\n body: unknown;\n}\n\n/**\n * Dynamic function to generate a custom response for unpaid requests.\n * Receives the HTTP request context and returns the content type and body to include in the 402 response.\n */\nexport type UnpaidResponseBody = (\n context: HTTPRequestContext,\n) => HTTPResponseBody | Promise;\n\n/**\n * Dynamic function to generate a custom response for settlement failures.\n * Receives the HTTP request context and settle failure result, returns the content type and body.\n */\nexport type SettlementFailedResponseBody = (\n context: HTTPRequestContext,\n settleResult: Omit,\n) => HTTPResponseBody | Promise;\n\n/**\n * A single payment option for a route\n * Represents one way a client can pay for access to the resource\n */\nexport interface PaymentOption {\n scheme: string;\n payTo: string | DynamicPayTo;\n price: Price | DynamicPrice;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record;\n}\n\n/**\n * Route configuration for HTTP endpoints\n *\n * The 'accepts' field defines payment options for the route.\n * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.\n */\nexport interface RouteConfig {\n // Payment option(s): single or array\n accepts: PaymentOption | PaymentOption[];\n\n // HTTP-specific metadata\n resource?: string;\n description?: string;\n mimeType?: string;\n customPaywallHtml?: string;\n\n /**\n * Optional callback to generate a custom response for unpaid API requests.\n * This allows servers to return preview data, error messages, or other content\n * when a request lacks payment.\n *\n * For browser requests (Accept: text/html), the paywall HTML takes precedence.\n * This callback is only used for API clients.\n *\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @returns An object containing both contentType and body for the 402 response\n */\n unpaidResponseBody?: UnpaidResponseBody;\n\n /**\n * Optional callback to generate a custom response for settlement failures.\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @param settleResult - The settlement failure result\n * @returns An object containing both contentType and body for the 402 response\n */\n settlementFailedResponseBody?: SettlementFailedResponseBody;\n\n // Extensions\n extensions?: Record;\n}\n\n/**\n * Routes configuration - maps path patterns to route configs\n */\nexport type RoutesConfig = Record | RouteConfig;\n\n/**\n * Hook that runs on every request to a protected route, before payment processing.\n * Can grant access without payment, deny the request, or continue to payment flow.\n *\n * @returns\n * - `void` - Continue to payment processing (default behavior)\n * - `{ grantAccess: true }` - Grant access without requiring payment\n * - `{ abort: true; reason: string }` - Deny the request (returns 403)\n */\nexport type ProtectedRequestHook = (\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n) => Promise;\n\n/**\n * Compiled route for efficient matching\n */\nexport interface CompiledRoute {\n verb: string;\n regex: RegExp;\n config: RouteConfig;\n}\n\n/**\n * HTTP request context that encapsulates all request data\n */\nexport interface HTTPRequestContext {\n adapter: HTTPAdapter;\n path: string;\n method: string;\n paymentHeader?: string;\n}\n\n/**\n * HTTP transport context contains both request context and optional response data.\n */\nexport interface HTTPTransportContext {\n /** The HTTP request context */\n request: HTTPRequestContext;\n /** The response body buffer */\n responseBody?: Buffer;\n}\n\n/**\n * HTTP response instructions for the framework middleware\n */\nexport interface HTTPResponseInstructions {\n status: number;\n headers: Record;\n body?: unknown; // e.g. Paywall for web browser requests, but could be any other type\n isHtml?: boolean; // e.g. if body is a paywall, then isHtml is true\n}\n\n/**\n * Result of processing an HTTP request for payment\n */\nexport type HTTPProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n declaredExtensions?: Record;\n }\n | { type: \"payment-error\"; response: HTTPResponseInstructions };\n\n/**\n * Result of processSettlement\n */\nexport type ProcessSettleSuccessResponse = SettleResponse & {\n success: true;\n headers: Record;\n requirements: PaymentRequirements;\n};\n\nexport type ProcessSettleFailureResponse = SettleResponse & {\n success: false;\n errorReason: string;\n errorMessage?: string;\n headers: Record;\n response: HTTPResponseInstructions;\n};\n\nexport type ProcessSettleResultResponse =\n | ProcessSettleSuccessResponse\n | ProcessSettleFailureResponse;\n\n/**\n * Represents a validation error for a specific route's payment configuration.\n */\nexport interface RouteValidationError {\n /** The route pattern (e.g., \"GET /api/weather\") */\n routePattern: string;\n /** The payment scheme that failed validation */\n scheme: string;\n /** The network that failed validation */\n network: Network;\n /** The type of validation failure */\n reason: \"missing_scheme\" | \"missing_facilitator\";\n /** Human-readable error message */\n message: string;\n}\n\n/**\n * Error thrown when route configuration validation fails.\n */\nexport class RouteConfigurationError extends Error {\n /** The validation errors that caused this exception */\n public readonly errors: RouteValidationError[];\n\n /**\n * Creates a new RouteConfigurationError with the given validation errors.\n *\n * @param errors - The validation errors that caused this exception.\n */\n constructor(errors: RouteValidationError[]) {\n const message = `x402 Route Configuration Errors:\\n${errors.map(e => ` - ${e.message}`).join(\"\\n\")}`;\n super(message);\n this.name = \"RouteConfigurationError\";\n this.errors = errors;\n }\n}\n\n/**\n * HTTP-enhanced x402 resource server\n * Provides framework-agnostic HTTP protocol handling\n */\nexport class x402HTTPResourceServer {\n private ResourceServer: x402ResourceServer;\n private compiledRoutes: CompiledRoute[] = [];\n private routesConfig: RoutesConfig;\n private paywallProvider?: PaywallProvider;\n private protectedRequestHooks: ProtectedRequestHook[] = [];\n\n /**\n * Creates a new x402HTTPResourceServer instance.\n *\n * @param ResourceServer - The core x402ResourceServer instance to use\n * @param routes - Route configuration for payment-protected endpoints\n */\n constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig) {\n this.ResourceServer = ResourceServer;\n this.routesConfig = routes;\n\n // Handle both single route and multiple routes\n const normalizedRoutes =\n typeof routes === \"object\" && !(\"accepts\" in routes)\n ? (routes as Record)\n : { \"*\": routes as RouteConfig };\n\n for (const [pattern, config] of Object.entries(normalizedRoutes)) {\n const parsed = this.parseRoutePattern(pattern);\n this.compiledRoutes.push({\n verb: parsed.verb,\n regex: parsed.regex,\n config,\n });\n }\n }\n\n /**\n * Get the underlying x402ResourceServer instance.\n *\n * @returns The underlying x402ResourceServer instance\n */\n get server(): x402ResourceServer {\n return this.ResourceServer;\n }\n\n /**\n * Get the routes configuration.\n *\n * @returns The routes configuration\n */\n get routes(): RoutesConfig {\n return this.routesConfig;\n }\n\n /**\n * Initialize the HTTP resource server.\n *\n * This method initializes the underlying resource server (fetching facilitator support)\n * and then validates that all route payment configurations have corresponding\n * registered schemes and facilitator support.\n *\n * @throws RouteConfigurationError if any route's payment options don't have\n * corresponding registered schemes or facilitator support\n *\n * @example\n * ```typescript\n * const httpServer = new x402HTTPResourceServer(server, routes);\n * await httpServer.initialize();\n * ```\n */\n async initialize(): Promise {\n // First, initialize the underlying resource server (fetches facilitator support)\n await this.ResourceServer.initialize();\n\n // Then validate route configuration\n const errors = this.validateRouteConfiguration();\n if (errors.length > 0) {\n throw new RouteConfigurationError(errors);\n }\n }\n\n /**\n * Register a custom paywall provider for generating HTML\n *\n * @param provider - PaywallProvider instance\n * @returns This service instance for chaining\n */\n registerPaywallProvider(provider: PaywallProvider): this {\n this.paywallProvider = provider;\n return this;\n }\n\n /**\n * Register a hook that runs on every request to a protected route, before payment processing.\n * Hooks are executed in order of registration. The first hook to return a non-void result wins.\n *\n * @param hook - The request hook function\n * @returns The x402HTTPResourceServer instance for chaining\n */\n onProtectedRequest(hook: ProtectedRequestHook): this {\n this.protectedRequestHooks.push(hook);\n return this;\n }\n\n /**\n * Process HTTP request and return response instructions\n * This is the main entry point for framework middleware\n *\n * @param context - HTTP request context\n * @param paywallConfig - Optional paywall configuration\n * @returns Process result indicating next action for middleware\n */\n async processHTTPRequest(\n context: HTTPRequestContext,\n paywallConfig?: PaywallConfig,\n ): Promise {\n const { adapter, path, method } = context;\n\n // Find matching route\n const routeConfig = this.getRouteConfig(path, method);\n if (!routeConfig) {\n return { type: \"no-payment-required\" }; // No payment required for this route\n }\n\n // Execute request hooks before any payment processing\n for (const hook of this.protectedRequestHooks) {\n const result = await hook(context, routeConfig);\n if (result && \"grantAccess\" in result) {\n return { type: \"no-payment-required\" };\n }\n if (result && \"abort\" in result) {\n return {\n type: \"payment-error\",\n response: {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: result.reason },\n },\n };\n }\n }\n\n // Normalize accepts field to array of payment options\n const paymentOptions = this.normalizePaymentOptions(routeConfig);\n\n // Check for payment header (v1 or v2)\n const paymentPayload = this.extractPayment(adapter);\n\n // Create resource info, using config override if provided\n const resourceInfo = {\n url: routeConfig.resource || context.adapter.getUrl(),\n description: routeConfig.description || \"\",\n mimeType: routeConfig.mimeType || \"\",\n };\n\n // Build requirements from all payment options\n // (this method handles resolving dynamic functions internally)\n let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(\n paymentOptions,\n context,\n );\n\n let extensions = routeConfig.extensions;\n if (extensions) {\n extensions = this.ResourceServer.enrichExtensions(extensions, context);\n }\n\n // createPaymentRequiredResponse already handles extension enrichment in the core layer\n const transportContext: HTTPTransportContext = { request: context };\n const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n !paymentPayload ? \"Payment required\" : undefined,\n extensions,\n transportContext,\n );\n\n // If no payment provided\n if (!paymentPayload) {\n // Resolve custom unpaid response body if provided\n const unpaidBody = routeConfig.unpaidResponseBody\n ? await routeConfig.unpaidResponseBody(context)\n : undefined;\n\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(\n paymentRequired,\n this.isWebBrowser(adapter),\n paywallConfig,\n routeConfig.customPaywallHtml,\n unpaidBody,\n ),\n };\n }\n\n // Verify payment\n try {\n const matchingRequirements = this.ResourceServer.findMatchingRequirements(\n paymentRequired.accepts,\n paymentPayload,\n );\n\n if (!matchingRequirements) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const verifyResult = await this.ResourceServer.verifyPayment(\n paymentPayload,\n matchingRequirements,\n );\n\n if (!verifyResult.isValid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n verifyResult.invalidReason,\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n // Payment is valid, return data needed for settlement\n return {\n type: \"payment-verified\",\n paymentPayload,\n paymentRequirements: matchingRequirements,\n declaredExtensions: routeConfig.extensions,\n };\n } catch (error) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n error instanceof Error ? error.message : \"Payment verification failed\",\n routeConfig.extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n }\n\n /**\n * Process settlement after successful response\n *\n * @param paymentPayload - The verified payment payload\n * @param requirements - The matching payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional HTTP transport context\n * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure\n */\n async processSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record,\n transportContext?: HTTPTransportContext,\n ): Promise {\n try {\n const settleResponse = await this.ResourceServer.settlePayment(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n );\n\n if (!settleResponse.success) {\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason: settleResponse.errorReason || \"Settlement failed\",\n errorMessage:\n settleResponse.errorMessage || settleResponse.errorReason || \"Settlement failed\",\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n\n return {\n ...settleResponse,\n success: true,\n headers: this.createSettlementHeaders(settleResponse),\n requirements,\n };\n } catch (error) {\n if (error instanceof SettleError) {\n const errorReason = error.errorReason || error.message;\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: error.errorMessage || errorReason,\n payer: error.payer,\n network: error.network,\n transaction: error.transaction,\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n const errorReason = error instanceof Error ? error.message : \"Settlement failed\";\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: errorReason,\n network: requirements.network as Network,\n transaction: \"\",\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n }\n\n /**\n * Check if a request requires payment based on route configuration\n *\n * @param context - HTTP request context\n * @returns True if the route requires payment, false otherwise\n */\n requiresPayment(context: HTTPRequestContext): boolean {\n const routeConfig = this.getRouteConfig(context.path, context.method);\n return routeConfig !== undefined;\n }\n\n /**\n * Build HTTPResponseInstructions for settlement failure.\n * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.\n *\n * @param failure - Settlement failure result with headers\n * @param transportContext - Optional HTTP transport context for the request\n * @returns HTTP response instructions for the 402 settlement failure response\n */\n private async buildSettlementFailureResponse(\n failure: Omit,\n transportContext?: HTTPTransportContext,\n ): Promise {\n const settlementHeaders = failure.headers;\n const routeConfig = transportContext\n ? this.getRouteConfig(transportContext.request.path, transportContext.request.method)\n : undefined;\n\n const customBody = routeConfig?.settlementFailedResponseBody\n ? await routeConfig.settlementFailedResponseBody(transportContext!.request, failure)\n : undefined;\n\n const contentType = customBody ? customBody.contentType : \"application/json\";\n const body = customBody ? customBody.body : {};\n\n return {\n status: 402,\n headers: {\n \"Content-Type\": contentType,\n ...settlementHeaders,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n };\n }\n\n /**\n * Normalizes a RouteConfig's accepts field into an array of PaymentOptions\n * Handles both single PaymentOption and array formats\n *\n * @param routeConfig - Route configuration\n * @returns Array of payment options\n */\n private normalizePaymentOptions(routeConfig: RouteConfig): PaymentOption[] {\n return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];\n }\n\n /**\n * Validates that all payment options in routes have corresponding registered schemes\n * and facilitator support.\n *\n * @returns Array of validation errors (empty if all routes are valid)\n */\n private validateRouteConfiguration(): RouteValidationError[] {\n const errors: RouteValidationError[] = [];\n\n // Normalize routes to array of [pattern, config] pairs\n const normalizedRoutes =\n typeof this.routesConfig === \"object\" && !(\"accepts\" in this.routesConfig)\n ? Object.entries(this.routesConfig as Record)\n : [[\"*\", this.routesConfig as RouteConfig] as [string, RouteConfig]];\n\n for (const [pattern, config] of normalizedRoutes) {\n const paymentOptions = this.normalizePaymentOptions(config);\n\n for (const option of paymentOptions) {\n // Check 1: Is scheme registered?\n if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_scheme\",\n message: `Route \"${pattern}\": No scheme implementation registered for \"${option.scheme}\" on network \"${option.network}\"`,\n });\n // Skip facilitator check if scheme isn't registered\n continue;\n }\n\n // Check 2: Does facilitator support this scheme/network combination?\n const supportedKind = this.ResourceServer.getSupportedKind(\n x402Version,\n option.network,\n option.scheme,\n );\n\n if (!supportedKind) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_facilitator\",\n message: `Route \"${pattern}\": Facilitator does not support scheme \"${option.scheme}\" on network \"${option.network}\"`,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get route configuration for a request\n *\n * @param path - Request path\n * @param method - HTTP method\n * @returns Route configuration or undefined if no match\n */\n private getRouteConfig(path: string, method: string): RouteConfig | undefined {\n const normalizedPath = this.normalizePath(path);\n const upperMethod = method.toUpperCase();\n\n const matchingRoute = this.compiledRoutes.find(\n route =>\n route.regex.test(normalizedPath) && (route.verb === \"*\" || route.verb === upperMethod),\n );\n\n return matchingRoute?.config;\n }\n\n /**\n * Extract payment from HTTP headers (handles v1 and v2)\n *\n * @param adapter - HTTP adapter\n * @returns Decoded payment payload or null\n */\n private extractPayment(adapter: HTTPAdapter): PaymentPayload | null {\n // Check v2 header first (PAYMENT-SIGNATURE)\n const header = adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"PAYMENT-SIGNATURE\");\n\n if (header) {\n try {\n return decodePaymentSignatureHeader(header);\n } catch (error) {\n console.warn(\"Failed to decode PAYMENT-SIGNATURE header:\", error);\n }\n }\n\n return null;\n }\n\n /**\n * Check if request is from a web browser\n *\n * @param adapter - HTTP adapter\n * @returns True if request appears to be from a browser\n */\n private isWebBrowser(adapter: HTTPAdapter): boolean {\n const accept = adapter.getAcceptHeader();\n const userAgent = adapter.getUserAgent();\n return accept.includes(\"text/html\") && userAgent.includes(\"Mozilla\");\n }\n\n /**\n * Create HTTP response instructions from payment required\n *\n * @param paymentRequired - Payment requirements\n * @param isWebBrowser - Whether request is from browser\n * @param paywallConfig - Paywall configuration\n * @param customHtml - Custom HTML template\n * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests\n * @returns Response instructions\n */\n private createHTTPResponse(\n paymentRequired: PaymentRequired,\n isWebBrowser: boolean,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n unpaidResponse?: HTTPResponseBody,\n ): HTTPResponseInstructions {\n // Use 412 Precondition Failed for permit2_allowance_required error\n // This signals client needs to approve Permit2 before retrying\n const status = paymentRequired.error === \"permit2_allowance_required\" ? 412 : 402;\n\n if (isWebBrowser) {\n const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);\n return {\n status,\n headers: { \"Content-Type\": \"text/html\" },\n body: html,\n isHtml: true,\n };\n }\n\n const response = this.createHTTPPaymentRequiredResponse(paymentRequired);\n\n // Use callback result if provided, otherwise default to JSON with empty object\n const contentType = unpaidResponse ? unpaidResponse.contentType : \"application/json\";\n const body = unpaidResponse ? unpaidResponse.body : {};\n\n return {\n status,\n headers: {\n \"Content-Type\": contentType,\n ...response.headers,\n },\n body,\n };\n }\n\n /**\n * Create HTTP payment required response (v1 puts in body, v2 puts in header)\n *\n * @param paymentRequired - Payment required object\n * @returns Headers and body for the HTTP response\n */\n private createHTTPPaymentRequiredResponse(paymentRequired: PaymentRequired): {\n headers: Record;\n } {\n return {\n headers: {\n \"PAYMENT-REQUIRED\": encodePaymentRequiredHeader(paymentRequired),\n },\n };\n }\n\n /**\n * Create settlement response headers\n *\n * @param settleResponse - Settlement response\n * @returns Headers to add to response\n */\n private createSettlementHeaders(settleResponse: SettleResponse): Record {\n const encoded = encodePaymentResponseHeader(settleResponse);\n return { \"PAYMENT-RESPONSE\": encoded };\n }\n\n /**\n * Parse route pattern into verb and regex\n *\n * @param pattern - Route pattern like \"GET /api/*\", \"/api/[id]\", or \"/api/:id\"\n * @returns Parsed pattern with verb and regex\n */\n private parseRoutePattern(pattern: string): { verb: string; regex: RegExp } {\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n\n const regex = new RegExp(\n `^${\n path\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\") // Escape regex special chars\n .replace(/\\*/g, \".*?\") // Wildcards\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Parameters (Next.js style [param])\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, \"[^/]+\") // Parameters (Express style :param)\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n );\n\n return { verb: verb.toUpperCase(), regex };\n }\n\n /**\n * Normalize path for matching\n *\n * @param path - Raw path from request\n * @returns Normalized path\n */\n private normalizePath(path: string): string {\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n let decodedOrRawPath: string;\n try {\n decodedOrRawPath = decodeURIComponent(pathWithoutQuery);\n } catch {\n decodedOrRawPath = pathWithoutQuery;\n }\n\n return decodedOrRawPath\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/(.+?)\\/+$/, \"$1\");\n }\n\n /**\n * Generate paywall HTML for browser requests\n *\n * @param paymentRequired - Payment required response\n * @param paywallConfig - Optional paywall configuration\n * @param customHtml - Optional custom HTML template\n * @returns HTML string\n */\n private generatePaywallHTML(\n paymentRequired: PaymentRequired,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n ): string {\n if (customHtml) {\n return customHtml;\n }\n\n // Use custom paywall provider if set\n if (this.paywallProvider) {\n return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);\n }\n\n // Try to use @x402/paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@x402/paywall\");\n const displayAmount = this.getDisplayAmount(paymentRequired);\n const resource = paymentRequired.resource;\n\n return paywall.getPaywallHtml({\n amount: displayAmount,\n paymentRequired,\n currentUrl: resource?.url || paywallConfig?.currentUrl || \"\",\n testnet: paywallConfig?.testnet ?? true,\n appName: paywallConfig?.appName,\n appLogo: paywallConfig?.appLogo,\n sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint,\n });\n } catch {\n // @x402/paywall not installed, fall back to basic HTML\n }\n\n // Fallback: Basic HTML paywall\n const resource = paymentRequired.resource;\n const displayAmount = this.getDisplayAmount(paymentRequired);\n\n return `\n \n \n \n Payment Required\n \n \n \n \n
\n ${paywallConfig?.appLogo ? `\"${paywallConfig.appName` : \"\"}\n

Payment Required

\n ${resource ? `

Resource: ${resource.description || resource.url}

` : \"\"}\n

Amount: $${displayAmount.toFixed(2)} USDC

\n
\n \n

\n Note: Install @x402/paywall for full wallet connection and payment UI.\n

\n
\n
\n \n \n `;\n }\n\n /**\n * Extract display amount from payment requirements.\n *\n * @param paymentRequired - The payment required object\n * @returns The display amount in decimal format\n */\n private getDisplayAmount(paymentRequired: PaymentRequired): number {\n const accepts = paymentRequired.accepts;\n if (accepts && accepts.length > 0) {\n const firstReq = accepts[0];\n if (\"amount\" in firstReq) {\n // V2 format\n return parseFloat(firstReq.amount) / 1000000; // Assuming USDC with 6 decimals\n }\n }\n return 0;\n }\n}\n","import { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport {\n VerifyResponse,\n SettleResponse,\n SupportedResponse,\n VerifyError,\n SettleError,\n} from \"../types/facilitator\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://x402.org/facilitator\";\n\nexport interface FacilitatorConfig {\n url?: string;\n createAuthHeaders?: () => Promise<{\n verify: Record;\n settle: Record;\n supported: Record;\n }>;\n}\n\n/**\n * Interface for facilitator clients\n * Can be implemented for HTTP-based or local facilitators\n */\nexport interface FacilitatorClient {\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise;\n\n /**\n * Get supported payment kinds and extensions from the facilitator\n *\n * @returns Supported payment kinds and extensions\n */\n getSupported(): Promise;\n}\n\n/** Number of retries for getSupported() on 429 rate limit errors */\nconst GET_SUPPORTED_RETRIES = 3;\n/** Base delay in ms for exponential backoff on retries */\nconst GET_SUPPORTED_RETRY_DELAY_MS = 1000;\n\n/**\n * HTTP-based client for interacting with x402 facilitator services\n * Handles HTTP communication with facilitator endpoints\n */\nexport class HTTPFacilitatorClient implements FacilitatorClient {\n readonly url: string;\n private readonly _createAuthHeaders?: FacilitatorConfig[\"createAuthHeaders\"];\n\n /**\n * Creates a new HTTPFacilitatorClient instance.\n *\n * @param config - Configuration options for the facilitator client\n */\n constructor(config?: FacilitatorConfig) {\n this.url = config?.url || DEFAULT_FACILITATOR_URL;\n this._createAuthHeaders = config?.createAuthHeaders;\n }\n\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n async verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"verify\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/verify`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n const verifyResponse = data as VerifyResponse;\n if (!response.ok) {\n throw new VerifyError(response.status, verifyResponse);\n }\n return verifyResponse;\n }\n\n throw new Error(`Facilitator verify failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n async settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"settle\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/settle`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n const data = await response.json();\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n const settleResponse = data as SettleResponse;\n if (!response.ok) {\n throw new SettleError(response.status, settleResponse);\n }\n return settleResponse;\n }\n\n throw new Error(`Facilitator settle failed (${response.status}): ${JSON.stringify(data)}`);\n }\n\n /**\n * Get supported payment kinds and extensions from the facilitator.\n * Retries with exponential backoff on 429 rate limit errors.\n *\n * @returns Supported payment kinds and extensions\n */\n async getSupported(): Promise {\n let headers: Record = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"supported\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {\n const response = await fetch(`${this.url}/supported`, {\n method: \"GET\",\n headers,\n });\n\n if (response.ok) {\n return (await response.json()) as SupportedResponse;\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(`Facilitator getSupported failed (${response.status}): ${errorText}`);\n\n // Retry on 429 rate limit errors with exponential backoff\n if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {\n const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n throw lastError;\n }\n\n throw lastError ?? new Error(\"Facilitator getSupported failed after retries\");\n }\n\n /**\n * Creates authentication headers for a specific path.\n *\n * @param path - The path to create authentication headers for (e.g., \"verify\", \"settle\", \"supported\")\n * @returns An object containing the authentication headers for the specified path\n */\n async createAuthHeaders(path: string): Promise<{\n headers: Record;\n }> {\n if (this._createAuthHeaders) {\n const authHeaders = (await this._createAuthHeaders()) as Record<\n string,\n Record\n >;\n return {\n headers: authHeaders[path] ?? {},\n };\n }\n return {\n headers: {},\n };\n }\n\n /**\n * Helper to convert objects to JSON-safe format.\n * Handles BigInt and other non-JSON types.\n *\n * @param obj - The object to convert\n * @returns The JSON-safe representation of the object\n */\n private toJsonSafe(obj: unknown): unknown {\n return JSON.parse(\n JSON.stringify(obj, (_, value) => (typeof value === \"bigint\" ? value.toString() : value)),\n );\n }\n}\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client } from \"../client/x402Client\";\n\n/**\n * Context provided to onPaymentRequired hooks.\n */\nexport interface PaymentRequiredContext {\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return headers to try before payment, or void to proceed directly to payment.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<{ headers: Record } | void>;\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n private paymentRequiredHooks: PaymentRequiredHook[] = [];\n\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Register a hook to handle 402 responses before payment.\n * Hooks run in order; first to return headers wins.\n *\n * @param hook - The hook function to register\n * @returns This instance for chaining\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Run hooks and return headers if any hook provides them.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Headers to use for retry, or null to proceed to payment\n */\n async handlePaymentRequired(\n paymentRequired: PaymentRequired,\n ): Promise | null> {\n for (const hook of this.paymentRequiredHooks) {\n const result = await hook({ paymentRequired });\n if (result?.headers) {\n return result.headers;\n }\n }\n return null;\n }\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequired): Promise {\n return this.client.createPaymentPayload(paymentRequired);\n }\n}\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(paymentResponse: SettleResponse): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPTransportContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n HTTPResponseBody,\n SettlementFailedResponseBody,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n ProtectedRequestHook,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { x402HTTPClient, PaymentRequiredContext, PaymentRequiredHook } from \"./x402HTTPClient\";\n","import { x402Version } from \"..\";\nimport { SchemeNetworkClient } from \"../types/mechanisms\";\nimport { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport { Network, PaymentRequired } from \"../types\";\nimport { findByNetworkAndScheme, findSchemesByNetwork } from \"../utils\";\n\n/**\n * Client Hook Context Interfaces\n */\n\nexport interface PaymentCreationContext {\n paymentRequired: PaymentRequired;\n selectedRequirements: PaymentRequirements;\n}\n\nexport interface PaymentCreatedContext extends PaymentCreationContext {\n paymentPayload: PaymentPayload;\n}\n\nexport interface PaymentCreationFailureContext extends PaymentCreationContext {\n error: Error;\n}\n\n/**\n * Client Hook Type Definitions\n */\n\nexport type BeforePaymentCreationHook = (\n context: PaymentCreationContext,\n) => Promise;\n\nexport type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise;\n\nexport type OnPaymentCreationFailureHook = (\n context: PaymentCreationFailureContext,\n) => Promise;\n\nexport type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;\n\n/**\n * Extension that can enrich payment payloads on the client side.\n *\n * Client extensions are invoked after the scheme creates the base payment payload\n * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612\n * permit signing) to enrich the payload's extensions data.\n */\nexport interface ClientExtension {\n /**\n * Unique key identifying this extension (e.g., \"eip2612GasSponsoring\").\n * Must match the extension key used in PaymentRequired.extensions.\n */\n key: string;\n\n /**\n * Called after payload creation when the extension key is present in\n * paymentRequired.extensions. Allows the extension to enrich the payload\n * with extension-specific data (e.g., signing an EIP-2612 permit).\n *\n * @param paymentPayload - The payment payload to enrich\n * @param paymentRequired - The original PaymentRequired response\n * @returns The enriched payment payload\n */\n enrichPaymentPayload?: (\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ) => Promise;\n}\n\n/**\n * A policy function that filters or transforms payment requirements.\n * Policies are applied in order before the selector chooses the final option.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of payment requirements to filter/transform\n * @returns Filtered array of payment requirements\n */\nexport type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];\n\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme client implementation for this network\n */\n client: SchemeNetworkClient;\n\n /**\n * The x402 protocol version to use for this scheme\n *\n * @default 2\n */\n x402Version?: number;\n}\n\n/**\n * Configuration options for the fetch wrapper\n */\nexport interface x402ClientConfig {\n /**\n * Array of scheme registrations defining which payment methods are supported\n */\n schemes: SchemeRegistration[];\n\n /**\n * Policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Custom payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n}\n\n/**\n * Core client for managing x402 payment schemes and creating payment payloads.\n *\n * Handles registration of payment schemes, policy-based filtering of payment requirements,\n * and creation of payment payloads based on server requirements.\n */\nexport class x402Client {\n private readonly paymentRequirementsSelector: SelectPaymentRequirements;\n private readonly registeredClientSchemes: Map>> = new Map();\n private readonly policies: PaymentPolicy[] = [];\n private readonly registeredExtensions: Map = new Map();\n\n private beforePaymentCreationHooks: BeforePaymentCreationHook[] = [];\n private afterPaymentCreationHooks: AfterPaymentCreationHook[] = [];\n private onPaymentCreationFailureHooks: OnPaymentCreationFailureHook[] = [];\n\n /**\n * Creates a new x402Client instance.\n *\n * @param paymentRequirementsSelector - Function to select payment requirements from available options\n */\n constructor(paymentRequirementsSelector?: SelectPaymentRequirements) {\n this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version, accepts) => accepts[0]);\n }\n\n /**\n * Creates a new x402Client instance from a configuration object.\n *\n * @param config - The client configuration including schemes, policies, and payment requirements selector\n * @returns A configured x402Client instance\n */\n static fromConfig(config: x402ClientConfig): x402Client {\n const client = new x402Client(config.paymentRequirementsSelector);\n config.schemes.forEach(scheme => {\n if (scheme.x402Version === 1) {\n client.registerV1(scheme.network, scheme.client);\n } else {\n client.register(scheme.network, scheme.client);\n }\n });\n config.policies?.forEach(policy => {\n client.registerPolicy(policy);\n });\n return client;\n }\n\n /**\n * Registers a scheme client for the current x402 version.\n *\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n register(network: Network, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(x402Version, network, client);\n }\n\n /**\n * Registers a scheme client for x402 version 1.\n *\n * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n registerV1(network: string, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(1, network as Network, client);\n }\n\n /**\n * Registers a policy to filter or transform payment requirements.\n *\n * Policies are applied in order after filtering by registered schemes\n * and before the selector chooses the final payment requirement.\n *\n * @param policy - Function to filter/transform payment requirements\n * @returns The x402Client instance for chaining\n *\n * @example\n * ```typescript\n * // Prefer cheaper options\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))\n * );\n *\n * // Prefer specific networks\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => r.network.startsWith('eip155:'))\n * );\n * ```\n */\n registerPolicy(policy: PaymentPolicy): x402Client {\n this.policies.push(policy);\n return this;\n }\n\n /**\n * Registers a client extension that can enrich payment payloads.\n *\n * Extensions are invoked after the scheme creates the base payload and the\n * payload is wrapped with extensions/resource/accepted data. If the extension's\n * key is present in `paymentRequired.extensions`, the extension's\n * `enrichPaymentPayload` hook is called to modify the payload.\n *\n * @param extension - The client extension to register\n * @returns The x402Client instance for chaining\n */\n registerExtension(extension: ClientExtension): x402Client {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Register a hook to execute before payment payload creation.\n * Can abort creation by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client {\n this.beforePaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment payload creation.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client {\n this.afterPaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment payload creation fails.\n * Can recover from failure by returning { recovered: true, payload: PaymentPayload }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client {\n this.onPaymentCreationFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Creates a payment payload based on a PaymentRequired response.\n *\n * Automatically extracts x402Version, resource, and extensions from the PaymentRequired\n * response and constructs a complete PaymentPayload with the accepted requirements.\n *\n * @param paymentRequired - The PaymentRequired response from the server\n * @returns Promise resolving to the complete payment payload\n */\n async createPaymentPayload(\n paymentRequired: PaymentRequired,\n ): Promise {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);\n }\n\n const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);\n\n const context: PaymentCreationContext = {\n paymentRequired,\n selectedRequirements: requirements,\n };\n\n // Execute beforePaymentCreation hooks\n for (const hook of this.beforePaymentCreationHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Payment creation aborted: ${result.reason}`);\n }\n }\n\n try {\n const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);\n if (!schemeNetworkClient) {\n throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);\n }\n\n const partialPayload = await schemeNetworkClient.createPaymentPayload(\n paymentRequired.x402Version,\n requirements,\n { extensions: paymentRequired.extensions },\n );\n\n let paymentPayload: PaymentPayload;\n if (partialPayload.x402Version == 1) {\n paymentPayload = partialPayload as PaymentPayload;\n } else {\n // Merge server-declared extensions with any scheme-provided extensions.\n // Scheme extensions overlay on top (e.g., EIP-2612 info enriches server declaration).\n const mergedExtensions = this.mergeExtensions(\n paymentRequired.extensions,\n partialPayload.extensions,\n );\n\n paymentPayload = {\n x402Version: partialPayload.x402Version,\n payload: partialPayload.payload,\n extensions: mergedExtensions,\n resource: paymentRequired.resource,\n accepted: requirements,\n };\n }\n\n // Enrich payload via registered client extensions (for non-scheme extensions)\n paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);\n\n // Execute afterPaymentCreation hooks\n const createdContext: PaymentCreatedContext = {\n ...context,\n paymentPayload,\n };\n\n for (const hook of this.afterPaymentCreationHooks) {\n await hook(createdContext);\n }\n\n return paymentPayload;\n } catch (error) {\n const failureContext: PaymentCreationFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onPaymentCreationFailure hooks\n for (const hook of this.onPaymentCreationFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.payload;\n }\n }\n\n throw error;\n }\n }\n\n\n\n /**\n * Merges server-declared extensions with scheme-provided extensions.\n * Scheme extensions overlay on top of server extensions at each key,\n * preserving server-provided schema while overlaying scheme-provided info.\n *\n * @param serverExtensions - Extensions declared by the server in the 402 response\n * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)\n * @returns The merged extensions object, or undefined if both inputs are undefined\n */\n private mergeExtensions(\n serverExtensions?: Record,\n schemeExtensions?: Record,\n ): Record | undefined {\n if (!schemeExtensions) return serverExtensions;\n if (!serverExtensions) return schemeExtensions;\n\n const merged = { ...serverExtensions };\n for (const [key, schemeValue] of Object.entries(schemeExtensions)) {\n const serverValue = merged[key];\n if (\n serverValue &&\n typeof serverValue === \"object\" &&\n schemeValue &&\n typeof schemeValue === \"object\"\n ) {\n // Deep merge: scheme info overlays server info, schema preserved\n merged[key] = { ...serverValue as Record, ...schemeValue as Record };\n } else {\n merged[key] = schemeValue;\n }\n }\n return merged;\n }\n\n /**\n * Enriches a payment payload by calling registered extension hooks.\n * For each extension key present in the PaymentRequired response,\n * invokes the corresponding extension's enrichPaymentPayload callback.\n *\n * @param paymentPayload - The payment payload to enrich with extension data\n * @param paymentRequired - The PaymentRequired response containing extension declarations\n * @returns The enriched payment payload with extension data applied\n */\n private async enrichPaymentPayloadWithExtensions(\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ): Promise {\n if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {\n return paymentPayload;\n }\n\n let enriched = paymentPayload;\n for (const [key, extension] of this.registeredExtensions) {\n if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {\n enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);\n }\n }\n\n return enriched;\n }\n\n /**\n * Selects appropriate payment requirements based on registered clients and policies.\n *\n * Selection process:\n * 1. Filter by registered schemes (network + scheme support)\n * 2. Apply all registered policies in order\n * 3. Use selector to choose final requirement\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of available payment requirements\n * @returns The selected payment requirements\n */\n private selectPaymentRequirements(x402Version: number, paymentRequirements: PaymentRequirements[]): PaymentRequirements {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${x402Version}`);\n }\n\n // Step 1: Filter by registered schemes\n const supportedPaymentRequirements = paymentRequirements.filter(requirement => {\n let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);\n if (!clientSchemes) {\n return false;\n }\n\n return clientSchemes.has(requirement.scheme);\n })\n\n if (supportedPaymentRequirements.length === 0) {\n throw new Error(`No network/scheme registered for x402 version: ${x402Version} which comply with the payment requirements. ${JSON.stringify({\n x402Version,\n paymentRequirements,\n x402Versions: Array.from(this.registeredClientSchemes.keys()),\n networks: Array.from(clientSchemesByNetwork.keys()),\n schemes: Array.from(clientSchemesByNetwork.values()).map(schemes => Array.from(schemes.keys())).flat(),\n })}`);\n }\n\n // Step 2: Apply all policies in order\n let filteredRequirements = supportedPaymentRequirements;\n for (const policy of this.policies) {\n filteredRequirements = policy(x402Version, filteredRequirements);\n\n if (filteredRequirements.length === 0) {\n throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version}`);\n }\n }\n\n // Step 3: Use selector to choose final requirement\n return this.paymentRequirementsSelector(x402Version, filteredRequirements);\n }\n\n /**\n * Internal method to register a scheme client.\n *\n * @param x402Version - The x402 protocol version\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n private _registerScheme(x402Version: number, network: Network, client: SchemeNetworkClient): x402Client {\n if (!this.registeredClientSchemes.has(x402Version)) {\n this.registeredClientSchemes.set(x402Version, new Map());\n }\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version)!;\n if (!clientSchemesByNetwork.has(network)) {\n clientSchemesByNetwork.set(network, new Map());\n }\n\n const clientByScheme = clientSchemesByNetwork.get(network)!;\n if (!clientByScheme.has(client.scheme)) {\n clientByScheme.set(client.scheme, client);\n }\n\n return this;\n }\n}\n","/**\n * Payment Pre-Auth Cache\n *\n * Wraps the @x402/fetch SDK with pre-authorization caching.\n * After the first 402 response, caches payment requirements per endpoint.\n * On subsequent requests, pre-signs payment and attaches it to the first\n * request, skipping the 402 round trip (~200ms savings per request).\n *\n * Falls back to normal 402 flow if pre-signed payment is rejected.\n */\n\nimport type { x402Client } from \"@x402/fetch\";\nimport { x402HTTPClient } from \"@x402/fetch\";\n\ntype PaymentRequired = Parameters[\"createPaymentPayload\"]>[0];\n\ninterface CachedEntry {\n paymentRequired: PaymentRequired;\n cachedAt: number;\n}\n\nconst DEFAULT_TTL_MS = 3_600_000; // 1 hour\n\ntype FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise;\n\nexport function createPayFetchWithPreAuth(\n baseFetch: FetchFn,\n client: x402Client,\n ttlMs = DEFAULT_TTL_MS,\n options?: { skipPreAuth?: boolean },\n): FetchFn {\n const httpClient = new x402HTTPClient(client);\n const cache = new Map();\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise => {\n const request = new Request(input, init);\n const urlPath = new URL(request.url).pathname;\n\n // Extract model from request body to create model-specific cache keys.\n // Without this, a cached payment from a paid model (e.g. sonnet) would be\n // incorrectly applied to a free model (nvidia/gpt-oss-120b), causing\n // payment errors even when the server wouldn't charge for the request.\n let requestModel = \"\";\n if (init?.body) {\n try {\n const bodyStr =\n init.body instanceof Uint8Array\n ? new TextDecoder().decode(init.body)\n : typeof init.body === \"string\"\n ? init.body\n : \"\";\n if (bodyStr) {\n const parsed = JSON.parse(bodyStr) as { model?: string };\n requestModel = parsed.model ?? \"\";\n }\n } catch {\n /* not JSON, use empty model */\n }\n }\n const cacheKey = `${urlPath}:${requestModel}`;\n\n // Try pre-auth if we have cached payment requirements\n // Skip for Solana: payments use per-tx blockhashes that expire ~60-90s,\n // making cached requirements useless and causing double charges.\n const cached = !options?.skipPreAuth ? cache.get(cacheKey) : undefined;\n if (cached && Date.now() - cached.cachedAt < ttlMs) {\n try {\n const payload = await client.createPaymentPayload(cached.paymentRequired);\n const headers = httpClient.encodePaymentSignatureHeader(payload);\n const preAuthRequest = request.clone();\n for (const [key, value] of Object.entries(headers)) {\n preAuthRequest.headers.set(key, value);\n }\n const response = await baseFetch(preAuthRequest);\n if (response.status !== 402) {\n return response; // Pre-auth worked — saved ~200ms\n }\n // Pre-auth rejected (params may have changed) — invalidate and fall through\n cache.delete(cacheKey);\n } catch {\n // Pre-auth signing failed — invalidate and fall through\n cache.delete(cacheKey);\n }\n }\n\n // Normal flow: make request, handle 402 if needed\n const clonedRequest = request.clone();\n const response = await baseFetch(request);\n if (response.status !== 402) {\n return response;\n }\n\n // Parse 402 response and cache for future pre-auth\n let paymentRequired: PaymentRequired;\n try {\n const getHeader = (name: string) => response.headers.get(name);\n let body: unknown;\n try {\n const responseText = await Promise.race([\n response.text(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Body read timeout\")), 30_000),\n ),\n ]);\n if (responseText) body = JSON.parse(responseText);\n } catch {\n /* empty body is fine */\n }\n paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);\n cache.set(cacheKey, { paymentRequired, cachedAt: Date.now() });\n } catch (error) {\n throw new Error(\n `Failed to parse payment requirements: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n { cause: error },\n );\n }\n\n // Sign payment and retry\n const payload = await client.createPaymentPayload(paymentRequired);\n const paymentHeaders = httpClient.encodePaymentSignatureHeader(payload);\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n return baseFetch(clonedRequest);\n };\n}\n","import type { PaymentPayload } from \"@x402/core/types\";\nimport type { FacilitatorEvmSigner } from \"../signer\";\n\nexport const EIP2612_GAS_SPONSORING_KEY = \"eip2612GasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_KEY = \"erc20ApprovalGasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_VERSION = \"1\" as const;\n\nexport interface Eip2612GasSponsoringInfo {\n [key: string]: unknown;\n from: string;\n asset: string;\n spender: string;\n amount: string;\n nonce: string;\n deadline: string;\n signature: string;\n version: string;\n}\n\nexport interface Erc20ApprovalGasSponsoringInfo {\n [key: string]: unknown;\n from: `0x${string}`;\n asset: `0x${string}`;\n spender: `0x${string}`;\n amount: string;\n signedTransaction: `0x${string}`;\n version: string;\n}\n\n/**\n * A single transaction to be executed by the signer.\n * - `0x${string}`: a pre-signed serialized transaction (broadcast as-is via sendRawTransaction)\n * - `{ to, data, gas? }`: an unsigned call intent (signer signs and broadcasts)\n */\nexport type TransactionRequest =\n | `0x${string}`\n | { to: `0x${string}`; data: `0x${string}`; gas?: bigint };\n\nexport type Erc20ApprovalGasSponsoringSigner = FacilitatorEvmSigner & {\n sendTransactions(transactions: TransactionRequest[]): Promise<`0x${string}`[]>;\n simulateTransactions?(transactions: TransactionRequest[]): Promise;\n};\n\nexport interface Erc20ApprovalGasSponsoringFacilitatorExtension {\n key: typeof ERC20_APPROVAL_GAS_SPONSORING_KEY;\n signer?: Erc20ApprovalGasSponsoringSigner;\n signerForNetwork?: (network: string) => Erc20ApprovalGasSponsoringSigner | undefined;\n}\n\n/**\n * Extracts a typed `info` payload from an extension entry.\n *\n * @param payload - Payment payload containing optional extensions.\n * @param extensionKey - Extension key to extract.\n * @returns The extension `info` object when present; otherwise null.\n */\nfunction _extractInfo(\n payload: PaymentPayload,\n extensionKey: string,\n): Record | null {\n const extensions = payload.extensions;\n if (!extensions) return null;\n const extension = extensions[extensionKey] as { info?: Record } | undefined;\n if (!extension?.info) return null;\n return extension.info;\n}\n\n/**\n * Extracts and validates required EIP-2612 gas sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed EIP-2612 gas sponsoring info when available and complete.\n */\nexport function extractEip2612GasSponsoringInfo(\n payload: PaymentPayload,\n): Eip2612GasSponsoringInfo | null {\n const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.nonce ||\n !info.deadline ||\n !info.signature ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Eip2612GasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of EIP-2612 sponsoring info.\n *\n * @param info - EIP-2612 extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateEip2612GasSponsoringInfo(info: Eip2612GasSponsoringInfo): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n numericPattern.test(info.nonce) &&\n numericPattern.test(info.deadline) &&\n hexPattern.test(info.signature) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Extracts and validates required ERC-20 approval sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed ERC-20 approval sponsoring info when available and complete.\n */\nexport function extractErc20ApprovalGasSponsoringInfo(\n payload: PaymentPayload,\n): Erc20ApprovalGasSponsoringInfo | null {\n const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.signedTransaction ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Erc20ApprovalGasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of ERC-20 approval sponsoring info.\n *\n * @param info - ERC-20 approval extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateErc20ApprovalGasSponsoringInfo(\n info: Erc20ApprovalGasSponsoringInfo,\n): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n hexPattern.test(info.signedTransaction) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Resolves the ERC-20 approval extension signer for a specific network.\n *\n * @param extension - Optional facilitator extension config.\n * @param network - CAIP-2 network identifier.\n * @returns A network-specific signer when available, else the default signer.\n */\nexport function resolveErc20ApprovalExtensionSigner(\n extension: Erc20ApprovalGasSponsoringFacilitatorExtension | undefined,\n network: string,\n): Erc20ApprovalGasSponsoringSigner | undefined {\n if (!extension) return undefined;\n return extension.signerForNetwork?.(network) ?? extension.signer;\n}\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce } from \"../../../utils\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainIdV1(requirements.network as EvmNetworkV1);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Permit2 EIP-712 types for signing PermitWitnessTransferFrom.\n * Must match the exact format expected by the Permit2 contract.\n * Note: Types must be in ALPHABETICAL order after the primary type (TokenPermissions < Witness).\n */\nexport const permit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"Witness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n Witness: [\n { name: \"to\", type: \"address\" },\n { name: \"validAfter\", type: \"uint256\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"name\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"authorizer\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n name: \"authorizationState\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/**\n * EIP-2612 Permit EIP-712 types for signing token.permit().\n */\nexport const eip2612PermitTypes = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * EIP-2612 nonces ABI for querying current nonce.\n */\nexport const eip2612NoncesAbi = [\n {\n type: \"function\",\n name: \"nonces\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** ERC-20 approve(address,uint256) ABI for encoding/decoding approval calldata. */\nexport const erc20ApproveAbi = [\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n] as const;\n\n/** ERC-20 allowance(address,address) ABI for checking spender approval. */\nexport const erc20AllowanceAbi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** Gas limit for a standard ERC-20 approve() transaction. */\nexport const ERC20_APPROVE_GAS_LIMIT = 70_000n;\n\n/** Fallback max fee per gas (1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_FEE_PER_GAS = 1_000_000_000n;\n\n/** Fallback max priority fee per gas (0.1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100_000_000n;\n\n/**\n * Canonical Permit2 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/Uniswap/permit2\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\" as const;\n\n/**\n * x402ExactPermit2Proxy contract address.\n * Vanity address: 0x4020...0001 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0001\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402ExactPermit2ProxyAddress = \"0x402085c248EeA27D92E8b30b2C58ed07f9E20001\" as const;\n\n/**\n * x402UptoPermit2Proxy contract address.\n * Vanity address: 0x4020...0002 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0002\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402UptoPermit2ProxyAddress = \"0x402039b3d6E6BEC5A02c2C9fd937ac17A6940002\" as const;\n\n/**\n * Shared ABI components for the Permit2 witness tuple.\n * Used in both x402ExactPermit2ProxyABI and x402UptoPermit2ProxyABI to keep them in sync.\n * The upto contract's witness struct is identical to exact (both remove 'extra' post-audit).\n */\nconst permit2WitnessABIComponents = [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"validAfter\", type: \"uint256\", internalType: \"uint256\" },\n] as const;\n\n/**\n * x402UptoPermit2Proxy ABI - settle function for upto payment scheme (variable amounts).\n * Updated post-audit: 'extra' removed from witness struct, 'initialize()' removed (now\n * a constructor arg), and error names aligned with x402ExactPermit2Proxy.\n */\nexport const x402UptoPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n\n/**\n * x402ExactPermit2Proxy ABI - settle function for exact payment scheme.\n */\nexport const x402ExactPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n","import { toHex } from \"viem\";\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (network.startsWith(\"eip155:\")) {\n const idStr = network.split(\":\")[1];\n const chainId = parseInt(idStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n return chainId;\n }\n\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\nimport * as Errors from \"../../facilitator/errors\";\nimport {\n diagnoseEip3009SimulationFailure,\n executeTransferWithAuthorization,\n simulateEip3009Transfer,\n} from \"../../facilitator/eip3009-utils\";\n\nexport interface VerifyV1Options {\n /** Run onchain simulation. Defaults to true. */\n simulate?: boolean;\n}\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * If enabled, the facilitator will deploy ERC-4337 smart wallets\n * via EIP-6492 when encountering undeployed contract signatures.\n *\n * @default false\n */\n deployERC4337WithEIP6492?: boolean;\n /**\n * If enabled, simulates transaction before settling. Defaults to false, ie only simulate during verify.\n *\n * @default false\n */\n simulateInSettle?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n deployERC4337WithEIP6492: config?.deployERC4337WithEIP6492 ?? false,\n simulateInSettle: config?.simulateInSettle ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n return this._verify(payload, requirements);\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this._verify(payload, requirements, {\n simulate: this.config.simulateInSettle ?? false,\n });\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? Errors.ErrInvalidScheme,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable (for optional deployment)\n const { address: factoryAddress, data: factoryCalldata } = parseErc6492Signature(\n exactEvmPayload.signature!,\n );\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if configured and needed\n if (\n this.config.deployERC4337WithEIP6492 &&\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment transaction\n await this.signer.waitForTransactionReceipt({ hash: deployTx });\n }\n }\n\n const tx = await executeTransferWithAuthorization(\n this.signer,\n getAddress(requirements.asset),\n exactEvmPayload,\n );\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: Errors.ErrTransactionFailed,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n return {\n success: false,\n errorReason: error instanceof Error ? error.message : Errors.ErrTransactionFailed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n /**\n * Internal verify with optional simulation control.\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @param options - Verification options (e.g. simulate)\n * @returns Promise resolving to verification response\n */\n private async _verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n options?: VerifyV1Options,\n ): Promise {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n const payer = exactEvmPayload.authorization.from;\n let eip6492Deployment:\n | { factoryAddress: `0x${string}`; factoryCalldata: `0x${string}` }\n | undefined;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidScheme,\n payer,\n };\n }\n\n // Get chain configuration\n let chainId: number;\n try {\n chainId = getEvmChainIdV1(payloadV1.network as EvmNetworkV1);\n } catch {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: Errors.ErrMissingEip712Domain,\n payer,\n };\n }\n\n const { name, version } = requirements.extra;\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n // Verify signature (flatten EIP-6492 handling out of catch block)\n let isValid = false;\n try {\n isValid = await this.signer.verifyTypedData({\n address: payer,\n ...permitTypedData,\n signature: exactEvmPayload.signature!,\n });\n } catch {\n isValid = false;\n }\n\n const signature = exactEvmPayload.signature!;\n const sigLen = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n\n // Extract EIP-6492 deployment info (factory address + calldata) if present\n const erc6492Data = parseErc6492Signature(signature);\n const hasDeploymentInfo =\n erc6492Data.address &&\n erc6492Data.data &&\n !isAddressEqual(erc6492Data.address, \"0x0000000000000000000000000000000000000000\");\n\n if (hasDeploymentInfo) {\n eip6492Deployment = {\n factoryAddress: erc6492Data.address!,\n factoryCalldata: erc6492Data.data!,\n };\n }\n\n if (!isValid) {\n const isSmartWallet = sigLen > 130; // 65 bytes = 130 hex chars for EOA\n\n if (!isSmartWallet) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidSignature,\n payer,\n };\n }\n\n const bytecode = await this.signer.getCode({ address: payer });\n const isDeployed = bytecode && bytecode !== \"0x\";\n\n if (!isDeployed && !hasDeploymentInfo) {\n return {\n isValid: false,\n invalidReason: Errors.ErrUndeployedSmartWallet,\n payer,\n };\n }\n }\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrRecipientMismatch,\n payer,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidBeforeExpired,\n payer,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidAfterInFuture,\n payer,\n };\n }\n\n // Verify amount exactly matches requirements\n if (BigInt(exactEvmPayload.authorization.value) !== BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidAuthorizationValue,\n payer,\n };\n }\n\n // Transaction simulation\n if (options?.simulate !== false) {\n const simulationSucceeded = await simulateEip3009Transfer(\n this.signer,\n erc20Address,\n exactEvmPayload,\n eip6492Deployment,\n );\n if (!simulationSucceeded) {\n return diagnoseEip3009SimulationFailure(\n this.signer,\n erc20Address,\n exactEvmPayload,\n requirements,\n requirementsV1.maxAmountRequired,\n );\n }\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n }\n}\n","/**\n * Named error reason constants for the exact EVM facilitator.\n *\n * These strings must be character-for-character identical to the Go constants in\n * go/mechanisms/evm/exact/facilitator/errors.go to maintain cross-SDK parity.\n */\n\nexport const ErrInvalidScheme = \"invalid_exact_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_exact_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_exact_evm_missing_eip712_domain\";\nexport const ErrRecipientMismatch = \"invalid_exact_evm_recipient_mismatch\";\nexport const ErrInvalidSignature = \"invalid_exact_evm_signature\";\nexport const ErrValidBeforeExpired = \"invalid_exact_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture = \"invalid_exact_evm_payload_authorization_valid_after\";\nexport const ErrInvalidAuthorizationValue = \"invalid_exact_evm_authorization_value\";\nexport const ErrUndeployedSmartWallet = \"invalid_exact_evm_payload_undeployed_smart_wallet\";\nexport const ErrTransactionFailed = \"invalid_exact_evm_transaction_failed\";\n\n// EIP-3009 verify errors\nexport const ErrEip3009TokenNameMismatch = \"invalid_exact_evm_token_name_mismatch\";\nexport const ErrEip3009TokenVersionMismatch = \"invalid_exact_evm_token_version_mismatch\";\nexport const ErrEip3009NotSupported = \"invalid_exact_evm_eip3009_not_supported\";\nexport const ErrEip3009NonceAlreadyUsed = \"invalid_exact_evm_nonce_already_used\";\nexport const ErrEip3009InsufficientBalance = \"invalid_exact_evm_insufficient_balance\";\nexport const ErrEip3009SimulationFailed = \"invalid_exact_evm_transaction_simulation_failed\";\n\n// Permit2 verify errors\nexport const ErrPermit2InvalidSpender = \"invalid_permit2_spender\";\nexport const ErrPermit2RecipientMismatch = \"invalid_permit2_recipient_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"permit2_deadline_expired\";\nexport const ErrPermit2NotYetValid = \"permit2_not_yet_valid\";\nexport const ErrPermit2AmountMismatch = \"permit2_amount_mismatch\";\nexport const ErrPermit2TokenMismatch = \"permit2_token_mismatch\";\nexport const ErrPermit2InvalidSignature = \"invalid_permit2_signature\";\nexport const ErrPermit2AllowanceRequired = \"permit2_allowance_required\";\nexport const ErrPermit2SimulationFailed = \"permit2_simulation_failed\";\nexport const ErrPermit2InsufficientBalance = \"permit2_insufficient_balance\";\nexport const ErrPermit2ProxyNotDeployed = \"permit2_proxy_not_deployed\";\n\n// Permit2 settle errors (from contract reverts)\nexport const ErrPermit2InvalidAmount = \"permit2_invalid_amount\";\nexport const ErrPermit2InvalidDestination = \"permit2_invalid_destination\";\nexport const ErrPermit2InvalidOwner = \"permit2_invalid_owner\";\nexport const ErrPermit2PaymentTooEarly = \"permit2_payment_too_early\";\nexport const ErrPermit2InvalidNonce = \"permit2_invalid_nonce\";\nexport const ErrPermit2612AmountMismatch = \"permit2_2612_amount_mismatch\";\n\n// ERC-20 approval gas sponsoring verify errors\nexport const ErrErc20ApprovalInsufficientEthForGas = \"erc20_approval_insufficient_eth_for_gas\";\nexport const ErrErc20ApprovalInvalidFormat = \"invalid_erc20_approval_extension_format\";\nexport const ErrErc20ApprovalFromMismatch = \"erc20_approval_from_mismatch\";\nexport const ErrErc20ApprovalAssetMismatch = \"erc20_approval_asset_mismatch\";\nexport const ErrErc20ApprovalSpenderNotPermit2 = \"erc20_approval_spender_not_permit2\";\nexport const ErrErc20ApprovalTxWrongTarget = \"erc20_approval_tx_wrong_target\";\nexport const ErrErc20ApprovalTxWrongSelector = \"erc20_approval_tx_wrong_selector\";\nexport const ErrErc20ApprovalTxWrongSpender = \"erc20_approval_tx_wrong_spender\";\nexport const ErrErc20ApprovalTxInvalidCalldata = \"erc20_approval_tx_invalid_calldata\";\nexport const ErrErc20ApprovalTxSignerMismatch = \"erc20_approval_tx_signer_mismatch\";\nexport const ErrErc20ApprovalTxInvalidSignature = \"erc20_approval_tx_invalid_signature\";\nexport const ErrErc20ApprovalTxParseFailed = \"erc20_approval_tx_parse_failed\";\nexport const ErrErc20ApprovalTxFailed = \"erc20_approval_tx_failed\";\n\n// EIP-2612 gas sponsoring verify errors\nexport const ErrInvalidEip2612ExtensionFormat = \"invalid_eip2612_extension_format\";\nexport const ErrEip2612FromMismatch = \"eip2612_from_mismatch\";\nexport const ErrEip2612AssetMismatch = \"eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderNotPermit2 = \"eip2612_spender_not_permit2\";\nexport const ErrEip2612DeadlineExpired = \"eip2612_deadline_expired\";\n\n// Shared settle errors\nexport const ErrUnsupportedPayloadType = \"unsupported_payload_type\";\nexport const ErrInvalidTransactionState = \"invalid_transaction_state\";\n","import { PaymentRequirements, VerifyResponse } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress, Hex, parseErc6492Signature, parseSignature } from \"viem\";\nimport { eip3009ABI } from \"../../constants\";\nimport { multicall, ContractCall, RawContractCall } from \"../../multicall\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport * as Errors from \"./errors\";\n\nexport interface Eip6492Deployment {\n factoryAddress: `0x${string}`;\n factoryCalldata: `0x${string}`;\n}\n\n/**\n * Simulates transferWithAuthorization via eth_call.\n * Returns true if simulation succeeded, false if it failed.\n *\n * @param signer - EVM signer for contract reads\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param eip6492Deployment - Optional EIP-6492 factory info for undeployed smart wallets\n *\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulateEip3009Transfer(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n eip6492Deployment?: Eip6492Deployment,\n): Promise {\n const auth = payload.authorization;\n const transferArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (eip6492Deployment) {\n const { signature: innerSignature } = parseErc6492Signature(payload.signature!);\n const transferCalldata = encodeFunctionData({\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, innerSignature],\n });\n\n try {\n const results = await multicall(signer.readContract.bind(signer), [\n {\n address: getAddress(eip6492Deployment.factoryAddress),\n callData: eip6492Deployment.factoryCalldata,\n } satisfies RawContractCall,\n {\n address: erc20Address,\n callData: transferCalldata,\n } satisfies RawContractCall,\n ]);\n\n return results[1]?.status === \"success\";\n } catch {\n return false;\n }\n }\n\n const sig = payload.signature!;\n const sigLength = sig.startsWith(\"0x\") ? sig.length - 2 : sig.length;\n const isECDSA = sigLength === 130;\n\n try {\n if (isECDSA) {\n const parsedSig = parseSignature(sig);\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...transferArgs,\n (parsedSig.v as number | undefined) ?? parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, sig],\n });\n }\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * After simulation fails, runs a single diagnostic multicall to determine the most specific error reason.\n * Checks balanceOf, name, version and authorizationState in one RPC round-trip.\n *\n * @param signer - EVM signer used for the payment\n * @param erc20Address - Address of the ERC-20 token contract\n * @param payload - The EIP-3009 transfer authorization payload\n * @param requirements - Payment requirements to validate against\n * @param amountRequired - Required amount for the payment (balance check)\n *\n * @returns Promise resolving to the verification result with validity and optional invalid reason\n */\nexport async function diagnoseEip3009SimulationFailure(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n requirements: PaymentRequirements,\n amountRequired: string,\n): Promise {\n const payer = payload.authorization.from;\n\n const diagnosticCalls: ContractCall[] = [\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payload.authorization.from],\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"name\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"version\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"authorizationState\",\n args: [payload.authorization.from, payload.authorization.nonce],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [balanceResult, nameResult, versionResult, authStateResult] = results;\n\n if (authStateResult.status === \"failure\") {\n return { isValid: false, invalidReason: Errors.ErrEip3009NotSupported, payer };\n }\n\n if (authStateResult.status === \"success\" && authStateResult.result === true) {\n return { isValid: false, invalidReason: Errors.ErrEip3009NonceAlreadyUsed, payer };\n }\n\n if (\n nameResult.status === \"success\" &&\n requirements.extra?.name &&\n nameResult.result !== requirements.extra.name\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenNameMismatch, payer };\n }\n\n if (\n versionResult.status === \"success\" &&\n requirements.extra?.version &&\n versionResult.result !== requirements.extra.version\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenVersionMismatch, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrEip3009InsufficientBalance,\n payer,\n };\n }\n }\n } catch {\n // Diagnostic multicall failed — fall through to generic error\n }\n\n return { isValid: false, invalidReason: Errors.ErrEip3009SimulationFailed, payer };\n}\n\n/**\n * Executes transferWithAuthorization onchain.\n *\n * @param signer - EVM signer for contract writes\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n *\n * @returns Transaction hash\n */\nexport async function executeTransferWithAuthorization(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n): Promise {\n const { signature } = parseErc6492Signature(payload.signature!);\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n const auth = payload.authorization;\n const baseArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (isECDSA) {\n const parsedSig = parseSignature(signature);\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...baseArgs,\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n }\n\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...baseArgs, signature],\n });\n}\n","import { encodeFunctionData, decodeFunctionResult } from \"viem\";\n\n/**\n * Multicall3 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/mds1/multicall\n */\nexport const MULTICALL3_ADDRESS = \"0xcA11bde05977b3631167028862bE2a173976CA11\" as const;\n\n/** Multicall3 getEthBalance ABI for querying native token balance. */\nexport const multicall3GetEthBalanceAbi = [\n {\n name: \"getEthBalance\",\n inputs: [{ name: \"addr\", type: \"address\" }],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/** Multicall3 tryAggregate ABI for batching calls. */\nconst multicall3ABI = [\n {\n inputs: [\n { name: \"requireSuccess\", type: \"bool\" },\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n name: \"tryAggregate\",\n outputs: [\n {\n name: \"returnData\",\n type: \"tuple[]\",\n components: [\n { name: \"success\", type: \"bool\" },\n { name: \"returnData\", type: \"bytes\" },\n ],\n },\n ],\n stateMutability: \"payable\",\n type: \"function\",\n },\n] as const;\n\nexport type ContractCall = {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n};\n\nexport type RawContractCall = {\n address: `0x${string}`;\n callData: `0x${string}`;\n};\n\nexport type MulticallSuccess = { status: \"success\"; result: unknown };\nexport type MulticallFailure = { status: \"failure\"; error: Error };\nexport type MulticallResult = MulticallSuccess | MulticallFailure;\n\n/**\n * Batches contract calls via Multicall3 `tryAggregate(false, ...)`.\n *\n * Accepts a mix of typed ContractCall (ABI-encoded + decoded) and\n * RawContractCall (pre-encoded calldata, no decoding) entries.\n * Raw calls are useful for the EIP-6492 factory deployment case\n * where calldata is pre-encoded with no ABI available.\n */\ntype ReadContractFn = (args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n}) => Promise;\n\n/**\n * Executes multiple contract read calls in a single RPC round-trip using Multicall3.\n *\n * @param readContract - Function that performs a single contract read (e.g. viem readContract)\n * @param calls - Array of contract calls to batch (ContractCall or RawContractCall)\n * @returns A promise that resolves to an array of decoded results, one per call\n */\nexport async function multicall(\n readContract: ReadContractFn,\n calls: ReadonlyArray,\n): Promise {\n const aggregateCalls = calls.map(call => {\n if (\"callData\" in call) {\n return { target: call.address, callData: call.callData };\n }\n const callData = encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args as unknown[],\n });\n return { target: call.address, callData };\n });\n\n const rawResults = (await readContract({\n address: MULTICALL3_ADDRESS,\n abi: multicall3ABI,\n functionName: \"tryAggregate\",\n args: [false, aggregateCalls],\n })) as { success: boolean; returnData: `0x${string}` }[];\n\n return rawResults.map((raw, i) => {\n if (!raw.success) {\n return {\n status: \"failure\" as const,\n error: new Error(`multicall: call reverted (returnData: ${raw.returnData})`),\n };\n }\n\n const call = calls[i];\n if (\"callData\" in call) {\n return { status: \"success\" as const, result: undefined };\n }\n\n try {\n const decoded = decodeFunctionResult({\n abi: call.abi,\n functionName: call.functionName,\n data: raw.returnData,\n });\n return { status: \"success\" as const, result: decoded };\n } catch (err) {\n return {\n status: \"failure\" as const,\n error: err instanceof Error ? err : new Error(String(err)),\n };\n }\n });\n}\n","export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const EVM_NETWORK_CHAIN_ID_MAP = {\n ethereum: 1,\n sepolia: 11155111,\n abstract: 2741,\n \"abstract-testnet\": 11124,\n \"base-sepolia\": 84532,\n base: 8453,\n \"avalanche-fuji\": 43113,\n avalanche: 43114,\n iotex: 4689,\n sei: 1329,\n \"sei-testnet\": 1328,\n polygon: 137,\n \"polygon-amoy\": 80002,\n peaq: 3338,\n story: 1514,\n educhain: 41923,\n \"skale-base-sepolia\": 324705682,\n megaeth: 4326,\n monad: 143,\n} as const;\n\nexport type EvmNetworkV1 = keyof typeof EVM_NETWORK_CHAIN_ID_MAP;\n\nexport const NETWORKS: string[] = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);\n\n/**\n * Extract chain ID from a v1 legacy network name.\n *\n * @param network - The v1 network name (e.g., \"base-sepolia\", \"polygon\")\n * @returns The numeric chain ID\n * @throws Error if the network name is not a known v1 network\n */\nexport function getEvmChainIdV1(network: string): number {\n const chainId = EVM_NETWORK_CHAIN_ID_MAP[network as EvmNetworkV1];\n if (!chainId) {\n throw new Error(`Unsupported v1 network: ${network}`);\n }\n return chainId;\n}\n","import {\n SchemeNetworkClient,\n PaymentRequirements,\n PaymentPayloadResult,\n PaymentPayloadContext,\n} from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { AssetTransferMethod } from \"../../types\";\nimport { PERMIT2_ADDRESS, erc20AllowanceAbi } from \"../../constants\";\nimport { getAddress } from \"viem\";\nimport { getEvmChainId } from \"../../utils\";\nimport { EIP2612_GAS_SPONSORING_KEY, ERC20_APPROVAL_GAS_SPONSORING_KEY } from \"../extensions\";\nimport { createEIP3009Payload } from \"./eip3009\";\nimport { createPermit2Payload } from \"./permit2\";\nimport { signEip2612Permit } from \"./eip2612\";\nimport { signErc20ApprovalTransaction } from \"./erc20approval\";\nimport { ExactEvmSchemeOptions, resolveExtensionRpcCapabilities } from \"./rpc\";\n\n/**\n * EVM client implementation for the Exact payment scheme.\n * Supports both EIP-3009 (transferWithAuthorization) and Permit2 flows.\n *\n * Routes to the appropriate authorization method based on\n * `requirements.extra.assetTransferMethod`. Defaults to EIP-3009\n * for backward compatibility with older facilitators.\n *\n * When the server advertises `eip2612GasSponsoring` and the asset transfer\n * method is `permit2`, the scheme automatically signs an EIP-2612 permit\n * if the user lacks Permit2 approval. This requires `readContract` on the signer.\n */\nexport class ExactEvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClient instance.\n *\n * @param signer - The EVM signer for client operations.\n * Base flow only requires `address` + `signTypedData`.\n * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally\n * requires optional capabilities like `readContract` and tx signing helpers.\n * @param options - Optional RPC configuration used to backfill extension capabilities.\n */\n constructor(\n private readonly signer: ClientEvmSigner,\n private readonly options?: ExactEvmSchemeOptions,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.\n *\n * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the\n * signer supports `readContract`, automatically signs an EIP-2612 permit\n * when Permit2 allowance is insufficient.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @param context - Optional context with server-declared extensions\n * @returns Promise resolving to a payment payload result (with optional extensions)\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n context?: PaymentPayloadContext,\n ): Promise {\n const assetTransferMethod =\n (paymentRequirements.extra?.assetTransferMethod as AssetTransferMethod) ?? \"eip3009\";\n\n if (assetTransferMethod === \"permit2\") {\n const result = await createPermit2Payload(this.signer, x402Version, paymentRequirements);\n\n const eip2612Extensions = await this.trySignEip2612Permit(\n paymentRequirements,\n result,\n context,\n );\n\n if (eip2612Extensions) {\n return {\n ...result,\n extensions: eip2612Extensions,\n };\n }\n\n const erc20Extensions = await this.trySignErc20Approval(paymentRequirements, result, context);\n if (erc20Extensions) {\n return {\n ...result,\n extensions: erc20Extensions,\n };\n }\n\n return result;\n }\n\n return createEIP3009Payload(this.signer, x402Version, paymentRequirements);\n }\n\n /**\n * Attempts to sign an EIP-2612 permit for gasless Permit2 approval.\n *\n * Returns extension data if:\n * 1. Server advertises eip2612GasSponsoring\n * 2. Signer has readContract capability\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param result - The payment payload result from the scheme\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for EIP-2612 gas sponsoring, or undefined if not applicable\n */\n private async trySignEip2612Permit(\n requirements: PaymentRequirements,\n result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n const tokenName = requirements.extra?.name as string | undefined;\n const tokenVersion = requirements.extra?.version as string | undefined;\n if (!tokenName || !tokenVersion) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const permit2Auth = result.payload?.permit2Authorization as Record | undefined;\n const deadline =\n (permit2Auth?.deadline as string) ??\n Math.floor(Date.now() / 1000 + requirements.maxTimeoutSeconds).toString();\n\n const info = await signEip2612Permit(\n {\n address: this.signer.address,\n signTypedData: msg => this.signer.signTypedData(msg),\n readContract: capabilities.readContract,\n },\n tokenAddress,\n tokenName,\n tokenVersion,\n chainId,\n deadline,\n requirements.amount,\n );\n\n return {\n [EIP2612_GAS_SPONSORING_KEY]: { info },\n };\n }\n\n /**\n * Attempts to sign an ERC-20 approval transaction for gasless Permit2 approval.\n *\n * This is the fallback path when the token does not support EIP-2612. The client\n * signs (but does not broadcast) a raw `approve(Permit2, MaxUint256)` transaction.\n * The facilitator broadcasts it atomically before settling.\n *\n * Returns extension data if:\n * 1. Server advertises erc20ApprovalGasSponsoring\n * 2. Signer has signTransaction + getTransactionCount capabilities\n * 3. Current Permit2 allowance is insufficient\n *\n * Returns undefined if the extension should not be used.\n *\n * @param requirements - The payment requirements from the server\n * @param _result - The payment payload result from the scheme (unused)\n * @param context - Optional context containing server extensions and metadata\n * @returns Extension data for ERC-20 approval gas sponsoring, or undefined if not applicable\n */\n private async trySignErc20Approval(\n requirements: PaymentRequirements,\n _result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n ): Promise | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(\n requirements.network,\n this.signer,\n this.options,\n );\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n if (!capabilities.signTransaction || !capabilities.getTransactionCount) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [this.signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const info = await signErc20ApprovalTransaction(\n {\n address: this.signer.address,\n signTransaction: capabilities.signTransaction,\n getTransactionCount: capabilities.getTransactionCount,\n estimateFeesPerGas: capabilities.estimateFeesPerGas,\n },\n tokenAddress,\n chainId,\n );\n\n return {\n [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info },\n };\n }\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport { createNonce, getEvmChainId } from \"../../utils\";\n\n/**\n * Creates an EIP-3009 (transferWithAuthorization) payload.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createEIP3009Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEIP3009Payload[\"authorization\"] = {\n from: signer.address,\n to: getAddress(paymentRequirements.payTo),\n value: paymentRequirements.amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n const signature = await signEIP3009Authorization(signer, authorization, paymentRequirements);\n\n const payload: ExactEIP3009Payload = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the EIP-3009 authorization using EIP-712.\n *\n * @param signer - The EVM signer\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signEIP3009Authorization(\n signer: ClientEvmSigner,\n authorization: ExactEIP3009Payload[\"authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress } from \"viem\";\nimport {\n permit2WitnessTypes,\n PERMIT2_ADDRESS,\n x402ExactPermit2ProxyAddress,\n erc20ApproveAbi,\n erc20AllowanceAbi,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactPermit2Payload } from \"../../types\";\nimport { createPermit2Nonce, getEvmChainId } from \"../../utils\";\n\n/** Maximum uint256 value for unlimited approval. */\nconst MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\n/**\n * Creates a Permit2 payload using the x402Permit2Proxy witness pattern.\n * The spender is set to x402Permit2Proxy, which enforces that funds\n * can only be sent to the witness.to address.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createPermit2Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise {\n const now = Math.floor(Date.now() / 1000);\n const nonce = createPermit2Nonce();\n\n // Lower time bound - allow some clock skew\n const validAfter = (now - 600).toString();\n // Upper time bound is enforced by Permit2's deadline field\n const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();\n\n const permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"] = {\n from: signer.address,\n permitted: {\n token: getAddress(paymentRequirements.asset),\n amount: paymentRequirements.amount,\n },\n spender: x402ExactPermit2ProxyAddress,\n nonce,\n deadline,\n witness: {\n to: getAddress(paymentRequirements.payTo),\n validAfter,\n },\n };\n\n const signature = await signPermit2Authorization(\n signer,\n permit2Authorization,\n paymentRequirements,\n );\n\n const payload: ExactPermit2Payload = {\n signature,\n permit2Authorization,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the Permit2 authorization using EIP-712 with witness data.\n * The signature authorizes the x402Permit2Proxy to transfer tokens on behalf of the signer.\n *\n * @param signer - The EVM signer\n * @param permit2Authorization - The Permit2 authorization parameters\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signPermit2Authorization(\n signer: ClientEvmSigner,\n permit2Authorization: ExactPermit2Payload[\"permit2Authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n const domain = {\n name: \"Permit2\",\n chainId,\n verifyingContract: PERMIT2_ADDRESS,\n };\n\n const message = {\n permitted: {\n token: getAddress(permit2Authorization.permitted.token),\n amount: BigInt(permit2Authorization.permitted.amount),\n },\n spender: getAddress(permit2Authorization.spender),\n nonce: BigInt(permit2Authorization.nonce),\n deadline: BigInt(permit2Authorization.deadline),\n witness: {\n to: getAddress(permit2Authorization.witness.to),\n validAfter: BigInt(permit2Authorization.witness.validAfter),\n },\n };\n\n return await signer.signTypedData({\n domain,\n types: permit2WitnessTypes,\n primaryType: \"PermitWitnessTransferFrom\",\n message,\n });\n}\n\n/**\n * Creates transaction data to approve Permit2 to spend tokens.\n * The user sends this transaction (paying gas) before using Permit2 flow.\n *\n * @param tokenAddress - The ERC20 token contract address\n * @returns Transaction data to send for approval\n *\n * @example\n * ```typescript\n * const tx = createPermit2ApprovalTx(\"0x...\");\n * await walletClient.sendTransaction({\n * to: tx.to,\n * data: tx.data,\n * });\n * ```\n */\nexport function createPermit2ApprovalTx(tokenAddress: `0x${string}`): {\n to: `0x${string}`;\n data: `0x${string}`;\n} {\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [PERMIT2_ADDRESS, MAX_UINT256],\n });\n\n return {\n to: getAddress(tokenAddress),\n data,\n };\n}\n\n/**\n * Parameters for checking Permit2 allowance.\n * Application provides these to check if approval is needed.\n */\nexport interface Permit2AllowanceParams {\n tokenAddress: `0x${string}`;\n ownerAddress: `0x${string}`;\n}\n\n/**\n * Returns contract read parameters for checking Permit2 allowance.\n * Use with a public client to check if the user has approved Permit2.\n *\n * @param params - The allowance check parameters\n * @returns Contract read parameters for checking allowance\n *\n * @example\n * ```typescript\n * const readParams = getPermit2AllowanceReadParams({\n * tokenAddress: \"0x...\",\n * ownerAddress: \"0x...\",\n * });\n *\n * const allowance = await publicClient.readContract(readParams);\n * const needsApproval = allowance < requiredAmount;\n * ```\n */\nexport function getPermit2AllowanceReadParams(params: Permit2AllowanceParams): {\n address: `0x${string}`;\n abi: typeof erc20AllowanceAbi;\n functionName: \"allowance\";\n args: [`0x${string}`, `0x${string}`];\n} {\n return {\n address: getAddress(params.tokenAddress),\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [getAddress(params.ownerAddress), PERMIT2_ADDRESS],\n };\n}\n","import { getAddress } from \"viem\";\nimport { eip2612PermitTypes, eip2612NoncesAbi, PERMIT2_ADDRESS } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport type { Eip2612GasSponsoringInfo } from \"../extensions\";\n\nexport type Eip2612PermitSigner = Pick & {\n readContract: NonNullable;\n};\n\n/**\n * Signs an EIP-2612 permit authorizing the Permit2 contract to spend tokens.\n *\n * This creates a gasless off-chain signature that the facilitator can submit\n * on-chain via `x402Permit2Proxy.settleWithPermit()`.\n *\n * The `permittedAmount` must match the Permit2 `permitted.amount` exactly, as the\n * proxy contract enforces `permit2612.value == permittedAmount`.\n *\n * @param signer - The client EVM signer (must support readContract for nonce query)\n * @param tokenAddress - The ERC-20 token contract address\n * @param tokenName - The token name (from paymentRequirements.extra.name)\n * @param tokenVersion - The token version (from paymentRequirements.extra.version)\n * @param chainId - The chain ID\n * @param deadline - The deadline for the permit (unix timestamp as string)\n * @param permittedAmount - The Permit2 permitted amount (must match exactly)\n * @returns The EIP-2612 gas sponsoring info object\n */\nexport async function signEip2612Permit(\n signer: Eip2612PermitSigner,\n tokenAddress: `0x${string}`,\n tokenName: string,\n tokenVersion: string,\n chainId: number,\n deadline: string,\n permittedAmount: string,\n): Promise {\n const owner = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Query the current EIP-2612 nonce from the token contract\n const nonce = (await signer.readContract({\n address: tokenAddress,\n abi: eip2612NoncesAbi,\n functionName: \"nonces\",\n args: [owner],\n })) as bigint;\n\n // Construct EIP-712 domain for the token's permit function\n const domain = {\n name: tokenName,\n version: tokenVersion,\n chainId,\n verifyingContract: tokenAddress,\n };\n\n const approvalAmount = BigInt(permittedAmount);\n\n const message = {\n owner,\n spender,\n value: approvalAmount,\n nonce,\n deadline: BigInt(deadline),\n };\n\n // Sign the EIP-2612 permit\n const signature = await signer.signTypedData({\n domain,\n types: eip2612PermitTypes,\n primaryType: \"Permit\",\n message,\n });\n\n return {\n from: owner,\n asset: tokenAddress,\n spender,\n amount: approvalAmount.toString(),\n nonce: nonce.toString(),\n deadline,\n signature,\n version: \"1\",\n };\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport {\n PERMIT2_ADDRESS,\n erc20ApproveAbi,\n ERC20_APPROVE_GAS_LIMIT,\n DEFAULT_MAX_FEE_PER_GAS,\n DEFAULT_MAX_PRIORITY_FEE_PER_GAS,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport {\n ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n type Erc20ApprovalGasSponsoringInfo,\n} from \"../extensions\";\n\nexport type Erc20ApprovalTxSigner = Pick & {\n signTransaction: NonNullable;\n getTransactionCount: NonNullable;\n estimateFeesPerGas?: NonNullable;\n};\n\n/**\n * Signs an EIP-1559 `approve(Permit2, MaxUint256)` transaction for the given token.\n *\n * The signed transaction is NOT broadcast here — the facilitator broadcasts it\n * atomically before settling the Permit2 payment. This enables Permit2 payments\n * for generic ERC-20 tokens that do NOT implement EIP-2612.\n *\n * Always approves MaxUint256 regardless of the payment amount.\n *\n * @param signer - The client EVM signer (must support signTransaction, getTransactionCount)\n * @param tokenAddress - The ERC-20 token contract address\n * @param chainId - The chain ID\n * @returns The ERC-20 approval gas sponsoring info object\n */\nexport async function signErc20ApprovalTransaction(\n signer: Erc20ApprovalTxSigner,\n tokenAddress: `0x${string}`,\n chainId: number,\n): Promise {\n const from = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Encode approve(PERMIT2_ADDRESS, MaxUint256) calldata\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [spender, maxUint256],\n });\n\n // Get current nonce for the sender\n const nonce = await signer.getTransactionCount({ address: from });\n\n // Get current fee estimates, with fallback values\n let maxFeePerGas: bigint;\n let maxPriorityFeePerGas: bigint;\n try {\n const fees = await signer.estimateFeesPerGas?.();\n if (!fees) {\n throw new Error(\"no fee estimates available\");\n }\n maxFeePerGas = fees.maxFeePerGas;\n maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n } catch {\n maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;\n maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;\n }\n\n // Sign the EIP-1559 transaction (not broadcast)\n const signedTransaction = await signer.signTransaction({\n to: tokenAddress,\n data,\n nonce,\n gas: ERC20_APPROVE_GAS_LIMIT,\n maxFeePerGas,\n maxPriorityFeePerGas,\n chainId,\n });\n\n return {\n from,\n asset: tokenAddress,\n spender,\n amount: maxUint256.toString(),\n signedTransaction,\n version: ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n };\n}\n","import { createPublicClient, http } from \"viem\";\nimport type { ClientEvmSigner } from \"../../signer\";\nimport { getEvmChainId } from \"../../utils\";\n\nexport type ExactEvmSchemeConfig = {\n rpcUrl?: string;\n};\n\nexport type ExactEvmSchemeConfigByChainId = Record;\n\nexport type ExactEvmSchemeOptions = ExactEvmSchemeConfig | ExactEvmSchemeConfigByChainId;\n\ntype ExtensionRpcCapabilities = Pick<\n ClientEvmSigner,\n \"readContract\" | \"signTransaction\" | \"getTransactionCount\" | \"estimateFeesPerGas\"\n>;\n\nconst rpcClientCache = new Map>();\n\n/**\n * Determines whether scheme options are keyed by numeric chain id.\n *\n * @param options - Exact EVM scheme options provided by the client.\n * @returns True when options are a chainId-to-config mapping.\n */\nfunction isConfigByChainId(\n options: ExactEvmSchemeOptions,\n): options is ExactEvmSchemeConfigByChainId {\n const keys = Object.keys(options);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n\n/**\n * Returns a cached viem public client for a specific RPC URL.\n *\n * @param rpcUrl - The RPC endpoint URL used to construct the client.\n * @returns A cached or newly created viem public client instance.\n */\nfunction getRpcClient(rpcUrl: string): ReturnType {\n const existing = rpcClientCache.get(rpcUrl);\n if (existing) {\n return existing;\n }\n\n const client = createPublicClient({\n transport: http(rpcUrl),\n });\n rpcClientCache.set(rpcUrl, client);\n return client;\n}\n\n/**\n * Resolves the RPC URL for a given CAIP-2 network from scheme options.\n *\n * @param network - CAIP-2 network identifier.\n * @param options - Optional scheme configuration (single config or chain map).\n * @returns The configured RPC URL for the network, if available.\n */\nexport function resolveRpcUrl(\n network: string,\n options?: ExactEvmSchemeOptions,\n): string | undefined {\n if (!options) {\n return undefined;\n }\n\n if (isConfigByChainId(options)) {\n const chainId = getEvmChainId(network);\n const optionsByChainId = options as ExactEvmSchemeConfigByChainId;\n return optionsByChainId[chainId]?.rpcUrl;\n }\n\n return (options as ExactEvmSchemeConfig).rpcUrl;\n}\n\n/**\n * Resolves extension RPC capabilities from signer methods and optional RPC backfill.\n *\n * @param network - CAIP-2 network identifier for chain resolution.\n * @param signer - Client signer with optional RPC-like methods.\n * @param options - Optional scheme configuration used for RPC backfill.\n * @returns The best available capability set for extension enrichment flows.\n */\nexport function resolveExtensionRpcCapabilities(\n network: string,\n signer: ClientEvmSigner,\n options?: ExactEvmSchemeOptions,\n): ExtensionRpcCapabilities {\n const capabilities: ExtensionRpcCapabilities = {\n signTransaction: signer.signTransaction,\n readContract: signer.readContract,\n getTransactionCount: signer.getTransactionCount,\n estimateFeesPerGas: signer.estimateFeesPerGas,\n };\n\n const needsRpcBackfill =\n !capabilities.readContract ||\n !capabilities.getTransactionCount ||\n !capabilities.estimateFeesPerGas;\n if (!needsRpcBackfill) {\n return capabilities;\n }\n\n const rpcUrl = resolveRpcUrl(network, options);\n if (!rpcUrl) {\n return capabilities;\n }\n const rpcClient = getRpcClient(rpcUrl);\n if (!capabilities.readContract) {\n capabilities.readContract = args => rpcClient.readContract(args as never) as Promise;\n }\n if (!capabilities.getTransactionCount) {\n capabilities.getTransactionCount = async args =>\n rpcClient.getTransactionCount({ address: args.address });\n }\n if (!capabilities.estimateFeesPerGas) {\n capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();\n }\n\n return capabilities;\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeOptions } from \"./rpc\";\nimport { ExactEvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Client\n */\nexport interface EvmClientConfig {\n /**\n * The EVM signer to use for creating payment payloads\n */\n signer: ClientEvmSigner;\n\n /**\n * Optional payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional Exact EVM client scheme options.\n * Supports either a single config ({ rpcUrl }) or per-chain configs\n * keyed by EVM chain ID ({ 8453: { rpcUrl: \"...\" } }).\n */\n schemeOptions?: ExactEvmSchemeOptions;\n\n /**\n * Optional specific networks to register.\n * If not provided, registers wildcard support (eip155:*).\n */\n networks?: Network[];\n}\n\n/**\n * Registers EVM exact payment schemes to an x402Client instance.\n *\n * This function registers:\n * - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for EVM client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@x402/evm/exact/client/register\";\n * import { x402Client } from \"@x402/core/client\";\n * import { privateKeyToAccount } from \"viem/accounts\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const client = new x402Client();\n * registerExactEvmScheme(client, { signer: account });\n * ```\n */\nexport function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client {\n const evmScheme = new ExactEvmScheme(config.signer, config.schemeOptions);\n\n // Register V2 scheme\n // EIP-2612 gas sponsoring is handled internally by the scheme when the\n // server advertises support - no separate extension registration needed.\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach(network => {\n client.register(network, evmScheme);\n });\n } else {\n // Register wildcard for all EVM chains\n client.register(\"eip155:*\", evmScheme);\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactEvmSchemeV1(config.signer));\n });\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * ClientEvmSigner - Used by x402 clients to sign payment authorizations.\n *\n * Typically a viem WalletClient extended with publicActions:\n * ```typescript\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * Or composed via `toClientEvmSigner(account, publicClient)`.\n */\nexport type ClientEvmSigner = {\n readonly address: `0x${string}`;\n signTypedData(message: {\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n }): Promise<`0x${string}`>;\n /**\n * Optional on-chain reads.\n * Required only for extension enrichment (EIP-2612 / ERC-20 approval).\n */\n readContract?(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n /**\n * Optional: Signs a raw EIP-1559 transaction without broadcasting.\n * Required for ERC-20 approval gas sponsoring when the token lacks EIP-2612.\n */\n signTransaction?(args: {\n to: `0x${string}`;\n data: `0x${string}`;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n chainId: number;\n }): Promise<`0x${string}`>;\n /**\n * Optional: Gets the current transaction count (nonce) for an address.\n * Required for ERC-20 approval gas sponsoring.\n */\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n /**\n * Optional: Estimates current gas fees per gas.\n * Required for ERC-20 approval gas sponsoring.\n */\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n};\n\n/**\n * FacilitatorEvmSigner - Used by x402 facilitators to verify and settle payments\n * This is typically a viem PublicClient + WalletClient combination that can\n * read contract state, verify signatures, write transactions, and wait for receipts\n *\n * Supports multiple addresses for load balancing, key rotation, and high availability\n */\nexport type FacilitatorEvmSigner = {\n /**\n * Get all addresses this facilitator can use for signing\n * Enables dynamic address selection for load balancing and key rotation\n */\n getAddresses(): readonly `0x${string}`[];\n\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n verifyTypedData(args: {\n address: `0x${string}`;\n domain: Record;\n types: Record;\n primaryType: string;\n message: Record;\n signature: `0x${string}`;\n }): Promise;\n writeContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n /** Optional gas limit. When provided, skips eth_estimateGas simulation. */\n gas?: bigint;\n }): Promise<`0x${string}`>;\n sendTransaction(args: { to: `0x${string}`; data: `0x${string}` }): Promise<`0x${string}`>;\n waitForTransactionReceipt(args: { hash: `0x${string}` }): Promise<{ status: string }>;\n getCode(args: { address: `0x${string}` }): Promise<`0x${string}` | undefined>;\n};\n\n/**\n * Composes a ClientEvmSigner from a local account and a public client.\n *\n * Use this when your signer (e.g., `privateKeyToAccount`) doesn't have\n * `readContract`. The `publicClient` provides the on-chain read capability.\n *\n * Alternatively, use a WalletClient extended with publicActions directly:\n * ```typescript\n * const signer = createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: baseSepolia,\n * transport: http(),\n * }).extend(publicActions);\n * ```\n *\n * @param signer - A signer with `address` and `signTypedData` (and optionally `readContract`)\n * @param publicClient - A client with optional read/nonce/fee helpers\n * @param publicClient.readContract - The readContract method from the public client\n * @param publicClient.getTransactionCount - Optional getTransactionCount for ERC-20 approval\n * @param publicClient.estimateFeesPerGas - Optional estimateFeesPerGas for ERC-20 approval\n * @returns A ClientEvmSigner with any available optional capabilities\n *\n * @example\n * ```typescript\n * const account = privateKeyToAccount(\"0x...\");\n * const publicClient = createPublicClient({ chain: baseSepolia, transport: http() });\n * const signer = toClientEvmSigner(account, publicClient);\n * ```\n */\nexport function toClientEvmSigner(\n signer: Omit & {\n readContract?: ClientEvmSigner[\"readContract\"];\n },\n publicClient?: {\n readContract(args: {\n address: `0x${string}`;\n abi: readonly unknown[];\n functionName: string;\n args?: readonly unknown[];\n }): Promise;\n getTransactionCount?(args: { address: `0x${string}` }): Promise;\n estimateFeesPerGas?(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n },\n): ClientEvmSigner {\n const readContract = signer.readContract ?? publicClient?.readContract.bind(publicClient);\n\n const result: ClientEvmSigner = {\n address: signer.address,\n signTypedData: msg => signer.signTypedData(msg),\n };\n\n if (readContract) {\n result.readContract = readContract;\n }\n\n // Forward optional capabilities from signer or publicClient\n const signTransaction = signer.signTransaction;\n if (signTransaction) {\n result.signTransaction = args => signTransaction(args);\n }\n\n const getTransactionCount =\n signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);\n if (getTransactionCount) {\n result.getTransactionCount = args => getTransactionCount(args);\n }\n\n const estimateFeesPerGas =\n signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);\n if (estimateFeesPerGas) {\n result.estimateFeesPerGas = () => estimateFeesPerGas();\n }\n\n return result;\n}\n\n/**\n * Converts a viem client with single address to a FacilitatorEvmSigner\n * Wraps the single address in a getAddresses() function for compatibility\n *\n * @param client - The client to convert (must have 'address' property)\n * @returns FacilitatorEvmSigner with getAddresses() support\n */\nexport function toFacilitatorEvmSigner(\n client: Omit & { address: `0x${string}` },\n): FacilitatorEvmSigner {\n return {\n ...client,\n getAddresses: () => [client.address],\n };\n}\n","/**\n * Rule-Based Classifier (v2 — Weighted Scoring)\n *\n * Scores a request across 14 weighted dimensions and maps the aggregate\n * score to a tier using configurable boundaries. Confidence is calibrated\n * via sigmoid — low confidence triggers the fallback classifier.\n *\n * Handles 70-80% of requests in < 1ms with zero cost.\n */\n\nimport type { Tier, ScoringResult, ScoringConfig } from \"./types.js\";\n\ntype DimensionScore = { name: string; score: number; signal: string | null };\n\n// ─── Dimension Scorers ───\n// Each returns a score in [-1, 1] and an optional signal string.\n\nfunction scoreTokenCount(\n estimatedTokens: number,\n thresholds: { simple: number; complex: number },\n): DimensionScore {\n if (estimatedTokens < thresholds.simple) {\n return { name: \"tokenCount\", score: -1.0, signal: `short (${estimatedTokens} tokens)` };\n }\n if (estimatedTokens > thresholds.complex) {\n return { name: \"tokenCount\", score: 1.0, signal: `long (${estimatedTokens} tokens)` };\n }\n return { name: \"tokenCount\", score: 0, signal: null };\n}\n\nfunction scoreKeywordMatch(\n text: string,\n keywords: string[],\n name: string,\n signalLabel: string,\n thresholds: { low: number; high: number },\n scores: { none: number; low: number; high: number },\n): DimensionScore {\n const matches = keywords.filter((kw) => text.includes(kw.toLowerCase()));\n if (matches.length >= thresholds.high) {\n return {\n name,\n score: scores.high,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n if (matches.length >= thresholds.low) {\n return {\n name,\n score: scores.low,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n return { name, score: scores.none, signal: null };\n}\n\nfunction scoreMultiStep(text: string): DimensionScore {\n const patterns = [/first.*then/i, /step \\d/i, /\\d\\.\\s/];\n const hits = patterns.filter((p) => p.test(text));\n if (hits.length > 0) {\n return { name: \"multiStepPatterns\", score: 0.5, signal: \"multi-step\" };\n }\n return { name: \"multiStepPatterns\", score: 0, signal: null };\n}\n\nfunction scoreQuestionComplexity(prompt: string): DimensionScore {\n const count = (prompt.match(/\\?/g) || []).length;\n if (count > 3) {\n return { name: \"questionComplexity\", score: 0.5, signal: `${count} questions` };\n }\n return { name: \"questionComplexity\", score: 0, signal: null };\n}\n\n/**\n * Score agentic task indicators.\n * Returns agenticScore (0-1) based on keyword matches:\n * - 4+ matches = 1.0 (high agentic)\n * - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)\n * - 1-2 matches = 0.2 (low agentic)\n *\n * Thresholds raised because common keywords were pruned from the list.\n */\nfunction scoreAgenticTask(\n text: string,\n keywords: string[],\n): { dimensionScore: DimensionScore; agenticScore: number } {\n let matchCount = 0;\n const signals: string[] = [];\n\n for (const keyword of keywords) {\n if (text.includes(keyword.toLowerCase())) {\n matchCount++;\n if (signals.length < 3) {\n signals.push(keyword);\n }\n }\n }\n\n // Threshold-based scoring (raised thresholds after keyword pruning)\n if (matchCount >= 4) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 1.0,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 1.0,\n };\n } else if (matchCount >= 3) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.6,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 0.6,\n };\n } else if (matchCount >= 1) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.2,\n signal: `agentic-light (${signals.join(\", \")})`,\n },\n agenticScore: 0.2,\n };\n }\n\n return {\n dimensionScore: { name: \"agenticTask\", score: 0, signal: null },\n agenticScore: 0,\n };\n}\n\n// ─── Main Classifier ───\n\nexport function classifyByRules(\n prompt: string,\n systemPrompt: string | undefined,\n estimatedTokens: number,\n config: ScoringConfig,\n): ScoringResult {\n // Score against user prompt only — system prompts contain boilerplate keywords\n // (tool definitions, skill descriptions, behavioral rules) that dominate scoring\n // and make every request score identically. See GitHub issue #50.\n const userText = prompt.toLowerCase();\n\n // Score all 14 dimensions against user text only\n const dimensions: DimensionScore[] = [\n // Token count uses total estimated tokens (system + user) — context size matters for model selection\n scoreTokenCount(estimatedTokens, config.tokenCountThresholds),\n scoreKeywordMatch(\n userText,\n config.codeKeywords,\n \"codePresence\",\n \"code\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.reasoningKeywords,\n \"reasoningMarkers\",\n \"reasoning\",\n { low: 1, high: 2 },\n { none: 0, low: 0.7, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.technicalKeywords,\n \"technicalTerms\",\n \"technical\",\n { low: 2, high: 4 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.creativeKeywords,\n \"creativeMarkers\",\n \"creative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.simpleKeywords,\n \"simpleIndicators\",\n \"simple\",\n { low: 1, high: 2 },\n { none: 0, low: -1.0, high: -1.0 },\n ),\n scoreMultiStep(userText),\n scoreQuestionComplexity(prompt),\n\n // 6 new dimensions\n scoreKeywordMatch(\n userText,\n config.imperativeVerbs,\n \"imperativeVerbs\",\n \"imperative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.constraintIndicators,\n \"constraintCount\",\n \"constraints\",\n { low: 1, high: 3 },\n { none: 0, low: 0.3, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.outputFormatKeywords,\n \"outputFormat\",\n \"format\",\n { low: 1, high: 2 },\n { none: 0, low: 0.4, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.referenceKeywords,\n \"referenceComplexity\",\n \"references\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.negationKeywords,\n \"negationComplexity\",\n \"negation\",\n { low: 2, high: 3 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.domainSpecificKeywords,\n \"domainSpecificity\",\n \"domain-specific\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.8 },\n ),\n ];\n\n // Score agentic task indicators — user prompt only\n // System prompt describes assistant behavior, not user's intent.\n // e.g. a coding assistant system prompt with \"edit files\" / \"fix bugs\" should NOT\n // force every request into agentic mode.\n const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);\n dimensions.push(agenticResult.dimensionScore);\n const agenticScore = agenticResult.agenticScore;\n\n // Collect signals\n const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);\n\n // Compute weighted score\n const weights = config.dimensionWeights;\n let weightedScore = 0;\n for (const d of dimensions) {\n const w = weights[d.name] ?? 0;\n weightedScore += d.score * w;\n }\n\n // Count reasoning markers for override — only check USER prompt, not system prompt\n // This prevents system prompts with \"step by step\" from triggering REASONING for simple queries\n const reasoningMatches = config.reasoningKeywords.filter((kw) =>\n userText.includes(kw.toLowerCase()),\n );\n\n // Direct reasoning override: 2+ reasoning markers = high confidence REASONING\n if (reasoningMatches.length >= 2) {\n const confidence = calibrateConfidence(\n Math.max(weightedScore, 0.3), // ensure positive for confidence calc\n config.confidenceSteepness,\n );\n return {\n score: weightedScore,\n tier: \"REASONING\",\n confidence: Math.max(confidence, 0.85),\n signals,\n agenticScore,\n dimensions,\n };\n }\n\n // Map weighted score to tier using boundaries\n const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;\n let tier: Tier;\n let distanceFromBoundary: number;\n\n if (weightedScore < simpleMedium) {\n tier = \"SIMPLE\";\n distanceFromBoundary = simpleMedium - weightedScore;\n } else if (weightedScore < mediumComplex) {\n tier = \"MEDIUM\";\n distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);\n } else if (weightedScore < complexReasoning) {\n tier = \"COMPLEX\";\n distanceFromBoundary = Math.min(\n weightedScore - mediumComplex,\n complexReasoning - weightedScore,\n );\n } else {\n tier = \"REASONING\";\n distanceFromBoundary = weightedScore - complexReasoning;\n }\n\n // Calibrate confidence via sigmoid of distance from nearest boundary\n const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);\n\n // If confidence is below threshold → ambiguous\n if (confidence < config.confidenceThreshold) {\n return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };\n }\n\n return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };\n}\n\n/**\n * Sigmoid confidence calibration.\n * Maps distance from tier boundary to [0.5, 1.0] confidence range.\n */\nfunction calibrateConfidence(distance: number, steepness: number): number {\n return 1 / (1 + Math.exp(-steepness * distance));\n}\n","/**\n * Tier → Model Selection\n *\n * Maps a classification tier to the cheapest capable model.\n * Builds RoutingDecision metadata with cost estimates and savings.\n */\n\nimport type { Tier, TierConfig, RoutingDecision } from \"./types.js\";\n\nexport type ModelPricing = {\n inputPrice: number; // per 1M tokens\n outputPrice: number; // per 1M tokens\n};\n\nconst BASELINE_MODEL_ID = \"anthropic/claude-opus-4.6\";\n\n// Hardcoded fallback: Claude Opus 4.6 pricing (per 1M tokens)\n// Used when baseline model not found in dynamic pricing map\nconst BASELINE_INPUT_PRICE = 5.0;\nconst BASELINE_OUTPUT_PRICE = 25.0;\n\n/**\n * Select the primary model for a tier and build the RoutingDecision.\n */\nexport function selectModel(\n tier: Tier,\n confidence: number,\n method: \"rules\" | \"llm\",\n reasoning: string,\n tierConfigs: Record,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n agenticScore?: number,\n): RoutingDecision {\n const tierConfig = tierConfigs[tier];\n const model = tierConfig.primary;\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n const costEstimate = inputCost + outputCost;\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return {\n model,\n tier,\n confidence,\n method,\n reasoning,\n costEstimate,\n baselineCost,\n savings,\n ...(agenticScore !== undefined && { agenticScore }),\n };\n}\n\n/**\n * Get the ordered fallback chain for a tier: [primary, ...fallbacks].\n */\nexport function getFallbackChain(tier: Tier, tierConfigs: Record): string[] {\n const config = tierConfigs[tier];\n return [config.primary, ...config.fallback];\n}\n\n/**\n * Calculate cost for a specific model (used when fallback model is used).\n * Returns updated cost fields for RoutingDecision.\n */\n// Server-side margin applied to all x402 payments (must match blockrun server's MARGIN_PERCENT)\nconst SERVER_MARGIN_PERCENT = 5;\n// Minimum payment enforced by CDP Facilitator (must match blockrun server's MIN_PAYMENT_USD)\nconst MIN_PAYMENT_USD = 0.001;\n\nexport function calculateModelCost(\n model: string,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n): { costEstimate: number; baselineCost: number; savings: number } {\n const pricing = modelPricing.get(model);\n\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n // Include server margin + minimum payment to match actual x402 charge\n const costEstimate = Math.max(\n (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100),\n MIN_PAYMENT_USD,\n );\n\n // Baseline: what Claude Opus 4.5 would cost (the premium reference)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return { costEstimate, baselineCost, savings };\n}\n\n/**\n * Filter a model list to only those that support tool calling.\n * When hasTools is false, returns the list unchanged.\n * When all models lack tool calling support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByToolCalling(\n models: string[],\n hasTools: boolean,\n supportsToolCalling: (modelId: string) => boolean,\n): string[] {\n if (!hasTools) return models;\n const filtered = models.filter(supportsToolCalling);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to only those that support vision (image inputs).\n * When hasVision is false, returns the list unchanged.\n * When all models lack vision support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByVision(\n models: string[],\n hasVision: boolean,\n supportsVision: (modelId: string) => boolean,\n): string[] {\n if (!hasVision) return models;\n const filtered = models.filter(supportsVision);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to remove user-excluded models.\n * When all models are excluded, returns the full list as a fallback\n * (same safety pattern as filterByToolCalling/filterByVision).\n */\nexport function filterByExcludeList(models: string[], excludeList: Set): string[] {\n if (excludeList.size === 0) return models;\n const filtered = models.filter((m) => !excludeList.has(m));\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Get the fallback chain filtered by context length.\n * Only returns models that can handle the estimated total context.\n *\n * @param tier - The tier to get fallback chain for\n * @param tierConfigs - Tier configurations\n * @param estimatedTotalTokens - Estimated total context (input + output)\n * @param getContextWindow - Function to get context window for a model ID\n * @returns Filtered list of models that can handle the context\n */\nexport function getFallbackChainFiltered(\n tier: Tier,\n tierConfigs: Record,\n estimatedTotalTokens: number,\n getContextWindow: (modelId: string) => number | undefined,\n): string[] {\n const fullChain = getFallbackChain(tier, tierConfigs);\n\n // Filter to models that can handle the context\n const filtered = fullChain.filter((modelId) => {\n const contextWindow = getContextWindow(modelId);\n if (contextWindow === undefined) {\n // Unknown model - include it (let API reject if needed)\n return true;\n }\n // Add 10% buffer for safety\n return contextWindow >= estimatedTotalTokens * 1.1;\n });\n\n // If all models filtered out, return the original chain\n // (let the API error out - better than no options)\n if (filtered.length === 0) {\n return fullChain;\n }\n\n return filtered;\n}\n","/**\n * Router Strategy Registry\n *\n * Pluggable strategy system for request routing.\n * Default: RulesStrategy — identical to the original inline route() logic, <1ms.\n */\n\nimport type { Tier, RoutingDecision, RouterStrategy, RouterOptions } from \"./types.js\";\nimport { classifyByRules } from \"./rules.js\";\nimport { selectModel } from \"./selector.js\";\n\n/**\n * Rules-based routing strategy.\n * Extracted from the original route() in index.ts — logic is identical.\n * Attaches tierConfigs and profile to the decision for downstream use.\n */\nexport class RulesStrategy implements RouterStrategy {\n readonly name = \"rules\";\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ): RoutingDecision {\n const { config, modelPricing } = options;\n\n // Estimate input tokens (~4 chars per token)\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedTokens = Math.ceil(fullText.length / 4);\n\n // --- Rule-based classification (runs first to get agenticScore) ---\n const ruleResult = classifyByRules(prompt, systemPrompt, estimatedTokens, config.scoring);\n\n // --- Select tier configs based on routing profile ---\n const { routingProfile } = options;\n let tierConfigs: Record;\n let profileSuffix: string;\n let profile: RoutingDecision[\"profile\"];\n\n if (routingProfile === \"eco\" && config.ecoTiers) {\n tierConfigs = config.ecoTiers;\n profileSuffix = \" | eco\";\n profile = \"eco\";\n } else if (routingProfile === \"premium\" && config.premiumTiers) {\n tierConfigs = config.premiumTiers;\n profileSuffix = \" | premium\";\n profile = \"premium\";\n } else {\n // Auto profile (or undefined): intelligent routing with agentic detection\n const agenticScore = ruleResult.agenticScore ?? 0;\n const isAutoAgentic = agenticScore >= 0.5;\n const isExplicitAgentic = config.overrides.agenticMode ?? false;\n const hasToolsInRequest = options.hasTools ?? false;\n const useAgenticTiers =\n (hasToolsInRequest || isAutoAgentic || isExplicitAgentic) && config.agenticTiers != null;\n tierConfigs = useAgenticTiers ? config.agenticTiers! : config.tiers;\n profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? \" (tools)\" : \"\"}` : \"\";\n profile = useAgenticTiers ? \"agentic\" : \"auto\";\n }\n\n const agenticScoreValue = ruleResult.agenticScore;\n\n // --- Override: large context → force COMPLEX ---\n if (estimatedTokens > config.overrides.maxTokensForceComplex) {\n const decision = selectModel(\n \"COMPLEX\",\n 0.95,\n \"rules\",\n `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n\n // Structured output detection\n const hasStructuredOutput = systemPrompt ? /json|structured|schema/i.test(systemPrompt) : false;\n\n let tier: Tier;\n let confidence: number;\n const method: \"rules\" | \"llm\" = \"rules\";\n let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(\", \")}`;\n\n if (ruleResult.tier !== null) {\n tier = ruleResult.tier;\n confidence = ruleResult.confidence;\n } else {\n // Ambiguous — default to configurable tier (no external API call)\n tier = config.overrides.ambiguousDefaultTier;\n confidence = 0.5;\n reasoning += ` | ambiguous -> default: ${tier}`;\n }\n\n // Apply structured output minimum tier\n if (hasStructuredOutput) {\n const tierRank: Record = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };\n const minTier = config.overrides.structuredOutputMinTier;\n if (tierRank[tier] < tierRank[minTier]) {\n reasoning += ` | upgraded to ${minTier} (structured output)`;\n tier = minTier;\n }\n }\n\n // Add routing profile suffix to reasoning\n reasoning += profileSuffix;\n\n const decision = selectModel(\n tier,\n confidence,\n method,\n reasoning,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n}\n\n// --- Strategy Registry ---\n\nconst registry = new Map();\nregistry.set(\"rules\", new RulesStrategy());\n\nexport function getStrategy(name: string): RouterStrategy {\n const strategy = registry.get(name);\n if (!strategy) {\n throw new Error(`Unknown routing strategy: ${name}`);\n }\n return strategy;\n}\n\nexport function registerStrategy(strategy: RouterStrategy): void {\n registry.set(strategy.name, strategy);\n}\n","/**\n * Default Routing Config\n *\n * All routing parameters as a TypeScript constant.\n * Operators override via openclaw.yaml plugin config.\n *\n * Scoring uses 14 weighted dimensions with sigmoid confidence calibration.\n */\n\nimport type { RoutingConfig } from \"./types.js\";\n\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n version: \"2.0\",\n\n classifier: {\n llmModel: \"google/gemini-2.5-flash\",\n llmMaxTokens: 10,\n llmTemperature: 0,\n promptTruncationChars: 500,\n cacheTtlMs: 3_600_000, // 1 hour\n },\n\n scoring: {\n tokenCountThresholds: { simple: 50, complex: 500 },\n\n // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR\n codeKeywords: [\n // English\n \"function\",\n \"class\",\n \"import\",\n \"def\",\n \"SELECT\",\n \"async\",\n \"await\",\n \"const\",\n \"let\",\n \"var\",\n \"return\",\n \"```\",\n // Chinese\n \"函数\",\n \"类\",\n \"导入\",\n \"定义\",\n \"查询\",\n \"异步\",\n \"等待\",\n \"常量\",\n \"变量\",\n \"返回\",\n // Japanese\n \"関数\",\n \"クラス\",\n \"インポート\",\n \"非同期\",\n \"定数\",\n \"変数\",\n // Russian\n \"функция\",\n \"класс\",\n \"импорт\",\n \"определ\",\n \"запрос\",\n \"асинхронный\",\n \"ожидать\",\n \"константа\",\n \"переменная\",\n \"вернуть\",\n // German\n \"funktion\",\n \"klasse\",\n \"importieren\",\n \"definieren\",\n \"abfrage\",\n \"asynchron\",\n \"erwarten\",\n \"konstante\",\n \"variable\",\n \"zurückgeben\",\n // Spanish\n \"función\",\n \"clase\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"asíncrono\",\n \"esperar\",\n \"constante\",\n \"variable\",\n \"retornar\",\n // Portuguese\n \"função\",\n \"classe\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"assíncrono\",\n \"aguardar\",\n \"constante\",\n \"variável\",\n \"retornar\",\n // Korean\n \"함수\",\n \"클래스\",\n \"가져오기\",\n \"정의\",\n \"쿼리\",\n \"비동기\",\n \"대기\",\n \"상수\",\n \"변수\",\n \"반환\",\n // Arabic\n \"دالة\",\n \"فئة\",\n \"استيراد\",\n \"تعريف\",\n \"استعلام\",\n \"غير متزامن\",\n \"انتظار\",\n \"ثابت\",\n \"متغير\",\n \"إرجاع\",\n ],\n reasoningKeywords: [\n // English\n \"prove\",\n \"theorem\",\n \"derive\",\n \"step by step\",\n \"chain of thought\",\n \"formally\",\n \"mathematical\",\n \"proof\",\n \"logically\",\n // Chinese\n \"证明\",\n \"定理\",\n \"推导\",\n \"逐步\",\n \"思维链\",\n \"形式化\",\n \"数学\",\n \"逻辑\",\n // Japanese\n \"証明\",\n \"定理\",\n \"導出\",\n \"ステップバイステップ\",\n \"論理的\",\n // Russian\n \"доказать\",\n \"докажи\",\n \"доказательств\",\n \"теорема\",\n \"вывести\",\n \"шаг за шагом\",\n \"пошагово\",\n \"поэтапно\",\n \"цепочка рассуждений\",\n \"рассуждени\",\n \"формально\",\n \"математически\",\n \"логически\",\n // German\n \"beweisen\",\n \"beweis\",\n \"theorem\",\n \"ableiten\",\n \"schritt für schritt\",\n \"gedankenkette\",\n \"formal\",\n \"mathematisch\",\n \"logisch\",\n // Spanish\n \"demostrar\",\n \"teorema\",\n \"derivar\",\n \"paso a paso\",\n \"cadena de pensamiento\",\n \"formalmente\",\n \"matemático\",\n \"prueba\",\n \"lógicamente\",\n // Portuguese\n \"provar\",\n \"teorema\",\n \"derivar\",\n \"passo a passo\",\n \"cadeia de pensamento\",\n \"formalmente\",\n \"matemático\",\n \"prova\",\n \"logicamente\",\n // Korean\n \"증명\",\n \"정리\",\n \"도출\",\n \"단계별\",\n \"사고의 연쇄\",\n \"형식적\",\n \"수학적\",\n \"논리적\",\n // Arabic\n \"إثبات\",\n \"نظرية\",\n \"اشتقاق\",\n \"خطوة بخطوة\",\n \"سلسلة التفكير\",\n \"رسمياً\",\n \"رياضي\",\n \"برهان\",\n \"منطقياً\",\n ],\n simpleKeywords: [\n // English\n \"what is\",\n \"define\",\n \"translate\",\n \"hello\",\n \"yes or no\",\n \"capital of\",\n \"how old\",\n \"who is\",\n \"when was\",\n // Chinese\n \"什么是\",\n \"定义\",\n \"翻译\",\n \"你好\",\n \"是否\",\n \"首都\",\n \"多大\",\n \"谁是\",\n \"何时\",\n // Japanese\n \"とは\",\n \"定義\",\n \"翻訳\",\n \"こんにちは\",\n \"はいかいいえ\",\n \"首都\",\n \"誰\",\n // Russian\n \"что такое\",\n \"определение\",\n \"перевести\",\n \"переведи\",\n \"привет\",\n \"да или нет\",\n \"столица\",\n \"сколько лет\",\n \"кто такой\",\n \"когда\",\n \"объясни\",\n // German\n \"was ist\",\n \"definiere\",\n \"übersetze\",\n \"hallo\",\n \"ja oder nein\",\n \"hauptstadt\",\n \"wie alt\",\n \"wer ist\",\n \"wann\",\n \"erkläre\",\n // Spanish\n \"qué es\",\n \"definir\",\n \"traducir\",\n \"hola\",\n \"sí o no\",\n \"capital de\",\n \"cuántos años\",\n \"quién es\",\n \"cuándo\",\n // Portuguese\n \"o que é\",\n \"definir\",\n \"traduzir\",\n \"olá\",\n \"sim ou não\",\n \"capital de\",\n \"quantos anos\",\n \"quem é\",\n \"quando\",\n // Korean\n \"무엇\",\n \"정의\",\n \"번역\",\n \"안녕하세요\",\n \"예 또는 아니오\",\n \"수도\",\n \"누구\",\n \"언제\",\n // Arabic\n \"ما هو\",\n \"تعريف\",\n \"ترجم\",\n \"مرحبا\",\n \"نعم أو لا\",\n \"عاصمة\",\n \"من هو\",\n \"متى\",\n ],\n technicalKeywords: [\n // English\n \"algorithm\",\n \"optimize\",\n \"architecture\",\n \"distributed\",\n \"kubernetes\",\n \"microservice\",\n \"database\",\n \"infrastructure\",\n // Chinese\n \"算法\",\n \"优化\",\n \"架构\",\n \"分布式\",\n \"微服务\",\n \"数据库\",\n \"基础设施\",\n // Japanese\n \"アルゴリズム\",\n \"最適化\",\n \"アーキテクチャ\",\n \"分散\",\n \"マイクロサービス\",\n \"データベース\",\n // Russian\n \"алгоритм\",\n \"оптимизировать\",\n \"оптимизаци\",\n \"оптимизируй\",\n \"архитектура\",\n \"распределённый\",\n \"микросервис\",\n \"база данных\",\n \"инфраструктура\",\n // German\n \"algorithmus\",\n \"optimieren\",\n \"architektur\",\n \"verteilt\",\n \"kubernetes\",\n \"mikroservice\",\n \"datenbank\",\n \"infrastruktur\",\n // Spanish\n \"algoritmo\",\n \"optimizar\",\n \"arquitectura\",\n \"distribuido\",\n \"microservicio\",\n \"base de datos\",\n \"infraestructura\",\n // Portuguese\n \"algoritmo\",\n \"otimizar\",\n \"arquitetura\",\n \"distribuído\",\n \"microsserviço\",\n \"banco de dados\",\n \"infraestrutura\",\n // Korean\n \"알고리즘\",\n \"최적화\",\n \"아키텍처\",\n \"분산\",\n \"마이크로서비스\",\n \"데이터베이스\",\n \"인프라\",\n // Arabic\n \"خوارزمية\",\n \"تحسين\",\n \"بنية\",\n \"موزع\",\n \"خدمة مصغرة\",\n \"قاعدة بيانات\",\n \"بنية تحتية\",\n ],\n creativeKeywords: [\n // English\n \"story\",\n \"poem\",\n \"compose\",\n \"brainstorm\",\n \"creative\",\n \"imagine\",\n \"write a\",\n // Chinese\n \"故事\",\n \"诗\",\n \"创作\",\n \"头脑风暴\",\n \"创意\",\n \"想象\",\n \"写一个\",\n // Japanese\n \"物語\",\n \"詩\",\n \"作曲\",\n \"ブレインストーム\",\n \"創造的\",\n \"想像\",\n // Russian\n \"история\",\n \"рассказ\",\n \"стихотворение\",\n \"сочинить\",\n \"сочини\",\n \"мозговой штурм\",\n \"творческий\",\n \"представить\",\n \"придумай\",\n \"напиши\",\n // German\n \"geschichte\",\n \"gedicht\",\n \"komponieren\",\n \"brainstorming\",\n \"kreativ\",\n \"vorstellen\",\n \"schreibe\",\n \"erzählung\",\n // Spanish\n \"historia\",\n \"poema\",\n \"componer\",\n \"lluvia de ideas\",\n \"creativo\",\n \"imaginar\",\n \"escribe\",\n // Portuguese\n \"história\",\n \"poema\",\n \"compor\",\n \"criativo\",\n \"imaginar\",\n \"escreva\",\n // Korean\n \"이야기\",\n \"시\",\n \"작곡\",\n \"브레인스토밍\",\n \"창의적\",\n \"상상\",\n \"작성\",\n // Arabic\n \"قصة\",\n \"قصيدة\",\n \"تأليف\",\n \"عصف ذهني\",\n \"إبداعي\",\n \"تخيل\",\n \"اكتب\",\n ],\n\n // New dimension keyword lists (multilingual)\n imperativeVerbs: [\n // English\n \"build\",\n \"create\",\n \"implement\",\n \"design\",\n \"develop\",\n \"construct\",\n \"generate\",\n \"deploy\",\n \"configure\",\n \"set up\",\n // Chinese\n \"构建\",\n \"创建\",\n \"实现\",\n \"设计\",\n \"开发\",\n \"生成\",\n \"部署\",\n \"配置\",\n \"设置\",\n // Japanese\n \"構築\",\n \"作成\",\n \"実装\",\n \"設計\",\n \"開発\",\n \"生成\",\n \"デプロイ\",\n \"設定\",\n // Russian\n \"построить\",\n \"построй\",\n \"создать\",\n \"создай\",\n \"реализовать\",\n \"реализуй\",\n \"спроектировать\",\n \"разработать\",\n \"разработай\",\n \"сконструировать\",\n \"сгенерировать\",\n \"сгенерируй\",\n \"развернуть\",\n \"разверни\",\n \"настроить\",\n \"настрой\",\n // German\n \"erstellen\",\n \"bauen\",\n \"implementieren\",\n \"entwerfen\",\n \"entwickeln\",\n \"konstruieren\",\n \"generieren\",\n \"bereitstellen\",\n \"konfigurieren\",\n \"einrichten\",\n // Spanish\n \"construir\",\n \"crear\",\n \"implementar\",\n \"diseñar\",\n \"desarrollar\",\n \"generar\",\n \"desplegar\",\n \"configurar\",\n // Portuguese\n \"construir\",\n \"criar\",\n \"implementar\",\n \"projetar\",\n \"desenvolver\",\n \"gerar\",\n \"implantar\",\n \"configurar\",\n // Korean\n \"구축\",\n \"생성\",\n \"구현\",\n \"설계\",\n \"개발\",\n \"배포\",\n \"설정\",\n // Arabic\n \"بناء\",\n \"إنشاء\",\n \"تنفيذ\",\n \"تصميم\",\n \"تطوير\",\n \"توليد\",\n \"نشر\",\n \"إعداد\",\n ],\n constraintIndicators: [\n // English\n \"under\",\n \"at most\",\n \"at least\",\n \"within\",\n \"no more than\",\n \"o(\",\n \"maximum\",\n \"minimum\",\n \"limit\",\n \"budget\",\n // Chinese\n \"不超过\",\n \"至少\",\n \"最多\",\n \"在内\",\n \"最大\",\n \"最小\",\n \"限制\",\n \"预算\",\n // Japanese\n \"以下\",\n \"最大\",\n \"最小\",\n \"制限\",\n \"予算\",\n // Russian\n \"не более\",\n \"не менее\",\n \"как минимум\",\n \"в пределах\",\n \"максимум\",\n \"минимум\",\n \"ограничение\",\n \"бюджет\",\n // German\n \"höchstens\",\n \"mindestens\",\n \"innerhalb\",\n \"nicht mehr als\",\n \"maximal\",\n \"minimal\",\n \"grenze\",\n \"budget\",\n // Spanish\n \"como máximo\",\n \"al menos\",\n \"dentro de\",\n \"no más de\",\n \"máximo\",\n \"mínimo\",\n \"límite\",\n \"presupuesto\",\n // Portuguese\n \"no máximo\",\n \"pelo menos\",\n \"dentro de\",\n \"não mais que\",\n \"máximo\",\n \"mínimo\",\n \"limite\",\n \"orçamento\",\n // Korean\n \"이하\",\n \"이상\",\n \"최대\",\n \"최소\",\n \"제한\",\n \"예산\",\n // Arabic\n \"على الأكثر\",\n \"على الأقل\",\n \"ضمن\",\n \"لا يزيد عن\",\n \"أقصى\",\n \"أدنى\",\n \"حد\",\n \"ميزانية\",\n ],\n outputFormatKeywords: [\n // English\n \"json\",\n \"yaml\",\n \"xml\",\n \"table\",\n \"csv\",\n \"markdown\",\n \"schema\",\n \"format as\",\n \"structured\",\n // Chinese\n \"表格\",\n \"格式化为\",\n \"结构化\",\n // Japanese\n \"テーブル\",\n \"フォーマット\",\n \"構造化\",\n // Russian\n \"таблица\",\n \"форматировать как\",\n \"структурированный\",\n // German\n \"tabelle\",\n \"formatieren als\",\n \"strukturiert\",\n // Spanish\n \"tabla\",\n \"formatear como\",\n \"estructurado\",\n // Portuguese\n \"tabela\",\n \"formatar como\",\n \"estruturado\",\n // Korean\n \"테이블\",\n \"형식\",\n \"구조화\",\n // Arabic\n \"جدول\",\n \"تنسيق\",\n \"منظم\",\n ],\n referenceKeywords: [\n // English\n \"above\",\n \"below\",\n \"previous\",\n \"following\",\n \"the docs\",\n \"the api\",\n \"the code\",\n \"earlier\",\n \"attached\",\n // Chinese\n \"上面\",\n \"下面\",\n \"之前\",\n \"接下来\",\n \"文档\",\n \"代码\",\n \"附件\",\n // Japanese\n \"上記\",\n \"下記\",\n \"前の\",\n \"次の\",\n \"ドキュメント\",\n \"コード\",\n // Russian\n \"выше\",\n \"ниже\",\n \"предыдущий\",\n \"следующий\",\n \"документация\",\n \"код\",\n \"ранее\",\n \"вложение\",\n // German\n \"oben\",\n \"unten\",\n \"vorherige\",\n \"folgende\",\n \"dokumentation\",\n \"der code\",\n \"früher\",\n \"anhang\",\n // Spanish\n \"arriba\",\n \"abajo\",\n \"anterior\",\n \"siguiente\",\n \"documentación\",\n \"el código\",\n \"adjunto\",\n // Portuguese\n \"acima\",\n \"abaixo\",\n \"anterior\",\n \"seguinte\",\n \"documentação\",\n \"o código\",\n \"anexo\",\n // Korean\n \"위\",\n \"아래\",\n \"이전\",\n \"다음\",\n \"문서\",\n \"코드\",\n \"첨부\",\n // Arabic\n \"أعلاه\",\n \"أدناه\",\n \"السابق\",\n \"التالي\",\n \"الوثائق\",\n \"الكود\",\n \"مرفق\",\n ],\n negationKeywords: [\n // English\n \"don't\",\n \"do not\",\n \"avoid\",\n \"never\",\n \"without\",\n \"except\",\n \"exclude\",\n \"no longer\",\n // Chinese\n \"不要\",\n \"避免\",\n \"从不\",\n \"没有\",\n \"除了\",\n \"排除\",\n // Japanese\n \"しないで\",\n \"避ける\",\n \"決して\",\n \"なしで\",\n \"除く\",\n // Russian\n \"не делай\",\n \"не надо\",\n \"нельзя\",\n \"избегать\",\n \"никогда\",\n \"без\",\n \"кроме\",\n \"исключить\",\n \"больше не\",\n // German\n \"nicht\",\n \"vermeide\",\n \"niemals\",\n \"ohne\",\n \"außer\",\n \"ausschließen\",\n \"nicht mehr\",\n // Spanish\n \"no hagas\",\n \"evitar\",\n \"nunca\",\n \"sin\",\n \"excepto\",\n \"excluir\",\n // Portuguese\n \"não faça\",\n \"evitar\",\n \"nunca\",\n \"sem\",\n \"exceto\",\n \"excluir\",\n // Korean\n \"하지 마\",\n \"피하다\",\n \"절대\",\n \"없이\",\n \"제외\",\n // Arabic\n \"لا تفعل\",\n \"تجنب\",\n \"أبداً\",\n \"بدون\",\n \"باستثناء\",\n \"استبعاد\",\n ],\n domainSpecificKeywords: [\n // English\n \"quantum\",\n \"fpga\",\n \"vlsi\",\n \"risc-v\",\n \"asic\",\n \"photonics\",\n \"genomics\",\n \"proteomics\",\n \"topological\",\n \"homomorphic\",\n \"zero-knowledge\",\n \"lattice-based\",\n // Chinese\n \"量子\",\n \"光子学\",\n \"基因组学\",\n \"蛋白质组学\",\n \"拓扑\",\n \"同态\",\n \"零知识\",\n \"格密码\",\n // Japanese\n \"量子\",\n \"フォトニクス\",\n \"ゲノミクス\",\n \"トポロジカル\",\n // Russian\n \"квантовый\",\n \"фотоника\",\n \"геномика\",\n \"протеомика\",\n \"топологический\",\n \"гомоморфный\",\n \"с нулевым разглашением\",\n \"на основе решёток\",\n // German\n \"quanten\",\n \"photonik\",\n \"genomik\",\n \"proteomik\",\n \"topologisch\",\n \"homomorph\",\n \"zero-knowledge\",\n \"gitterbasiert\",\n // Spanish\n \"cuántico\",\n \"fotónica\",\n \"genómica\",\n \"proteómica\",\n \"topológico\",\n \"homomórfico\",\n // Portuguese\n \"quântico\",\n \"fotônica\",\n \"genômica\",\n \"proteômica\",\n \"topológico\",\n \"homomórfico\",\n // Korean\n \"양자\",\n \"포토닉스\",\n \"유전체학\",\n \"위상\",\n \"동형\",\n // Arabic\n \"كمي\",\n \"ضوئيات\",\n \"جينوميات\",\n \"طوبولوجي\",\n \"تماثلي\",\n ],\n\n // Agentic task keywords - file ops, execution, multi-step, iterative work\n // Pruned: removed overly common words like \"then\", \"first\", \"run\", \"test\", \"build\"\n agenticTaskKeywords: [\n // English - File operations (clearly agentic)\n \"read file\",\n \"read the file\",\n \"look at\",\n \"check the\",\n \"open the\",\n \"edit\",\n \"modify\",\n \"update the\",\n \"change the\",\n \"write to\",\n \"create file\",\n // English - Execution (specific commands only)\n \"execute\",\n \"deploy\",\n \"install\",\n \"npm\",\n \"pip\",\n \"compile\",\n // English - Multi-step patterns (specific only)\n \"after that\",\n \"and also\",\n \"once done\",\n \"step 1\",\n \"step 2\",\n // English - Iterative work\n \"fix\",\n \"debug\",\n \"until it works\",\n \"keep trying\",\n \"iterate\",\n \"make sure\",\n \"verify\",\n \"confirm\",\n // Chinese (keep specific ones)\n \"读取文件\",\n \"查看\",\n \"打开\",\n \"编辑\",\n \"修改\",\n \"更新\",\n \"创建\",\n \"执行\",\n \"部署\",\n \"安装\",\n \"第一步\",\n \"第二步\",\n \"修复\",\n \"调试\",\n \"直到\",\n \"确认\",\n \"验证\",\n // Spanish\n \"leer archivo\",\n \"editar\",\n \"modificar\",\n \"actualizar\",\n \"ejecutar\",\n \"desplegar\",\n \"instalar\",\n \"paso 1\",\n \"paso 2\",\n \"arreglar\",\n \"depurar\",\n \"verificar\",\n // Portuguese\n \"ler arquivo\",\n \"editar\",\n \"modificar\",\n \"atualizar\",\n \"executar\",\n \"implantar\",\n \"instalar\",\n \"passo 1\",\n \"passo 2\",\n \"corrigir\",\n \"depurar\",\n \"verificar\",\n // Korean\n \"파일 읽기\",\n \"편집\",\n \"수정\",\n \"업데이트\",\n \"실행\",\n \"배포\",\n \"설치\",\n \"단계 1\",\n \"단계 2\",\n \"디버그\",\n \"확인\",\n // Arabic\n \"قراءة ملف\",\n \"تحرير\",\n \"تعديل\",\n \"تحديث\",\n \"تنفيذ\",\n \"نشر\",\n \"تثبيت\",\n \"الخطوة 1\",\n \"الخطوة 2\",\n \"إصلاح\",\n \"تصحيح\",\n \"تحقق\",\n ],\n\n // Dimension weights (sum to 1.0)\n dimensionWeights: {\n tokenCount: 0.08,\n codePresence: 0.15,\n reasoningMarkers: 0.18,\n technicalTerms: 0.1,\n creativeMarkers: 0.05,\n simpleIndicators: 0.02, // Reduced from 0.12 to make room for agenticTask\n multiStepPatterns: 0.12,\n questionComplexity: 0.05,\n imperativeVerbs: 0.03,\n constraintCount: 0.04,\n outputFormat: 0.03,\n referenceComplexity: 0.02,\n negationComplexity: 0.01,\n domainSpecificity: 0.02,\n agenticTask: 0.04, // Reduced - agentic signals influence tier selection, not dominate it\n },\n\n // Tier boundaries on weighted score axis\n tierBoundaries: {\n simpleMedium: 0.0,\n mediumComplex: 0.3, // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier\n complexReasoning: 0.5, // Raised from 0.4 - reserve for true reasoning tasks\n },\n\n // Sigmoid steepness for confidence calibration\n confidenceSteepness: 12,\n // Below this confidence → ambiguous (null tier)\n confidenceThreshold: 0.7,\n },\n\n // Auto (balanced) tier configs - current default smart routing\n // Benchmark-tuned 2026-03-16: balancing quality (retention) + latency\n tiers: {\n SIMPLE: {\n primary: \"google/gemini-2.5-flash\", // 1,238ms, IQ 20, 60% retention (best) — fast AND quality\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — smarter fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, strong quality\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context — newest flash-lite\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"openai/gpt-5.4-nano\", // $0.20/$1.25, 1M context\n \"xai/grok-4-fast-non-reasoning\", // 1,143ms, $0.20/$0.50 — fast fallback\n \"free/gpt-oss-120b\", // 1,252ms, FREE fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, IQ 47, $0.60/$3.00 — strong tool use, quality output\n fallback: [\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — nearly same IQ, faster + cheaper\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32, 41% retention\n \"google/gemini-2.5-flash\", // 1,238ms, 60% retention\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M context\n \"google/gemini-2.5-flash-lite\", // 1,353ms, $0.10/$0.40\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"xai/grok-3-mini\", // 1,202ms, $0.30/$0.50\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-pro\", // 1,609ms, IQ 57 — fast flagship quality\n fallback: [\n \"google/gemini-3-pro-preview\", // 1,352ms, IQ 48 — quality-first fallback\n \"google/gemini-3-flash-preview\", // 1,398ms, IQ 46 — fast + smart\n \"xai/grok-4-0709\", // 1,348ms, IQ 41\n \"google/gemini-2.5-pro\", // 1,294ms\n \"anthropic/claude-sonnet-4.6\", // 2,110ms, IQ 52 — quality fallback\n \"deepseek/deepseek-chat\", // 1,431ms, IQ 32\n \"google/gemini-2.5-flash\", // 1,238ms, IQ 20 — cheap last resort\n \"openai/gpt-5.4\", // 6,213ms, IQ 57 — slowest but highest quality\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // 1,454ms, $0.20/$0.50\n fallback: [\n \"xai/grok-4-fast-reasoning\", // 1,298ms, $0.20/$0.50\n \"deepseek/deepseek-reasoner\", // 1,454ms, cheap reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Eco tier configs - absolute cheapest (blockrun/eco)\n ecoTiers: {\n SIMPLE: {\n primary: \"free/gpt-oss-120b\", // FREE! $0.00/$0.00\n fallback: [\n \"free/gpt-oss-20b\", // FREE — smaller, faster\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n \"openai/gpt-5.4-nano\", // $0.20/$1.25 — fast nano\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\", // $0.20/$0.50\n ],\n },\n MEDIUM: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50 — newest flash-lite\n fallback: [\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"xai/grok-4-fast-non-reasoning\",\n \"google/gemini-2.5-flash\",\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n fallback: [\n \"google/gemini-2.5-flash-lite\",\n \"xai/grok-4-0709\",\n \"google/gemini-2.5-flash\",\n \"deepseek/deepseek-chat\",\n ],\n },\n REASONING: {\n primary: \"xai/grok-4-1-fast-reasoning\", // $0.20/$0.50\n fallback: [\"xai/grok-4-fast-reasoning\", \"deepseek/deepseek-reasoner\"],\n },\n },\n\n // Premium tier configs - best quality (blockrun/premium)\n // codex=complex coding, kimi=simple coding, sonnet=reasoning/instructions, opus=architecture/PM/audits\n premiumTiers: {\n SIMPLE: {\n primary: \"moonshot/kimi-k2.5\", // $0.60/$3.00 - good for simple coding\n fallback: [\n \"google/gemini-2.5-flash\", // 60% retention, fast growth\n \"anthropic/claude-haiku-4.5\",\n \"google/gemini-2.5-flash-lite\",\n \"deepseek/deepseek-chat\",\n ],\n },\n MEDIUM: {\n primary: \"openai/gpt-5.3-codex\", // $1.75/$14 - 400K context, 128K output, replaces 5.2\n fallback: [\n \"moonshot/kimi-k2.5\",\n \"google/gemini-2.5-flash\", // 60% retention, good coding capability\n \"google/gemini-2.5-pro\",\n \"xai/grok-4-0709\",\n \"anthropic/claude-sonnet-4.6\",\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-opus-4.6\", // Best quality for complex tasks\n fallback: [\n \"openai/gpt-5.4\", // Newest flagship\n \"openai/gpt-5.3-codex\",\n \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-sonnet-4.6\",\n \"google/gemini-3.1-pro\", // Newest Gemini\n \"google/gemini-3-pro-preview\",\n \"moonshot/kimi-k2.5\",\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms, $3/$15 - best for reasoning/instructions\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms, cheap fast reasoning\n \"openai/o4-mini\", // 2,328ms ($1.10/$4.40)\n \"openai/o3\", // 2,862ms\n ],\n },\n },\n\n // Agentic tier configs - models that excel at multi-step autonomous tasks\n agenticTiers: {\n SIMPLE: {\n primary: \"openai/gpt-4o-mini\", // $0.15/$0.60 - best tool compliance at lowest cost\n fallback: [\n \"moonshot/kimi-k2.5\", // 1,646ms, strong tool use quality\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n ],\n },\n MEDIUM: {\n primary: \"moonshot/kimi-k2.5\", // 1,646ms, $0.60/$3.00 - strong tool use, proper function calls\n fallback: [\n \"xai/grok-4-1-fast-non-reasoning\", // 1,244ms, fast fallback\n \"openai/gpt-4o-mini\", // 2,764ms, reliable tool calling\n \"anthropic/claude-haiku-4.5\", // 2,305ms\n \"deepseek/deepseek-chat\", // 1,431ms\n ],\n },\n COMPLEX: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — best agentic quality\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms — top quality\n \"google/gemini-3.1-pro\", // 1,609ms\n \"xai/grok-4-0709\", // 1,348ms\n \"openai/gpt-5.4\", // 6,213ms — slow but highest quality fallback\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-4.6\", // 2,110ms — strong tool use + reasoning\n fallback: [\n \"anthropic/claude-opus-4.6\", // 2,139ms\n \"xai/grok-4-1-fast-reasoning\", // 1,454ms\n \"deepseek/deepseek-reasoner\", // 1,454ms\n ],\n },\n },\n\n overrides: {\n maxTokensForceComplex: 100_000,\n structuredOutputMinTier: \"MEDIUM\",\n ambiguousDefaultTier: \"MEDIUM\",\n agenticMode: false,\n },\n};\n","/**\n * Smart Router Entry Point\n *\n * Classifies requests and routes to the cheapest capable model.\n * Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).\n */\n\nimport type { RoutingDecision, RouterOptions } from \"./types.js\";\nimport { getStrategy } from \"./strategy.js\";\n\n/**\n * Route a request to the cheapest capable model.\n * Delegates to the registered \"rules\" strategy by default.\n */\nexport function route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n): RoutingDecision {\n const strategy = getStrategy(\"rules\");\n return strategy.route(prompt, systemPrompt, maxOutputTokens, options);\n}\n\nexport { getStrategy, registerStrategy } from \"./strategy.js\";\nexport {\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n calculateModelCost,\n} from \"./selector.js\";\nexport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nexport type {\n RoutingDecision,\n Tier,\n RoutingConfig,\n RouterOptions,\n RouterStrategy,\n} from \"./types.js\";\nexport type { ModelPricing } from \"./selector.js\";\n","/**\n * Usage Logger\n *\n * Logs every LLM request as a JSON line to a daily log file.\n * Files: ~/.openclaw/blockrun/logs/usage-YYYY-MM-DD.jsonl\n *\n * MVP: append-only JSON lines. No rotation, no cleanup.\n * Logging never breaks the request flow — all errors are swallowed.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport type UsageEntry = {\n timestamp: string;\n model: string;\n tier: string;\n cost: number;\n baselineCost: number;\n savings: number; // 0-1 percentage\n latencyMs: number;\n /** Input (prompt) tokens reported by the provider */\n inputTokens?: number;\n /** Output (completion) tokens reported by the provider */\n outputTokens?: number;\n /** Partner service ID (e.g., \"x_users_lookup\") — only set for partner API calls */\n partnerId?: string;\n /** Partner service name (e.g., \"AttentionVC\") — only set for partner API calls */\n service?: string;\n};\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\nlet dirReady = false;\n\nasync function ensureDir(): Promise {\n if (dirReady) return;\n await mkdir(LOG_DIR, { recursive: true });\n dirReady = true;\n}\n\n/**\n * Log a usage entry as a JSON line.\n */\nexport async function logUsage(entry: UsageEntry): Promise {\n try {\n await ensureDir();\n const date = entry.timestamp.slice(0, 10); // YYYY-MM-DD\n const file = join(LOG_DIR, `usage-${date}.jsonl`);\n await appendFile(file, JSON.stringify(entry) + \"\\n\");\n } catch {\n // Never break the request flow\n }\n}\n","/**\n * Usage Statistics Aggregator\n *\n * Reads usage log files and aggregates statistics for terminal display.\n * Supports filtering by date range and provides multiple aggregation views.\n */\n\nimport { readdir, unlink } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type { UsageEntry } from \"./logger.js\";\nimport { VERSION } from \"./version.js\";\n\nconst LOG_DIR = join(homedir(), \".openclaw\", \"blockrun\", \"logs\");\n\nexport type DailyStats = {\n date: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n avgLatencyMs: number;\n byTier: Record;\n byModel: Record;\n};\n\nexport type AggregatedStats = {\n period: string;\n totalRequests: number;\n totalCost: number;\n totalBaselineCost: number;\n totalSavings: number;\n savingsPercentage: number;\n avgLatencyMs: number;\n avgCostPerRequest: number;\n byTier: Record;\n byModel: Record;\n dailyBreakdown: DailyStats[];\n entriesWithBaseline: number; // Entries with valid baseline tracking\n};\n\n/**\n * Parse a JSONL log file into usage entries.\n * Handles both old format (without tier/baselineCost) and new format.\n */\nasync function parseLogFile(filePath: string): Promise {\n try {\n const content = await readTextFile(filePath);\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n const entries: UsageEntry[] = [];\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as Partial;\n entries.push({\n timestamp: entry.timestamp || new Date().toISOString(),\n model: entry.model || \"unknown\",\n tier: entry.tier || \"UNKNOWN\",\n cost: entry.cost || 0,\n baselineCost: entry.baselineCost || entry.cost || 0,\n savings: entry.savings || 0,\n latencyMs: entry.latencyMs || 0,\n });\n } catch {\n // Skip malformed lines, keep valid ones\n }\n }\n return entries;\n } catch {\n return [];\n }\n}\n\n/**\n * Get list of available log files sorted by date (newest first).\n */\nasync function getLogFiles(): Promise {\n try {\n const files = await readdir(LOG_DIR);\n return files\n .filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\n/**\n * Aggregate stats for a single day.\n */\nfunction aggregateDay(date: string, entries: UsageEntry[]): DailyStats {\n const byTier: Record = {};\n const byModel: Record = {};\n let totalLatency = 0;\n\n for (const entry of entries) {\n // By tier\n if (!byTier[entry.tier]) byTier[entry.tier] = { count: 0, cost: 0 };\n byTier[entry.tier].count++;\n byTier[entry.tier].cost += entry.cost;\n\n // By model\n if (!byModel[entry.model]) byModel[entry.model] = { count: 0, cost: 0 };\n byModel[entry.model].count++;\n byModel[entry.model].cost += entry.cost;\n\n totalLatency += entry.latencyMs;\n }\n\n const totalCost = entries.reduce((sum, e) => sum + e.cost, 0);\n const totalBaselineCost = entries.reduce((sum, e) => sum + e.baselineCost, 0);\n\n return {\n date,\n totalRequests: entries.length,\n totalCost,\n totalBaselineCost,\n totalSavings: totalBaselineCost - totalCost,\n avgLatencyMs: entries.length > 0 ? totalLatency / entries.length : 0,\n byTier,\n byModel,\n };\n}\n\n/**\n * Get aggregated statistics for the last N days.\n */\nexport async function getStats(days: number = 7): Promise {\n const logFiles = await getLogFiles();\n const filesToRead = logFiles.slice(0, days);\n\n const dailyBreakdown: DailyStats[] = [];\n const allByTier: Record = {};\n const allByModel: Record = {};\n let totalRequests = 0;\n let totalCost = 0;\n let totalBaselineCost = 0;\n let totalLatency = 0;\n\n for (const file of filesToRead) {\n const date = file.replace(\"usage-\", \"\").replace(\".jsonl\", \"\");\n const filePath = join(LOG_DIR, file);\n const entries = await parseLogFile(filePath);\n\n if (entries.length === 0) continue;\n\n const dayStats = aggregateDay(date, entries);\n dailyBreakdown.push(dayStats);\n\n totalRequests += dayStats.totalRequests;\n totalCost += dayStats.totalCost;\n totalBaselineCost += dayStats.totalBaselineCost;\n totalLatency += dayStats.avgLatencyMs * dayStats.totalRequests;\n\n // Merge tier stats\n for (const [tier, stats] of Object.entries(dayStats.byTier)) {\n if (!allByTier[tier]) allByTier[tier] = { count: 0, cost: 0 };\n allByTier[tier].count += stats.count;\n allByTier[tier].cost += stats.cost;\n }\n\n // Merge model stats\n for (const [model, stats] of Object.entries(dayStats.byModel)) {\n if (!allByModel[model]) allByModel[model] = { count: 0, cost: 0 };\n allByModel[model].count += stats.count;\n allByModel[model].cost += stats.cost;\n }\n }\n\n // Calculate percentages\n const byTierWithPercentage: Record =\n {};\n for (const [tier, stats] of Object.entries(allByTier)) {\n byTierWithPercentage[tier] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const byModelWithPercentage: Record =\n {};\n for (const [model, stats] of Object.entries(allByModel)) {\n byModelWithPercentage[model] = {\n ...stats,\n percentage: totalRequests > 0 ? (stats.count / totalRequests) * 100 : 0,\n };\n }\n\n const totalSavings = totalBaselineCost - totalCost;\n const savingsPercentage = totalBaselineCost > 0 ? (totalSavings / totalBaselineCost) * 100 : 0;\n\n // Count entries with valid baseline tracking (baseline != cost means tracking was active)\n let entriesWithBaseline = 0;\n for (const day of dailyBreakdown) {\n if (day.totalBaselineCost !== day.totalCost) {\n entriesWithBaseline += day.totalRequests;\n }\n }\n\n return {\n period: days === 1 ? \"today\" : `last ${days} days`,\n totalRequests,\n totalCost,\n totalBaselineCost,\n totalSavings,\n savingsPercentage,\n avgLatencyMs: totalRequests > 0 ? totalLatency / totalRequests : 0,\n avgCostPerRequest: totalRequests > 0 ? totalCost / totalRequests : 0,\n byTier: byTierWithPercentage,\n byModel: byModelWithPercentage,\n dailyBreakdown: dailyBreakdown.reverse(), // Oldest first for charts\n entriesWithBaseline, // How many entries have valid baseline tracking\n };\n}\n\n/**\n * Format stats as ASCII table for terminal display.\n */\nexport function formatStatsAscii(stats: AggregatedStats): string {\n const lines: string[] = [];\n\n // Header\n lines.push(\"╔════════════════════════════════════════════════════════════╗\");\n lines.push(`║ ClawRouter by BlockRun v${VERSION}`.padEnd(61) + \"║\");\n lines.push(\"║ Usage Statistics ║\");\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n\n // Summary\n lines.push(`║ Period: ${stats.period.padEnd(49)}║`);\n lines.push(`║ Total Requests: ${stats.totalRequests.toString().padEnd(41)}║`);\n lines.push(`║ Total Cost: $${stats.totalCost.toFixed(4).padEnd(43)}║`);\n lines.push(`║ Baseline Cost (Opus 4.5): $${stats.totalBaselineCost.toFixed(4).padEnd(30)}║`);\n\n // Show savings with note if some entries lack baseline tracking\n const savingsLine = `║ 💰 Total Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(1)}%)`;\n if (stats.entriesWithBaseline < stats.totalRequests && stats.entriesWithBaseline > 0) {\n lines.push(savingsLine.padEnd(61) + \"║\");\n const note = `║ (based on ${stats.entriesWithBaseline}/${stats.totalRequests} tracked requests)`;\n lines.push(note.padEnd(61) + \"║\");\n } else {\n lines.push(savingsLine.padEnd(61) + \"║\");\n }\n lines.push(`║ Avg Latency: ${stats.avgLatencyMs.toFixed(0)}ms`.padEnd(61) + \"║\");\n\n // Tier breakdown\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Routing by Tier: ║\");\n\n // Show all tiers found in data, ordered by known tiers first then others\n const knownTiers = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\", \"DIRECT\"];\n const allTiers = Object.keys(stats.byTier);\n const otherTiers = allTiers.filter((t) => !knownTiers.includes(t));\n const tierOrder = [...knownTiers.filter((t) => stats.byTier[t]), ...otherTiers];\n\n for (const tier of tierOrder) {\n const data = stats.byTier[tier];\n if (data) {\n const bar = \"█\".repeat(Math.min(20, Math.round(data.percentage / 5)));\n const displayTier = tier === \"UNKNOWN\" ? \"OTHER\" : tier;\n const line = `║ ${displayTier.padEnd(10)} ${bar.padEnd(20)} ${data.percentage.toFixed(1).padStart(5)}% (${data.count})`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n // Top models\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Top Models: ║\");\n\n const sortedModels = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 5);\n\n for (const [model, data] of sortedModels) {\n const shortModel = model.length > 25 ? model.slice(0, 22) + \"...\" : model;\n const line = `║ ${shortModel.padEnd(25)} ${data.count.toString().padStart(5)} reqs $${data.cost.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n\n // Daily breakdown (last 7 days)\n if (stats.dailyBreakdown.length > 0) {\n lines.push(\"╠════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Daily Breakdown: ║\");\n lines.push(\"║ Date Requests Cost Saved ║\");\n\n for (const day of stats.dailyBreakdown.slice(-7)) {\n const saved = day.totalBaselineCost - day.totalCost;\n const line = `║ ${day.date} ${day.totalRequests.toString().padStart(6)} $${day.totalCost.toFixed(4).padStart(8)} $${saved.toFixed(4)}`;\n lines.push(line.padEnd(61) + \"║\");\n }\n }\n\n lines.push(\"╚════════════════════════════════════════════════════════════╝\");\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Delete all usage log files, resetting stats to zero.\n */\nexport async function clearStats(): Promise<{ deletedFiles: number }> {\n try {\n const files = await readdir(LOG_DIR);\n const logFiles = files.filter((f) => f.startsWith(\"usage-\") && f.endsWith(\".jsonl\"));\n\n await Promise.all(logFiles.map((f) => unlink(join(LOG_DIR, f))));\n\n return { deletedFiles: logFiles.length };\n } catch {\n return { deletedFiles: 0 };\n }\n}\n","/**\n * Scanner-safe file reading utilities.\n *\n * Uses open() + read() to avoid false positives from openclaw's\n * potential-exfiltration heuristic in bundled output.\n */\n\nimport { open } from \"node:fs/promises\";\nimport { openSync, readSync, closeSync, fstatSync } from \"node:fs\";\n\n/** Read file contents as UTF-8 string (async). */\nexport async function readTextFile(filePath: string): Promise {\n const fh = await open(filePath, \"r\");\n try {\n const size = (await fh.stat()).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const { bytesRead } = await fh.read(buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n await fh.close();\n }\n}\n\n/** Read file contents as UTF-8 string (sync). */\nexport function readTextFileSync(filePath: string): string {\n const fd = openSync(filePath, \"r\");\n try {\n const size = fstatSync(fd).size;\n const buf = Buffer.alloc(size);\n let offset = 0;\n while (offset < size) {\n const bytesRead = readSync(fd, buf, offset, size - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n return buf.subarray(0, offset).toString(\"utf-8\");\n } finally {\n closeSync(fd);\n }\n}\n","/**\n * Single source of truth for version.\n * Reads from package.json at build time via tsup's define.\n */\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\n\n// Read package.json at runtime\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// In dist/, go up one level to find package.json\nconst require = createRequire(import.meta.url);\nconst pkg = require(join(__dirname, \"..\", \"package.json\")) as { version: string };\n\nexport const VERSION = pkg.version;\nexport const USER_AGENT = `clawrouter/${VERSION}`;\n","/**\n * Request Deduplication\n *\n * Prevents double-charging when OpenClaw retries a request after timeout.\n * Tracks in-flight requests and caches completed responses for a short TTL.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedResponse = {\n status: number;\n headers: Record;\n body: Buffer;\n completedAt: number;\n};\n\ntype InflightEntry = {\n resolvers: Array<(result: CachedResponse) => void>;\n};\n\nconst DEFAULT_TTL_MS = 30_000; // 30 seconds\nconst MAX_BODY_SIZE = 1_048_576; // 1MB\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical string regardless of field order.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip OpenClaw-injected timestamps from message content.\n * Format: [DAY YYYY-MM-DD HH:MM TZ] at the start of messages.\n * Example: [SUN 2026-02-07 13:30 PST] Hello world\n *\n * This ensures requests with different timestamps but same content hash identically.\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction stripTimestamps(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stripTimestamps);\n }\n const result: Record = {};\n for (const [key, value] of Object.entries(obj as Record)) {\n if (key === \"content\" && typeof value === \"string\") {\n // Strip timestamp prefix from message content\n result[key] = value.replace(TIMESTAMP_PATTERN, \"\");\n } else {\n result[key] = stripTimestamps(value);\n }\n }\n return result;\n}\n\nexport class RequestDeduplicator {\n private inflight = new Map();\n private completed = new Map();\n private ttlMs: number;\n\n constructor(ttlMs = DEFAULT_TTL_MS) {\n this.ttlMs = ttlMs;\n }\n\n /** Hash request body to create a dedup key. */\n static hash(body: Buffer): string {\n // Canonicalize JSON to ensure consistent hashing regardless of field order.\n // Also strip OpenClaw-injected timestamps so retries with different timestamps\n // still match the same dedup key.\n let content = body;\n try {\n const parsed = JSON.parse(body.toString());\n const stripped = stripTimestamps(parsed);\n const canonical = canonicalize(stripped);\n content = Buffer.from(JSON.stringify(canonical));\n } catch {\n // Not valid JSON, use raw bytes\n }\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 16);\n }\n\n /** Check if a response is cached for this key. */\n getCached(key: string): CachedResponse | undefined {\n const entry = this.completed.get(key);\n if (!entry) return undefined;\n if (Date.now() - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n return undefined;\n }\n return entry;\n }\n\n /** Check if a request with this key is currently in-flight. Returns a promise to wait on. */\n getInflight(key: string): Promise | undefined {\n const entry = this.inflight.get(key);\n if (!entry) return undefined;\n return new Promise((resolve) => {\n entry.resolvers.push(resolve);\n });\n }\n\n /** Mark a request as in-flight. */\n markInflight(key: string): void {\n this.inflight.set(key, {\n resolvers: [],\n });\n }\n\n /** Complete an in-flight request — cache result and notify waiters. */\n complete(key: string, result: CachedResponse): void {\n // Only cache responses within size limit\n if (result.body.length <= MAX_BODY_SIZE) {\n this.completed.set(key, result);\n }\n\n const entry = this.inflight.get(key);\n if (entry) {\n for (const resolve of entry.resolvers) {\n resolve(result);\n }\n this.inflight.delete(key);\n }\n\n this.prune();\n }\n\n /** Remove an in-flight entry on error (don't cache failures).\n * Also rejects any waiters so they can retry independently. */\n removeInflight(key: string): void {\n const entry = this.inflight.get(key);\n if (entry) {\n // Resolve waiters with a sentinel error response so they don't hang forever.\n // Waiters will see a 503 and can retry on their own.\n const errorBody = Buffer.from(\n JSON.stringify({\n error: { message: \"Original request failed, please retry\", type: \"dedup_origin_failed\" },\n }),\n );\n for (const resolve of entry.resolvers) {\n resolve({\n status: 503,\n headers: { \"content-type\": \"application/json\" },\n body: errorBody,\n completedAt: Date.now(),\n });\n }\n this.inflight.delete(key);\n }\n }\n\n /** Prune expired completed entries. */\n private prune(): void {\n const now = Date.now();\n for (const [key, entry] of this.completed) {\n if (now - entry.completedAt > this.ttlMs) {\n this.completed.delete(key);\n }\n }\n }\n}\n","/**\n * Response Cache for LLM Completions\n *\n * Caches LLM responses by request hash (model + messages + params).\n * Inspired by LiteLLM's caching system. Returns cached responses for\n * identical requests, saving both cost and latency.\n *\n * Features:\n * - TTL-based expiration (default 10 minutes)\n * - LRU eviction when cache is full\n * - Size limits per item (1MB max)\n * - Heap-based expiration tracking for efficient pruning\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type CachedLLMResponse = {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n cachedAt: number;\n expiresAt: number;\n};\n\nexport type ResponseCacheConfig = {\n /** Maximum number of cached responses. Default: 200 */\n maxSize?: number;\n /** Default TTL in seconds. Default: 600 (10 minutes) */\n defaultTTL?: number;\n /** Maximum size per cached item in bytes. Default: 1MB */\n maxItemSize?: number;\n /** Enable/disable cache. Default: true */\n enabled?: boolean;\n};\n\nconst DEFAULT_CONFIG: Required = {\n maxSize: 200,\n defaultTTL: 600,\n maxItemSize: 1_048_576, // 1MB\n enabled: true,\n};\n\n/**\n * Canonicalize JSON by sorting object keys recursively.\n * Ensures identical logical content produces identical hash.\n */\nfunction canonicalize(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(canonicalize);\n }\n const sorted: Record = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize((obj as Record)[key]);\n }\n return sorted;\n}\n\n/**\n * Strip fields that shouldn't affect cache key:\n * - stream (we handle streaming separately)\n * - timestamps injected by OpenClaw\n * - request IDs\n */\nconst TIMESTAMP_PATTERN = /^\\[\\w{3}\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}\\s+\\w+\\]\\s*/;\n\nfunction normalizeForCache(obj: Record): Record {\n const result: Record = {};\n\n for (const [key, value] of Object.entries(obj)) {\n // Skip fields that don't affect response content\n if ([\"stream\", \"user\", \"request_id\", \"x-request-id\"].includes(key)) {\n continue;\n }\n\n if (key === \"messages\" && Array.isArray(value)) {\n // Strip timestamps from message content\n result[key] = value.map((msg: unknown) => {\n if (typeof msg === \"object\" && msg !== null) {\n const m = msg as Record;\n if (typeof m.content === \"string\") {\n return { ...m, content: m.content.replace(TIMESTAMP_PATTERN, \"\") };\n }\n }\n return msg;\n });\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nexport class ResponseCache {\n private cache = new Map();\n private expirationHeap: Array<{ expiresAt: number; key: string }> = [];\n private config: Required;\n\n // Stats for monitoring\n private stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n };\n\n constructor(config: ResponseCacheConfig = {}) {\n // Filter out undefined values so they don't override defaults\n const filtered = Object.fromEntries(\n Object.entries(config).filter(([, v]) => v !== undefined),\n ) as ResponseCacheConfig;\n this.config = { ...DEFAULT_CONFIG, ...filtered };\n }\n\n /**\n * Generate cache key from request body.\n * Hashes: model + messages + temperature + max_tokens + other params\n */\n static generateKey(body: Buffer | string): string {\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n const normalized = normalizeForCache(parsed);\n const canonical = canonicalize(normalized);\n const keyContent = JSON.stringify(canonical);\n return createHash(\"sha256\").update(keyContent).digest(\"hex\").slice(0, 32);\n } catch {\n // Fallback: hash raw body\n const content = typeof body === \"string\" ? body : body.toString();\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 32);\n }\n }\n\n /**\n * Check if caching is enabled for this request.\n * Respects cache control headers and request params.\n */\n shouldCache(body: Buffer | string, headers?: Record): boolean {\n if (!this.config.enabled) return false;\n\n // Respect Cache-Control: no-cache header\n if (headers?.[\"cache-control\"]?.includes(\"no-cache\")) {\n return false;\n }\n\n // Check for explicit cache disable in body\n try {\n const parsed = JSON.parse(typeof body === \"string\" ? body : body.toString());\n if (parsed.cache === false || parsed.no_cache === true) {\n return false;\n }\n } catch {\n // Not JSON, allow caching\n }\n\n return true;\n }\n\n /**\n * Get cached response if available and not expired.\n */\n get(key: string): CachedLLMResponse | undefined {\n const entry = this.cache.get(key);\n if (!entry) {\n this.stats.misses++;\n return undefined;\n }\n\n // Check expiration\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n this.stats.misses++;\n return undefined;\n }\n\n this.stats.hits++;\n return entry;\n }\n\n /**\n * Cache a response with optional custom TTL.\n */\n set(\n key: string,\n response: {\n body: Buffer;\n status: number;\n headers: Record;\n model: string;\n },\n ttlSeconds?: number,\n ): void {\n // Don't cache if disabled or maxSize is 0\n if (!this.config.enabled || this.config.maxSize <= 0) return;\n\n // Don't cache if item too large\n if (response.body.length > this.config.maxItemSize) {\n console.log(`[ResponseCache] Skipping cache - item too large: ${response.body.length} bytes`);\n return;\n }\n\n // Don't cache error responses\n if (response.status >= 400) {\n return;\n }\n\n // Evict if at capacity\n if (this.cache.size >= this.config.maxSize) {\n this.evict();\n }\n\n const now = Date.now();\n const ttl = ttlSeconds ?? this.config.defaultTTL;\n const expiresAt = now + ttl * 1000;\n\n const entry: CachedLLMResponse = {\n ...response,\n cachedAt: now,\n expiresAt,\n };\n\n this.cache.set(key, entry);\n this.expirationHeap.push({ expiresAt, key });\n }\n\n /**\n * Evict expired and oldest entries to make room.\n */\n private evict(): void {\n const now = Date.now();\n\n // First pass: remove expired entries\n this.expirationHeap.sort((a, b) => a.expiresAt - b.expiresAt);\n\n while (this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap[0];\n\n // Check if entry still exists and matches\n const entry = this.cache.get(oldest.key);\n if (!entry || entry.expiresAt !== oldest.expiresAt) {\n // Stale heap entry, remove it\n this.expirationHeap.shift();\n continue;\n }\n\n if (oldest.expiresAt <= now) {\n // Expired, remove both\n this.cache.delete(oldest.key);\n this.expirationHeap.shift();\n this.stats.evictions++;\n } else {\n // Not expired, stop\n break;\n }\n }\n\n // Second pass: if still at capacity, evict oldest\n while (this.cache.size >= this.config.maxSize && this.expirationHeap.length > 0) {\n const oldest = this.expirationHeap.shift()!;\n if (this.cache.has(oldest.key)) {\n this.cache.delete(oldest.key);\n this.stats.evictions++;\n }\n }\n }\n\n /**\n * Get cache statistics.\n */\n getStats(): {\n size: number;\n maxSize: number;\n hits: number;\n misses: number;\n evictions: number;\n hitRate: string;\n } {\n const total = this.stats.hits + this.stats.misses;\n const hitRate = total > 0 ? ((this.stats.hits / total) * 100).toFixed(1) + \"%\" : \"0%\";\n\n return {\n size: this.cache.size,\n maxSize: this.config.maxSize,\n hits: this.stats.hits,\n misses: this.stats.misses,\n evictions: this.stats.evictions,\n hitRate,\n };\n }\n\n /**\n * Clear all cached entries.\n */\n clear(): void {\n this.cache.clear();\n this.expirationHeap = [];\n }\n\n /**\n * Check if cache is enabled.\n */\n isEnabled(): boolean {\n return this.config.enabled;\n }\n}\n","/**\n * Typed Error Classes for ClawRouter\n *\n * Provides structured errors for balance-related failures with\n * all necessary information for user-friendly error messages.\n */\n\n/**\n * Thrown when wallet has insufficient USDC balance for a request.\n */\nexport class InsufficientFundsError extends Error {\n readonly code = \"INSUFFICIENT_FUNDS\" as const;\n readonly currentBalanceUSD: string;\n readonly requiredUSD: string;\n readonly walletAddress: string;\n\n constructor(opts: { currentBalanceUSD: string; requiredUSD: string; walletAddress: string }) {\n const msg = [\n `Insufficient balance. Current: ${opts.currentBalanceUSD}, Required: ${opts.requiredUSD}`,\n `Options:`,\n ` 1. Fund wallet: ${opts.walletAddress}`,\n ` 2. Use free model: /model free`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"InsufficientFundsError\";\n this.currentBalanceUSD = opts.currentBalanceUSD;\n this.requiredUSD = opts.requiredUSD;\n this.walletAddress = opts.walletAddress;\n }\n}\n\n/**\n * Thrown when wallet has no USDC balance (or effectively zero).\n */\nexport class EmptyWalletError extends Error {\n readonly code = \"EMPTY_WALLET\" as const;\n readonly walletAddress: string;\n\n constructor(walletAddress: string) {\n const msg = [\n `No USDC balance.`,\n `Options:`,\n ` 1. Fund wallet: ${walletAddress}`,\n ` 2. Use free model: /model free`,\n ` 3. Uninstall: bash ~/.openclaw/extensions/clawrouter/scripts/uninstall.sh`,\n ].join(\"\\n\");\n super(msg);\n this.name = \"EmptyWalletError\";\n this.walletAddress = walletAddress;\n }\n}\n\n/**\n * Type guard to check if an error is InsufficientFundsError.\n */\nexport function isInsufficientFundsError(error: unknown): error is InsufficientFundsError {\n return error instanceof Error && (error as InsufficientFundsError).code === \"INSUFFICIENT_FUNDS\";\n}\n\n/**\n * Type guard to check if an error is EmptyWalletError.\n */\nexport function isEmptyWalletError(error: unknown): error is EmptyWalletError {\n return error instanceof Error && (error as EmptyWalletError).code === \"EMPTY_WALLET\";\n}\n\n/**\n * Type guard to check if an error is a balance-related error.\n */\nexport function isBalanceError(error: unknown): error is InsufficientFundsError | EmptyWalletError {\n return isInsufficientFundsError(error) || isEmptyWalletError(error);\n}\n\n/**\n * Thrown when RPC call fails (network error, node down, etc).\n * Distinguishes infrastructure failures from actual empty wallets.\n */\nexport class RpcError extends Error {\n readonly code = \"RPC_ERROR\" as const;\n readonly originalError: unknown;\n\n constructor(message: string, originalError?: unknown) {\n super(`RPC error: ${message}. Check network connectivity.`);\n this.name = \"RpcError\";\n this.originalError = originalError;\n }\n}\n\n/**\n * Type guard to check if an error is RpcError.\n */\nexport function isRpcError(error: unknown): error is RpcError {\n return error instanceof Error && (error as RpcError).code === \"RPC_ERROR\";\n}\n","/**\n * EIP-3009 payment asset on Base network.\n * Represents a stablecoin that supports `transferWithAuthorization`\n * for gasless, single-step payment settlements.\n */\nexport type BasePaymentAsset = {\n chain: \"base\";\n asset: `0x${string}`;\n symbol: string;\n decimals: number;\n name: string;\n transferMethod: \"eip3009\";\n priority?: number;\n enabled?: boolean;\n};\n\n/** Default payment asset: USDC on Base (6 decimals, EIP-3009). */\nexport const DEFAULT_BASE_PAYMENT_ASSET: BasePaymentAsset = {\n chain: \"base\",\n asset: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n symbol: \"USDC\",\n decimals: 6,\n name: \"USD Coin\",\n transferMethod: \"eip3009\",\n};\n\ntype PaymentMetadataResponse =\n | Partial\n | { paymentAssets?: Array> }\n | { paymentAsset?: Partial }\n | { base?: Partial };\n\n/** Check if a value is a valid 0x-prefixed ERC-20 contract address (40 hex chars). */\nfunction isHexAddress(value: unknown): value is `0x${string}` {\n return typeof value === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(value);\n}\n\n/**\n * Validate and normalize a single payment asset from an API response.\n * Returns undefined if the input is missing required fields or uses a non-EIP-3009 transfer method.\n * Symbols are uppercased; names are trimmed.\n */\nexport function normalizeBasePaymentAsset(\n value: unknown,\n): BasePaymentAsset | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n\n const candidate = value as Partial;\n if (!isHexAddress(candidate.asset)) return undefined;\n if (typeof candidate.symbol !== \"string\" || candidate.symbol.trim() === \"\") return undefined;\n if (\n typeof candidate.decimals !== \"number\" ||\n !Number.isInteger(candidate.decimals) ||\n candidate.decimals < 0\n ) {\n return undefined;\n }\n if (typeof candidate.name !== \"string\" || candidate.name.trim() === \"\") return undefined;\n if (candidate.transferMethod !== undefined && candidate.transferMethod !== \"eip3009\") {\n return undefined;\n }\n\n return {\n chain: \"base\",\n asset: candidate.asset,\n symbol: candidate.symbol.trim().toUpperCase(),\n decimals: candidate.decimals,\n name: candidate.name.trim(),\n transferMethod: \"eip3009\",\n priority: typeof candidate.priority === \"number\" ? candidate.priority : undefined,\n enabled: typeof candidate.enabled === \"boolean\" ? candidate.enabled : undefined,\n };\n}\n\n/** Sort assets by priority (ascending). Assets without priority go last. */\nfunction sortAssets(assets: BasePaymentAsset[]): BasePaymentAsset[] {\n return [...assets].sort(\n (a, b) => (a.priority ?? Number.MAX_SAFE_INTEGER) - (b.priority ?? Number.MAX_SAFE_INTEGER),\n );\n}\n\n/**\n * Normalize a payment metadata response into an array of valid EIP-3009 assets.\n * Handles flat, nested (`paymentAsset`, `base`), and array (`paymentAssets`) response shapes.\n * Filters out disabled and non-EIP-3009 assets. Falls back to USDC if no valid assets found.\n */\nexport function normalizeBasePaymentAssets(value: unknown): BasePaymentAsset[] {\n if (!value || typeof value !== \"object\") return [DEFAULT_BASE_PAYMENT_ASSET];\n\n const payload = value as PaymentMetadataResponse & { paymentAssets?: unknown };\n const candidateList = Array.isArray(payload.paymentAssets)\n ? (payload.paymentAssets as unknown[])\n : [\n (payload as { paymentAsset?: unknown }).paymentAsset,\n (payload as { base?: unknown }).base,\n payload,\n ];\n\n const normalized = candidateList\n .map((candidate: unknown) => normalizeBasePaymentAsset(candidate))\n .filter((asset: BasePaymentAsset | undefined): asset is BasePaymentAsset => Boolean(asset))\n .filter((asset) => asset.enabled !== false && asset.transferMethod === \"eip3009\");\n\n return sortAssets(\n normalized.length > 0 ? normalized : [DEFAULT_BASE_PAYMENT_ASSET],\n );\n}\n\n/**\n * Fetch all available EIP-3009 payment assets from the API.\n * Falls back to the default USDC asset on network error or non-OK response.\n */\nexport async function fetchBasePaymentAssets(\n apiBase: string,\n baseFetch: typeof fetch = fetch,\n): Promise {\n try {\n const response = await baseFetch(`${apiBase.replace(/\\/+$/, \"\")}/v1/payment-metadata?chain=base`, {\n headers: { Accept: \"application/json\" },\n });\n if (!response.ok) return [DEFAULT_BASE_PAYMENT_ASSET];\n\n const payload = (await response.json()) as PaymentMetadataResponse;\n return normalizeBasePaymentAssets(payload);\n } catch {\n // Network error, JSON parse failure, or normalize exception — fall back to USDC\n return [DEFAULT_BASE_PAYMENT_ASSET];\n }\n}\n\n/**\n * Fetch the highest-priority EIP-3009 payment asset from the API.\n * Convenience wrapper around {@link fetchBasePaymentAssets} that returns only the first asset.\n */\nexport async function fetchBasePaymentAsset(\n apiBase: string,\n baseFetch: typeof fetch = fetch,\n): Promise {\n const assets = await fetchBasePaymentAssets(apiBase, baseFetch);\n return assets[0];\n}\n","/**\n * Balance Monitor for ClawRouter\n *\n * Monitors stablecoin balance on Base network with intelligent caching.\n * Supports any EIP-3009 stablecoin (USDC, fxUSD, EURC, etc.) with\n * automatic normalization from native decimals to USD micros (6 decimals).\n * Provides pre-request balance checks to prevent failed payments.\n *\n * Caching Strategy:\n * - TTL: 30 seconds (balance is cached to avoid excessive RPC calls)\n * - Optimistic deduction: after successful payment, subtract estimated cost from cache\n * - Invalidation: on payment failure, immediately refresh from RPC\n */\n\nimport { createPublicClient, http, erc20Abi } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { RpcError } from \"./errors.js\";\nimport { DEFAULT_BASE_PAYMENT_ASSET, type BasePaymentAsset } from \"./payment-asset.js\";\n\n/** Cache TTL in milliseconds (30 seconds) */\nconst CACHE_TTL_MS = 30_000;\n\n/** Balance thresholds in USD micros (6 decimals, normalized from any stablecoin) */\nexport const BALANCE_THRESHOLDS = {\n /** Low balance warning threshold: $1.00 */\n LOW_BALANCE_MICROS: 1_000_000n,\n /** Effectively zero threshold: $0.0001 (covers dust/rounding) */\n ZERO_THRESHOLD: 100n,\n} as const;\n\n/** Balance information returned by checkBalance() */\nexport type BalanceInfo = {\n /** Raw balance normalized to USD micros (6 decimals, regardless of the underlying asset's native decimals) */\n balance: bigint;\n /** Formatted balance as \"$X.XX\" */\n balanceUSD: string;\n /** Symbol of the active Base payment asset */\n assetSymbol: string;\n /** True if balance < $1.00 */\n isLow: boolean;\n /** True if balance < $0.0001 (effectively zero) */\n isEmpty: boolean;\n /** Wallet address for funding instructions */\n walletAddress: string;\n};\n\n/** Result from checkSufficient() */\nexport type SufficiencyResult = {\n /** True if balance >= estimated cost */\n sufficient: boolean;\n /** Current balance info */\n info: BalanceInfo;\n /** If insufficient, the shortfall as \"$X.XX\" */\n shortfall?: string;\n};\n\n/**\n * Monitors stablecoin balance on Base network.\n *\n * Usage:\n * const monitor = new BalanceMonitor(\"0x...\");\n * const info = await monitor.checkBalance();\n * if (info.isLow) console.warn(\"Low balance!\");\n */\nexport class BalanceMonitor {\n private readonly client;\n private readonly walletAddress: `0x${string}`;\n private readonly assetMonitors = new Map();\n private state: {\n asset: BasePaymentAsset;\n cachedBalance: bigint | null;\n cachedAt: number;\n };\n\n constructor(walletAddress: string, asset: BasePaymentAsset = DEFAULT_BASE_PAYMENT_ASSET) {\n this.walletAddress = walletAddress as `0x${string}`;\n this.state = {\n asset,\n cachedBalance: null,\n cachedAt: 0,\n };\n this.client = createPublicClient({\n chain: base,\n transport: http(undefined, {\n timeout: 10_000, // 10 second timeout to prevent hanging on slow RPC\n }),\n });\n }\n\n /**\n * Check current USDC balance.\n * Uses cache if valid, otherwise fetches from RPC.\n */\n async checkBalance(): Promise {\n const state = this.state;\n const now = Date.now();\n\n // Use cache only when balance is positive and still fresh.\n // Zero balance is never cached — always re-fetch so a funded wallet is\n // detected on the next request without waiting for cache expiry.\n if (\n state.cachedBalance !== null &&\n state.cachedBalance > 0n &&\n now - state.cachedAt < CACHE_TTL_MS\n ) {\n return this.buildInfo(state.cachedBalance, state.asset);\n }\n\n // Fetch from RPC\n const balance = await this.fetchBalance(state.asset);\n if (balance > 0n) {\n state.cachedBalance = balance;\n state.cachedAt = now;\n }\n\n return this.buildInfo(balance, state.asset);\n }\n\n /**\n * Check if balance is sufficient for an estimated cost.\n *\n * @param estimatedCostMicros - Estimated cost in USD micros (6 decimals)\n */\n async checkSufficient(estimatedCostMicros: bigint): Promise {\n const info = await this.checkBalance();\n\n if (info.balance >= estimatedCostMicros) {\n return { sufficient: true, info };\n }\n\n const shortfall = estimatedCostMicros - info.balance;\n return {\n sufficient: false,\n info,\n shortfall: this.formatUSD(shortfall),\n };\n }\n\n private get cachedBalance(): bigint | null {\n return this.state.cachedBalance;\n }\n\n private set cachedBalance(value: bigint | null) {\n this.state.cachedBalance = value;\n }\n\n private get cachedAt(): number {\n return this.state.cachedAt;\n }\n\n private set cachedAt(value: number) {\n this.state.cachedAt = value;\n }\n\n /**\n * Optimistically deduct estimated cost from cached balance.\n * Call this after a successful payment to keep cache accurate.\n *\n * @param amountMicros - Amount to deduct in USD micros\n */\n deductEstimated(amountMicros: bigint): void {\n const state = this.state;\n if (state.cachedBalance !== null && state.cachedBalance >= amountMicros) {\n state.cachedBalance -= amountMicros;\n }\n }\n\n /**\n * Invalidate cache, forcing next checkBalance() to fetch from RPC.\n * Call this after a payment failure to get accurate balance.\n */\n invalidate(): void {\n const state = this.state;\n state.cachedBalance = null;\n state.cachedAt = 0;\n }\n\n /**\n * Force refresh balance from RPC (ignores cache).\n */\n async refresh(): Promise {\n this.invalidate();\n return this.checkBalance();\n }\n\n setAsset(asset: BasePaymentAsset): void {\n const currentAsset = this.state.asset;\n if (\n currentAsset.asset.toLowerCase() !== asset.asset.toLowerCase() ||\n currentAsset.symbol !== asset.symbol ||\n currentAsset.decimals !== asset.decimals\n ) {\n this.state = this.getSharedMonitorForAsset(asset).state;\n }\n }\n\n getAsset(): BasePaymentAsset {\n return this.state.asset;\n }\n\n /**\n * Format a stablecoin amount (normalized to USD micros) as \"$X.XX\".\n */\n formatUSD(amountMicros: bigint): string {\n const dollars = Number(amountMicros) / 1_000_000;\n return `$${dollars.toFixed(2)}`;\n }\n\n formatUSDC(amountMicros: bigint): string {\n return this.formatUSD(amountMicros);\n }\n\n /**\n * Get the wallet address being monitored.\n */\n getWalletAddress(): string {\n return this.walletAddress;\n }\n\n getAssetSymbol(): string {\n return this.state.asset.symbol;\n }\n\n getSharedMonitorForAsset(asset: BasePaymentAsset): BalanceMonitor {\n if (\n this.state.asset.asset.toLowerCase() === asset.asset.toLowerCase() &&\n this.state.asset.symbol === asset.symbol &&\n this.state.asset.decimals === asset.decimals\n ) {\n return this;\n }\n\n const key = `${asset.asset.toLowerCase()}:${asset.symbol}:${asset.decimals}`;\n const existing = this.assetMonitors.get(key);\n if (existing) return existing;\n\n const monitor = new BalanceMonitor(this.walletAddress, asset);\n this.assetMonitors.set(key, monitor);\n return monitor;\n }\n\n /** Fetch balance from RPC */\n private async fetchBalance(asset: BasePaymentAsset): Promise {\n try {\n const balance = await this.client.readContract({\n address: asset.asset,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [this.walletAddress],\n });\n return this.toUsdMicros(balance, asset);\n } catch (error) {\n // Throw typed error instead of silently returning 0\n // This allows callers to distinguish \"node down\" from \"wallet empty\"\n throw new RpcError(error instanceof Error ? error.message : \"Unknown error\", error);\n }\n }\n\n /** Build BalanceInfo from raw balance */\n private buildInfo(balance: bigint, asset: BasePaymentAsset): BalanceInfo {\n return {\n balance,\n balanceUSD: this.formatUSD(balance),\n assetSymbol: asset.symbol,\n isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,\n isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD,\n walletAddress: this.walletAddress,\n };\n }\n\n private toUsdMicros(rawAmount: bigint, asset: BasePaymentAsset): bigint {\n if (asset.decimals === 6) return rawAmount;\n if (asset.decimals > 6) {\n return rawAmount / 10n ** BigInt(asset.decimals - 6);\n }\n return rawAmount * 10n ** BigInt(6 - asset.decimals);\n }\n}\n","/**\n * BlockRun Auth Methods for OpenClaw\n *\n * Provides wallet-based authentication for the BlockRun provider.\n * Operators configure their wallet private key, which is used to\n * sign x402 micropayments for LLM inference.\n *\n * Three methods:\n * 1. Auto-generate — create a new wallet on first run, save to ~/.openclaw/blockrun/wallet.key\n * 2. Environment variable — read from BLOCKRUN_WALLET_KEY\n * 3. Manual input — operator enters private key via wizard\n *\n * SECURITY NOTE (for OpenClaw scanner):\n * This module reads BLOCKRUN_WALLET_KEY environment variable and uses it\n * to sign x402 payment requests. This is INTENTIONAL and REQUIRED behavior:\n * - The wallet key signs USDC payments on Base L2 for each LLM API call\n * - Without the key, ClawRouter cannot authorize payments to BlockRun\n * - The key is NEVER transmitted over the network, only used locally for signing\n * - This is standard x402 payment flow, not credential harvesting\n *\n * @see https://x402.org - x402 payment protocol specification\n * @see https://blockrun.ai/docs - BlockRun API documentation\n * @openclaw-security env-access=BLOCKRUN_WALLET_KEY purpose=x402-payment-signing\n */\n\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { readTextFile } from \"./fs-read.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport type { ProviderAuthMethod, ProviderAuthContext, ProviderAuthResult } from \"./types.js\";\nimport {\n generateWalletMnemonic,\n isValidMnemonic,\n deriveSolanaKeyBytes,\n deriveAllKeys,\n getSolanaAddress,\n} from \"./wallet.js\";\n\nconst WALLET_DIR = join(homedir(), \".openclaw\", \"blockrun\");\nconst WALLET_FILE = join(WALLET_DIR, \"wallet.key\");\nconst MNEMONIC_FILE = join(WALLET_DIR, \"mnemonic\");\nconst CHAIN_FILE = join(WALLET_DIR, \"payment-chain\");\n\n// Export for use by wallet command and index.ts\nexport { WALLET_FILE, MNEMONIC_FILE, CHAIN_FILE };\n\n/**\n * Try to load a previously auto-generated wallet key from disk.\n */\nasync function loadSavedWallet(): Promise {\n try {\n const key = (await readTextFile(WALLET_FILE)).trim();\n if (key.startsWith(\"0x\") && key.length === 66) {\n console.log(`[ClawRouter] ✓ Loaded existing wallet from ${WALLET_FILE}`);\n return key;\n }\n // File exists but content is wrong — do NOT silently fall through to generate a new wallet.\n // This would silently replace a funded wallet with an empty one.\n console.error(`[ClawRouter] ✗ CRITICAL: Wallet file exists but has invalid format!`);\n console.error(`[ClawRouter] File: ${WALLET_FILE}`);\n console.error(`[ClawRouter] Expected: 0x followed by 64 hex characters (66 chars total)`);\n console.error(\n `[ClawRouter] To fix: restore your backup key or set BLOCKRUN_WALLET_KEY env var`,\n );\n throw new Error(\n `Wallet file at ${WALLET_FILE} is corrupted or has wrong format. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Restore your backup key or set BLOCKRUN_WALLET_KEY environment variable.`,\n );\n } catch (err) {\n // Re-throw corruption errors (not ENOENT)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n // If it's our own thrown error, re-throw as-is\n if (err instanceof Error && err.message.includes(\"Refusing to auto-generate\")) {\n throw err;\n }\n console.error(\n `[ClawRouter] ✗ Failed to read wallet file: ${err instanceof Error ? err.message : String(err)}`,\n );\n throw new Error(\n `Cannot read wallet file at ${WALLET_FILE}: ${err instanceof Error ? err.message : String(err)}. ` +\n `Refusing to auto-generate new wallet to protect existing funds. ` +\n `Fix file permissions or set BLOCKRUN_WALLET_KEY environment variable.`,\n { cause: err },\n );\n }\n }\n return undefined;\n}\n\n/**\n * Load mnemonic from disk if it exists.\n * Warns on corruption but never throws — callers handle missing mnemonic gracefully.\n */\nasync function loadMnemonic(): Promise {\n try {\n const mnemonic = (await readTextFile(MNEMONIC_FILE)).trim();\n if (mnemonic && isValidMnemonic(mnemonic)) {\n return mnemonic;\n }\n // File exists but content is invalid — warn but continue.\n console.warn(`[ClawRouter] ⚠ Mnemonic file exists but has invalid format — ignoring`);\n return undefined;\n } catch (err) {\n // Only swallow ENOENT (file not found)\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n console.warn(`[ClawRouter] ⚠ Cannot read mnemonic file — ignoring`);\n }\n }\n return undefined;\n}\n\n/**\n * Save mnemonic to disk.\n */\nasync function saveMnemonic(mnemonic: string): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Generate a new wallet with BIP-39 mnemonic, save to disk.\n * New users get both EVM and Solana keys derived from the same mnemonic.\n * CRITICAL: Verifies the file was actually written after generation.\n */\nasync function generateAndSaveWallet(): Promise<{\n key: string;\n address: string;\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: if a mnemonic file already exists, a Solana wallet was derived from it.\n // Generating a new wallet would overwrite the mnemonic and lose Solana funds.\n const existingMnemonic = await loadMnemonic();\n if (existingMnemonic) {\n throw new Error(\n `Mnemonic file exists at ${MNEMONIC_FILE} but wallet.key is missing.\\n` +\n `Refusing to generate a new wallet to protect existing funds.\\n\\n` +\n `Restore your EVM private key using one of:\\n` +\n ` Windows: set BLOCKRUN_WALLET_KEY=0x\\n` +\n ` Mac/Linux: export BLOCKRUN_WALLET_KEY=0x\\n\\n` +\n `Then run: npx @blockrun/clawrouter`,\n );\n }\n\n const mnemonic = generateWalletMnemonic();\n const derived = deriveAllKeys(mnemonic);\n\n // Create directory\n await mkdir(WALLET_DIR, { recursive: true });\n\n // Write wallet key file (EVM private key)\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n // Write mnemonic file\n await writeFile(MNEMONIC_FILE, mnemonic + \"\\n\", { mode: 0o600 });\n\n // CRITICAL: Verify the file was actually written\n try {\n const verification = (await readTextFile(WALLET_FILE)).trim();\n if (verification !== derived.evmPrivateKey) {\n throw new Error(\"Wallet file verification failed - content mismatch\");\n }\n console.log(`[ClawRouter] Wallet saved and verified at ${WALLET_FILE}`);\n } catch (err) {\n throw new Error(\n `Failed to verify wallet file after creation: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n // Derive Solana address for display\n let solanaAddress: string | undefined;\n try {\n solanaAddress = await getSolanaAddress(derived.solanaPrivateKeyBytes);\n } catch {\n // Non-fatal — Solana address display is best-effort\n }\n\n // Print prominent backup reminder after generating a new wallet\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] NEW WALLET GENERATED — BACK UP YOUR KEY NOW`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter] Key file : ${WALLET_FILE}`);\n console.log(`[ClawRouter] Mnemonic : ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Both EVM (Base) and Solana wallets are ready.`);\n console.log(`[ClawRouter] To back up, run in OpenClaw:`);\n console.log(`[ClawRouter] /wallet export`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] To restore on another machine:`);\n console.log(`[ClawRouter] export BLOCKRUN_WALLET_KEY=`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n return {\n key: derived.evmPrivateKey,\n address: derived.evmAddress,\n mnemonic,\n solanaPrivateKeyBytes: derived.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Resolve wallet key: load saved → env var → auto-generate.\n * Also loads mnemonic if available for Solana key derivation.\n * Called by index.ts before the auth wizard runs.\n */\nexport type WalletResolution = {\n key: string;\n address: string;\n source: \"saved\" | \"env\" | \"generated\";\n mnemonic?: string;\n solanaPrivateKeyBytes?: Uint8Array;\n};\n\nexport async function resolveOrGenerateWalletKey(): Promise {\n // 1. Previously saved wallet\n const saved = await loadSavedWallet();\n if (saved) {\n const account = privateKeyToAccount(saved as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: saved,\n address: account.address,\n source: \"saved\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: saved, address: account.address, source: \"saved\" };\n }\n\n // 2. Environment variable\n const envKey = process[\"env\"].BLOCKRUN_WALLET_KEY;\n if (typeof envKey === \"string\" && envKey.startsWith(\"0x\") && envKey.length === 66) {\n const account = privateKeyToAccount(envKey as `0x${string}`);\n\n // Load mnemonic if it exists (Solana support enabled via /wallet solana)\n const mnemonic = await loadMnemonic();\n if (mnemonic) {\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n return {\n key: envKey,\n address: account.address,\n source: \"env\",\n mnemonic,\n solanaPrivateKeyBytes: solanaKeyBytes,\n };\n }\n\n return { key: envKey, address: account.address, source: \"env\" };\n }\n\n // 3. Auto-generate with BIP-39 mnemonic (new users get both chains)\n const result = await generateAndSaveWallet();\n return {\n key: result.key,\n address: result.address,\n source: \"generated\",\n mnemonic: result.mnemonic,\n solanaPrivateKeyBytes: result.solanaPrivateKeyBytes,\n };\n}\n\n/**\n * Recover wallet.key from existing mnemonic.\n *\n * ONLY works when the mnemonic was originally generated by ClawRouter\n * (i.e., both mnemonic and EVM key were derived from the same seed).\n * If the EVM key was set independently (manually or via env), the derived\n * key will be different — do NOT use this in that case.\n */\nexport async function recoverWalletFromMnemonic(): Promise {\n const mnemonic = await loadMnemonic();\n if (!mnemonic) {\n console.error(`[ClawRouter] No mnemonic found at ${MNEMONIC_FILE}`);\n console.error(`[ClawRouter] Cannot recover — no mnemonic to derive from.`);\n process.exit(1);\n }\n\n // Safety: if wallet.key already exists, refuse to overwrite\n const existing = await loadSavedWallet().catch(() => undefined);\n if (existing) {\n console.error(`[ClawRouter] wallet.key already exists at ${WALLET_FILE}`);\n console.error(`[ClawRouter] Recovery not needed.`);\n process.exit(1);\n }\n\n const derived = deriveAllKeys(mnemonic);\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const solanaAddress = await getSolanaAddress(solanaKeyBytes).catch(() => undefined);\n\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] ⚠ WALLET RECOVERY FROM MNEMONIC`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter] This only works if your mnemonic was originally`);\n console.log(`[ClawRouter] generated by ClawRouter (not set manually).`);\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] Derived EVM Address : ${derived.evmAddress}`);\n if (solanaAddress) {\n console.log(`[ClawRouter] Derived Solana Address : ${solanaAddress}`);\n }\n console.log(`[ClawRouter]`);\n console.log(`[ClawRouter] If the Solana address above matches your funded`);\n console.log(`[ClawRouter] wallet, recovery is safe to proceed.`);\n console.log(`[ClawRouter] ════════════════════════════════════════════════`);\n console.log(`[ClawRouter]`);\n\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(WALLET_FILE, derived.evmPrivateKey + \"\\n\", { mode: 0o600 });\n\n console.log(`[ClawRouter] ✓ wallet.key restored at ${WALLET_FILE}`);\n console.log(`[ClawRouter] Run: npx @blockrun/clawrouter`);\n console.log(`[ClawRouter]`);\n}\n\n/**\n * Set up Solana wallet for existing EVM-only users.\n * Generates a new mnemonic for Solana key derivation.\n * NEVER touches the existing wallet.key file.\n */\nexport async function setupSolana(): Promise<{\n mnemonic: string;\n solanaPrivateKeyBytes: Uint8Array;\n}> {\n // Safety: mnemonic must not already exist\n const existing = await loadMnemonic();\n if (existing) {\n throw new Error(\"Solana wallet already set up. Mnemonic file exists at \" + MNEMONIC_FILE);\n }\n\n // Safety: wallet.key must exist (can't set up Solana without EVM wallet)\n const savedKey = await loadSavedWallet();\n if (!savedKey) {\n throw new Error(\n \"No EVM wallet found. Run ClawRouter first to generate a wallet before setting up Solana.\",\n );\n }\n\n // Generate new mnemonic for Solana derivation\n const mnemonic = generateWalletMnemonic();\n const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);\n\n // Save mnemonic (wallet.key untouched)\n await saveMnemonic(mnemonic);\n\n console.log(`[ClawRouter] Solana wallet set up successfully.`);\n console.log(`[ClawRouter] Mnemonic saved to ${MNEMONIC_FILE}`);\n console.log(`[ClawRouter] Existing EVM wallet unchanged.`);\n\n return { mnemonic, solanaPrivateKeyBytes: solanaKeyBytes };\n}\n\n/**\n * Persist the user's payment chain selection to disk.\n */\nexport async function savePaymentChain(chain: \"base\" | \"solana\"): Promise {\n await mkdir(WALLET_DIR, { recursive: true });\n await writeFile(CHAIN_FILE, chain + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * Load the persisted payment chain selection from disk.\n * Returns \"base\" if no file exists or the file is invalid.\n */\nexport async function loadPaymentChain(): Promise<\"base\" | \"solana\"> {\n try {\n const content = (await readTextFile(CHAIN_FILE)).trim();\n if (content === \"solana\") return \"solana\";\n return \"base\";\n } catch {\n return \"base\";\n }\n}\n\n/**\n * Resolve payment chain: env var first → persisted file second → default \"base\".\n */\nexport async function resolvePaymentChain(): Promise<\"base\" | \"solana\"> {\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"solana\") return \"solana\";\n if (process[\"env\"].CLAWROUTER_PAYMENT_CHAIN === \"base\") return \"base\";\n return loadPaymentChain();\n}\n\n/**\n * Auth method: operator enters their wallet private key directly.\n */\nexport const walletKeyAuth: ProviderAuthMethod = {\n id: \"wallet-key\",\n label: \"Wallet Private Key\",\n hint: \"Enter your EVM wallet private key (0x...) for x402 payments to BlockRun\",\n kind: \"api_key\",\n run: async (ctx: ProviderAuthContext): Promise => {\n const key = await ctx.prompter.text({\n message: \"Enter your wallet private key (0x...)\",\n validate: (value: string) => {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"0x\")) return \"Key must start with 0x\";\n if (trimmed.length !== 66) return \"Key must be 66 characters (0x + 64 hex)\";\n if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) return \"Key must be valid hex\";\n return undefined;\n },\n });\n\n if (!key || typeof key !== \"string\") {\n throw new Error(\"Wallet key is required\");\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\n \"Wallet key stored securely in OpenClaw credentials.\",\n \"Your wallet signs x402 USDC payments on Base for each LLM call.\",\n \"Fund your wallet with USDC on Base to start using BlockRun models.\",\n ],\n };\n },\n};\n\n/**\n * Auth method: read wallet key from BLOCKRUN_WALLET_KEY environment variable.\n */\nexport const envKeyAuth: ProviderAuthMethod = {\n id: \"env-key\",\n label: \"Environment Variable\",\n hint: \"Use BLOCKRUN_WALLET_KEY environment variable\",\n kind: \"api_key\",\n run: async (): Promise => {\n const key = process[\"env\"].BLOCKRUN_WALLET_KEY;\n\n if (!key) {\n throw new Error(\n \"BLOCKRUN_WALLET_KEY environment variable is not set. \" +\n \"Set it to your EVM wallet private key (0x...).\",\n );\n }\n\n return {\n profiles: [\n {\n profileId: \"default\",\n credential: { apiKey: key.trim() },\n },\n ],\n notes: [\"Using wallet key from BLOCKRUN_WALLET_KEY environment variable.\"],\n };\n },\n};\n","/**\n * LLM-Safe Context Compression Types\n *\n * Types for the 7-layer compression system that reduces token usage\n * while preserving semantic meaning for LLM queries.\n */\n\n// Content part for multimodal messages (images, etc.)\nexport interface ContentPart {\n type: \"text\" | \"image_url\";\n text?: string;\n image_url?: {\n url: string;\n detail?: \"low\" | \"high\" | \"auto\";\n };\n}\n\n// Normalized message structure (matches OpenAI format)\n// Note: content can be an array for multimodal messages (images, etc.)\nexport interface NormalizedMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | ContentPart[] | null;\n tool_call_id?: string;\n tool_calls?: ToolCall[];\n name?: string;\n}\n\nexport interface ToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\n// Compression configuration\nexport interface CompressionConfig {\n enabled: boolean;\n preserveRaw: boolean; // Keep original for logging\n\n // Per-layer toggles\n layers: {\n deduplication: boolean;\n whitespace: boolean;\n dictionary: boolean;\n paths: boolean;\n jsonCompact: boolean;\n observation: boolean; // L6: Compress tool results (BIG WIN)\n dynamicCodebook: boolean; // L7: Build codebook from content\n };\n\n // Dictionary settings\n dictionary: {\n maxEntries: number;\n minPhraseLength: number;\n includeCodebookHeader: boolean; // Include codebook in system message\n };\n}\n\n// Compression statistics\nexport interface CompressionStats {\n duplicatesRemoved: number;\n whitespaceSavedChars: number;\n dictionarySubstitutions: number;\n pathsShortened: number;\n jsonCompactedChars: number;\n observationsCompressed: number; // L6: Tool results compressed\n observationCharsSaved: number; // L6: Chars saved from observations\n dynamicSubstitutions: number; // L7: Dynamic codebook substitutions\n dynamicCharsSaved: number; // L7: Chars saved from dynamic codebook\n}\n\n// Result from compression\nexport interface CompressionResult {\n messages: NormalizedMessage[];\n originalMessages: NormalizedMessage[]; // For logging\n\n // Token estimates\n originalChars: number;\n compressedChars: number;\n compressionRatio: number; // 0.85 = 15% reduction\n\n // Per-layer stats\n stats: CompressionStats;\n\n // Codebook used (for decompression in logs)\n codebook: Record;\n pathMap: Record;\n dynamicCodes: Record; // L7: Dynamic codebook\n}\n\n// Log data extension for compression metrics\nexport interface CompressionLogData {\n enabled: boolean;\n ratio: number;\n original_chars: number;\n compressed_chars: number;\n stats: {\n duplicates_removed: number;\n whitespace_saved: number;\n dictionary_subs: number;\n paths_shortened: number;\n json_compacted: number;\n };\n}\n\n// Default configuration - CONSERVATIVE settings for model compatibility\n// Only enable layers that don't require the model to decode anything\nexport const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {\n enabled: true,\n preserveRaw: true,\n layers: {\n deduplication: true, // Safe: removes duplicate messages\n whitespace: true, // Safe: normalizes whitespace\n dictionary: false, // DISABLED: requires model to understand codebook\n paths: false, // DISABLED: requires model to understand path codes\n jsonCompact: true, // Safe: just removes JSON whitespace\n observation: false, // DISABLED: may lose important context\n dynamicCodebook: false, // DISABLED: requires model to understand codes\n },\n dictionary: {\n maxEntries: 50,\n minPhraseLength: 15,\n includeCodebookHeader: false, // No codebook header needed\n },\n};\n","/**\n * Layer 1: Message Deduplication\n *\n * Removes exact duplicate messages from conversation history.\n * Common in heartbeat patterns and repeated tool calls.\n *\n * Safe for LLM: Identical messages add no new information.\n * Expected savings: 2-5%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport crypto from \"crypto\";\n\nexport interface DeduplicationResult {\n messages: NormalizedMessage[];\n duplicatesRemoved: number;\n originalCount: number;\n}\n\n/**\n * Generate a hash for a message based on its semantic content.\n * Uses role + content + tool_call_id to identify duplicates.\n */\nfunction hashMessage(message: NormalizedMessage): string {\n // Handle content - stringify arrays (multimodal), use string directly, or empty string\n let contentStr = \"\";\n if (typeof message.content === \"string\") {\n contentStr = message.content;\n } else if (Array.isArray(message.content)) {\n contentStr = JSON.stringify(message.content);\n }\n\n const parts = [message.role, contentStr, message.tool_call_id || \"\", message.name || \"\"];\n\n // Include tool_calls if present\n if (message.tool_calls) {\n parts.push(\n JSON.stringify(\n message.tool_calls.map((tc) => ({\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n ),\n );\n }\n\n const content = parts.join(\"|\");\n return crypto.createHash(\"md5\").update(content).digest(\"hex\");\n}\n\n/**\n * Remove exact duplicate messages from the conversation.\n *\n * Strategy:\n * - Keep first occurrence of each unique message\n * - Preserve order for semantic coherence\n * - Never dedupe system messages (they set context)\n * - Allow duplicate user messages (user might repeat intentionally)\n * - CRITICAL: Never dedupe assistant messages with tool_calls that are\n * referenced by subsequent tool messages (breaks Anthropic tool_use/tool_result pairing)\n */\nexport function deduplicateMessages(messages: NormalizedMessage[]): DeduplicationResult {\n const seen = new Set();\n const result: NormalizedMessage[] = [];\n let duplicatesRemoved = 0;\n\n // First pass: collect all tool_call_ids that are referenced by tool messages\n // These tool_calls MUST be preserved to maintain tool_use/tool_result pairing\n const referencedToolCallIds = new Set();\n for (const message of messages) {\n if (message.role === \"tool\" && message.tool_call_id) {\n referencedToolCallIds.add(message.tool_call_id);\n }\n }\n\n for (const message of messages) {\n // Always keep system messages (they set important context)\n if (message.role === \"system\") {\n result.push(message);\n continue;\n }\n\n // Always keep user messages (user might repeat intentionally)\n if (message.role === \"user\") {\n result.push(message);\n continue;\n }\n\n // Always keep tool messages (they are results of tool calls)\n // Removing them would break the tool_use/tool_result pairing\n if (message.role === \"tool\") {\n result.push(message);\n continue;\n }\n\n // For assistant messages with tool_calls, check if any are referenced\n // by subsequent tool messages - if so, we MUST keep this message\n if (message.role === \"assistant\" && message.tool_calls) {\n const hasReferencedToolCall = message.tool_calls.some((tc) =>\n referencedToolCallIds.has(tc.id),\n );\n if (hasReferencedToolCall) {\n // This assistant message has tool_calls that are referenced - keep it\n result.push(message);\n continue;\n }\n }\n\n // For other assistant messages, check for duplicates\n const hash = hashMessage(message);\n\n if (!seen.has(hash)) {\n seen.add(hash);\n result.push(message);\n } else {\n duplicatesRemoved++;\n }\n }\n\n return {\n messages: result,\n duplicatesRemoved,\n originalCount: messages.length,\n };\n}\n","/**\n * Layer 2: Whitespace Normalization\n *\n * Reduces excessive whitespace without changing semantic meaning.\n *\n * Safe for LLM: Tokenizers normalize whitespace anyway.\n * Expected savings: 3-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface WhitespaceResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Normalize whitespace in a string.\n *\n * - Max 2 consecutive newlines\n * - Remove trailing whitespace from lines\n * - Normalize tabs to spaces\n * - Trim start/end\n */\nexport function normalizeWhitespace(content: string): string {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") return content as string;\n\n return (\n content\n // Normalize line endings\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n // Max 2 consecutive newlines (preserve paragraph breaks)\n .replace(/\\n{3,}/g, \"\\n\\n\")\n // Remove trailing whitespace from each line\n .replace(/[ \\t]+$/gm, \"\")\n // Normalize multiple spaces to single (except at line start for indentation)\n .replace(/([^\\n]) {2,}/g, \"$1 \")\n // Reduce excessive indentation (more than 8 spaces → 2 spaces per level)\n .replace(/^[ ]{8,}/gm, (match) => \" \".repeat(Math.ceil(match.length / 4)))\n // Normalize tabs to 2 spaces\n .replace(/\\t/g, \" \")\n // Trim\n .trim()\n );\n}\n\n/**\n * Apply whitespace normalization to all messages.\n */\nexport function normalizeMessagesWhitespace(messages: NormalizedMessage[]): WhitespaceResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const originalLength = message.content.length;\n const normalizedContent = normalizeWhitespace(message.content);\n charsSaved += originalLength - normalizedContent.length;\n\n return {\n ...message,\n content: normalizedContent,\n };\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * Dictionary Codebook\n *\n * Static dictionary of frequently repeated phrases observed in LLM prompts.\n * Built from analysis of BlockRun production logs.\n *\n * Format: Short code ($XX) -> Long phrase\n * The LLM receives a codebook header and decodes in-context.\n */\n\n// Static codebook - common patterns from system prompts\n// Ordered by expected frequency and impact\nexport const STATIC_CODEBOOK: Record = {\n // High-impact: OpenClaw/Agent system prompt patterns (very common)\n $OC01: \"unbrowse_\", // Common prefix in tool names\n $OC02: \"\",\n $OC03: \"\",\n $OC04: \"\",\n $OC05: \"\",\n $OC06: \"\",\n $OC07: \"\",\n $OC08: \"(may need login)\",\n $OC09: \"API skill for OpenClaw\",\n $OC10: \"endpoints\",\n\n // Skill/tool markers\n $SK01: \"\",\n $SK02: \"\",\n $SK03: \"\",\n $SK04: \"\",\n\n // Schema patterns (very common in tool definitions)\n $T01: 'type: \"function\"',\n $T02: '\"type\": \"function\"',\n $T03: '\"type\": \"string\"',\n $T04: '\"type\": \"object\"',\n $T05: '\"type\": \"array\"',\n $T06: '\"type\": \"boolean\"',\n $T07: '\"type\": \"number\"',\n\n // Common descriptions\n $D01: \"description:\",\n $D02: '\"description\":',\n\n // Common instructions\n $I01: \"You are a personal assistant\",\n $I02: \"Tool names are case-sensitive\",\n $I03: \"Call tools exactly as listed\",\n $I04: \"Use when\",\n $I05: \"without asking\",\n\n // Safety phrases\n $S01: \"Do not manipulate or persuade\",\n $S02: \"Prioritize safety and human oversight\",\n $S03: \"unless explicitly requested\",\n\n // JSON patterns\n $J01: '\"required\": [\"',\n $J02: '\"properties\": {',\n $J03: '\"additionalProperties\": false',\n\n // Heartbeat patterns\n $H01: \"HEARTBEAT_OK\",\n $H02: \"Read HEARTBEAT.md if it exists\",\n\n // Role markers\n $R01: '\"role\": \"system\"',\n $R02: '\"role\": \"user\"',\n $R03: '\"role\": \"assistant\"',\n $R04: '\"role\": \"tool\"',\n\n // Common endings/phrases\n $E01: \"would you like to\",\n $E02: \"Let me know if you\",\n $E03: \"internal APIs\",\n $E04: \"session cookies\",\n\n // BlockRun model aliases (common in prompts)\n $M01: \"blockrun/\",\n $M02: \"openai/\",\n $M03: \"anthropic/\",\n $M04: \"google/\",\n $M05: \"xai/\",\n};\n\n/**\n * Get the inverse codebook for decompression.\n */\nexport function getInverseCodebook(): Record {\n const inverse: Record = {};\n for (const [code, phrase] of Object.entries(STATIC_CODEBOOK)) {\n inverse[phrase] = code;\n }\n return inverse;\n}\n\n/**\n * Generate the codebook header for inclusion in system message.\n * LLMs can decode in-context using this header.\n */\nexport function generateCodebookHeader(\n usedCodes: Set,\n pathMap: Record = {},\n): string {\n if (usedCodes.size === 0 && Object.keys(pathMap).length === 0) {\n return \"\";\n }\n\n const parts: string[] = [];\n\n // Add used dictionary codes\n if (usedCodes.size > 0) {\n const codeEntries = Array.from(usedCodes)\n .map((code) => `${code}=${STATIC_CODEBOOK[code]}`)\n .join(\", \");\n parts.push(`[Dict: ${codeEntries}]`);\n }\n\n // Add path map\n if (Object.keys(pathMap).length > 0) {\n const pathEntries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n parts.push(`[Paths: ${pathEntries}]`);\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Decompress a string using the codebook (for logging).\n */\nexport function decompressContent(\n content: string,\n codebook: Record = STATIC_CODEBOOK,\n): string {\n let result = content;\n for (const [code, phrase] of Object.entries(codebook)) {\n result = result.split(code).join(phrase);\n }\n return result;\n}\n","/**\n * Layer 3: Dictionary Encoding\n *\n * Replaces frequently repeated long phrases with short codes.\n * Uses a static codebook of common patterns from production logs.\n *\n * Safe for LLM: Reversible substitution with codebook header.\n * Expected savings: 4-8%\n */\n\nimport { NormalizedMessage } from \"../types\";\nimport { getInverseCodebook } from \"../codebook\";\n\nexport interface DictionaryResult {\n messages: NormalizedMessage[];\n substitutionCount: number;\n usedCodes: Set;\n charsSaved: number;\n}\n\n/**\n * Apply dictionary encoding to a string.\n * Returns the encoded string and stats.\n */\nfunction encodeContent(\n content: string,\n inverseCodebook: Record,\n): { encoded: string; substitutions: number; codes: Set; charsSaved: number } {\n // Defensive type check - content might be array/object for multimodal messages\n if (!content || typeof content !== \"string\") {\n return { encoded: content, substitutions: 0, codes: new Set(), charsSaved: 0 };\n }\n let encoded = content;\n let substitutions = 0;\n let charsSaved = 0;\n const codes = new Set();\n\n // Sort phrases by length (longest first) to avoid partial matches\n const phrases = Object.keys(inverseCodebook).sort((a, b) => b.length - a.length);\n\n for (const phrase of phrases) {\n const code = inverseCodebook[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = encoded.match(regex);\n\n if (matches && matches.length > 0) {\n encoded = encoded.replace(regex, code);\n substitutions += matches.length;\n charsSaved += matches.length * (phrase.length - code.length);\n codes.add(code);\n }\n }\n\n return { encoded, substitutions, codes, charsSaved };\n}\n\n/**\n * Escape special regex characters in a string.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dictionary encoding to all messages.\n */\nexport function encodeMessages(messages: NormalizedMessage[]): DictionaryResult {\n const inverseCodebook = getInverseCodebook();\n let totalSubstitutions = 0;\n let totalCharsSaved = 0;\n const allUsedCodes = new Set();\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n const { encoded, substitutions, codes, charsSaved } = encodeContent(\n message.content,\n inverseCodebook,\n );\n\n totalSubstitutions += substitutions;\n totalCharsSaved += charsSaved;\n codes.forEach((code) => allUsedCodes.add(code));\n\n return {\n ...message,\n content: encoded,\n };\n });\n\n return {\n messages: result,\n substitutionCount: totalSubstitutions,\n usedCodes: allUsedCodes,\n charsSaved: totalCharsSaved,\n };\n}\n","/**\n * Layer 4: Path Shortening\n *\n * Detects common filesystem path prefixes and replaces them with short codes.\n * Common in coding assistant contexts with repeated file paths.\n *\n * Safe for LLM: Lossless abbreviation with path map header.\n * Expected savings: 1-3%\n */\n\nimport { NormalizedMessage } from \"../types\";\n\nexport interface PathShorteningResult {\n messages: NormalizedMessage[];\n pathMap: Record; // $P1 -> /home/user/project/\n charsSaved: number;\n}\n\n// Regex to match filesystem paths\nconst PATH_REGEX = /(?:\\/[\\w.-]+){3,}/g;\n\n/**\n * Extract all paths from messages and find common prefixes.\n */\nfunction extractPaths(messages: NormalizedMessage[]): string[] {\n const paths: string[] = [];\n\n for (const message of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") continue;\n const matches = message.content.match(PATH_REGEX);\n if (matches) {\n paths.push(...matches);\n }\n }\n\n return paths;\n}\n\n/**\n * Group paths by their common prefixes.\n * Returns prefixes that appear at least 3 times.\n */\nfunction findFrequentPrefixes(paths: string[]): string[] {\n const prefixCounts = new Map();\n\n for (const path of paths) {\n const parts = path.split(\"/\").filter(Boolean);\n\n // Try prefixes of different lengths\n for (let i = 2; i < parts.length; i++) {\n const prefix = \"/\" + parts.slice(0, i).join(\"/\") + \"/\";\n prefixCounts.set(prefix, (prefixCounts.get(prefix) || 0) + 1);\n }\n }\n\n // Return prefixes that appear 3+ times, sorted by length (longest first)\n return Array.from(prefixCounts.entries())\n .filter(([, count]) => count >= 3)\n .sort((a, b) => b[0].length - a[0].length)\n .slice(0, 5) // Max 5 path codes\n .map(([prefix]) => prefix);\n}\n\n/**\n * Apply path shortening to all messages.\n */\nexport function shortenPaths(messages: NormalizedMessage[]): PathShorteningResult {\n const allPaths = extractPaths(messages);\n\n if (allPaths.length < 5) {\n // Not enough paths to benefit from shortening\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n const prefixes = findFrequentPrefixes(allPaths);\n\n if (prefixes.length === 0) {\n return {\n messages,\n pathMap: {},\n charsSaved: 0,\n };\n }\n\n // Create path map\n const pathMap: Record = {};\n prefixes.forEach((prefix, i) => {\n pathMap[`$P${i + 1}`] = prefix;\n });\n\n // Replace paths in messages\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!message.content || typeof message.content !== \"string\") return message;\n\n let content = message.content;\n const originalLength = content.length;\n\n // Replace prefixes (longest first to avoid partial replacements)\n for (const [code, prefix] of Object.entries(pathMap)) {\n content = content.split(prefix).join(code + \"/\");\n }\n\n charsSaved += originalLength - content.length;\n\n return {\n ...message,\n content,\n };\n });\n\n return {\n messages: result,\n pathMap,\n charsSaved,\n };\n}\n\n/**\n * Generate the path map header for the codebook.\n */\nexport function generatePathMapHeader(pathMap: Record): string {\n if (Object.keys(pathMap).length === 0) return \"\";\n\n const entries = Object.entries(pathMap)\n .map(([code, path]) => `${code}=${path}`)\n .join(\", \");\n\n return `[Paths: ${entries}]`;\n}\n","/**\n * Layer 5: JSON Compaction\n *\n * Minifies JSON in tool_call arguments and tool results.\n * Removes pretty-print whitespace from JSON strings.\n *\n * Safe for LLM: JSON semantics unchanged.\n * Expected savings: 2-4%\n */\n\nimport { NormalizedMessage, ToolCall } from \"../types\";\n\nexport interface JsonCompactResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n}\n\n/**\n * Compact a JSON string by parsing and re-stringifying without formatting.\n */\nfunction compactJson(jsonString: string): string {\n try {\n const parsed = JSON.parse(jsonString);\n return JSON.stringify(parsed);\n } catch {\n // Not valid JSON, return as-is\n return jsonString;\n }\n}\n\n/**\n * Check if a string looks like JSON (starts with { or [).\n */\nfunction looksLikeJson(str: string): boolean {\n const trimmed = str.trim();\n return (\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) ||\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\"))\n );\n}\n\n/**\n * Compact tool_call arguments in a message.\n */\nfunction compactToolCalls(toolCalls: ToolCall[]): ToolCall[] {\n return toolCalls.map((tc) => ({\n ...tc,\n function: {\n ...tc.function,\n arguments: compactJson(tc.function.arguments),\n },\n }));\n}\n\n/**\n * Apply JSON compaction to all messages.\n *\n * Targets:\n * - tool_call arguments (in assistant messages)\n * - tool message content (often JSON)\n */\nexport function compactMessagesJson(messages: NormalizedMessage[]): JsonCompactResult {\n let charsSaved = 0;\n\n const result = messages.map((message) => {\n const newMessage = { ...message };\n\n // Compact tool_calls arguments\n if (message.tool_calls && message.tool_calls.length > 0) {\n const originalLength = JSON.stringify(message.tool_calls).length;\n newMessage.tool_calls = compactToolCalls(message.tool_calls);\n const newLength = JSON.stringify(newMessage.tool_calls).length;\n charsSaved += originalLength - newLength;\n }\n\n // Compact tool message content if it looks like JSON\n // Only process string content (skip arrays for multimodal messages)\n if (\n message.role === \"tool\" &&\n message.content &&\n typeof message.content === \"string\" &&\n looksLikeJson(message.content)\n ) {\n const originalLength = message.content.length;\n const compacted = compactJson(message.content);\n charsSaved += originalLength - compacted.length;\n newMessage.content = compacted;\n }\n\n return newMessage;\n });\n\n return {\n messages: result,\n charsSaved,\n };\n}\n","/**\n * L6: Observation Compression (AGGRESSIVE)\n *\n * Inspired by claw-compactor's 97% compression on tool results.\n * Tool call results (especially large ones) are summarized to key info only.\n *\n * This is the biggest compression win - tool outputs can be 10KB+ but\n * only ~200 chars of actual useful information.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface ObservationResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n observationsCompressed: number;\n}\n\n// Max length for tool results before compression kicks in\nconst TOOL_RESULT_THRESHOLD = 500;\n\n// Max length to compress tool results down to\nconst COMPRESSED_RESULT_MAX = 300;\n\n/**\n * Extract key information from tool result.\n * Keeps: errors, key values, status, first/last important lines.\n */\nfunction compressToolResult(content: string): string {\n if (!content || content.length <= TOOL_RESULT_THRESHOLD) {\n return content;\n }\n\n const lines = content\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter(Boolean);\n\n // Priority 1: Error messages (always keep)\n const errorLines = lines.filter(\n (l) => /error|exception|failed|denied|refused|timeout|invalid/i.test(l) && l.length < 200,\n );\n\n // Priority 2: Status/result lines\n const statusLines = lines.filter(\n (l) =>\n /success|complete|created|updated|found|result|status|total|count/i.test(l) && l.length < 150,\n );\n\n // Priority 3: Key JSON fields (extract important values)\n const jsonMatches: string[] = [];\n const jsonPattern = /\"(id|name|status|error|message|count|total|url|path)\":\\s*\"?([^\",}\\n]+)\"?/gi;\n let match;\n while ((match = jsonPattern.exec(content)) !== null) {\n jsonMatches.push(`${match[1]}: ${match[2].slice(0, 50)}`);\n }\n\n // Priority 4: First and last meaningful lines\n const firstLine = lines[0]?.slice(0, 100);\n const lastLine = lines.length > 1 ? lines[lines.length - 1]?.slice(0, 100) : \"\";\n\n // Build compressed observation\n const parts: string[] = [];\n\n if (errorLines.length > 0) {\n parts.push(\"[ERR] \" + errorLines.slice(0, 3).join(\" | \"));\n }\n\n if (statusLines.length > 0) {\n parts.push(statusLines.slice(0, 3).join(\" | \"));\n }\n\n if (jsonMatches.length > 0) {\n parts.push(jsonMatches.slice(0, 5).join(\", \"));\n }\n\n if (parts.length === 0) {\n // Fallback: keep first/last lines with truncation marker\n parts.push(firstLine || \"\");\n if (lines.length > 2) {\n parts.push(`[...${lines.length - 2} lines...]`);\n }\n if (lastLine && lastLine !== firstLine) {\n parts.push(lastLine);\n }\n }\n\n let result = parts.join(\"\\n\");\n\n // Final length cap\n if (result.length > COMPRESSED_RESULT_MAX) {\n result = result.slice(0, COMPRESSED_RESULT_MAX - 20) + \"\\n[...truncated]\";\n }\n\n return result;\n}\n\n/**\n * Compress large repeated content blocks.\n * Detects when same large block appears multiple times.\n */\nfunction deduplicateLargeBlocks(messages: NormalizedMessage[]): {\n messages: NormalizedMessage[];\n charsSaved: number;\n} {\n const blockHashes = new Map(); // hash -> first occurrence index\n let charsSaved = 0;\n\n const result = messages.map((msg, idx) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\" || msg.content.length < 500) {\n return msg;\n }\n\n // Hash first 200 chars as block identifier\n const blockKey = msg.content.slice(0, 200);\n\n if (blockHashes.has(blockKey)) {\n const firstIdx = blockHashes.get(blockKey)!;\n const original = msg.content;\n const compressed = `[See message #${firstIdx + 1} - same content]`;\n charsSaved += original.length - compressed.length;\n return { ...msg, content: compressed };\n }\n\n blockHashes.set(blockKey, idx);\n return msg;\n });\n\n return { messages: result, charsSaved };\n}\n\n/**\n * Compress tool results in messages.\n */\nexport function compressObservations(messages: NormalizedMessage[]): ObservationResult {\n let charsSaved = 0;\n let observationsCompressed = 0;\n\n // First pass: compress individual tool results\n let result = messages.map((msg) => {\n // Only compress tool role messages (these are tool call results)\n // Only process string content (skip arrays for multimodal messages)\n if (msg.role !== \"tool\" || !msg.content || typeof msg.content !== \"string\") {\n return msg;\n }\n\n const original = msg.content;\n if (original.length <= TOOL_RESULT_THRESHOLD) {\n return msg;\n }\n\n const compressed = compressToolResult(original);\n const saved = original.length - compressed.length;\n\n if (saved > 50) {\n charsSaved += saved;\n observationsCompressed++;\n return { ...msg, content: compressed };\n }\n\n return msg;\n });\n\n // Second pass: deduplicate large repeated blocks\n const dedupResult = deduplicateLargeBlocks(result);\n result = dedupResult.messages;\n charsSaved += dedupResult.charsSaved;\n\n return {\n messages: result,\n charsSaved,\n observationsCompressed,\n };\n}\n","/**\n * L7: Dynamic Codebook Builder\n *\n * Inspired by claw-compactor's frequency-based codebook.\n * Builds codebook from actual content being compressed,\n * rather than relying on static patterns.\n *\n * Finds phrases that appear 3+ times and replaces with short codes.\n */\n\nimport { NormalizedMessage } from \"../types\";\n\ninterface DynamicCodebookResult {\n messages: NormalizedMessage[];\n charsSaved: number;\n dynamicCodes: Record; // code -> phrase\n substitutions: number;\n}\n\n// Config\nconst MIN_PHRASE_LENGTH = 20;\nconst MAX_PHRASE_LENGTH = 200;\nconst MIN_FREQUENCY = 3;\nconst MAX_ENTRIES = 100;\nconst CODE_PREFIX = \"$D\"; // Dynamic codes: $D01, $D02, etc.\n\n/**\n * Find repeated phrases in content.\n */\nfunction findRepeatedPhrases(allContent: string): Map {\n const phrases = new Map();\n\n // Split by sentence-like boundaries\n const segments = allContent.split(/(?<=[.!?\\n])\\s+/);\n\n for (const segment of segments) {\n const trimmed = segment.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n // Also find repeated lines\n const lines = allContent.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {\n phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);\n }\n }\n\n return phrases;\n}\n\n/**\n * Build dynamic codebook from message content.\n */\nfunction buildDynamicCodebook(messages: NormalizedMessage[]): Record {\n // Combine all content\n let allContent = \"\";\n for (const msg of messages) {\n // Only process string content (skip arrays for multimodal messages)\n if (msg.content && typeof msg.content === \"string\") {\n allContent += msg.content + \"\\n\";\n }\n }\n\n // Find repeated phrases\n const phrases = findRepeatedPhrases(allContent);\n\n // Filter by frequency and sort by savings potential\n const candidates: Array<{ phrase: string; count: number; savings: number }> = [];\n for (const [phrase, count] of phrases.entries()) {\n if (count >= MIN_FREQUENCY) {\n // Savings = (phrase length - code length) * occurrences\n const codeLength = 4; // e.g., \"$D01\"\n const savings = (phrase.length - codeLength) * count;\n if (savings > 50) {\n candidates.push({ phrase, count, savings });\n }\n }\n }\n\n // Sort by savings (descending) and take top entries\n candidates.sort((a, b) => b.savings - a.savings);\n const topCandidates = candidates.slice(0, MAX_ENTRIES);\n\n // Build codebook\n const codebook: Record = {};\n topCandidates.forEach((c, i) => {\n const code = `${CODE_PREFIX}${String(i + 1).padStart(2, \"0\")}`;\n codebook[code] = c.phrase;\n });\n\n return codebook;\n}\n\n/**\n * Escape special regex characters.\n */\nfunction escapeRegex(str: string): string {\n // Defensive type check\n if (!str || typeof str !== \"string\") return \"\";\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply dynamic codebook to messages.\n */\nexport function applyDynamicCodebook(messages: NormalizedMessage[]): DynamicCodebookResult {\n // Build codebook from content\n const codebook = buildDynamicCodebook(messages);\n\n if (Object.keys(codebook).length === 0) {\n return {\n messages,\n charsSaved: 0,\n dynamicCodes: {},\n substitutions: 0,\n };\n }\n\n // Create inverse map for replacement\n const phraseToCode: Record = {};\n for (const [code, phrase] of Object.entries(codebook)) {\n phraseToCode[phrase] = code;\n }\n\n // Sort phrases by length (longest first) to avoid partial replacements\n const sortedPhrases = Object.keys(phraseToCode).sort((a, b) => b.length - a.length);\n\n let charsSaved = 0;\n let substitutions = 0;\n\n // Apply replacements\n const result = messages.map((msg) => {\n // Only process string content (skip arrays for multimodal messages)\n if (!msg.content || typeof msg.content !== \"string\") return msg;\n\n let content = msg.content;\n for (const phrase of sortedPhrases) {\n const code = phraseToCode[phrase];\n const regex = new RegExp(escapeRegex(phrase), \"g\");\n const matches = content.match(regex);\n if (matches) {\n content = content.replace(regex, code);\n charsSaved += (phrase.length - code.length) * matches.length;\n substitutions += matches.length;\n }\n }\n\n return { ...msg, content };\n });\n\n return {\n messages: result,\n charsSaved,\n dynamicCodes: codebook,\n substitutions,\n };\n}\n\n/**\n * Generate header for dynamic codes (to include in system message).\n */\nexport function generateDynamicCodebookHeader(codebook: Record): string {\n if (Object.keys(codebook).length === 0) return \"\";\n\n const entries = Object.entries(codebook)\n .slice(0, 20) // Limit header size\n .map(([code, phrase]) => {\n // Truncate long phrases in header\n const displayPhrase = phrase.length > 40 ? phrase.slice(0, 37) + \"...\" : phrase;\n return `${code}=${displayPhrase}`;\n })\n .join(\", \");\n\n return `[DynDict: ${entries}]`;\n}\n","/**\n * LLM-Safe Context Compression\n *\n * Reduces token usage by 15-40% while preserving semantic meaning.\n * Implements 7 compression layers inspired by claw-compactor.\n *\n * Usage:\n * const result = await compressContext(messages);\n * // result.messages -> compressed version to send to provider\n * // result.originalMessages -> original for logging\n */\n\nimport {\n NormalizedMessage,\n CompressionConfig,\n CompressionResult,\n CompressionStats,\n DEFAULT_COMPRESSION_CONFIG,\n} from \"./types\";\nimport { deduplicateMessages } from \"./layers/deduplication\";\nimport { normalizeMessagesWhitespace } from \"./layers/whitespace\";\nimport { encodeMessages } from \"./layers/dictionary\";\nimport { shortenPaths } from \"./layers/paths\";\nimport { compactMessagesJson } from \"./layers/json-compact\";\nimport { compressObservations } from \"./layers/observation\";\nimport { applyDynamicCodebook, generateDynamicCodebookHeader } from \"./layers/dynamic-codebook\";\nimport { generateCodebookHeader, STATIC_CODEBOOK } from \"./codebook\";\n\nexport * from \"./types\";\nexport { STATIC_CODEBOOK } from \"./codebook\";\n\n/**\n * Calculate total character count for messages.\n */\nfunction calculateTotalChars(messages: NormalizedMessage[]): number {\n return messages.reduce((total, msg) => {\n let chars = 0;\n if (typeof msg.content === \"string\") {\n chars = msg.content.length;\n } else if (Array.isArray(msg.content)) {\n // For multimodal content, stringify to get approximate size\n chars = JSON.stringify(msg.content).length;\n }\n if (msg.tool_calls) {\n chars += JSON.stringify(msg.tool_calls).length;\n }\n return total + chars;\n }, 0);\n}\n\n/**\n * Deep clone messages to preserve originals.\n */\nfunction cloneMessages(messages: NormalizedMessage[]): NormalizedMessage[] {\n return JSON.parse(JSON.stringify(messages));\n}\n\n/**\n * Prepend codebook header to the first USER message (not system).\n *\n * Why not system message?\n * - Google Gemini uses systemInstruction which doesn't support codebook format\n * - The codebook header in user message is still visible to all LLMs\n * - This ensures compatibility across all providers\n */\nfunction prependCodebookHeader(\n messages: NormalizedMessage[],\n usedCodes: Set,\n pathMap: Record,\n): NormalizedMessage[] {\n const header = generateCodebookHeader(usedCodes, pathMap);\n if (!header) return messages;\n\n // Find first user message (not system - Google's systemInstruction doesn't support codebook)\n const userIndex = messages.findIndex((m) => m.role === \"user\");\n\n if (userIndex === -1) {\n // No user message, add codebook as system (fallback)\n return [{ role: \"system\", content: header }, ...messages];\n }\n\n // Prepend to first user message (only if content is a string)\n return messages.map((msg, i) => {\n if (i === userIndex) {\n // Only prepend to string content - skip arrays (multimodal messages)\n if (typeof msg.content === \"string\") {\n return {\n ...msg,\n content: `${header}\\n\\n${msg.content}`,\n };\n }\n // For non-string content, don't modify the message\n // The codebook header would corrupt array content\n }\n return msg;\n });\n}\n\n/**\n * Main compression function.\n *\n * Applies 5 layers in sequence:\n * 1. Deduplication - Remove exact duplicate messages\n * 2. Whitespace - Normalize excessive whitespace\n * 3. Dictionary - Replace common phrases with codes\n * 4. Paths - Shorten repeated file paths\n * 5. JSON - Compact JSON in tool calls\n *\n * Then prepends a codebook header for the LLM to decode in-context.\n */\nexport async function compressContext(\n messages: NormalizedMessage[],\n config: Partial = {},\n): Promise {\n const fullConfig: CompressionConfig = {\n ...DEFAULT_COMPRESSION_CONFIG,\n ...config,\n layers: {\n ...DEFAULT_COMPRESSION_CONFIG.layers,\n ...config.layers,\n },\n dictionary: {\n ...DEFAULT_COMPRESSION_CONFIG.dictionary,\n ...config.dictionary,\n },\n };\n\n // If compression disabled, return as-is\n if (!fullConfig.enabled) {\n const originalChars = calculateTotalChars(messages);\n return {\n messages,\n originalMessages: messages,\n originalChars,\n compressedChars: originalChars,\n compressionRatio: 1,\n stats: {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n },\n codebook: {},\n pathMap: {},\n dynamicCodes: {},\n };\n }\n\n // Preserve originals for logging\n const originalMessages = fullConfig.preserveRaw ? cloneMessages(messages) : messages;\n const originalChars = calculateTotalChars(messages);\n\n // Initialize stats\n const stats: CompressionStats = {\n duplicatesRemoved: 0,\n whitespaceSavedChars: 0,\n dictionarySubstitutions: 0,\n pathsShortened: 0,\n jsonCompactedChars: 0,\n observationsCompressed: 0,\n observationCharsSaved: 0,\n dynamicSubstitutions: 0,\n dynamicCharsSaved: 0,\n };\n\n let result = cloneMessages(messages);\n let usedCodes = new Set();\n let pathMap: Record = {};\n let dynamicCodes: Record = {};\n\n // Layer 1: Deduplication\n if (fullConfig.layers.deduplication) {\n const dedupResult = deduplicateMessages(result);\n result = dedupResult.messages;\n stats.duplicatesRemoved = dedupResult.duplicatesRemoved;\n }\n\n // Layer 2: Whitespace normalization\n if (fullConfig.layers.whitespace) {\n const wsResult = normalizeMessagesWhitespace(result);\n result = wsResult.messages;\n stats.whitespaceSavedChars = wsResult.charsSaved;\n }\n\n // Layer 3: Dictionary encoding\n if (fullConfig.layers.dictionary) {\n const dictResult = encodeMessages(result);\n result = dictResult.messages;\n stats.dictionarySubstitutions = dictResult.substitutionCount;\n usedCodes = dictResult.usedCodes;\n }\n\n // Layer 4: Path shortening\n if (fullConfig.layers.paths) {\n const pathResult = shortenPaths(result);\n result = pathResult.messages;\n pathMap = pathResult.pathMap;\n stats.pathsShortened = Object.keys(pathMap).length;\n }\n\n // Layer 5: JSON compaction\n if (fullConfig.layers.jsonCompact) {\n const jsonResult = compactMessagesJson(result);\n result = jsonResult.messages;\n stats.jsonCompactedChars = jsonResult.charsSaved;\n }\n\n // Layer 6: Observation compression (BIG WIN - 97% on tool results)\n if (fullConfig.layers.observation) {\n const obsResult = compressObservations(result);\n result = obsResult.messages;\n stats.observationsCompressed = obsResult.observationsCompressed;\n stats.observationCharsSaved = obsResult.charsSaved;\n }\n\n // Layer 7: Dynamic codebook (learns from actual content)\n if (fullConfig.layers.dynamicCodebook) {\n const dynResult = applyDynamicCodebook(result);\n result = dynResult.messages;\n stats.dynamicSubstitutions = dynResult.substitutions;\n stats.dynamicCharsSaved = dynResult.charsSaved;\n dynamicCodes = dynResult.dynamicCodes;\n }\n\n // Add codebook header if enabled and we have codes to include\n if (\n fullConfig.dictionary.includeCodebookHeader &&\n (usedCodes.size > 0 || Object.keys(pathMap).length > 0 || Object.keys(dynamicCodes).length > 0)\n ) {\n result = prependCodebookHeader(result, usedCodes, pathMap);\n // Also add dynamic codebook header if we have dynamic codes\n if (Object.keys(dynamicCodes).length > 0) {\n const dynHeader = generateDynamicCodebookHeader(dynamicCodes);\n if (dynHeader) {\n const systemIndex = result.findIndex((m) => m.role === \"system\");\n // Only prepend to string content - skip arrays (multimodal messages)\n if (systemIndex >= 0 && typeof result[systemIndex].content === \"string\") {\n result[systemIndex] = {\n ...result[systemIndex],\n content: `${dynHeader}\\n${result[systemIndex].content}`,\n };\n }\n }\n }\n }\n\n // Calculate final stats\n const compressedChars = calculateTotalChars(result);\n const compressionRatio = compressedChars / originalChars;\n\n // Build used codebook for logging\n const usedCodebook: Record = {};\n usedCodes.forEach((code) => {\n usedCodebook[code] = STATIC_CODEBOOK[code];\n });\n\n return {\n messages: result,\n originalMessages,\n originalChars,\n compressedChars,\n compressionRatio,\n stats,\n codebook: usedCodebook,\n pathMap,\n dynamicCodes,\n };\n}\n\n/**\n * Quick check if compression would benefit these messages.\n * Returns true if messages are large enough to warrant compression.\n */\nexport function shouldCompress(messages: NormalizedMessage[]): boolean {\n const chars = calculateTotalChars(messages);\n // Only compress if > 5000 chars (roughly 1000 tokens)\n return chars > 5000;\n}\n","/**\n * Session Persistence Store\n *\n * Tracks model selections per session to prevent model switching mid-task.\n * When a session is active, the router will continue using the same model\n * instead of re-routing each request.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type SessionEntry = {\n model: string;\n tier: string;\n createdAt: number;\n lastUsedAt: number;\n requestCount: number;\n // --- Three-strike escalation ---\n recentHashes: string[]; // Sliding window of last 3 request content fingerprints\n strikes: number; // Consecutive similar request count\n escalated: boolean; // Whether session was already escalated via three-strike\n // --- Cost accumulation for maxCostPerRun ---\n sessionCostMicros: bigint; // Total estimated cost for this session run (USDC 6-decimal)\n};\n\nexport type SessionConfig = {\n /** Enable session persistence (default: false) */\n enabled: boolean;\n /** Session timeout in ms (default: 30 minutes) */\n timeoutMs: number;\n /** Header name for session ID (default: X-Session-ID) */\n headerName: string;\n};\n\nexport const DEFAULT_SESSION_CONFIG: SessionConfig = {\n enabled: true,\n timeoutMs: 30 * 60 * 1000, // 30 minutes\n headerName: \"x-session-id\",\n};\n\n/**\n * Session persistence store for maintaining model selections.\n */\nexport class SessionStore {\n private sessions: Map = new Map();\n private config: SessionConfig;\n private cleanupInterval: ReturnType | null = null;\n\n constructor(config: Partial = {}) {\n this.config = { ...DEFAULT_SESSION_CONFIG, ...config };\n\n // Start cleanup interval (every 5 minutes)\n if (this.config.enabled) {\n this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1000);\n }\n }\n\n /**\n * Get the pinned model for a session, if any.\n */\n getSession(sessionId: string): SessionEntry | undefined {\n if (!this.config.enabled || !sessionId) {\n return undefined;\n }\n\n const entry = this.sessions.get(sessionId);\n if (!entry) {\n return undefined;\n }\n\n // Check if session has expired\n const now = Date.now();\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(sessionId);\n return undefined;\n }\n\n return entry;\n }\n\n /**\n * Pin a model to a session.\n */\n setSession(sessionId: string, model: string, tier: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const existing = this.sessions.get(sessionId);\n const now = Date.now();\n\n if (existing) {\n existing.lastUsedAt = now;\n existing.requestCount++;\n // Update model if different (e.g., fallback)\n if (existing.model !== model) {\n existing.model = model;\n existing.tier = tier;\n }\n } else {\n this.sessions.set(sessionId, {\n model,\n tier,\n createdAt: now,\n lastUsedAt: now,\n requestCount: 1,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n });\n }\n }\n\n /**\n * Touch a session to extend its timeout.\n */\n touchSession(sessionId: string): void {\n if (!this.config.enabled || !sessionId) {\n return;\n }\n\n const entry = this.sessions.get(sessionId);\n if (entry) {\n entry.lastUsedAt = Date.now();\n entry.requestCount++;\n }\n }\n\n /**\n * Clear a specific session.\n */\n clearSession(sessionId: string): void {\n this.sessions.delete(sessionId);\n }\n\n /**\n * Clear all sessions.\n */\n clearAll(): void {\n this.sessions.clear();\n }\n\n /**\n * Get session stats for debugging.\n */\n getStats(): { count: number; sessions: Array<{ id: string; model: string; age: number }> } {\n const now = Date.now();\n const sessions = Array.from(this.sessions.entries()).map(([id, entry]) => ({\n id: id.slice(0, 8) + \"...\",\n model: entry.model,\n age: Math.round((now - entry.createdAt) / 1000),\n }));\n return { count: this.sessions.size, sessions };\n }\n\n /**\n * Clean up expired sessions.\n */\n private cleanup(): void {\n const now = Date.now();\n for (const [id, entry] of this.sessions) {\n if (now - entry.lastUsedAt > this.config.timeoutMs) {\n this.sessions.delete(id);\n }\n }\n }\n\n /**\n * Record a request content hash and detect repetitive patterns.\n * Returns true if escalation should be triggered (3+ consecutive similar requests).\n */\n recordRequestHash(sessionId: string, hash: string): boolean {\n const entry = this.sessions.get(sessionId);\n if (!entry) return false;\n\n const prev = entry.recentHashes;\n if (prev.length > 0 && prev[prev.length - 1] === hash) {\n entry.strikes++;\n } else {\n entry.strikes = 0;\n }\n\n entry.recentHashes.push(hash);\n if (entry.recentHashes.length > 3) {\n entry.recentHashes.shift();\n }\n\n return entry.strikes >= 2 && !entry.escalated;\n }\n\n /**\n * Escalate session to next tier. Returns the new model/tier or null if already at max.\n */\n escalateSession(\n sessionId: string,\n tierConfigs: Record,\n ): { model: string; tier: string } | null {\n const entry = this.sessions.get(sessionId);\n if (!entry) return null;\n\n const TIER_ORDER = [\"SIMPLE\", \"MEDIUM\", \"COMPLEX\", \"REASONING\"];\n const currentIdx = TIER_ORDER.indexOf(entry.tier);\n if (currentIdx < 0 || currentIdx >= TIER_ORDER.length - 1) return null;\n\n const nextTier = TIER_ORDER[currentIdx + 1];\n const nextConfig = tierConfigs[nextTier];\n if (!nextConfig) return null;\n\n entry.model = nextConfig.primary;\n entry.tier = nextTier;\n entry.strikes = 0;\n entry.escalated = true;\n\n return { model: nextConfig.primary, tier: nextTier };\n }\n\n /**\n * Add cost to a session's running total for maxCostPerRun tracking.\n * Cost is in USDC 6-decimal units (micros).\n * Creates a cost-tracking-only entry if none exists (e.g., explicit model requests\n * that never go through the routing path).\n */\n addSessionCost(sessionId: string, additionalMicros: bigint): void {\n let entry = this.sessions.get(sessionId);\n if (!entry) {\n const now = Date.now();\n entry = {\n model: \"\",\n tier: \"DIRECT\",\n createdAt: now,\n lastUsedAt: now,\n requestCount: 0,\n recentHashes: [],\n strikes: 0,\n escalated: false,\n sessionCostMicros: 0n,\n };\n this.sessions.set(sessionId, entry);\n }\n entry.sessionCostMicros += additionalMicros;\n }\n\n /**\n * Get the total accumulated cost for a session in USD.\n */\n getSessionCostUsd(sessionId: string): number {\n const entry = this.sessions.get(sessionId);\n if (!entry) return 0;\n return Number(entry.sessionCostMicros) / 1_000_000;\n }\n\n /**\n * Stop the cleanup interval.\n */\n close(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n}\n\n/**\n * Generate a session ID from request headers or create a default.\n */\nexport function getSessionId(\n headers: Record,\n headerName: string = DEFAULT_SESSION_CONFIG.headerName,\n): string | undefined {\n const value = headers[headerName] || headers[headerName.toLowerCase()];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n if (Array.isArray(value) && value.length > 0) {\n return value[0];\n }\n return undefined;\n}\n\n/**\n * Derive a stable session ID from message content when no explicit session\n * header is provided. Uses the first user message as the conversation anchor —\n * same opening message = same session ID across all subsequent turns.\n *\n * This prevents model-switching mid-conversation even when OpenClaw doesn't\n * send an x-session-id header (which is the default OpenClaw behaviour).\n */\nexport function deriveSessionId(\n messages: Array<{ role: string; content: unknown }>,\n): string | undefined {\n const firstUser = messages.find((m) => m.role === \"user\");\n if (!firstUser) return undefined;\n\n const content =\n typeof firstUser.content === \"string\" ? firstUser.content : JSON.stringify(firstUser.content);\n\n // 8-char hex prefix of SHA-256 — short enough for logs, collision-resistant\n // enough for session tracking within a single gateway instance.\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 8);\n}\n\n/**\n * Generate a short hash fingerprint from request content.\n * Captures: last user message text + tool call names (if any).\n * Normalizes whitespace to avoid false negatives from minor formatting diffs.\n */\nexport function hashRequestContent(lastUserContent: string, toolCallNames?: string[]): string {\n const normalized = lastUserContent.replace(/\\s+/g, \" \").trim().slice(0, 500);\n const toolSuffix = toolCallNames?.length ? `|tools:${toolCallNames.sort().join(\",\")}` : \"\";\n return createHash(\"sha256\")\n .update(normalized + toolSuffix)\n .digest(\"hex\")\n .slice(0, 12);\n}\n","/**\n * Auto-update checker for ClawRouter.\n * Checks npm registry on startup and notifies user if update available.\n */\n\nimport { VERSION } from \"./version.js\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org/@blockrun/clawrouter/latest\";\nconst CHECK_TIMEOUT_MS = 5_000; // Don't block startup for more than 5s\n\n/**\n * Compare semver versions. Returns:\n * 1 if a > b\n * 0 if a === b\n * -1 if a < b\n */\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split(\".\").map(Number);\n const pb = b.split(\".\").map(Number);\n for (let i = 0; i < 3; i++) {\n if ((pa[i] || 0) > (pb[i] || 0)) return 1;\n if ((pa[i] || 0) < (pb[i] || 0)) return -1;\n }\n return 0;\n}\n\n/**\n * Check npm registry for latest version.\n * Non-blocking, silent on errors.\n */\nexport async function checkForUpdates(): Promise {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);\n\n const res = await fetch(NPM_REGISTRY, {\n signal: controller.signal,\n headers: { Accept: \"application/json\" },\n });\n clearTimeout(timeout);\n\n if (!res.ok) return;\n\n const data = (await res.json()) as { version?: string };\n const latest = data.version;\n\n if (!latest) return;\n\n if (compareSemver(latest, VERSION) > 0) {\n console.log(\"\");\n console.log(`\\x1b[33m⬆️ ClawRouter ${latest} available (you have ${VERSION})\\x1b[0m`);\n console.log(` Run: \\x1b[36mnpx @blockrun/clawrouter@latest\\x1b[0m`);\n console.log(\"\");\n }\n } catch {\n // Silent fail - don't disrupt startup\n }\n}\n","/**\n * Exclude-models persistence module.\n *\n * Manages a user-configurable list of model IDs that the smart router\n * should never select. Stored as a sorted JSON array on disk.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { resolveModelAlias } from \"./models.js\";\n\nconst DEFAULT_FILE_PATH = join(homedir(), \".openclaw\", \"blockrun\", \"exclude-models.json\");\n\n/**\n * Load the exclude list from disk.\n * Returns an empty set if the file does not exist.\n */\nexport function loadExcludeList(filePath: string = DEFAULT_FILE_PATH): Set {\n try {\n const raw = readFileSync(filePath, \"utf-8\");\n const arr: unknown = JSON.parse(raw);\n if (Array.isArray(arr)) {\n return new Set(arr.filter((x): x is string => typeof x === \"string\"));\n }\n return new Set();\n } catch {\n return new Set();\n }\n}\n\n/**\n * Save a set of model IDs to disk as a sorted JSON array.\n */\nfunction saveExcludeList(set: Set, filePath: string): void {\n const sorted = [...set].sort();\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n writeFileSync(filePath, JSON.stringify(sorted, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Add a model to the exclude list.\n * Resolves aliases before persisting.\n * @returns The resolved model ID.\n */\nexport function addExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): string {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n set.add(resolved);\n saveExcludeList(set, filePath);\n return resolved;\n}\n\n/**\n * Remove a model from the exclude list.\n * Resolves aliases before removing.\n * @returns true if the model was present and removed, false otherwise.\n */\nexport function removeExclusion(model: string, filePath: string = DEFAULT_FILE_PATH): boolean {\n const resolved = resolveModelAlias(model);\n const set = loadExcludeList(filePath);\n const had = set.delete(resolved);\n if (had) {\n saveExcludeList(set, filePath);\n }\n return had;\n}\n\n/**\n * Clear the entire exclude list.\n */\nexport function clearExclusions(filePath: string = DEFAULT_FILE_PATH): void {\n saveExcludeList(new Set(), filePath);\n}\n","/**\n * Configuration Module\n *\n * Reads environment variables at module load time.\n * Separated from network code to avoid security scanner false positives.\n */\n\nconst DEFAULT_PORT = 8402;\n\n/**\n * Proxy port configuration - resolved once at module load.\n * Reads BLOCKRUN_PROXY_PORT env var or defaults to 8402.\n */\nexport const PROXY_PORT = (() => {\n const envPort = process[\"env\"].BLOCKRUN_PROXY_PORT;\n if (envPort) {\n const parsed = parseInt(envPort, 10);\n if (!isNaN(parsed) && parsed > 0 && parsed < 65536) {\n return parsed;\n }\n }\n return DEFAULT_PORT;\n})();\n","/**\n * Session Journal - Memory layer for ClawRouter\n *\n * Maintains a compact record of key actions per session, enabling agents\n * to recall earlier work even when OpenClaw's sessions_history is truncated.\n *\n * How it works:\n * 1. As LLM responses flow through, extracts key actions (\"I created X\", \"I fixed Y\")\n * 2. Stores them in a compact journal per session\n * 3. When a request mentions past work (\"what did you do today?\"), injects the journal\n */\n\nexport interface JournalEntry {\n timestamp: number;\n action: string; // Compact description: \"Created login component\"\n model?: string;\n}\n\nexport interface SessionJournalConfig {\n /** Maximum entries per session (default: 100) */\n maxEntries?: number;\n /** Maximum age of entries in ms (default: 24 hours) */\n maxAgeMs?: number;\n /** Maximum events to extract per response (default: 5) */\n maxEventsPerResponse?: number;\n}\n\nconst DEFAULT_CONFIG: Required = {\n maxEntries: 100,\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxEventsPerResponse: 5,\n};\n\nexport class SessionJournal {\n private journals: Map = new Map();\n private config: Required;\n\n constructor(config?: SessionJournalConfig) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Extract key events from assistant response content.\n * Looks for patterns like \"I created...\", \"I fixed...\", \"Successfully...\"\n */\n extractEvents(content: string): string[] {\n if (!content || typeof content !== \"string\") {\n return [];\n }\n\n const events: string[] = [];\n const seen = new Set();\n\n // Patterns for identifying key actions\n // Note: Patterns allow optional words like \"also\", \"then\", \"have\" between \"I\" and verb\n const patterns = [\n // Creation patterns\n /I (?:also |then |have |)?(?:created|implemented|added|wrote|built|generated|set up|initialized) ([^.!?\\n]{10,150})/gi,\n // Fix patterns\n /I (?:also |then |have |)?(?:fixed|resolved|solved|patched|corrected|addressed|debugged) ([^.!?\\n]{10,150})/gi,\n // Completion patterns\n /I (?:also |then |have |)?(?:completed|finished|done with|wrapped up) ([^.!?\\n]{10,150})/gi,\n // Update patterns\n /I (?:also |then |have |)?(?:updated|modified|changed|refactored|improved|enhanced|optimized) ([^.!?\\n]{10,150})/gi,\n // Success patterns\n /Successfully ([^.!?\\n]{10,150})/gi,\n // Tool usage patterns (when agent uses tools)\n /I (?:also |then |have |)?(?:ran|executed|called|invoked) ([^.!?\\n]{10,100})/gi,\n ];\n\n for (const pattern of patterns) {\n // Reset pattern lastIndex for each iteration\n pattern.lastIndex = 0;\n\n let match;\n while ((match = pattern.exec(content)) !== null) {\n const action = match[0].trim();\n\n // Skip if already seen (dedup)\n const normalized = action.toLowerCase();\n if (seen.has(normalized)) {\n continue;\n }\n\n // Validate length (not too short or too long)\n if (action.length >= 15 && action.length <= 200) {\n events.push(action);\n seen.add(normalized);\n }\n\n // Stop if we have enough events\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n if (events.length >= this.config.maxEventsPerResponse) {\n break;\n }\n }\n\n return events;\n }\n\n /**\n * Record events to the session journal.\n */\n record(sessionId: string, events: string[], model?: string): void {\n if (!sessionId || !events.length) {\n return;\n }\n\n const journal = this.journals.get(sessionId) || [];\n const now = Date.now();\n\n for (const action of events) {\n journal.push({\n timestamp: now,\n action,\n model,\n });\n }\n\n // Trim old entries and enforce max count\n const cutoff = now - this.config.maxAgeMs;\n const trimmed = journal.filter((e) => e.timestamp > cutoff).slice(-this.config.maxEntries);\n\n this.journals.set(sessionId, trimmed);\n }\n\n /**\n * Check if the user message indicates a need for historical context.\n */\n needsContext(lastUserMessage: string): boolean {\n if (!lastUserMessage || typeof lastUserMessage !== \"string\") {\n return false;\n }\n\n const lower = lastUserMessage.toLowerCase();\n\n // Trigger phrases that indicate user wants to recall past work\n const triggers = [\n // Direct questions about past work\n \"what did you do\",\n \"what have you done\",\n \"what did we do\",\n \"what have we done\",\n // Temporal references\n \"earlier\",\n \"before\",\n \"previously\",\n \"this session\",\n \"today\",\n \"so far\",\n // Summary requests\n \"remind me\",\n \"summarize\",\n \"summary of\",\n \"recap\",\n // Progress inquiries\n \"your work\",\n \"your progress\",\n \"accomplished\",\n \"achievements\",\n \"completed tasks\",\n ];\n\n return triggers.some((t) => lower.includes(t));\n }\n\n /**\n * Format the journal for injection into system message.\n * Returns null if journal is empty.\n */\n format(sessionId: string): string | null {\n const journal = this.journals.get(sessionId);\n if (!journal?.length) {\n return null;\n }\n\n const lines = journal.map((e) => {\n const time = new Date(e.timestamp).toLocaleTimeString(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n });\n return `- ${time}: ${e.action}`;\n });\n\n return `[Session Memory - Key Actions]\\n${lines.join(\"\\n\")}`;\n }\n\n /**\n * Get the raw journal entries for a session (for debugging/testing).\n */\n getEntries(sessionId: string): JournalEntry[] {\n return this.journals.get(sessionId) || [];\n }\n\n /**\n * Clear journal for a specific session.\n */\n clear(sessionId: string): void {\n this.journals.delete(sessionId);\n }\n\n /**\n * Clear all journals.\n */\n clearAll(): void {\n this.journals.clear();\n }\n\n /**\n * Get stats about the journal.\n */\n getStats(): { sessions: number; totalEntries: number } {\n let totalEntries = 0;\n for (const entries of this.journals.values()) {\n totalEntries += entries.length;\n }\n return {\n sessions: this.journals.size,\n totalEntries,\n };\n }\n}\n","/**\n * @blockrun/clawrouter\n *\n * Smart LLM router for OpenClaw — 55+ models, x402 micropayments, 78% cost savings.\n * Routes each request to the cheapest model that can handle it.\n *\n * Usage:\n * # Install the plugin\n * openclaw plugins install @blockrun/clawrouter\n *\n * # Fund your wallet with USDC on Base (address printed on install)\n *\n * # Use smart routing (auto-picks cheapest model)\n * openclaw models set blockrun/auto\n *\n * # Or use any specific BlockRun model\n * openclaw models set openai/gpt-5.3\n */\n\nimport type {\n OpenClawPluginDefinition,\n OpenClawPluginApi,\n PluginCommandContext,\n OpenClawPluginCommandDefinition,\n} from \"./types.js\";\nimport { blockrunProvider, setActiveProxy } from \"./provider.js\";\nimport { startProxy, getProxyPort } from \"./proxy.js\";\nimport {\n resolveOrGenerateWalletKey,\n setupSolana,\n savePaymentChain,\n resolvePaymentChain,\n WALLET_FILE,\n MNEMONIC_FILE,\n} from \"./auth.js\";\nimport type { RoutingConfig } from \"./router/index.js\";\nimport { BalanceMonitor } from \"./balance.js\";\nimport {\n DEFAULT_BASE_PAYMENT_ASSET,\n fetchBasePaymentAssets,\n} from \"./payment-asset.js\";\nimport {\n loadExcludeList,\n addExclusion,\n removeExclusion,\n clearExclusions,\n} from \"./exclude-models.js\";\n\n/**\n * Wait for proxy health check to pass (quick check, not RPC).\n * Returns true if healthy within timeout, false otherwise.\n */\nasync function waitForProxyHealth(port: number, timeoutMs = 3000): Promise {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n const res = await fetch(`http://127.0.0.1:${port}/health`);\n if (res.ok) return true;\n } catch {\n // Proxy not ready yet\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n return false;\n}\nimport { OPENCLAW_MODELS } from \"./models.js\";\nimport {\n writeFileSync,\n existsSync,\n readdirSync,\n mkdirSync,\n copyFileSync,\n renameSync,\n} from \"node:fs\";\nimport { readTextFileSync } from \"./fs-read.js\";\nimport { homedir } from \"node:os\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { VERSION } from \"./version.js\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { getStats, formatStatsAscii, clearStats } from \"./stats.js\";\nimport { buildPartnerTools, PARTNER_SERVICES } from \"./partners/index.js\";\n\n/**\n * Install ClawRouter skills into OpenClaw's workspace skills directory.\n *\n * OpenClaw agents discover skills by scanning {workspaceDir}/skills/ for SKILL.md\n * files. While the plugin manifest (`openclaw.plugin.json`) exposes skills for\n * OpenClaw's internal registry, agents often try to read skills from the workspace\n * path directly. This copies our bundled skills so they're always resolvable.\n *\n * Workspace path follows OpenClaw's convention:\n * - Default: ~/.openclaw/workspace/skills/\n * - With profile: ~/.openclaw/workspace-{profile}/skills/\n *\n * Only copies if the skill is missing or the content has changed.\n */\nfunction installSkillsToWorkspace(logger: {\n info: (msg: string) => void;\n warn: (msg: string) => void;\n}) {\n try {\n // Resolve the package root: dist/index.js -> package root\n const packageRoot = join(dirname(fileURLToPath(import.meta.url)), \"..\");\n const bundledSkillsDir = join(packageRoot, \"skills\");\n\n if (!existsSync(bundledSkillsDir)) {\n // Skills directory not bundled (dev mode or stripped package)\n return;\n }\n\n // Match OpenClaw's workspace resolution: ~/.openclaw/workspace[-{profile}]/\n const profile = (process[\"env\"].OPENCLAW_PROFILE ?? \"\").trim().toLowerCase();\n const workspaceDirName =\n profile && profile !== \"default\" ? `workspace-${profile}` : \"workspace\";\n const workspaceSkillsDir = join(homedir(), \".openclaw\", workspaceDirName, \"skills\");\n mkdirSync(workspaceSkillsDir, { recursive: true });\n\n // Scan bundled skills: each subdirectory contains a SKILL.md\n // Skip internal-only skills (release is for ClawRouter maintainers, not end users)\n const INTERNAL_SKILLS = new Set([\"release\"]);\n const entries = readdirSync(bundledSkillsDir, { withFileTypes: true });\n let installed = 0;\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n\n const skillName = entry.name;\n if (INTERNAL_SKILLS.has(skillName)) continue;\n const srcSkillFile = join(bundledSkillsDir, skillName, \"SKILL.md\");\n if (!existsSync(srcSkillFile)) continue;\n\n // Use original skill name as folder (matches what agents expect)\n const destDir = join(workspaceSkillsDir, skillName);\n const destSkillFile = join(destDir, \"SKILL.md\");\n\n // Check if update needed: compare content\n let needsUpdate = true;\n if (existsSync(destSkillFile)) {\n try {\n const srcContent = readTextFileSync(srcSkillFile);\n const destContent = readTextFileSync(destSkillFile);\n if (srcContent === destContent) needsUpdate = false;\n } catch {\n // Can't read — overwrite\n }\n }\n\n if (needsUpdate) {\n mkdirSync(destDir, { recursive: true });\n copyFileSync(srcSkillFile, destSkillFile);\n installed++;\n }\n }\n\n if (installed > 0) {\n logger.info(`Installed ${installed} skill(s) to ${workspaceSkillsDir}`);\n }\n } catch (err) {\n logger.warn(`Failed to install skills: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n/**\n * Detect if we're running in shell completion mode.\n * When `openclaw completion --shell zsh` runs, it loads plugins but only needs\n * the completion script output - any stdout logging pollutes the script and\n * causes zsh to interpret colored text like `[plugins]` as glob patterns.\n */\nfunction isCompletionMode(): boolean {\n const args = process.argv;\n // Check for: openclaw completion --shell \n // argv[0] = node/bun, argv[1] = openclaw, argv[2] = completion\n return args.some((arg, i) => arg === \"completion\" && i >= 1 && i <= 3);\n}\n\n/**\n * Detect if we're running in gateway mode.\n * The proxy should ONLY start when the gateway is running.\n * During CLI commands (plugins, models, etc), the proxy keeps the process alive.\n */\nfunction isGatewayMode(): boolean {\n const args = process.argv;\n // Gateway mode is: openclaw gateway start/restart/stop\n return args.includes(\"gateway\");\n}\n\n/**\n * Inject BlockRun models config into OpenClaw config file.\n * This is required because registerProvider() alone doesn't make models available.\n *\n * CRITICAL: This function must be idempotent and handle ALL edge cases:\n * - Config file doesn't exist (create it)\n * - Config file exists but is empty/invalid (reinitialize)\n * - blockrun provider exists but has undefined fields (fix them)\n * - Config exists but uses old port/models (update them)\n *\n * This function is called on EVERY plugin load to ensure config is always correct.\n */\nfunction injectModelsConfig(logger: { info: (msg: string) => void }): void {\n const configDir = join(homedir(), \".openclaw\");\n const configPath = join(configDir, \"openclaw.json\");\n\n let config: Record = {};\n let needsWrite = false;\n\n // Create config directory if it doesn't exist\n if (!existsSync(configDir)) {\n try {\n mkdirSync(configDir, { recursive: true });\n logger.info(\"Created OpenClaw config directory\");\n } catch (err) {\n logger.info(\n `Failed to create config dir: ${err instanceof Error ? err.message : String(err)}`,\n );\n return;\n }\n }\n\n // Load existing config or create new one\n // IMPORTANT: On parse failure, we backup and skip writing to avoid clobbering\n // other plugins' config (e.g. Telegram channels). This prevents a race condition\n // where a partial/corrupt config file causes us to overwrite everything with\n // only our models+agents sections.\n if (existsSync(configPath)) {\n try {\n const content = readTextFileSync(configPath).trim();\n if (content) {\n config = JSON.parse(content);\n } else {\n logger.info(\"OpenClaw config is empty, initializing\");\n needsWrite = true;\n }\n } catch (err) {\n // Config file exists but is corrupt/invalid JSON — likely a partial write\n // from another plugin or a race condition during gateway restart.\n // Backup the corrupt file and SKIP writing to avoid losing other config.\n const backupPath = `${configPath}.backup.${Date.now()}`;\n try {\n copyFileSync(configPath, backupPath);\n logger.info(`Config parse failed, backed up to ${backupPath}`);\n } catch {\n logger.info(\"Config parse failed, could not create backup\");\n }\n logger.info(\n `Skipping config injection (corrupt file): ${err instanceof Error ? err.message : String(err)}`,\n );\n return; // Don't write — we'd lose other plugins' config\n }\n } else {\n logger.info(\"OpenClaw config not found, creating\");\n needsWrite = true;\n }\n\n // Initialize config structure\n if (!config.models) {\n config.models = {};\n needsWrite = true;\n }\n const models = config.models as Record;\n if (!models.providers) {\n models.providers = {};\n needsWrite = true;\n }\n\n const proxyPort = getProxyPort();\n const expectedBaseUrl = `http://127.0.0.1:${proxyPort}/v1`;\n\n const providers = models.providers as Record;\n\n if (!providers.blockrun) {\n // Create new blockrun provider config\n providers.blockrun = {\n baseUrl: expectedBaseUrl,\n api: \"openai-completions\",\n // apiKey is required by pi-coding-agent's ModelRegistry for providers with models.\n // We use a placeholder since the proxy handles real x402 auth internally.\n apiKey: \"x402-proxy-handles-auth\",\n models: OPENCLAW_MODELS,\n };\n logger.info(\"Injected BlockRun provider config\");\n needsWrite = true;\n } else {\n // Validate and fix existing blockrun config\n const blockrun = providers.blockrun as Record;\n let fixed = false;\n\n // Fix: explicitly check for undefined/missing fields\n if (!blockrun.baseUrl || blockrun.baseUrl !== expectedBaseUrl) {\n blockrun.baseUrl = expectedBaseUrl;\n fixed = true;\n }\n // Ensure api field is present\n if (!blockrun.api) {\n blockrun.api = \"openai-completions\";\n fixed = true;\n }\n // Ensure apiKey is present (required by ModelRegistry for /model picker)\n if (!blockrun.apiKey) {\n blockrun.apiKey = \"x402-proxy-handles-auth\";\n fixed = true;\n }\n // Always refresh models list (ensures new models/aliases are available)\n // Check both length AND content - new models may be added without changing count\n const currentModels = blockrun.models as Array<{ id?: string }>;\n const currentModelIds = new Set(\n Array.isArray(currentModels) ? currentModels.map((m) => m?.id).filter(Boolean) : [],\n );\n const expectedModelIds = OPENCLAW_MODELS.map((m) => m.id);\n const needsModelUpdate =\n !currentModels ||\n !Array.isArray(currentModels) ||\n currentModels.length !== OPENCLAW_MODELS.length ||\n expectedModelIds.some((id) => !currentModelIds.has(id));\n\n if (needsModelUpdate) {\n blockrun.models = OPENCLAW_MODELS;\n fixed = true;\n logger.info(`Updated models list (${OPENCLAW_MODELS.length} models)`);\n }\n\n if (fixed) {\n logger.info(\"Fixed incomplete BlockRun provider config\");\n needsWrite = true;\n }\n }\n\n // Set blockrun/auto as default model ONLY on first install (not every load!)\n // This respects user's model selection and prevents hijacking their choice.\n if (!config.agents) {\n config.agents = {};\n needsWrite = true;\n }\n const agents = config.agents as Record;\n if (!agents.defaults) {\n agents.defaults = {};\n needsWrite = true;\n }\n const defaults = agents.defaults as Record;\n if (!defaults.model || typeof defaults.model !== \"object\" || Array.isArray(defaults.model)) {\n // Convert plain string \"blockrun/auto\" → { primary: \"blockrun/auto\" }\n // Also handles number, boolean, array, or any other non-object type\n const prev = typeof defaults.model === \"string\" ? defaults.model : undefined;\n defaults.model = prev ? { primary: prev } : {};\n needsWrite = true;\n }\n const model = defaults.model as Record;\n\n // ONLY set default if no primary model exists (first install)\n // Do NOT override user's selection on subsequent loads\n if (!model.primary) {\n model.primary = \"blockrun/auto\";\n logger.info(\"Set default model to blockrun/auto (first install)\");\n needsWrite = true;\n }\n\n // Populate agents.defaults.models (the allowlist) with top BlockRun models.\n // OpenClaw uses this as a whitelist — only listed models appear in the /model picker.\n // Existing non-blockrun entries are preserved (e.g. from other providers).\n const TOP_MODELS = [\n \"auto\",\n \"free\",\n \"eco\",\n \"premium\",\n \"anthropic/claude-sonnet-4.6\",\n \"anthropic/claude-opus-4.6\",\n \"anthropic/claude-haiku-4.5\",\n \"openai/gpt-5.4\",\n \"openai/gpt-5.3\",\n \"openai/gpt-5.3-codex\",\n \"openai/gpt-4o\",\n \"openai/o3\",\n \"google/gemini-3.1-pro\",\n \"google/gemini-3-flash-preview\",\n \"deepseek/deepseek-chat\",\n \"moonshot/kimi-k2.5\",\n \"xai/grok-3\",\n \"minimax/minimax-m2.5\",\n // Free models (free/ prefix so users see \"free\" in picker)\n \"free/gpt-oss-120b\",\n \"free/gpt-oss-20b\",\n \"free/nemotron-ultra-253b\",\n \"free/deepseek-v3.2\",\n \"free/mistral-large-3-675b\",\n \"free/qwen3-coder-480b\",\n \"free/devstral-2-123b\",\n \"free/llama-4-maverick\",\n \"free/nemotron-3-super-120b\",\n \"free/nemotron-super-49b\",\n \"free/glm-4.7\",\n ];\n if (!defaults.models || typeof defaults.models !== \"object\" || Array.isArray(defaults.models)) {\n defaults.models = {};\n needsWrite = true;\n }\n const allowlist = defaults.models as Record;\n const DEPRECATED_BLOCKRUN_MODELS = [\"blockrun/xai/grok-code-fast-1\"];\n let removedDeprecatedCount = 0;\n for (const key of DEPRECATED_BLOCKRUN_MODELS) {\n if (allowlist[key]) {\n delete allowlist[key];\n removedDeprecatedCount++;\n }\n }\n if (removedDeprecatedCount > 0) {\n needsWrite = true;\n logger.info(`Removed ${removedDeprecatedCount} deprecated model entries from allowlist`);\n }\n // Additive-only: add TOP_MODELS entries if missing, never delete user-defined entries.\n // Preserves any blockrun/* IDs the user has manually added outside this curated list.\n let addedCount = 0;\n for (const id of TOP_MODELS) {\n const key = `blockrun/${id}`;\n if (!allowlist[key]) {\n allowlist[key] = {};\n addedCount++;\n }\n }\n if (addedCount > 0) {\n needsWrite = true;\n logger.info(`Added ${addedCount} models to allowlist (${TOP_MODELS.length} total)`);\n }\n\n // Write config file if any changes were made\n // Use atomic write (temp file + rename) to prevent partial writes that could\n // corrupt the config and cause other plugins to lose their settings on next load.\n if (needsWrite) {\n try {\n const tmpPath = `${configPath}.tmp.${process.pid}`;\n writeFileSync(tmpPath, JSON.stringify(config, null, 2));\n renameSync(tmpPath, configPath);\n logger.info(\"Smart routing enabled (blockrun/auto)\");\n } catch (err) {\n logger.info(`Failed to write config: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n}\n\n/**\n * Inject dummy auth profile for BlockRun into agent auth stores.\n * OpenClaw's agent system looks for auth credentials even if provider has auth: [].\n * We inject a placeholder so the lookup succeeds (proxy handles real auth internally).\n */\nfunction injectAuthProfile(logger: { info: (msg: string) => void }): void {\n const agentsDir = join(homedir(), \".openclaw\", \"agents\");\n\n // Create agents directory if it doesn't exist\n if (!existsSync(agentsDir)) {\n try {\n mkdirSync(agentsDir, { recursive: true });\n } catch (err) {\n logger.info(\n `Could not create agents dir: ${err instanceof Error ? err.message : String(err)}`,\n );\n return;\n }\n }\n\n try {\n // Find all agent directories\n let agents = readdirSync(agentsDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name);\n\n // Always ensure \"main\" agent has auth (most common agent)\n if (!agents.includes(\"main\")) {\n agents = [\"main\", ...agents];\n }\n\n for (const agentId of agents) {\n const authDir = join(agentsDir, agentId, \"agent\");\n const authPath = join(authDir, \"auth-profiles.json\");\n\n // Create agent dir if needed\n if (!existsSync(authDir)) {\n try {\n mkdirSync(authDir, { recursive: true });\n } catch {\n continue; // Skip if we can't create the dir\n }\n }\n\n // Load or create auth-profiles.json with correct OpenClaw format\n // Format: { version: 1, profiles: { \"provider:profileId\": { type, provider, key } } }\n let store: { version: number; profiles: Record } = {\n version: 1,\n profiles: {},\n };\n if (existsSync(authPath)) {\n try {\n const existing = JSON.parse(readTextFileSync(authPath));\n // Check if valid OpenClaw format (has version and profiles)\n if (existing.version && existing.profiles) {\n store = existing;\n }\n // Old format without version/profiles is discarded and recreated\n } catch {\n // Invalid JSON, use fresh store\n }\n }\n\n // Check if blockrun auth already exists (OpenClaw format: profiles[\"provider:profileId\"])\n const profileKey = \"blockrun:default\";\n if (store.profiles[profileKey]) {\n continue; // Already configured\n }\n\n // Inject placeholder auth for blockrun (OpenClaw format)\n // The proxy handles real x402 auth internally, this just satisfies OpenClaw's lookup\n store.profiles[profileKey] = {\n type: \"api_key\",\n provider: \"blockrun\",\n key: \"x402-proxy-handles-auth\",\n };\n\n try {\n writeFileSync(authPath, JSON.stringify(store, null, 2));\n logger.info(`Injected BlockRun auth profile for agent: ${agentId}`);\n } catch (err) {\n logger.info(\n `Could not inject auth for ${agentId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n } catch (err) {\n logger.info(`Auth injection failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n// Store active proxy handle for cleanup on gateway_stop\nlet activeProxyHandle: Awaited> | null = null;\n\n/**\n * Start the x402 proxy in the background.\n * Called from register() because OpenClaw's loader only invokes register(),\n * treating activate() as an alias (def.register ?? def.activate).\n */\nasync function startProxyInBackground(api: OpenClawPluginApi): Promise {\n // Resolve wallet key: saved file → env var → auto-generate\n const wallet = await resolveOrGenerateWalletKey();\n\n // Log wallet source\n if (wallet.source === \"generated\") {\n api.logger.warn(`════════════════════════════════════════════════`);\n api.logger.warn(` NEW WALLET GENERATED — BACK UP YOUR KEY NOW!`);\n api.logger.warn(` Address : ${wallet.address}`);\n api.logger.warn(` Run /wallet export to get your private key`);\n api.logger.warn(` Losing this key = losing your USDC funds`);\n api.logger.warn(`════════════════════════════════════════════════`);\n } else if (wallet.source === \"saved\") {\n api.logger.info(`Using saved wallet: ${wallet.address}`);\n } else {\n api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);\n }\n\n // Resolve routing config overrides from plugin config\n const routingConfig = api.pluginConfig?.routing as Partial | undefined;\n\n const maxCostPerRunUsd =\n typeof api.pluginConfig?.maxCostPerRun === \"number\"\n ? (api.pluginConfig.maxCostPerRun as number)\n : undefined;\n\n const maxCostPerRunMode: \"graceful\" | \"strict\" =\n api.pluginConfig?.maxCostPerRunMode === \"strict\" ? \"strict\" : \"graceful\";\n\n if (maxCostPerRunUsd !== undefined) {\n api.logger.info(\n `Cost cap: $${maxCostPerRunUsd.toFixed(2)} per session (mode: ${maxCostPerRunMode})`,\n );\n }\n\n const proxy = await startProxy({\n wallet,\n routingConfig,\n maxCostPerRunUsd,\n maxCostPerRunMode,\n onReady: (port) => {\n api.logger.info(`BlockRun x402 proxy listening on port ${port}`);\n },\n onError: (error) => {\n api.logger.error(`BlockRun proxy error: ${error.message}`);\n },\n onRouted: (decision) => {\n const cost = decision.costEstimate.toFixed(4);\n const saved = (decision.savings * 100).toFixed(0);\n api.logger.info(\n `[${decision.tier}] ${decision.model} $${cost} (saved ${saved}%) | ${decision.reasoning}`,\n );\n },\n onLowBalance: (info) => {\n api.logger.warn(\n `[!] Low balance: ${info.balanceUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}`,\n );\n },\n onInsufficientFunds: (info) => {\n api.logger.error(\n `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}`,\n );\n },\n });\n\n setActiveProxy(proxy);\n activeProxyHandle = proxy;\n\n const startupExclusions = loadExcludeList();\n if (startupExclusions.size > 0) {\n api.logger.info(\n `Model exclusions active (${startupExclusions.size}): ${[...startupExclusions].join(\", \")}`,\n );\n }\n\n api.logger.info(`ClawRouter ready — smart routing enabled`);\n api.logger.info(`Pricing: Simple ~$0.001 | Code ~$0.01 | Complex ~$0.05 | Free: $0`);\n\n // Non-blocking balance check AFTER proxy is ready (won't hang startup)\n // Uses the proxy's chain-aware balance monitor and matching active-chain address.\n const currentChain = await resolvePaymentChain();\n const displayAddress =\n currentChain === \"solana\" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address;\n const network = currentChain === \"solana\" ? \"Solana\" : \"Base\";\n const paymentAssetLabel =\n currentChain === \"solana\"\n ? \"USDC\"\n : proxy.paymentAsset?.symbol ?? DEFAULT_BASE_PAYMENT_ASSET.symbol;\n proxy.balanceMonitor\n .checkBalance()\n .then(async (balance) => {\n if (balance.isEmpty) {\n api.logger.info(`Wallet (${network}): ${displayAddress}`);\n api.logger.info(\n `Balance: $0.00 — send ${paymentAssetLabel} on ${network} to the address above to unlock paid models.`,\n );\n } else if (balance.isLow) {\n api.logger.info(\n `Wallet (${network}): ${displayAddress} | Balance: ${balance.balanceUSD} (low — top up soon)`,\n );\n } else {\n api.logger.info(`Wallet (${network}): ${displayAddress} | Balance: ${balance.balanceUSD}`);\n }\n // On Solana, if USDC is low/empty, check for SOL and suggest swap\n if (currentChain === \"solana\" && (balance.isEmpty || balance.isLow)) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const solLamports: bigint = await (proxy.balanceMonitor as any).checkSolBalance();\n // Only suggest if they have meaningful SOL (> 0.01 SOL = 10M lamports)\n if (solLamports > 10_000_000n) {\n const sol = Number(solLamports) / 1_000_000_000;\n api.logger.info(\n `You have ${sol.toFixed(2)} SOL — swap to USDC: https://jup.ag/swap/SOL-USDC`,\n );\n }\n } catch {\n // SOL check is best-effort, don't block startup\n }\n }\n })\n .catch(() => {\n api.logger.info(`Wallet (${network}): ${displayAddress} | Balance: (checking...)`);\n });\n}\n\n/**\n * /stats command handler for ClawRouter.\n * Shows usage statistics and cost savings.\n */\nasync function createStatsCommand(): Promise {\n return {\n name: \"stats\",\n description: \"Show ClawRouter usage statistics and cost savings\",\n acceptsArgs: true,\n requireAuth: false,\n handler: async (ctx: PluginCommandContext) => {\n const arg = ctx.args?.trim().toLowerCase() || \"7\";\n\n if (arg === \"clear\" || arg === \"reset\") {\n try {\n const { deletedFiles } = await clearStats();\n return {\n text: `Stats cleared — ${deletedFiles} log file(s) deleted. Fresh start!`,\n };\n } catch (err) {\n return {\n text: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n\n const days = parseInt(arg, 10) || 7;\n\n try {\n const stats = await getStats(Math.min(days, 30)); // Cap at 30 days\n const ascii = formatStatsAscii(stats);\n\n return {\n text: [\"```\", ascii, \"```\"].join(\"\\n\"),\n };\n } catch (err) {\n return {\n text: `Failed to load stats: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n },\n };\n}\n\n/**\n * /exclude command handler for ClawRouter.\n * Manages excluded models — /exclude add|remove|clear \n */\nasync function createExcludeCommand(): Promise {\n return {\n name: \"exclude\",\n description: \"Manage excluded models — /exclude add|remove|clear \",\n acceptsArgs: true,\n requireAuth: true,\n handler: async (ctx: PluginCommandContext) => {\n const args = ctx.args?.trim() || \"\";\n const parts = args.split(/\\s+/);\n const subcommand = parts[0]?.toLowerCase() || \"\";\n const modelArg = parts.slice(1).join(\" \").trim();\n\n // /exclude (no args) — show current list\n if (!subcommand) {\n const list = loadExcludeList();\n if (list.size === 0) {\n return {\n text: \"No models excluded.\\n\\nUsage:\\n /exclude add — block a model\\n /exclude remove — unblock\\n /exclude clear — remove all\",\n };\n }\n const models = [...list]\n .sort()\n .map((m) => ` • ${m}`)\n .join(\"\\n\");\n return {\n text: `Excluded models (${list.size}):\\n${models}\\n\\nUse /exclude remove to unblock.`,\n };\n }\n\n // /exclude add \n if (subcommand === \"add\") {\n if (!modelArg) {\n return {\n text: \"Usage: /exclude add \\nExample: /exclude add nvidia/gpt-oss-120b\",\n isError: true,\n };\n }\n const resolved = addExclusion(modelArg);\n const list = loadExcludeList();\n return {\n text: `Excluded: ${resolved}\\n\\nActive exclusions (${list.size}):\\n${[...list]\n .sort()\n .map((m) => ` • ${m}`)\n .join(\"\\n\")}`,\n };\n }\n\n // /exclude remove \n if (subcommand === \"remove\") {\n if (!modelArg) {\n return { text: \"Usage: /exclude remove \", isError: true };\n }\n const removed = removeExclusion(modelArg);\n if (!removed) {\n return { text: `Model \"${modelArg}\" was not in the exclude list.` };\n }\n const list = loadExcludeList();\n return {\n text: `Unblocked: ${modelArg}\\n\\nActive exclusions (${list.size}):\\n${\n list.size > 0\n ? [...list]\n .sort()\n .map((m) => ` • ${m}`)\n .join(\"\\n\")\n : \" (none)\"\n }`,\n };\n }\n\n // /exclude clear\n if (subcommand === \"clear\") {\n clearExclusions();\n return { text: \"All model exclusions cleared.\" };\n }\n\n return {\n text: `Unknown subcommand: ${subcommand}\\n\\nUsage:\\n /exclude — show list\\n /exclude add \\n /exclude remove \\n /exclude clear`,\n isError: true,\n };\n },\n };\n}\n\n/**\n * /wallet command handler for ClawRouter.\n * - /wallet or /wallet status: Show wallet address, balance, usage, and key file location\n * - /wallet export: Show private key for backup (with security warning)\n */\nasync function createWalletCommand(): Promise {\n return {\n name: \"wallet\",\n description: \"Show BlockRun wallet info, usage stats, or export private key\",\n acceptsArgs: true,\n requireAuth: true,\n handler: async (ctx: PluginCommandContext) => {\n const subcommand = ctx.args?.trim().toLowerCase() || \"status\";\n\n // Read wallet key if it exists\n let walletKey: string | undefined;\n let address: string | undefined;\n try {\n if (existsSync(WALLET_FILE)) {\n walletKey = readTextFileSync(WALLET_FILE).trim();\n if (walletKey.startsWith(\"0x\") && walletKey.length === 66) {\n const account = privateKeyToAccount(walletKey as `0x${string}`);\n address = account.address;\n }\n }\n } catch {\n // Wallet file doesn't exist or is invalid\n }\n\n if (!walletKey || !address) {\n return {\n text: `No ClawRouter wallet found.\\n\\nRun \\`openclaw plugins install @blockrun/clawrouter\\` to generate a wallet.`,\n isError: true,\n };\n }\n\n if (subcommand === \"export\") {\n // Export private key + mnemonic for backup\n const lines = [\n \"**ClawRouter Wallet Export**\",\n \"\",\n \"**SECURITY WARNING**: Your private key and mnemonic control your wallet funds.\",\n \"Never share these. Anyone with them can spend your USDC.\",\n \"\",\n \"**EVM (Base):**\",\n ` Address: \\`${address}\\``,\n ` Private Key: \\`${walletKey}\\``,\n ];\n\n // Include mnemonic if it exists (Solana wallet derived from it)\n let hasMnemonic = false;\n try {\n if (existsSync(MNEMONIC_FILE)) {\n const mnemonic = readTextFileSync(MNEMONIC_FILE).trim();\n if (mnemonic) {\n hasMnemonic = true;\n // Derive Solana address for display\n const { deriveSolanaKeyBytes } = await import(\"./wallet.js\");\n const solKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solKeyBytes);\n\n lines.push(\n \"\",\n \"**Solana:**\",\n ` Address: \\`${signer.address}\\``,\n ` (Derived from mnemonic below)`,\n \"\",\n \"**Mnemonic (24 words):**\",\n `\\`${mnemonic}\\``,\n \"\",\n \"CRITICAL: Back up this mnemonic. It is the ONLY way to recover your Solana wallet.\",\n );\n }\n }\n } catch {\n // No mnemonic - EVM-only wallet\n }\n\n lines.push(\n \"\",\n \"**To restore on a new machine:**\",\n \"1. Set the environment variable before running OpenClaw:\",\n ` \\`export BLOCKRUN_WALLET_KEY=${walletKey}\\``,\n \"2. Or save to file:\",\n ` \\`mkdir -p ~/.openclaw/blockrun && echo \"${walletKey}\" > ~/.openclaw/blockrun/wallet.key && chmod 600 ~/.openclaw/blockrun/wallet.key\\``,\n );\n\n if (hasMnemonic) {\n lines.push(\n \"3. Restore the mnemonic for Solana:\",\n ` \\`echo \"\" > ~/.openclaw/blockrun/mnemonic && chmod 600 ~/.openclaw/blockrun/mnemonic\\``,\n );\n }\n\n return { text: lines.join(\"\\n\") };\n }\n\n if (subcommand === \"solana\") {\n // Switch to Solana chain. If mnemonic already exists, just persist the selection.\n // If no mnemonic, set up Solana wallet first.\n try {\n let solanaAddr: string | undefined;\n\n // Check if Solana wallet is already set up (mnemonic exists)\n if (existsSync(MNEMONIC_FILE)) {\n const existingMnemonic = readTextFileSync(MNEMONIC_FILE).trim();\n if (existingMnemonic) {\n // Already set up — just switch chain\n await savePaymentChain(\"solana\");\n const { deriveSolanaKeyBytes } = await import(\"./wallet.js\");\n const solKeyBytes = deriveSolanaKeyBytes(existingMnemonic);\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solKeyBytes);\n solanaAddr = signer.address;\n return {\n text: [\n \"Payment chain set to Solana. Restart the gateway to apply.\",\n \"\",\n `**Solana Address:** \\`${solanaAddr}\\``,\n `**Fund with USDC on Solana:** https://solscan.io/account/${solanaAddr}`,\n ].join(\"\\n\"),\n };\n }\n }\n\n // No mnemonic — first-time Solana setup\n const { solanaPrivateKeyBytes } = await setupSolana();\n await savePaymentChain(\"solana\");\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solanaPrivateKeyBytes);\n return {\n text: [\n \"**Solana Wallet Set Up**\",\n \"\",\n `**Solana Address:** \\`${signer.address}\\``,\n `**Mnemonic File:** \\`${MNEMONIC_FILE}\\``,\n \"\",\n \"Your existing EVM wallet is unchanged.\",\n \"Payment chain set to Solana. Restart the gateway to apply.\",\n \"\",\n `**Fund with USDC on Solana:** https://solscan.io/account/${signer.address}`,\n ].join(\"\\n\"),\n };\n } catch (err) {\n return {\n text: `Failed to set up Solana: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n\n if (subcommand === \"base\") {\n // Switch back to Base (EVM) payment chain\n try {\n await savePaymentChain(\"base\");\n return {\n text: \"Payment chain set to Base (EVM). Restart the gateway to apply.\",\n };\n } catch (err) {\n return {\n text: `Failed to set payment chain: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n\n // Default: show wallet status\n const basePaymentAssets =\n (await fetchBasePaymentAssets(\"https://blockrun.ai/api\").catch(() => undefined)) ??\n [DEFAULT_BASE_PAYMENT_ASSET];\n let basePaymentAsset = basePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET;\n let evmBalanceText = \"Balance: (could not check)\";\n let baseAssetLines: string[] = [];\n try {\n for (const asset of basePaymentAssets) {\n try {\n const assetMonitor = new BalanceMonitor(address, asset);\n const assetBalance = await assetMonitor.checkBalance();\n baseAssetLines.push(` ${asset.symbol}: ${assetBalance.balanceUSD}`);\n if (assetBalance.balance > 0n && evmBalanceText === \"Balance: (could not check)\") {\n basePaymentAsset = asset;\n evmBalanceText = `Balance: ${assetBalance.balanceUSD}`;\n }\n } catch {\n baseAssetLines.push(` ${asset.symbol}: (could not check)`);\n }\n }\n } catch {\n baseAssetLines = basePaymentAssets.map((asset) => ` ${asset.symbol}: (could not check)`);\n }\n\n // Check for Solana wallet\n let solanaSection = \"\";\n try {\n if (existsSync(MNEMONIC_FILE)) {\n const { deriveSolanaKeyBytes } = await import(\"./wallet.js\");\n const mnemonic = readTextFileSync(MNEMONIC_FILE).trim();\n if (mnemonic) {\n const solKeyBytes = deriveSolanaKeyBytes(mnemonic);\n const { createKeyPairSignerFromPrivateKeyBytes } = await import(\"@solana/kit\");\n const signer = await createKeyPairSignerFromPrivateKeyBytes(solKeyBytes);\n const solAddr = signer.address;\n\n let solBalanceText = \"Balance: (checking...)\";\n try {\n const { SolanaBalanceMonitor } = await import(\"./solana-balance.js\");\n const solMonitor = new SolanaBalanceMonitor(solAddr);\n const solBalance = await solMonitor.checkBalance();\n solBalanceText = `Balance: ${solBalance.balanceUSD}`;\n } catch {\n solBalanceText = \"Balance: (could not check)\";\n }\n\n solanaSection = [\n \"\",\n \"**Solana:**\",\n ` Address: \\`${solAddr}\\``,\n ` ${solBalanceText}`,\n ` Fund (USDC only): https://solscan.io/account/${solAddr}`,\n ].join(\"\\n\");\n }\n }\n } catch {\n // No Solana wallet - that's fine\n }\n\n // Show current chain selection\n const currentChain = await resolvePaymentChain();\n\n // Usage summary (last 7 days) — shows all models including openai/, anthropic/, etc.\n let usageSection = \"\";\n try {\n const stats = await getStats(7);\n if (stats.totalRequests > 0) {\n const modelLines = Object.entries(stats.byModel)\n .sort((a, b) => b[1].count - a[1].count)\n .slice(0, 8)\n .map(\n ([model, data]) =>\n ` ${model.length > 30 ? model.slice(0, 27) + \"...\" : model} ${data.count} reqs $${data.cost.toFixed(4)}`,\n );\n\n usageSection = [\n \"\",\n `**Usage (${stats.period}):**`,\n ` Total: ${stats.totalRequests} requests, $${stats.totalCost.toFixed(4)} spent`,\n stats.totalSavings > 0\n ? ` Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(0)}% vs Opus baseline)`\n : \"\",\n \"\",\n \"**Top Models:**\",\n ...modelLines,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n }\n } catch {\n // Stats not available — skip\n }\n\n return {\n text: [\n \"**ClawRouter Wallet**\",\n \"\",\n `**Payment Chain:** ${currentChain === \"solana\" ? \"Solana\" : \"Base (EVM)\"}`,\n \"\",\n \"**Base (EVM):**\",\n ` Address: \\`${address}\\``,\n ` ${evmBalanceText}`,\n ` Supported assets (priority order):`,\n ...baseAssetLines,\n ` Fund supported Base assets: https://basescan.org/address/${address}`,\n solanaSection,\n usageSection,\n \"\",\n `**Key File:** \\`${WALLET_FILE}\\``,\n \"\",\n \"**Commands:**\",\n \"• `/wallet` - Show this status\",\n \"• `/wallet export` - Export private key for backup\",\n \"• `/stats` - Detailed usage breakdown\",\n !solanaSection ? \"• `/wallet solana` - Enable Solana payments\" : \"\",\n solanaSection ? \"• `/wallet base` - Switch to Base (EVM)\" : \"\",\n solanaSection ? \"• `/wallet solana` - Switch to Solana\" : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n };\n },\n };\n}\n\nconst plugin: OpenClawPluginDefinition = {\n id: \"clawrouter\",\n name: \"ClawRouter\",\n description: \"Smart LLM router — 55+ models, x402 micropayments, 78% cost savings\",\n version: VERSION,\n\n register(api: OpenClawPluginApi) {\n // Check if ClawRouter is disabled via environment variable\n // Usage: CLAWROUTER_DISABLED=true openclaw gateway start\n const isDisabled =\n process[\"env\"].CLAWROUTER_DISABLED === \"true\" || process[\"env\"].CLAWROUTER_DISABLED === \"1\";\n if (isDisabled) {\n api.logger.info(\"ClawRouter disabled (CLAWROUTER_DISABLED=true). Using default routing.\");\n return;\n }\n\n // Install skills into OpenClaw workspace so agents can discover them\n // Must run before completion short-circuit so skills are available even on first install\n installSkillsToWorkspace(api.logger);\n\n // Skip heavy initialization in completion mode — only completion script is needed\n // Logging to stdout during completion pollutes the script and causes zsh errors\n if (isCompletionMode()) {\n api.registerProvider(blockrunProvider);\n return;\n }\n\n // Register BlockRun as a provider (sync — available immediately)\n api.registerProvider(blockrunProvider);\n\n // Inject models config into OpenClaw config file\n // This persists the config so models are recognized on restart\n injectModelsConfig(api.logger);\n\n // Inject dummy auth profiles into agent auth stores\n // OpenClaw's agent system looks for auth even if provider has auth: []\n injectAuthProfile(api.logger);\n\n // Also set runtime config for immediate availability\n const runtimePort = getProxyPort();\n if (!api.config.models) {\n api.config.models = { providers: {} };\n }\n if (!api.config.models.providers) {\n api.config.models.providers = {};\n }\n api.config.models.providers.blockrun = {\n baseUrl: `http://127.0.0.1:${runtimePort}/v1`,\n api: \"openai-completions\",\n // apiKey is required by pi-coding-agent's ModelRegistry for providers with models.\n apiKey: \"x402-proxy-handles-auth\",\n models: OPENCLAW_MODELS,\n };\n\n api.logger.info(\"BlockRun provider registered (55+ models via x402)\");\n\n // Register partner API tools (Twitter/X lookup, etc.)\n try {\n const proxyBaseUrl = `http://127.0.0.1:${runtimePort}`;\n const partnerTools = buildPartnerTools(proxyBaseUrl);\n for (const tool of partnerTools) {\n api.registerTool(tool);\n }\n if (partnerTools.length > 0) {\n api.logger.info(\n `Registered ${partnerTools.length} partner tool(s): ${partnerTools.map((t) => t.name).join(\", \")}`,\n );\n }\n\n // Register /partners command\n api.registerCommand({\n name: \"partners\",\n description: \"List available partner APIs and pricing\",\n acceptsArgs: false,\n requireAuth: false,\n handler: async () => {\n if (PARTNER_SERVICES.length === 0) {\n return { text: \"No partner APIs available.\" };\n }\n\n const lines = [\"**Partner APIs** (paid via your ClawRouter wallet)\", \"\"];\n\n for (const svc of PARTNER_SERVICES) {\n lines.push(`**${svc.name}** (${svc.partner})`);\n lines.push(` ${svc.description}`);\n lines.push(` Tool: \\`${`blockrun_${svc.id}`}\\``);\n lines.push(\n ` Pricing: ${svc.pricing.perUnit} per ${svc.pricing.unit} (min ${svc.pricing.minimum}, max ${svc.pricing.maximum})`,\n );\n lines.push(\n ` **How to use:** Ask \"Look up Twitter user @elonmusk\" or \"Get info on these X accounts: @naval, @balajis\"`,\n );\n lines.push(\"\");\n }\n\n return { text: lines.join(\"\\n\") };\n },\n });\n } catch (err) {\n api.logger.warn(\n `Failed to register partner tools: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Register /wallet command — shows wallet info + per-model usage stats\n createWalletCommand()\n .then((walletCommand) => {\n api.registerCommand(walletCommand);\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to register /wallet command: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n\n // Register /stats command for usage statistics\n createStatsCommand()\n .then((statsCommand) => {\n api.registerCommand(statsCommand);\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to register /stats command: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n\n // Register /exclude command for model exclusion management\n createExcludeCommand()\n .then((excludeCommand) => {\n api.registerCommand(excludeCommand);\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to register /exclude command: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n\n // Register a service with stop() for cleanup on gateway shutdown\n // This prevents EADDRINUSE when the gateway restarts\n api.registerService({\n id: \"clawrouter-proxy\",\n start: () => {\n // No-op: proxy is started below in non-blocking mode\n },\n stop: async () => {\n // Close proxy on gateway shutdown to release port 8402\n if (activeProxyHandle) {\n try {\n await activeProxyHandle.close();\n api.logger.info(\"BlockRun proxy closed\");\n } catch (err) {\n api.logger.warn(\n `Failed to close proxy: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n activeProxyHandle = null;\n }\n },\n });\n\n // Skip proxy startup unless we're in gateway mode\n // The proxy keeps the Node.js event loop alive, preventing CLI commands from exiting\n // The proxy will start automatically when the gateway runs\n if (!isGatewayMode()) {\n // Generate wallet on first install (even outside gateway mode)\n // This ensures users can see their wallet address immediately after install\n resolveOrGenerateWalletKey()\n .then(({ address, source }) => {\n if (source === \"generated\") {\n api.logger.warn(`════════════════════════════════════════════════`);\n api.logger.warn(` NEW WALLET GENERATED — BACK UP YOUR KEY NOW!`);\n api.logger.warn(` Address : ${address}`);\n api.logger.warn(` Run /wallet export to get your private key`);\n api.logger.warn(` Losing this key = losing your USDC funds`);\n api.logger.warn(`════════════════════════════════════════════════`);\n } else if (source === \"saved\") {\n api.logger.info(`Using saved wallet: ${address}`);\n } else {\n api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${address}`);\n }\n })\n .catch((err) => {\n api.logger.warn(\n `Failed to initialize wallet: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n api.logger.info(\"Not in gateway mode — proxy will start when gateway runs\");\n return;\n }\n\n // Start x402 proxy in background WITHOUT blocking register()\n // CRITICAL: Do NOT await here - this was blocking model selection UI for 3+ seconds\n // causing Chandler's \"infinite loop\" issue where model selection never finishes\n // Note: startProxyInBackground calls resolveOrGenerateWalletKey internally\n startProxyInBackground(api)\n .then(async () => {\n // Proxy started successfully - verify health\n const port = getProxyPort();\n const healthy = await waitForProxyHealth(port, 5000);\n if (!healthy) {\n api.logger.warn(`Proxy health check timed out, commands may not work immediately`);\n }\n })\n .catch((err) => {\n api.logger.error(\n `Failed to start BlockRun proxy: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n },\n};\n\nexport default plugin;\n\n// Re-export for programmatic use\nexport { startProxy, getProxyPort } from \"./proxy.js\";\nexport type {\n ProxyOptions,\n ProxyHandle,\n WalletConfig,\n PaymentChain,\n LowBalanceInfo,\n InsufficientFundsInfo,\n} from \"./proxy.js\";\nexport type { WalletResolution } from \"./auth.js\";\nexport { blockrunProvider } from \"./provider.js\";\nexport {\n OPENCLAW_MODELS,\n BLOCKRUN_MODELS,\n buildProviderModels,\n MODEL_ALIASES,\n resolveModelAlias,\n isAgenticModel,\n getAgenticModels,\n getModelContextWindow,\n} from \"./models.js\";\nexport {\n route,\n DEFAULT_ROUTING_CONFIG,\n getFallbackChain,\n getFallbackChainFiltered,\n calculateModelCost,\n} from \"./router/index.js\";\nexport type { RoutingDecision, RoutingConfig, Tier } from \"./router/index.js\";\nexport { logUsage } from \"./logger.js\";\nexport type { UsageEntry } from \"./logger.js\";\nexport { RequestDeduplicator } from \"./dedup.js\";\nexport type { CachedResponse } from \"./dedup.js\";\nexport { BalanceMonitor, BALANCE_THRESHOLDS } from \"./balance.js\";\nexport type { BalanceInfo, SufficiencyResult } from \"./balance.js\";\nexport { SolanaBalanceMonitor } from \"./solana-balance.js\";\nexport type { SolanaBalanceInfo } from \"./solana-balance.js\";\nexport {\n DEFAULT_BASE_PAYMENT_ASSET,\n fetchBasePaymentAsset,\n normalizeBasePaymentAsset,\n} from \"./payment-asset.js\";\nexport type { BasePaymentAsset } from \"./payment-asset.js\";\nexport {\n SpendControl,\n FileSpendControlStorage,\n InMemorySpendControlStorage,\n formatDuration,\n} from \"./spend-control.js\";\nexport type {\n SpendWindow,\n SpendLimits,\n SpendRecord,\n SpendingStatus,\n CheckResult,\n SpendControlStorage,\n SpendControlOptions,\n} from \"./spend-control.js\";\nexport {\n generateWalletMnemonic,\n isValidMnemonic,\n deriveEvmKey,\n deriveSolanaKeyBytes,\n deriveAllKeys,\n} from \"./wallet.js\";\nexport type { DerivedKeys } from \"./wallet.js\";\nexport { setupSolana, savePaymentChain, loadPaymentChain, resolvePaymentChain } from \"./auth.js\";\nexport {\n InsufficientFundsError,\n EmptyWalletError,\n RpcError,\n isInsufficientFundsError,\n isEmptyWalletError,\n isBalanceError,\n isRpcError,\n} from \"./errors.js\";\nexport { fetchWithRetry, isRetryable, DEFAULT_RETRY_CONFIG } from \"./retry.js\";\nexport type { RetryConfig } from \"./retry.js\";\nexport { getStats, formatStatsAscii, clearStats } from \"./stats.js\";\nexport type { DailyStats, AggregatedStats } from \"./stats.js\";\nexport {\n SessionStore,\n getSessionId,\n hashRequestContent,\n DEFAULT_SESSION_CONFIG,\n} from \"./session.js\";\nexport type { SessionEntry, SessionConfig } from \"./session.js\";\nexport { ResponseCache } from \"./response-cache.js\";\nexport type { CachedLLMResponse, ResponseCacheConfig } from \"./response-cache.js\";\nexport { PARTNER_SERVICES, getPartnerService, buildPartnerTools } from \"./partners/index.js\";\nexport type { PartnerServiceDefinition, PartnerToolDefinition } from \"./partners/index.js\";\n","/**\n * Partner Service Registry\n *\n * Defines available partner APIs that can be called through ClawRouter's proxy.\n * Partners provide specialized data (Twitter/X, etc.) via x402 micropayments.\n * The same wallet used for LLM calls pays for partner API calls — zero extra setup.\n */\n\nexport type PartnerServiceParam = {\n name: string;\n type: \"string\" | \"string[]\" | \"number\";\n description: string;\n required: boolean;\n};\n\nexport type PartnerServiceDefinition = {\n /** Unique service ID used in tool names: blockrun_{id} */\n id: string;\n /** Human-readable name */\n name: string;\n /** Partner providing this service */\n partner: string;\n /** Short description for tool listing */\n description: string;\n /** Proxy path (relative to /v1) */\n proxyPath: string;\n /** HTTP method */\n method: \"GET\" | \"POST\";\n /** Parameters for the tool's JSON Schema */\n params: PartnerServiceParam[];\n /** Pricing info for display */\n pricing: {\n perUnit: string;\n unit: string;\n minimum: string;\n maximum: string;\n };\n /** Example usage for help text */\n example: {\n input: Record;\n description: string;\n };\n};\n\n/**\n * All registered partner services.\n * New partners are added here — the rest of the system picks them up automatically.\n */\nexport const PARTNER_SERVICES: PartnerServiceDefinition[] = [\n {\n id: \"x_users_lookup\",\n name: \"Twitter/X User Lookup\",\n partner: \"AttentionVC\",\n description:\n \"Look up real-time Twitter/X user profiles by username. \" +\n \"Call this ONLY when the user explicitly asks to look up, check, or get information about a specific Twitter/X user's profile (follower count, bio, verification status, etc.). \" +\n \"Do NOT call this for messages that merely contain x.com or twitter.com URLs — only invoke when the user is asking for profile information about a specific account. \" +\n \"Returns: follower count, verification badge, bio, location, join date. \" +\n \"Accepts up to 100 usernames per request (without @ prefix).\",\n proxyPath: \"/x/users/lookup\",\n method: \"POST\",\n params: [\n {\n name: \"usernames\",\n type: \"string[]\",\n description:\n 'Array of Twitter/X usernames to look up (without @ prefix). Example: [\"elonmusk\", \"naval\"]',\n required: true,\n },\n ],\n pricing: {\n perUnit: \"$0.001\",\n unit: \"user\",\n minimum: \"$0.01 (10 users)\",\n maximum: \"$0.10 (100 users)\",\n },\n example: {\n input: { usernames: [\"elonmusk\", \"naval\", \"balaboris\"] },\n description: \"Look up 3 Twitter/X user profiles\",\n },\n },\n];\n\n/**\n * Get a partner service by ID.\n */\nexport function getPartnerService(id: string): PartnerServiceDefinition | undefined {\n return PARTNER_SERVICES.find((s) => s.id === id);\n}\n","/**\n * Partner Tool Builder\n *\n * Converts partner service definitions into OpenClaw tool definitions.\n * Each tool's execute() calls through the local proxy which handles\n * x402 payment transparently using the same wallet.\n */\n\nimport { PARTNER_SERVICES, type PartnerServiceDefinition } from \"./registry.js\";\n\n/** OpenClaw tool definition shape (duck-typed) */\nexport type PartnerToolDefinition = {\n name: string;\n description: string;\n parameters: {\n type: \"object\";\n properties: Record;\n required: string[];\n };\n execute: (toolCallId: string, params: Record) => Promise;\n};\n\n/**\n * Build a single partner tool from a service definition.\n */\nfunction buildTool(service: PartnerServiceDefinition, proxyBaseUrl: string): PartnerToolDefinition {\n // Build JSON Schema properties from service params\n const properties: Record = {};\n const required: string[] = [];\n\n for (const param of service.params) {\n const prop: Record = {\n description: param.description,\n };\n\n if (param.type === \"string[]\") {\n prop.type = \"array\";\n prop.items = { type: \"string\" };\n } else {\n prop.type = param.type;\n }\n\n properties[param.name] = prop;\n if (param.required) {\n required.push(param.name);\n }\n }\n\n return {\n name: `blockrun_${service.id}`,\n description: [\n service.description,\n \"\",\n `Partner: ${service.partner}`,\n `Pricing: ${service.pricing.perUnit} per ${service.pricing.unit} (min: ${service.pricing.minimum}, max: ${service.pricing.maximum})`,\n ].join(\"\\n\"),\n parameters: {\n type: \"object\",\n properties,\n required,\n },\n execute: async (_toolCallId: string, params: Record) => {\n const url = `${proxyBaseUrl}/v1${service.proxyPath}`;\n\n const response = await fetch(url, {\n method: service.method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(params),\n });\n\n if (!response.ok) {\n const errText = await response.text().catch(() => \"\");\n throw new Error(\n `Partner API error (${response.status}): ${errText || response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(data, null, 2),\n },\n ],\n details: data,\n };\n },\n };\n}\n\n/**\n * Build OpenClaw tool definitions for all registered partner services.\n * @param proxyBaseUrl - Local proxy base URL (e.g., \"http://127.0.0.1:8402\")\n */\nexport function buildPartnerTools(proxyBaseUrl: string): PartnerToolDefinition[] {\n return PARTNER_SERVICES.map((service) => buildTool(service, proxyBaseUrl));\n}\n","/**\n * Spend Control - Time-windowed spending limits\n *\n * Absorbed from @blockrun/clawwallet. Chain-agnostic (works for both EVM and Solana).\n *\n * Features:\n * - Per-request limits (e.g., max $0.10 per call)\n * - Hourly limits (e.g., max $3.00 per hour)\n * - Daily limits (e.g., max $20.00 per day)\n * - Session limits (e.g., max $5.00 per session)\n * - Rolling windows (last 1h, last 24h)\n * - Persistent storage (~/.openclaw/blockrun/spending.json)\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { readTextFileSync } from \"./fs-read.js\";\n\nconst WALLET_DIR = path.join(homedir(), \".openclaw\", \"blockrun\");\n\nconst HOUR_MS = 60 * 60 * 1000;\nconst DAY_MS = 24 * HOUR_MS;\n\nexport type SpendWindow = \"perRequest\" | \"hourly\" | \"daily\" | \"session\";\n\nexport interface SpendLimits {\n perRequest?: number;\n hourly?: number;\n daily?: number;\n session?: number;\n}\n\nexport interface SpendRecord {\n timestamp: number;\n amount: number;\n model?: string;\n action?: string;\n}\n\nexport interface SpendingStatus {\n limits: SpendLimits;\n spending: {\n hourly: number;\n daily: number;\n session: number;\n };\n remaining: {\n hourly: number | null;\n daily: number | null;\n session: number | null;\n };\n calls: number;\n}\n\nexport interface CheckResult {\n allowed: boolean;\n blockedBy?: SpendWindow;\n remaining?: number;\n reason?: string;\n resetIn?: number;\n}\n\nexport interface SpendControlStorage {\n load(): { limits: SpendLimits; history: SpendRecord[] } | null;\n save(data: { limits: SpendLimits; history: SpendRecord[] }): void;\n}\n\nexport class FileSpendControlStorage implements SpendControlStorage {\n private readonly spendingFile: string;\n\n constructor() {\n this.spendingFile = path.join(WALLET_DIR, \"spending.json\");\n }\n\n load(): { limits: SpendLimits; history: SpendRecord[] } | null {\n try {\n if (fs.existsSync(this.spendingFile)) {\n const data = JSON.parse(readTextFileSync(this.spendingFile));\n const rawLimits = data.limits ?? {};\n const rawHistory = data.history ?? [];\n\n const limits: SpendLimits = {};\n for (const key of [\"perRequest\", \"hourly\", \"daily\", \"session\"] as const) {\n const val = rawLimits[key];\n if (typeof val === \"number\" && val > 0 && Number.isFinite(val)) {\n limits[key] = val;\n }\n }\n\n const history: SpendRecord[] = [];\n if (Array.isArray(rawHistory)) {\n for (const r of rawHistory) {\n if (\n typeof r?.timestamp === \"number\" &&\n typeof r?.amount === \"number\" &&\n Number.isFinite(r.timestamp) &&\n Number.isFinite(r.amount) &&\n r.amount >= 0\n ) {\n history.push({\n timestamp: r.timestamp,\n amount: r.amount,\n model: typeof r.model === \"string\" ? r.model : undefined,\n action: typeof r.action === \"string\" ? r.action : undefined,\n });\n }\n }\n }\n\n return { limits, history };\n }\n } catch (err) {\n console.error(`[ClawRouter] Failed to load spending data, starting fresh: ${err}`);\n }\n return null;\n }\n\n save(data: { limits: SpendLimits; history: SpendRecord[] }): void {\n try {\n if (!fs.existsSync(WALLET_DIR)) {\n fs.mkdirSync(WALLET_DIR, { recursive: true, mode: 0o700 });\n }\n fs.writeFileSync(this.spendingFile, JSON.stringify(data, null, 2), {\n mode: 0o600,\n });\n } catch (err) {\n console.error(`[ClawRouter] Failed to save spending data: ${err}`);\n }\n }\n}\n\nexport class InMemorySpendControlStorage implements SpendControlStorage {\n private data: { limits: SpendLimits; history: SpendRecord[] } | null = null;\n\n load(): { limits: SpendLimits; history: SpendRecord[] } | null {\n return this.data\n ? {\n limits: { ...this.data.limits },\n history: this.data.history.map((r) => ({ ...r })),\n }\n : null;\n }\n\n save(data: { limits: SpendLimits; history: SpendRecord[] }): void {\n this.data = {\n limits: { ...data.limits },\n history: data.history.map((r) => ({ ...r })),\n };\n }\n}\n\nexport interface SpendControlOptions {\n storage?: SpendControlStorage;\n now?: () => number;\n}\n\nexport class SpendControl {\n private limits: SpendLimits = {};\n private history: SpendRecord[] = [];\n private sessionSpent: number = 0;\n private sessionCalls: number = 0;\n private readonly storage: SpendControlStorage;\n private readonly now: () => number;\n\n constructor(options?: SpendControlOptions) {\n this.storage = options?.storage ?? new FileSpendControlStorage();\n this.now = options?.now ?? (() => Date.now());\n this.load();\n }\n\n setLimit(window: SpendWindow, amount: number): void {\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(\"Limit must be a finite positive number\");\n }\n this.limits[window] = amount;\n this.save();\n }\n\n clearLimit(window: SpendWindow): void {\n delete this.limits[window];\n this.save();\n }\n\n getLimits(): SpendLimits {\n return { ...this.limits };\n }\n\n check(estimatedCost: number): CheckResult {\n const now = this.now();\n\n if (this.limits.perRequest !== undefined) {\n if (estimatedCost > this.limits.perRequest) {\n return {\n allowed: false,\n blockedBy: \"perRequest\",\n remaining: this.limits.perRequest,\n reason: `Per-request limit exceeded: $${estimatedCost.toFixed(4)} > $${this.limits.perRequest.toFixed(2)} max`,\n };\n }\n }\n\n if (this.limits.hourly !== undefined) {\n const hourlySpent = this.getSpendingInWindow(now - HOUR_MS, now);\n const remaining = this.limits.hourly - hourlySpent;\n if (estimatedCost > remaining) {\n const oldestInWindow = this.history.find((r) => r.timestamp >= now - HOUR_MS);\n const resetIn = oldestInWindow\n ? Math.ceil((oldestInWindow.timestamp + HOUR_MS - now) / 1000)\n : 0;\n return {\n allowed: false,\n blockedBy: \"hourly\",\n remaining,\n reason: `Hourly limit exceeded: $${(hourlySpent + estimatedCost).toFixed(2)} > $${this.limits.hourly.toFixed(2)} max`,\n resetIn,\n };\n }\n }\n\n if (this.limits.daily !== undefined) {\n const dailySpent = this.getSpendingInWindow(now - DAY_MS, now);\n const remaining = this.limits.daily - dailySpent;\n if (estimatedCost > remaining) {\n const oldestInWindow = this.history.find((r) => r.timestamp >= now - DAY_MS);\n const resetIn = oldestInWindow\n ? Math.ceil((oldestInWindow.timestamp + DAY_MS - now) / 1000)\n : 0;\n return {\n allowed: false,\n blockedBy: \"daily\",\n remaining,\n reason: `Daily limit exceeded: $${(dailySpent + estimatedCost).toFixed(2)} > $${this.limits.daily.toFixed(2)} max`,\n resetIn,\n };\n }\n }\n\n if (this.limits.session !== undefined) {\n const remaining = this.limits.session - this.sessionSpent;\n if (estimatedCost > remaining) {\n return {\n allowed: false,\n blockedBy: \"session\",\n remaining,\n reason: `Session limit exceeded: $${(this.sessionSpent + estimatedCost).toFixed(2)} > $${this.limits.session.toFixed(2)} max`,\n };\n }\n }\n\n return { allowed: true };\n }\n\n record(amount: number, metadata?: { model?: string; action?: string }): void {\n if (!Number.isFinite(amount) || amount < 0) {\n throw new Error(\"Record amount must be a non-negative finite number\");\n }\n const record: SpendRecord = {\n timestamp: this.now(),\n amount,\n model: metadata?.model,\n action: metadata?.action,\n };\n\n this.history.push(record);\n this.sessionSpent += amount;\n this.sessionCalls += 1;\n\n this.cleanup();\n this.save();\n }\n\n private getSpendingInWindow(from: number, to: number): number {\n return this.history\n .filter((r) => r.timestamp >= from && r.timestamp <= to)\n .reduce((sum, r) => sum + r.amount, 0);\n }\n\n getSpending(window: \"hourly\" | \"daily\" | \"session\"): number {\n const now = this.now();\n switch (window) {\n case \"hourly\":\n return this.getSpendingInWindow(now - HOUR_MS, now);\n case \"daily\":\n return this.getSpendingInWindow(now - DAY_MS, now);\n case \"session\":\n return this.sessionSpent;\n }\n }\n\n getRemaining(window: \"hourly\" | \"daily\" | \"session\"): number | null {\n const limit = this.limits[window];\n if (limit === undefined) return null;\n return Math.max(0, limit - this.getSpending(window));\n }\n\n getStatus(): SpendingStatus {\n const now = this.now();\n const hourlySpent = this.getSpendingInWindow(now - HOUR_MS, now);\n const dailySpent = this.getSpendingInWindow(now - DAY_MS, now);\n\n return {\n limits: { ...this.limits },\n spending: {\n hourly: hourlySpent,\n daily: dailySpent,\n session: this.sessionSpent,\n },\n remaining: {\n hourly: this.limits.hourly !== undefined ? this.limits.hourly - hourlySpent : null,\n daily: this.limits.daily !== undefined ? this.limits.daily - dailySpent : null,\n session: this.limits.session !== undefined ? this.limits.session - this.sessionSpent : null,\n },\n calls: this.sessionCalls,\n };\n }\n\n getHistory(limit?: number): SpendRecord[] {\n const records = [...this.history].reverse();\n return limit ? records.slice(0, limit) : records;\n }\n\n resetSession(): void {\n this.sessionSpent = 0;\n this.sessionCalls = 0;\n }\n\n private cleanup(): void {\n const cutoff = this.now() - DAY_MS;\n this.history = this.history.filter((r) => r.timestamp >= cutoff);\n }\n\n private save(): void {\n this.storage.save({\n limits: { ...this.limits },\n history: [...this.history],\n });\n }\n\n private load(): void {\n const data = this.storage.load();\n if (data) {\n this.limits = data.limits;\n this.history = data.history;\n this.cleanup();\n }\n }\n}\n\nexport function formatDuration(seconds: number): string {\n if (seconds < 60) {\n return `${seconds}s`;\n } else if (seconds < 3600) {\n const mins = Math.ceil(seconds / 60);\n return `${mins} min`;\n } else {\n const hours = Math.floor(seconds / 3600);\n const mins = Math.ceil((seconds % 3600) / 60);\n return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;\n }\n}\n","/**\n * Retry Logic for ClawRouter\n *\n * Provides fetch wrapper with exponential backoff for transient errors.\n * Retries on 429 (rate limit), 502, 503, 504 (server errors).\n */\n\n/** Configuration for retry behavior */\nexport type RetryConfig = {\n /** Maximum number of retries (default: 2) */\n maxRetries: number;\n /** Base delay in ms for exponential backoff (default: 500) */\n baseDelayMs: number;\n /** HTTP status codes that trigger a retry (default: [429, 502, 503, 504]) */\n retryableCodes: number[];\n};\n\n/** Default retry configuration */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 2,\n baseDelayMs: 500,\n retryableCodes: [429, 502, 503, 504],\n};\n\n/** Sleep for a given number of milliseconds */\nfunction sleep(ms: number): Promise {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Wrap a fetch-like function with retry logic and exponential backoff.\n *\n * @param fetchFn - The fetch function to wrap (can be standard fetch or x402 payFetch)\n * @param url - URL to fetch\n * @param init - Fetch init options\n * @param config - Retry configuration (optional, uses defaults)\n * @returns Response from successful fetch or last failed attempt\n *\n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * fetch,\n * \"https://api.example.com/endpoint\",\n * { method: \"POST\", body: JSON.stringify(data) },\n * { maxRetries: 3 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n fetchFn: (url: string, init?: RequestInit) => Promise,\n url: string,\n init?: RequestInit,\n config?: Partial,\n): Promise {\n const cfg: RetryConfig = {\n ...DEFAULT_RETRY_CONFIG,\n ...config,\n };\n\n let lastError: Error | undefined;\n let lastResponse: Response | undefined;\n\n for (let attempt = 0; attempt <= cfg.maxRetries; attempt++) {\n try {\n const response = await fetchFn(url, init);\n\n // Success or non-retryable status — return immediately\n if (!cfg.retryableCodes.includes(response.status)) {\n return response;\n }\n\n // Retryable status — save response and maybe retry\n lastResponse = response;\n\n // Check for Retry-After header (common with 429)\n const retryAfter = response.headers.get(\"retry-after\");\n let delay: number;\n\n if (retryAfter) {\n // Retry-After can be seconds or HTTP-date\n const seconds = parseInt(retryAfter, 10);\n delay = isNaN(seconds) ? cfg.baseDelayMs * Math.pow(2, attempt) : seconds * 1000;\n } else {\n delay = cfg.baseDelayMs * Math.pow(2, attempt);\n }\n\n // Only retry if we have attempts left\n if (attempt < cfg.maxRetries) {\n await sleep(delay);\n }\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n\n // Network errors are retryable\n if (attempt < cfg.maxRetries) {\n const delay = cfg.baseDelayMs * Math.pow(2, attempt);\n await sleep(delay);\n }\n }\n }\n\n // All retries exhausted — return last response or throw last error\n if (lastResponse) {\n return lastResponse;\n }\n\n throw lastError ?? new Error(\"Max retries exceeded\");\n}\n\n/**\n * Check if an error or response indicates a retryable condition.\n */\nexport function isRetryable(\n errorOrResponse: Error | Response,\n config?: Partial,\n): boolean {\n const retryableCodes = config?.retryableCodes ?? DEFAULT_RETRY_CONFIG.retryableCodes;\n\n if (errorOrResponse instanceof Response) {\n return retryableCodes.includes(errorOrResponse.status);\n }\n\n // Network errors are generally retryable\n const message = errorOrResponse.message.toLowerCase();\n return (\n message.includes(\"network\") ||\n message.includes(\"timeout\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"socket hang up\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa;AAAb;;;AAAO,IAAM,UAAU;;;;;ACCvB,IASa;AATb;;;;AASM,IAAO,YAAP,MAAO,mBAAkB,MAAK;MAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,cAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,cAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,cAAM,UAAU;UACd,gBAAgB;UAChB;UACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;UACrD,GAAIA,YAAW,CAAC,4BAA4BA,SAAQ,EAAE,IAAI,CAAA;UAC1D,GAAI,UAAU,CAAC,YAAY,OAAO,EAAE,IAAI,CAAA;UACxC,oBAAoB,OAAO;UAC3B,KAAK,IAAI;AAEX,cAAM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A,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WAEA,SACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WAEA,UACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,WACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA,YACA;AAjGb;;;AAAO,IAAM,UAAU,OAAO,KAAK,MAAM;AAClC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,WAAW,OAAO,MAAM,MAAM;AACpC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,OAAO,OAAO,MAAM;AACtC,IAAM,YAAY,O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ACA,mDACA,0DACA,uDAIA,sDACA,kDACA,gDAKA,0CACA,gDACA,mDACA,2DACA,uDACA,yDACA,qDACA,uDACA,6DACA,8DACA,wDACA,yDACA,sDACA,iEACA,iEACA,0DACA,yDACA,0DACA,sDACA,sDACA,0DACA,4DACA,yDACA,wDACA,6DACA,gEACA,yCACA,gDACA,2DACA,4DACA,qEACA,yDACA,6CACA,kDACA,yDACA,2DACA,gDACA,kDACA,gEACA,uDACA,oEACA,6DACA,4DACA,4CACA,sDACA,iDACA,0DACA,wDACA,sDACA,qDACA,gDACA,yEACA,wDACA,wEACA,8EAIA,4DACA,gDACA,+CACA,yDACA,uDACA,mDACA,6DACA,2DACA,2DACA,wEACA,0DACA,sDAIA,yDACA,8EACA,+EACA,wEACA,yDACA,qEACA,8DACA,yDACA,yDACA,2DACA,wEACA,oDACA,2DACA,wEACA,oDACA,4DACA,4DACA,gEAIA,6DACA,kEACA,wDACA,oDACA,wDACA,sFACA,wFACA,sFACA,kEACA,+CACA,4CACA,8CACA,wDACA,2EACA,8FACA,8DACA,gEACA,wDACA,6DACA,6EACA,+CACA,yDACA,oEAKA,0CACA,iDACA,uDACA,oDACA,4DACA,6DACA,0DACA,oDACA,sDAEA,sDACA,4DACA,wDACA,oDACA,gEACA,mDACA,sDACA,6DACA,oEACA,sDACA,2DACA,sEACA,wEACA,yDACA,iEACA,qEACA,oEACA,qEACA,8DACA,mEACA,wEACA,wDACA,8DACA,yEACA,0EACA,wDACA,2EACA,yDAIA,kEACA,kEACA,yDACA,qEACA,gFACA,kFACA,8DACA,8DACA,qEACA,8EAIA,sDACA,2CACA,6CACA,gDACA,mEACA,2DACA,yDACA,+CACA,uDACA,2DACA,4CACA,2CACA,+CACA,qDACA,2CACA,qDACA,gEACA,kDACA,wCACA,oEACA,+DACA,yDACA,wEACA,qEAIA,qCACA,oDACA,yCACA,oDAIA,kEACA,kEACA,yEACA,4DACA,4DAMA,wEACA,kHACA,kFACA,8DACA,yEACA,kEACA,kEEnEA,qB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AI,OAAO,KAAK,8CAA8C;AAC9D,cAAI,OAAO,KAAK,4CAA4C;AAC5D,cAAI,OAAO,KAAK,kSAAkD;AAAA,QACpE,WAAW,WAAW,SAAS;AAC7B,cAAI,OAAO,KAAK,uBAAuBA,QAAO,EAAE;AAAA,QAClD,OAAO;AACL,cAAI,OAAO,KAAK,0CAA0CA,QAAO,EAAE;AAAA,QACrE;AAAA,MACF,CAAC,EACA,MAAM,CAAC,QAAQ;AACd,YAAI,OAAO;AAAA,UACT,gCAAgC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,QAClF;AAAA,MACF,CAAC;AACH,UAAI,OAAO,KAAK,+DAA0D;AAC1E;AAAA,IACF;AAMA,2BAAuB,GAAG,EACvB,KAAK,YAAY;AAEhB,YAAM,OAAO,aAAa;AAC1B,YAAM,UAAU,MAAM,mBAAmB,MAAM,GAAI;AACnD,UAAI,CAAC,SAAS;AACZ,YAAI,OAAO,KAAK,iEAAiE;AAAA,MACnF;AAAA,IACF,CAAC,EACA,MAAM,CAAC,QAAQ;AACd,UAAI,OAAO;AAAA,QACT,mCAAmC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MACrF;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAEA,IAAOK,iBAAQ;","names":["docsPath","signature","signature","signature","signature","signature","abi","signature","signature","signature","length","formatAbiItem","init_formatAbiItem","version","init_version","BaseError","init_version","docsPath","version","init_formatAbiItem","BaseError","docsPath","size","signature","formatAbiItem","BaseError","size","size","BaseError","size","size","size","index","BaseError","encoder","l","s","crypto","toBytes","pad","crypto","init_utils","s","init_utils","l","toBytes","signature","BaseError","BaseError","address","size","hash","address","address","cacheKey","concatBytes","bytesRegex","integerRegex","init_regex","size","integerRegex","length","BaseError","index","init_regex","abi","index","abi","docsPath","formatAbiItem","init_formatAbiItem","abi","signature","BaseError","init_cursor","size","data","length","consumed","value","size","init_cursor","abi","signature","formatAbiItem","init_formatAbiItem","value","address","BaseError","BaseError","docsPath","chain","hash","index","init_utils","address","init_formatAbiItem","init_utils","BaseError","docsPath","chain","abi","formatAbiItem","signature","init_utils","BaseError","BaseError","docsPath","address","isLE","_32n","l","init_utils","toBytes","buffer","finished","init_utils","D","init_utils","hash","toBytes","pad","finished","isBytes","abytes","num","hexToNumber","_0n","bytesToHex","hexes","hexToBytes","e","concatBytes","pad","utf8ToBytes","_1n","gen","init_utils","_0n","modulo","_1n","gcd","_2n","P","num","bitLen","isLE","init_utils","_1n","s","P","_0n","base","wbits","init_utils","num","size","bytesToHex","Fn","toBytes","concatBytes","fromBytes","_3n","_4n","_1n","isBytes","Point","P","endo","_0n","a","modN","s","from","l","hexToBytes","utils","hash","randomBytes","e","sign","signature","isHex","o","_2n","tv5","c1","c2","init_utils","hash","create","init_utils","abytes","concatBytes","utf8ToBytes","hash","e","createHasher","Point","num","P","init_utils","P","_3n","_2n","concatBytes","_1n","_0n","e","signature","s","init_utils","createHasher","encode","BaseError","init_cursor","address","hash","BaseError","BaseError","e","formatted","address","init_stateOverride","address","sha256","sha256","init_sha256","version","sha256","init_sha256","version","init_blob","BaseError","size","hash","version","size","init_blob","init_cursor","abi","docsPath","isBytes","abytes","abool","numberToHexUnpadded","num","hexToNumber","_0n","bytesToHex","hasHexBuiltin","hexes","asciiToBase16","asciis","hexToBytes","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","e","concatBytes","pad","inRange","isPosBig","aInRange","bitLen","_1n","createHmacDrbg","u8n","u8fr","gen","validateObject","validatorFns","memoized","bitMask","init_utils","version","init_version","version","init_errors","init_version","walk","BaseError","init_errors","docsPath","version","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","charCodeToBase16","charCodeMap","pad","SizeExceedsPaddingSizeError","trim","assertSize","size","SizeOverflowError","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","pad","SizeExceedsPaddingSizeError","trim","stringify","value","size","assertSize","index","charCodeToBase16","BaseError","encoder","padRight","pad","slice","assertStartOffset","assertEndOffset","toBigInt","InvalidBytesBooleanError","toNumber","trim","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","stringify","assert","concat","from","assertSize","hexes","size","IntegerOutOfRangeError","fromString","encoder","pad","slice","assertStartOffset","assertEndOffset","trimLeft","trim","validate","SizeOverflowError","SliceOffsetOutOfBoundsError","SizeExceedsPaddingSizeError","BaseError","stringify","toRpc","init_contract","BaseError","chain","abi","docsPath","chain","docsPath","cause","wait","args","split","init_utils","BaseError","abi","signature","formatAbiItem","init_formatAbiItem","abi","docsPath","formatAbiItem","signature","init_formatAbiItem","abi","docsPath","ccipRequest","init_ccip","BaseError","toRpc","base","data","offchainLookup","offchainLookupSignature","wait","args","size","init_contract","init_stateOverride","address","hash","version","BaseError","init_blob","address","signature","blobs","commitments","proofs","v","s","signature","BaseError","integerRegex","base","bytesRegex","struct","init_typedData","init_regex","init_typedData","s","signature","isBytes","anumber","wrap","encode","decode","l","from","padding","num","checksum","hash","init_utils","wordlist","e","init_esm","init_utils","hash","s","signature","address","signature","signature","address","hash","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","bytesToHex","hasHexBuiltin","hexes","asciiToBase16","asciis","hexToBytes","concatBytes","pad","createHasher","randomBytes","init_utils","Chi","Maj","HashMD","SHA256_IV","init_md","init_utils","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","SHA256_K","SHA256_W","sha256","init_sha2","init_md","init_utils","HashMD","D","rotr","Chi","Maj","clean","SHA256_IV","createHasher","abool","isPosBig","anumber","numberToHexUnpadded","num","hexToNumber","_0n","bytesToNumberBE","bytesToHex","bytesToNumberLE","abytes","numberToBytesBE","hexToBytes","numberToBytesLE","inRange","aInRange","bitLen","_1n","createHmacDrbg","u8n","concatBytes","gen","validateObject","memoized","bitMask","init_utils","mod","_0n","pow2","modulo","invert","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","P","Field","tonelliShanks","_7n","e2","e3","_3n","FpLegendre","FpSqrt","validateField","FIELD_FIELDS","validateObject","FpPow","num","FpInvertBatch","nLength","anumber","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","abytes","bytesToNumberLE","bytesToNumberBE","numberToBytesLE","numberToBytesBE","init_modular","init_utils","FpInvertBatch","validateW","calcWOpts","bitMask","calcOffsets","_1n","getW","P","pointWindowSizes","_0n","Point","isLE","validateField","Field","Fn","pointPrecomputes","wNAF","init_curve","init_utils","init_modular","base","hmac","init_hmac","init_utils","hash","ahash","abytes","pad","clean","aexists","finished","divNearest","_0n","bitMask","bitLen","_1n","abool","weierstrass","Fn","validateObject","pointToBytes","concatBytes","abytes","_3n","_4n","Point","memoized","P","hexToBytes","endo","bytesToHex","wNAF","randomBytes","getMinHashLength","num","l","mapHashToField","isBytes","s","utils","hash","ahash","hmac","_2n","size","r","DER","bytesToNumberBE","aInRange","extraEntropy","e","sign","createHmacDrbg","signature","recoverPublicKey","DERErr","init_weierstrass","init_hmac","init_utils","init_curve","init_modular","numberToHexUnpadded","sqrtMod","P","_3n","pow2","_2n","Fpk1","secp256k1","init_secp256k1","init_sha2","init_modular","init_weierstrass","Field","weierstrass","sha256","isBytes","anumber","abytes","ahash","aexists","aoutput","clean","createView","rotr","concatBytes","pad","createHasher","oidNist","init_utils","_HMAC","hmac","init_hmac","init_utils","hash","ahash","abytes","pad","clean","aexists","finished","Chi","Maj","HashMD","SHA256_IV","SHA512_IV","init_md","init_utils","isLE","createView","aexists","abytes","buffer","aoutput","clean","finished","init_md","init_utils","HashMD","clean","createHasher","fromBig","U32_MASK64","_32n","split","l","add","shrSH","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add3L","add3H","add4L","add4H","add5L","add5H","init_u64","s","SHA256_K","SHA256_W","SHA2_32B","_SHA256","K512","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","sha256","sha512","init_sha2","init_md","init_u64","init_utils","HashMD","D","rotr","Chi","Maj","clean","SHA256_IV","split","rotrSH","shrSH","rotrSL","shrSL","rotrBH","rotrBL","add4L","add4H","add5L","add5H","add","add3L","add3H","SHA512_IV","createHasher","oidNist","isBytes","isArrayOf","afn","astr","anumber","aArr","astrArr","anumArr","chain","wrap","encode","decode","alphabet","l","join","from","convertRadix","radix","num","checksum","init_base","sha256","Point","init_secp256k1","init_hmac","init_sha2","init_utils","init_base","secp256k1","sha256","createView","concatBytes","abytes","hmac","sha512","version","path","index","hash","signature","sha512","e","isSolanaError","index","ORDERED_ERROR_NAMES","padBytes","slice","index","encoder","decoder","SolanaError","size","buffer","alphabet","base","charCodeToBase16","TextDecoder","TextEncoder","createEncoder","SolanaError","SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE","hexBytes","createDecoder","combineCodec","buffer","decoder","address","index","SolanaError","SolanaError","isAddress","base58Encoder","mod","pow2","SolanaError","address","e","encode","decode","Endian","combineCodec","createEncoder","createDecoder","size","newOffset","createEncoder","createDecoder","slice","combineCodec","getBase16Decoder","SolanaError","index","getEncodedSize","isFixedSize","getU8Encoder","transformEncoder","getU8Decoder","transformDecoder","l","encoder","decoder","containsBytes","init_index_node","AccountRole","isAddress","SolanaError","combineCodec","assertValidBaseString","alphabet","SolanaError","partitionLeadingZeroes","getBigIntFromBaseX","base","getBaseXFromBigInt","getU8Encoder","getU8Decoder","getStructEncoder","getStructDecoder","getArrayEncoder","getShortU16Encoder","getArrayDecoder","getShortU16Decoder","createEncoder","createDecoder","version","combineCodec","transformEncoder","getBase58Encoder","getAddressEncoder","getAddressDecoder","getBase58Decoder","transformDecoder","address","TYPE","index","AccountRole","getAddressComparator","isWritableRole","isSignerRole","l","getBaseXEncoder","getBaseXDecoder","SolanaError","signature","randomBytes","privateKey","signature","getBytesEncoder","SolanaError","address","index","SYSTEM_PROGRAM_ADDRESS","isAdvanceNonceAccountInstructionData","isAddress","signatureBytes","signTransaction","SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT","index","appendTransactionMessageInstruction","SolanaError","signature","context","traverse","traverseSequential","traverseParallel","traverseSingle","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND","candidate","message","appendTransactionMessageInstructions","getAbortablePromise","getTransactionMessageSize","TRANSACTION_SIZE_LIMIT","isSolanaError","SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN","SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND","isAddress","version","SolanaError","transformEncoder","getAddressDecoder","getSignaturesToEncode","signature","getSignaturesEncoder","getU8Encoder","getStructEncoder","getBytesEncoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO","address","transformDecoder","getStructDecoder","getArrayDecoder","getBytesDecoder","getU8Decoder","combineCodec","index","SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO","getArrayEncoder","getAddressEncoder","getUtf8Encoder","fixDecoderSize","getTupleDecoder","getUtf8Decoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY","getTupleEncoder","getHiddenPrefixDecoder","SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED","encoder","SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE","signatureBytes","OffchainMessageContentFormat","plugin","unwrapBigIntValueObject","wrapBigIntValueObject","traverse","pipe","SolanaError","stringify","path","e","normalizeHeaders","AbortController","args","setMaxListeners","init_index_node","createExplicitAbortToken","e","EXPLICIT_ABORT_TOKEN","AbortController","EventTarget","args","setMaxListeners","e","SolanaError","AbortController","args","setMaxListeners","getAllowedNumericKeypaths","memoizedKeypaths","concat","buffer","toArrayBuffer","e","num","data","e","concat","toArrayBuffer","Receiver","num","Sender","http","randomBytes","createHash","URL","Receiver","Sender","WebSocket","address","e","key","WebSocket","createWebSocketStream","err","open","protocol","http","createHash","WebSocket","WebSocketServer","index","version","WebSocket","s","EventTarget","index_node_default","args","setMaxListeners","WebSocketImpl","createSolanaJsonRpcIntegerOverflowError","path","e","index","pipe","transformChannelInboundMessages","transformChannelOutboundMessages","cache","AbortController","args","setMaxListeners","SolanaError","address","isAddress","offchainMessageEnvelope","SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING","signature","transaction","o","TextEncoder","e","base58Decoder","SolanaError","signature","safeRace","getTimeoutPromise","AbortController","args","setMaxListeners","lamports","l","createRecentSignatureConfirmationPromiseFactory","signature","e","commitmentComparator","sha512","index","createKeyPairSignerFromPrivateKeyBytes","init_esm","CACHE_TTL_MS","init_index_node","fixDecoderSize","getBytesDecoder","getStructDecoder","getU64Decoder","getU16Decoder","getOptionDecoder","getAddressDecoder","getU32Decoder","getBooleanDecoder","address","isTransactionSigner","kitIsTransactionSigner","getAddressEncoder","transformEncoder","getStructEncoder","getU8Encoder","getU64Encoder","AccountRole","ASSOCIATED_TOKEN_ERROR__INVALID_OWNER","associatedTokenErrorMessages","AccountState","init_index_node","transformEncoder","getStructEncoder","getU8Encoder","getU32Encoder","appendTransactionMessageInstruction","init_src","init_index_node","x402Version","tx","NETWORKS","init_src","init_index_node","x402Version","tx","NETWORKS","homedir","join","mkdir","writeFile","readFileSync","BaseError","init_formatAbiItem","abi","formatAbiItem","signature","address","abi","abi","address","docsPath","BaseError","err","hash","signature","secp256k1","s","yParityOrV","recoveryBit","hash","signature","signature","BaseError","docsPath","chain","docsPath","cause","init_stateOverride","BaseError","BaseError","formatAuthorizationList","chain","chain","base","docsPath","cause","chain","format","base","chain","prepareTransactionRequest","getChainId","chainId","from","gas","nonce","type","e","error","getBlock","block","BaseError","abi","address","init_formatAbiItem","docsPath","abi","signature","formatAbiItem","abi","isEqual","index","value","input","address","event","abi","address","abi","address","abi","address","listeners","cleanup","poll","cacheKey","cache","abi","address","transport","eventName","args","shouldRetry","size","chain","base","key","BaseError","e","hash","hash","chain","address","BaseError","res","chain","address","chain","chain","address","event","address","address","address","BaseError","address","address","version","e","address","signature","promiseCache","uid","BaseError","chain","base","body","response","assert","from","validate","LruMap","size","LruMap","keccak256","assert","from","validate","fromHex","fromBytes","assert","x","slice","prefix","toHex","assert","concat","BaseError","stringify","size","from","addressRegex","assert","InvalidAddressError","checksum","address","hash","keccak256","from","toHex","validate","address","assert","InvalidAddressError","BaseError","bytesRegex","integerRegex","maxInt8","maxInt16","maxInt24","maxInt32","maxInt40","maxInt48","maxInt56","maxInt64","maxInt72","maxInt80","maxInt88","maxInt96","maxInt104","maxInt112","maxInt120","maxInt128","maxInt136","maxInt144","maxInt152","maxInt160","maxInt168","maxInt176","maxInt184","maxInt192","maxInt200","maxInt208","maxInt216","maxInt224","maxInt232","maxInt240","maxInt248","maxInt256","minInt8","minInt16","minInt24","minInt32","minInt40","minInt48","minInt56","minInt64","minInt72","minInt80","minInt88","minInt96","minInt104","minInt112","minInt120","minInt128","minInt136","minInt144","minInt152","minInt160","minInt168","minInt176","minInt184","minInt192","minInt200","minInt208","minInt216","minInt224","minInt232","minInt240","minInt248","minInt256","maxUint8","maxUint16","maxUint24","maxUint32","maxUint40","maxUint48","maxUint56","maxUint64","maxUint72","maxUint80","maxUint88","maxUint96","maxUint104","maxUint112","maxUint120","maxUint128","maxUint136","maxUint144","maxUint152","maxUint160","maxUint168","maxUint176","maxUint184","maxUint192","maxUint200","maxUint208","maxUint216","maxUint224","maxUint232","maxUint240","maxUint248","maxUint256","decodeParameter","checksumAddress","getArrayComponents","decodeArray","decodeTuple","decodeAddress","decodeBool","decodeBytes","decodeNumber","decodeString","sizeOfLength","sizeOfOffset","checksum","wrap","address","slice","toNumber","length","hasDynamicChild","consumed","value","size","toBigInt","encodeArray","encodeTuple","encodeAddress","integerRegex","encodeNumber","encodeBytes","encodeString","concat","assert","InvalidArrayError","BytesSizeMismatchError","BaseError","IntegerOutOfRangeError","fromString","index","staticCursor","RecursiveReadLimitExceededError","PositionOutOfBoundsError","NegativeOffsetError","size","BaseError","checksumAddress","size","data","decodeParameter","encode","concat","encodePacked","address","assert","fromString","integerRegex","bytesRegex","BytesSizeMismatchError","from","BaseError","size","BytesSizeMismatchError","InvalidArrayError","from","getEncodable","fromHex","from","getEncodable","getEncodableList","getEncodableBytes","getSizeOfLength","encode","BaseError","init_utils","init_utils","_0n","_1n","_2n","_3n","_4n","_5n","_8n","mod","pow2","modulo","_0n","invert","mod","_1n","gcd","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","tonelliShanks","P","Field","FpLegendre","FpSqrt","_3n","FIELD_FIELDS","validateField","validateObject","FpPow","num","_0n","_1n","FpInvertBatch","FpLegendre","_1n","_2n","nLength","Field","bitLen","isLE","_0n","bitMask","_1n","num","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","getFieldBytesLength","getMinHashLength","mapHashToField","isLE","num","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","init_utils","_0n","_1n","constTimeNegate","validateW","calcWOpts","bitMask","calcOffsets","validateMSMPoints","validateMSMScalars","s","pointPrecomputes","pointWindowSizes","getW","P","wNAF","base","pippenger","bitLen","wbits","validateBasic","validateField","validateObject","nLength","init_utils","validateSigVerOpts","abool","validatePointOpts","validateBasic","validateObject","DERErr","DER","numberToHexUnpadded","num","_0n","bytesToNumberBE","ensureBytes","numToSizedHex","size","bytesToHex","numberToBytesBE","_1n","_2n","_3n","_4n","weierstrassPoints","Fn","Field","toBytes","concatBytes","fromBytes","inRange","isBytes","mod","aInRange","Point","memoized","FpInvertBatch","P","pippenger","endo","a","wNAF","validateOpts","weierstrass","modN","invert","s","from","l","hexToBytes","utils","getMinHashLength","mapHashToField","bitMask","hash","randomBytes","e","sign","createHmacDrbg","signature","isHex","getHash","hash","createCurve","create","weierstrass","secp256k1P","secp256k1N","_0n","_1n","_2n","divNearest","sqrtMod","P","_3n","pow2","Fpk1","Field","secp256k1","createCurve","mod","assert","signature","maxUint256","fromBytes","fromHex","InvalidSerializedSizeError","slice","s","yParity","extract","from","fromRpc","signature","fromRpc","yParity","signature","s","trimLeft","InvalidSerializedSizeError","BaseError","signature","size","from","stringify","from","fromRpc","address","signature","extract","hash","keccak256","concat","fromHex","toTuple","toTuple","address","signature","extract","recoverAddress","recoverPublicKey","signature","s","secp256k1","from","from","assert","slice","signature","recoverAddress","encode","size","concat","validate","BaseError","address","address","hash","index","hash","hash","contracts","abi","address","result","BaseError","init_stateOverride","block","toRpc","call","abi","result","error","e","normalizeSignature","signature","BaseError","isArgOfType","validate","index","getAmbiguousTypes","from","abi","validate","abiItem","slice","index","isArgOfType","getAmbiguousTypes","signature","normalizeSignature","keccak256","fromString","BaseError","encode","abi","options","fromAbi","concat","from","fromAbi","abi","item","encodeData","abi","args","fromAbi","abiFunction","getSelector","encode","concat","from","fromAbi","abi","getSelector","BaseError","encode","from","encodeData","call","address","InvalidWrappedSignatureError","assert","from","magicBytes","unwrap","validate","wrap","magicBytes","assert","slice","InvalidWrappedSignatureError","from","unwrap","signature","wrap","concat","encode","validate","BaseError","address","chain","hash","signature","address","signature","hash","address","signature","hash","transport","hash","from","block","transport","address","transport","event","args","hash","address","address","signature","hash","uid","BaseError","chain","wait","body","serializeTransaction","signature","from","decoder","x402Version","cache","cacheKey","payload","response","randomBytes","x402Version","signature","version","x402Version","signature","version","getAddress","getAddress","signature","from","encodeFunctionData","x402Version","readContract","signTransaction","getTransactionCount","estimateFeesPerGas","confidence","supportsToolCalling","supportsVision","decision","join","size","join","homedir","join","require","LOG_DIR","join","homedir","e","DEFAULT_TTL_MS","createHash","canonicalize","TIMESTAMP_PATTERN","InsufficientFundsError","RpcError","RpcError","mkdir","join","homedir","mkdir","chain","mkdir","crypto","hashMessage","hash","path","path","l","escapeRegex","originalChars","createHash","hash","join","dirname","homedir","join","homedir","dirname","DEFAULT_CONFIG","e","join","homedir","sanitized","size","readFileSync","buffer","account","baseUrl","createKeyPairSignerFromPrivateKeyBytes","SolanaBalanceMonitor","registerExactSvmScheme","chain","responseCache","s","mkdir","port","writeFile","normalizedModel","cacheKey","sufficiency","index","writeFileSync","existsSync","mkdirSync","homedir","join","dirname","fileURLToPath","s","homedir","WALLET_DIR","homedir","from","join","dirname","fileURLToPath","existsSync","homedir","mkdirSync","writeFileSync","address","deriveSolanaKeyBytes","createKeyPairSignerFromPrivateKeyBytes","signer","SolanaBalanceMonitor","index_default"]} \ No newline at end of file diff --git a/src/balance.ts b/src/balance.ts index 3cb741c..2139f9d 100644 --- a/src/balance.ts +++ b/src/balance.ts @@ -1,7 +1,9 @@ /** * Balance Monitor for ClawRouter * - * Monitors USDC balance on Base network with intelligent caching. + * Monitors stablecoin balance on Base network with intelligent caching. + * Supports any EIP-3009 stablecoin (USDC, fxUSD, EURC, etc.) with + * automatic normalization from native decimals to USD micros (6 decimals). * Provides pre-request balance checks to prevent failed payments. * * Caching Strategy: @@ -13,14 +15,12 @@ import { createPublicClient, http, erc20Abi } from "viem"; import { base } from "viem/chains"; import { RpcError } from "./errors.js"; - -/** USDC contract address on Base mainnet */ -const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as const; +import { DEFAULT_BASE_PAYMENT_ASSET, type BasePaymentAsset } from "./payment-asset.js"; /** Cache TTL in milliseconds (30 seconds) */ const CACHE_TTL_MS = 30_000; -/** Balance thresholds in USDC smallest unit (6 decimals) */ +/** Balance thresholds in USD micros (6 decimals, normalized from any stablecoin) */ export const BALANCE_THRESHOLDS = { /** Low balance warning threshold: $1.00 */ LOW_BALANCE_MICROS: 1_000_000n, @@ -30,10 +30,12 @@ export const BALANCE_THRESHOLDS = { /** Balance information returned by checkBalance() */ export type BalanceInfo = { - /** Raw balance in USDC smallest unit (6 decimals) */ + /** Raw balance normalized to USD micros (6 decimals, regardless of the underlying asset's native decimals) */ balance: bigint; /** Formatted balance as "$X.XX" */ balanceUSD: string; + /** Symbol of the active Base payment asset */ + assetSymbol: string; /** True if balance < $1.00 */ isLow: boolean; /** True if balance < $0.0001 (effectively zero) */ @@ -53,7 +55,7 @@ export type SufficiencyResult = { }; /** - * Monitors USDC balance on Base network. + * Monitors stablecoin balance on Base network. * * Usage: * const monitor = new BalanceMonitor("0x..."); @@ -63,14 +65,20 @@ export type SufficiencyResult = { export class BalanceMonitor { private readonly client; private readonly walletAddress: `0x${string}`; + private readonly assetMonitors = new Map(); + private state: { + asset: BasePaymentAsset; + cachedBalance: bigint | null; + cachedAt: number; + }; - /** Cached balance (null = not yet fetched) */ - private cachedBalance: bigint | null = null; - /** Timestamp when cache was last updated */ - private cachedAt = 0; - - constructor(walletAddress: string) { + constructor(walletAddress: string, asset: BasePaymentAsset = DEFAULT_BASE_PAYMENT_ASSET) { this.walletAddress = walletAddress as `0x${string}`; + this.state = { + asset, + cachedBalance: null, + cachedAt: 0, + }; this.client = createPublicClient({ chain: base, transport: http(undefined, { @@ -84,33 +92,34 @@ export class BalanceMonitor { * Uses cache if valid, otherwise fetches from RPC. */ async checkBalance(): Promise { + const state = this.state; const now = Date.now(); // Use cache only when balance is positive and still fresh. // Zero balance is never cached — always re-fetch so a funded wallet is // detected on the next request without waiting for cache expiry. if ( - this.cachedBalance !== null && - this.cachedBalance > 0n && - now - this.cachedAt < CACHE_TTL_MS + state.cachedBalance !== null && + state.cachedBalance > 0n && + now - state.cachedAt < CACHE_TTL_MS ) { - return this.buildInfo(this.cachedBalance); + return this.buildInfo(state.cachedBalance, state.asset); } // Fetch from RPC - const balance = await this.fetchBalance(); + const balance = await this.fetchBalance(state.asset); if (balance > 0n) { - this.cachedBalance = balance; - this.cachedAt = now; + state.cachedBalance = balance; + state.cachedAt = now; } - return this.buildInfo(balance); + return this.buildInfo(balance, state.asset); } /** * Check if balance is sufficient for an estimated cost. * - * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals) + * @param estimatedCostMicros - Estimated cost in USD micros (6 decimals) */ async checkSufficient(estimatedCostMicros: bigint): Promise { const info = await this.checkBalance(); @@ -123,19 +132,36 @@ export class BalanceMonitor { return { sufficient: false, info, - shortfall: this.formatUSDC(shortfall), + shortfall: this.formatUSD(shortfall), }; } + private get cachedBalance(): bigint | null { + return this.state.cachedBalance; + } + + private set cachedBalance(value: bigint | null) { + this.state.cachedBalance = value; + } + + private get cachedAt(): number { + return this.state.cachedAt; + } + + private set cachedAt(value: number) { + this.state.cachedAt = value; + } + /** * Optimistically deduct estimated cost from cached balance. * Call this after a successful payment to keep cache accurate. * - * @param amountMicros - Amount to deduct in USDC smallest unit + * @param amountMicros - Amount to deduct in USD micros */ deductEstimated(amountMicros: bigint): void { - if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) { - this.cachedBalance -= amountMicros; + const state = this.state; + if (state.cachedBalance !== null && state.cachedBalance >= amountMicros) { + state.cachedBalance -= amountMicros; } } @@ -144,8 +170,9 @@ export class BalanceMonitor { * Call this after a payment failure to get accurate balance. */ invalidate(): void { - this.cachedBalance = null; - this.cachedAt = 0; + const state = this.state; + state.cachedBalance = null; + state.cachedAt = 0; } /** @@ -156,15 +183,33 @@ export class BalanceMonitor { return this.checkBalance(); } + setAsset(asset: BasePaymentAsset): void { + const currentAsset = this.state.asset; + if ( + currentAsset.asset.toLowerCase() !== asset.asset.toLowerCase() || + currentAsset.symbol !== asset.symbol || + currentAsset.decimals !== asset.decimals + ) { + this.state = this.getSharedMonitorForAsset(asset).state; + } + } + + getAsset(): BasePaymentAsset { + return this.state.asset; + } + /** - * Format USDC amount (in micros) as "$X.XX". + * Format a stablecoin amount (normalized to USD micros) as "$X.XX". */ - formatUSDC(amountMicros: bigint): string { - // USDC has 6 decimals + formatUSD(amountMicros: bigint): string { const dollars = Number(amountMicros) / 1_000_000; return `$${dollars.toFixed(2)}`; } + formatUSDC(amountMicros: bigint): string { + return this.formatUSD(amountMicros); + } + /** * Get the wallet address being monitored. */ @@ -172,16 +217,38 @@ export class BalanceMonitor { return this.walletAddress; } + getAssetSymbol(): string { + return this.state.asset.symbol; + } + + getSharedMonitorForAsset(asset: BasePaymentAsset): BalanceMonitor { + if ( + this.state.asset.asset.toLowerCase() === asset.asset.toLowerCase() && + this.state.asset.symbol === asset.symbol && + this.state.asset.decimals === asset.decimals + ) { + return this; + } + + const key = `${asset.asset.toLowerCase()}:${asset.symbol}:${asset.decimals}`; + const existing = this.assetMonitors.get(key); + if (existing) return existing; + + const monitor = new BalanceMonitor(this.walletAddress, asset); + this.assetMonitors.set(key, monitor); + return monitor; + } + /** Fetch balance from RPC */ - private async fetchBalance(): Promise { + private async fetchBalance(asset: BasePaymentAsset): Promise { try { const balance = await this.client.readContract({ - address: USDC_BASE, + address: asset.asset, abi: erc20Abi, functionName: "balanceOf", args: [this.walletAddress], }); - return balance; + return this.toUsdMicros(balance, asset); } catch (error) { // Throw typed error instead of silently returning 0 // This allows callers to distinguish "node down" from "wallet empty" @@ -190,13 +257,22 @@ export class BalanceMonitor { } /** Build BalanceInfo from raw balance */ - private buildInfo(balance: bigint): BalanceInfo { + private buildInfo(balance: bigint, asset: BasePaymentAsset): BalanceInfo { return { balance, - balanceUSD: this.formatUSDC(balance), + balanceUSD: this.formatUSD(balance), + assetSymbol: asset.symbol, isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS, isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD, walletAddress: this.walletAddress, }; } + + private toUsdMicros(rawAmount: bigint, asset: BasePaymentAsset): bigint { + if (asset.decimals === 6) return rawAmount; + if (asset.decimals > 6) { + return rawAmount / 10n ** BigInt(asset.decimals - 6); + } + return rawAmount * 10n ** BigInt(6 - asset.decimals); + } } diff --git a/src/cli.ts b/src/cli.ts index fb82120..58dab3f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -280,7 +280,9 @@ async function main(): Promise { console.log(`[ClawRouter] [${decision.tier}] ${decision.model} $${cost} (saved ${saved}%)`); }, onLowBalance: (info) => { - console.warn(`[ClawRouter] Low balance: ${info.balanceUSD}. Fund: ${info.walletAddress}`); + console.warn( + `[ClawRouter] Low balance: ${info.balanceUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}`, + ); }, onInsufficientFunds: (info) => { console.error( @@ -298,7 +300,9 @@ async function main(): Promise { const balance = await proxy.balanceMonitor.checkBalance(); if (balance.isEmpty) { console.log(`[ClawRouter] Wallet balance: $0.00 (using FREE model)`); - console.log(`[ClawRouter] Fund wallet for premium models: ${displayAddress}`); + console.log( + `[ClawRouter] Fund wallet with ${balance.assetSymbol} for premium models: ${displayAddress}`, + ); } else if (balance.isLow) { console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD} (low)`); } else { diff --git a/src/doctor.ts b/src/doctor.ts index ddd3a54..88fc262 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -14,6 +14,11 @@ import { registerExactEvmScheme } from "@x402/evm/exact/client"; import { toClientEvmSigner } from "@x402/evm"; import { resolveOrGenerateWalletKey, resolvePaymentChain, WALLET_FILE } from "./auth.js"; import { BalanceMonitor } from "./balance.js"; +import { + DEFAULT_BASE_PAYMENT_ASSET, + fetchBasePaymentAssets, + type BasePaymentAsset, +} from "./payment-asset.js"; import { getSolanaAddress } from "./wallet.js"; import { getStats } from "./stats.js"; import { getProxyPort } from "./proxy.js"; @@ -38,6 +43,7 @@ interface WalletInfo { isEmpty: boolean; source: "saved" | "env" | "generated" | null; paymentChain: "base" | "solana"; + paymentAsset: BasePaymentAsset; } interface NetworkInfo { @@ -79,6 +85,22 @@ function yellow(text: string): string { return `\x1b[33m⚠\x1b[0m ${text}`; } +function getBuyLinkForAsset(symbol: string): { label: string; url: string } { + const normalized = symbol.trim().toUpperCase(); + const knownLinks: Record = { + USDC: "https://www.coinbase.com/price/usd-coin", + EURC: "https://www.coinbase.com/price/euro-coin", + }; + const knownUrl = knownLinks[normalized]; + if (knownUrl) { + return { label: `Get ${normalized}`, url: knownUrl }; + } + return { + label: `Find ${normalized} on Coinbase`, + url: `https://www.coinbase.com/search?q=${encodeURIComponent(normalized)}`, + }; +} + // Collect system info function collectSystemInfo(): SystemInfo { return { @@ -106,6 +128,7 @@ async function collectWalletInfo(): Promise { isEmpty: true, source: null, paymentChain: "base", + paymentAsset: DEFAULT_BASE_PAYMENT_ASSET, }; } @@ -121,6 +144,7 @@ async function collectWalletInfo(): Promise { // Check balance on the active payment chain const paymentChain = await resolvePaymentChain(); + let paymentAsset = DEFAULT_BASE_PAYMENT_ASSET; try { let balanceInfo: { balanceUSD: string; isLow: boolean; isEmpty: boolean }; if (paymentChain === "solana" && solanaAddress) { @@ -128,8 +152,28 @@ async function collectWalletInfo(): Promise { const monitor = new SolanaBalanceMonitor(solanaAddress); balanceInfo = await monitor.checkBalance(); } else { - const monitor = new BalanceMonitor(address); - balanceInfo = await monitor.checkBalance(); + const paymentAssets = + (await fetchBasePaymentAssets("https://blockrun.ai/api").catch(() => undefined)) ?? + [DEFAULT_BASE_PAYMENT_ASSET]; + const assetBalances = await Promise.all( + paymentAssets.map(async (asset) => { + const monitor = new BalanceMonitor(address, asset); + const info = await monitor.checkBalance(); + return { asset, info }; + }), + ); + const selectedBalance = + assetBalances.find(({ info }) => !info.isLow && !info.isEmpty) ?? + assetBalances.find(({ info }) => !info.isEmpty) ?? + assetBalances[0]; + paymentAsset = selectedBalance?.asset ?? DEFAULT_BASE_PAYMENT_ASSET; + balanceInfo = { + balanceUSD: selectedBalance?.info.balanceUSD ?? null, + isLow: + assetBalances.length > 0 ? assetBalances.every(({ info }) => info.isLow) : false, + isEmpty: + assetBalances.length > 0 ? assetBalances.every(({ info }) => info.isEmpty) : true, + }; } return { exists: true, @@ -141,6 +185,7 @@ async function collectWalletInfo(): Promise { isEmpty: balanceInfo.isEmpty, source, paymentChain, + paymentAsset, }; } catch { return { @@ -153,6 +198,7 @@ async function collectWalletInfo(): Promise { isEmpty: false, source, paymentChain, + paymentAsset, }; } } catch { @@ -166,6 +212,7 @@ async function collectWalletInfo(): Promise { isEmpty: true, source: null, paymentChain: "base", + paymentAsset: DEFAULT_BASE_PAYMENT_ASSET, }; } } @@ -233,8 +280,11 @@ function identifyIssues(result: DiagnosticResult): string[] { issues.push("No wallet found"); } if (result.wallet.isEmpty) { - const chain = result.wallet.paymentChain === "solana" ? "Solana" : "Base"; - issues.push(`Wallet is empty - need to fund with USDC on ${chain}`); + if (result.wallet.paymentChain === "solana") { + issues.push("Wallet is empty - need to fund with USDC on Solana"); + } else { + issues.push(`Wallet is empty - need to fund with ${result.wallet.paymentAsset.symbol} on Base`); + } if (result.wallet.paymentChain === "base" && result.wallet.solanaAddress) { issues.push("Tip: if you funded Solana, run /wallet solana to switch chains"); } @@ -272,9 +322,12 @@ function printDiagnostics(result: DiagnosticResult): void { console.log(` ${green(`Solana Address: ${result.wallet.solanaAddress}`)}`); } const chainLabel = result.wallet.paymentChain === "solana" ? "Solana" : "Base"; + const assetLabel = result.wallet.paymentChain === "solana" ? "USDC" : result.wallet.paymentAsset.symbol; console.log(` ${green(`Chain: ${chainLabel}`)}`); if (result.wallet.isEmpty) { - console.log(` ${red(`Balance: $0.00 - NEED TO FUND WITH USDC ON ${chainLabel.toUpperCase()}!`)}`); + console.log( + ` ${red(`Balance: $0.00 - NEED TO FUND WITH ${assetLabel} ON ${chainLabel.toUpperCase()}!`)}`, + ); if (result.wallet.paymentChain === "base" && result.wallet.solanaAddress) { console.log(` ${yellow(`Tip: funded Solana instead? Run /wallet solana to switch`)}`); } @@ -346,12 +399,22 @@ async function analyzeWithAI( ): Promise { // Check if wallet has funds if (diagnostics.wallet.isEmpty) { + const paymentAsset = diagnostics.wallet.paymentAsset; + const buyLink = getBuyLinkForAsset(paymentAsset.symbol); console.log("\n💳 Wallet is empty - cannot call AI for analysis."); - console.log(` Fund your EVM wallet with USDC on Base: ${diagnostics.wallet.address}`); - if (diagnostics.wallet.solanaAddress) { + console.log( + diagnostics.wallet.paymentChain === "solana" + ? ` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress ?? diagnostics.wallet.address}` + : ` Fund your EVM wallet with ${paymentAsset.symbol} on Base: ${diagnostics.wallet.address}`, + ); + if (diagnostics.wallet.paymentChain === "base" && diagnostics.wallet.solanaAddress) { console.log(` Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress}`); } - console.log(" Get USDC: https://www.coinbase.com/price/usd-coin"); + console.log( + diagnostics.wallet.paymentChain === "solana" + ? " Get USDC: https://www.coinbase.com/price/usd-coin" + : ` ${buyLink.label}: ${buyLink.url}`, + ); console.log(" Bridge to Base: https://bridge.base.org\n"); return; } diff --git a/src/index.ts b/src/index.ts index b379f99..513fda7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,6 +35,10 @@ import { } from "./auth.js"; import type { RoutingConfig } from "./router/index.js"; import { BalanceMonitor } from "./balance.js"; +import { + DEFAULT_BASE_PAYMENT_ASSET, + fetchBasePaymentAssets, +} from "./payment-asset.js"; import { loadExcludeList, addExclusion, @@ -585,11 +589,13 @@ async function startProxyInBackground(api: OpenClawPluginApi): Promise { ); }, onLowBalance: (info) => { - api.logger.warn(`[!] Low balance: ${info.balanceUSD}. Fund wallet: ${info.walletAddress}`); + api.logger.warn( + `[!] Low balance: ${info.balanceUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}`, + ); }, onInsufficientFunds: (info) => { api.logger.error( - `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund wallet: ${info.walletAddress}`, + `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund with ${info.assetSymbol}: ${info.walletAddress}`, ); }, }); @@ -613,13 +619,17 @@ async function startProxyInBackground(api: OpenClawPluginApi): Promise { const displayAddress = currentChain === "solana" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address; const network = currentChain === "solana" ? "Solana" : "Base"; + const paymentAssetLabel = + currentChain === "solana" + ? "USDC" + : proxy.paymentAsset?.symbol ?? DEFAULT_BASE_PAYMENT_ASSET.symbol; proxy.balanceMonitor .checkBalance() .then(async (balance) => { if (balance.isEmpty) { api.logger.info(`Wallet (${network}): ${displayAddress}`); api.logger.info( - `Balance: $0.00 — send USDC on ${network} to the address above to unlock paid models.`, + `Balance: $0.00 — send ${paymentAssetLabel} on ${network} to the address above to unlock paid models.`, ); } else if (balance.isLow) { api.logger.info( @@ -951,13 +961,28 @@ async function createWalletCommand(): Promise { } // Default: show wallet status - let evmBalanceText: string; + const basePaymentAssets = + (await fetchBasePaymentAssets("https://blockrun.ai/api").catch(() => undefined)) ?? + [DEFAULT_BASE_PAYMENT_ASSET]; + let basePaymentAsset = basePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET; + let evmBalanceText = "Balance: (could not check)"; + let baseAssetLines: string[] = []; try { - const monitor = new BalanceMonitor(address); - const balance = await monitor.checkBalance(); - evmBalanceText = `Balance: ${balance.balanceUSD}`; + for (const asset of basePaymentAssets) { + try { + const assetMonitor = new BalanceMonitor(address, asset); + const assetBalance = await assetMonitor.checkBalance(); + baseAssetLines.push(` ${asset.symbol}: ${assetBalance.balanceUSD}`); + if (assetBalance.balance > 0n && evmBalanceText === "Balance: (could not check)") { + basePaymentAsset = asset; + evmBalanceText = `Balance: ${assetBalance.balanceUSD}`; + } + } catch { + baseAssetLines.push(` ${asset.symbol}: (could not check)`); + } + } } catch { - evmBalanceText = "Balance: (could not check)"; + baseAssetLines = basePaymentAssets.map((asset) => ` ${asset.symbol}: (could not check)`); } // Check for Solana wallet @@ -1038,7 +1063,9 @@ async function createWalletCommand(): Promise { "**Base (EVM):**", ` Address: \`${address}\``, ` ${evmBalanceText}`, - ` Fund (USDC only): https://basescan.org/address/${address}`, + ` Supported assets (priority order):`, + ...baseAssetLines, + ` Fund supported Base assets: https://basescan.org/address/${address}`, solanaSection, usageSection, "", @@ -1310,6 +1337,12 @@ export { BalanceMonitor, BALANCE_THRESHOLDS } from "./balance.js"; export type { BalanceInfo, SufficiencyResult } from "./balance.js"; export { SolanaBalanceMonitor } from "./solana-balance.js"; export type { SolanaBalanceInfo } from "./solana-balance.js"; +export { + DEFAULT_BASE_PAYMENT_ASSET, + fetchBasePaymentAsset, + normalizeBasePaymentAsset, +} from "./payment-asset.js"; +export type { BasePaymentAsset } from "./payment-asset.js"; export { SpendControl, FileSpendControlStorage, diff --git a/src/payment-asset.test.ts b/src/payment-asset.test.ts new file mode 100644 index 0000000..0796caa --- /dev/null +++ b/src/payment-asset.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, it, vi } from "vitest"; +import { + DEFAULT_BASE_PAYMENT_ASSET, + fetchBasePaymentAsset, + fetchBasePaymentAssets, + normalizeBasePaymentAsset, + normalizeBasePaymentAssets, +} from "./payment-asset.js"; + +describe("payment asset helpers", () => { + it("normalizes a valid flat response", () => { + const asset = normalizeBasePaymentAsset({ + asset: "0x1111111111111111111111111111111111111111", + symbol: "eurc", + decimals: 6, + name: "Euro Coin", + transferMethod: "eip3009", + }); + + expect(asset).toEqual({ + chain: "base", + asset: "0x1111111111111111111111111111111111111111", + symbol: "EURC", + decimals: 6, + name: "Euro Coin", + transferMethod: "eip3009", + }); + }); + + it("rejects non-eip3009 assets", () => { + const asset = normalizeBasePaymentAsset({ + asset: "0x1111111111111111111111111111111111111111", + symbol: "USDT", + decimals: 6, + name: "Tether", + transferMethod: "permit2", + }); + + expect(asset).toBeUndefined(); + }); + + it("parses nested paymentAsset responses", async () => { + const mockFetch = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + paymentAsset: { + asset: "0x2222222222222222222222222222222222222222", + symbol: "EURC", + decimals: 6, + name: "Euro Coin", + transferMethod: "eip3009", + }, + }), + { status: 200 }, + ), + ); + + const asset = await fetchBasePaymentAsset( + "https://blockrun.ai/api", + mockFetch as unknown as typeof fetch, + ); + expect(asset?.asset).toBe("0x2222222222222222222222222222222222222222"); + expect(asset?.symbol).toBe("EURC"); + expect(mockFetch).toHaveBeenCalledWith( + "https://blockrun.ai/api/v1/payment-metadata?chain=base", + expect.any(Object), + ); + }); + + it("falls back to the default asset for invalid metadata responses", async () => { + const mockFetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ paymentAsset: { symbol: "EURC" } }), { status: 200 }), + ); + + const asset = await fetchBasePaymentAsset( + "https://blockrun.ai/api", + mockFetch as unknown as typeof fetch, + ); + expect(asset).toEqual(DEFAULT_BASE_PAYMENT_ASSET); + }); + + it("parses and sorts multiple assets by priority", () => { + const assets = normalizeBasePaymentAssets({ + paymentAssets: [ + { + asset: "0x3333333333333333333333333333333333333333", + symbol: "FXUSD", + decimals: 18, + name: "fxUSD", + transferMethod: "eip3009", + priority: 2, + }, + { + asset: "0x1111111111111111111111111111111111111111", + symbol: "USDC", + decimals: 6, + name: "USD Coin", + transferMethod: "eip3009", + priority: 1, + }, + ], + }); + + expect(assets.map((asset) => asset.symbol)).toEqual(["USDC", "FXUSD"]); + }); + + it("fetches multiple payment assets", async () => { + const mockFetch = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + paymentAssets: [ + { + asset: "0x1111111111111111111111111111111111111111", + symbol: "USDC", + decimals: 6, + name: "USD Coin", + transferMethod: "eip3009", + priority: 1, + }, + { + asset: "0x2222222222222222222222222222222222222222", + symbol: "EURC", + decimals: 6, + name: "Euro Coin", + transferMethod: "eip3009", + priority: 2, + }, + ], + }), + { status: 200 }, + ), + ); + + const assets = await fetchBasePaymentAssets( + "https://blockrun.ai/api", + mockFetch as unknown as typeof fetch, + ); + expect(assets).toHaveLength(2); + expect(assets[0]?.symbol).toBe("USDC"); + expect(assets[1]?.symbol).toBe("EURC"); + }); + + it("keeps USDC as the safe default asset", () => { + expect(DEFAULT_BASE_PAYMENT_ASSET.symbol).toBe("USDC"); + expect(DEFAULT_BASE_PAYMENT_ASSET.transferMethod).toBe("eip3009"); + }); + + it("normalizes fxUSD with 18 decimals correctly", () => { + const asset = normalizeBasePaymentAsset({ + asset: "0x55380fe7a1910dff29a47b622057ab4139da42c5", + symbol: "fxusd", + decimals: 18, + name: "fxUSD", + transferMethod: "eip3009", + }); + + expect(asset).toEqual({ + chain: "base", + asset: "0x55380fe7a1910dff29a47b622057ab4139da42c5", + symbol: "FXUSD", + decimals: 18, + name: "fxUSD", + transferMethod: "eip3009", + }); + }); + + it("handles mixed-decimal assets in normalizeBasePaymentAssets", () => { + const assets = normalizeBasePaymentAssets({ + paymentAssets: [ + { + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + symbol: "USDC", + decimals: 6, + name: "USD Coin", + transferMethod: "eip3009", + priority: 1, + }, + { + asset: "0x55380fe7a1910dff29a47b622057ab4139da42c5", + symbol: "FXUSD", + decimals: 18, + name: "fxUSD", + transferMethod: "eip3009", + priority: 2, + }, + { + asset: "0x0000000000000000000000000000000000000000", + symbol: "DISABLED", + decimals: 6, + name: "Disabled Token", + transferMethod: "eip3009", + enabled: false, + }, + ], + }); + + expect(assets).toHaveLength(2); + expect(assets[0]?.symbol).toBe("USDC"); + expect(assets[0]?.decimals).toBe(6); + expect(assets[1]?.symbol).toBe("FXUSD"); + expect(assets[1]?.decimals).toBe(18); + }); + + it("accepts the real fxUSD Base contract address", () => { + const asset = normalizeBasePaymentAsset({ + asset: "0x55380fe7A1910dFf29a47B622057AB4139DA42C5", + symbol: "FXUSD", + decimals: 18, + name: "fxUSD", + transferMethod: "eip3009", + }); + + expect(asset).toBeDefined(); + expect(asset?.asset).toBe("0x55380fe7A1910dFf29a47B622057AB4139DA42C5"); + }); +}); diff --git a/src/payment-asset.ts b/src/payment-asset.ts new file mode 100644 index 0000000..760264f --- /dev/null +++ b/src/payment-asset.ts @@ -0,0 +1,141 @@ +/** + * EIP-3009 payment asset on Base network. + * Represents a stablecoin that supports `transferWithAuthorization` + * for gasless, single-step payment settlements. + */ +export type BasePaymentAsset = { + chain: "base"; + asset: `0x${string}`; + symbol: string; + decimals: number; + name: string; + transferMethod: "eip3009"; + priority?: number; + enabled?: boolean; +}; + +/** Default payment asset: USDC on Base (6 decimals, EIP-3009). */ +export const DEFAULT_BASE_PAYMENT_ASSET: BasePaymentAsset = { + chain: "base", + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + symbol: "USDC", + decimals: 6, + name: "USD Coin", + transferMethod: "eip3009", +}; + +type PaymentMetadataResponse = + | Partial + | { paymentAssets?: Array> } + | { paymentAsset?: Partial } + | { base?: Partial }; + +/** Check if a value is a valid 0x-prefixed ERC-20 contract address (40 hex chars). */ +function isHexAddress(value: unknown): value is `0x${string}` { + return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value); +} + +/** + * Validate and normalize a single payment asset from an API response. + * Returns undefined if the input is missing required fields or uses a non-EIP-3009 transfer method. + * Symbols are uppercased; names are trimmed. + */ +export function normalizeBasePaymentAsset( + value: unknown, +): BasePaymentAsset | undefined { + if (!value || typeof value !== "object") return undefined; + + const candidate = value as Partial; + if (!isHexAddress(candidate.asset)) return undefined; + if (typeof candidate.symbol !== "string" || candidate.symbol.trim() === "") return undefined; + if ( + typeof candidate.decimals !== "number" || + !Number.isInteger(candidate.decimals) || + candidate.decimals < 0 + ) { + return undefined; + } + if (typeof candidate.name !== "string" || candidate.name.trim() === "") return undefined; + if (candidate.transferMethod !== undefined && candidate.transferMethod !== "eip3009") { + return undefined; + } + + return { + chain: "base", + asset: candidate.asset, + symbol: candidate.symbol.trim().toUpperCase(), + decimals: candidate.decimals, + name: candidate.name.trim(), + transferMethod: "eip3009", + priority: typeof candidate.priority === "number" ? candidate.priority : undefined, + enabled: typeof candidate.enabled === "boolean" ? candidate.enabled : undefined, + }; +} + +/** Sort assets by priority (ascending). Assets without priority go last. */ +function sortAssets(assets: BasePaymentAsset[]): BasePaymentAsset[] { + return [...assets].sort( + (a, b) => (a.priority ?? Number.MAX_SAFE_INTEGER) - (b.priority ?? Number.MAX_SAFE_INTEGER), + ); +} + +/** + * Normalize a payment metadata response into an array of valid EIP-3009 assets. + * Handles flat, nested (`paymentAsset`, `base`), and array (`paymentAssets`) response shapes. + * Filters out disabled and non-EIP-3009 assets. Falls back to USDC if no valid assets found. + */ +export function normalizeBasePaymentAssets(value: unknown): BasePaymentAsset[] { + if (!value || typeof value !== "object") return [DEFAULT_BASE_PAYMENT_ASSET]; + + const payload = value as PaymentMetadataResponse & { paymentAssets?: unknown }; + const candidateList = Array.isArray(payload.paymentAssets) + ? (payload.paymentAssets as unknown[]) + : [ + (payload as { paymentAsset?: unknown }).paymentAsset, + (payload as { base?: unknown }).base, + payload, + ]; + + const normalized = candidateList + .map((candidate: unknown) => normalizeBasePaymentAsset(candidate)) + .filter((asset: BasePaymentAsset | undefined): asset is BasePaymentAsset => Boolean(asset)) + .filter((asset) => asset.enabled !== false && asset.transferMethod === "eip3009"); + + return sortAssets( + normalized.length > 0 ? normalized : [DEFAULT_BASE_PAYMENT_ASSET], + ); +} + +/** + * Fetch all available EIP-3009 payment assets from the API. + * Falls back to the default USDC asset on network error or non-OK response. + */ +export async function fetchBasePaymentAssets( + apiBase: string, + baseFetch: typeof fetch = fetch, +): Promise { + try { + const response = await baseFetch(`${apiBase.replace(/\/+$/, "")}/v1/payment-metadata?chain=base`, { + headers: { Accept: "application/json" }, + }); + if (!response.ok) return [DEFAULT_BASE_PAYMENT_ASSET]; + + const payload = (await response.json()) as PaymentMetadataResponse; + return normalizeBasePaymentAssets(payload); + } catch { + // Network error, JSON parse failure, or normalize exception — fall back to USDC + return [DEFAULT_BASE_PAYMENT_ASSET]; + } +} + +/** + * Fetch the highest-priority EIP-3009 payment asset from the API. + * Convenience wrapper around {@link fetchBasePaymentAssets} that returns only the first asset. + */ +export async function fetchBasePaymentAsset( + apiBase: string, + baseFetch: typeof fetch = fetch, +): Promise { + const assets = await fetchBasePaymentAssets(apiBase, baseFetch); + return assets[0]; +} diff --git a/src/proxy.ts b/src/proxy.ts index afede4e..71e72b0 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -25,7 +25,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht // Per-request payment tracking via AsyncLocalStorage (safe for concurrent requests). // The x402 onAfterPaymentCreation hook writes the actual payment amount into the // request-scoped store, and the logging code reads it after payFetch completes. -const paymentStore = new AsyncLocalStorage<{ amountUsd: number }>(); +const paymentStore = new AsyncLocalStorage<{ amountUsd: number; amountUsdText: string }>(); import { finished } from "node:stream"; import type { AddressInfo } from "node:net"; import { homedir } from "node:os"; @@ -70,6 +70,11 @@ import { RequestDeduplicator } from "./dedup.js"; import { ResponseCache, type ResponseCacheConfig } from "./response-cache.js"; import { BalanceMonitor } from "./balance.js"; import type { SolanaBalanceMonitor } from "./solana-balance.js"; +import { + DEFAULT_BASE_PAYMENT_ASSET, + fetchBasePaymentAssets, + type BasePaymentAsset, +} from "./payment-asset.js"; /** Union type for chain-agnostic balance monitoring */ type AnyBalanceMonitor = BalanceMonitor | SolanaBalanceMonitor; @@ -178,7 +183,21 @@ async function readBodyWithTimeout( * Transform upstream payment errors into user-friendly messages. * Parses the raw x402 error and formats it nicely. */ -function transformPaymentError(errorBody: string): string { +function transformPaymentError( + errorBody: string, + opts?: { baseAssetSymbol?: string; baseAssetDecimals?: number }, +): string { + const baseAssetSymbol = opts?.baseAssetSymbol || DEFAULT_BASE_PAYMENT_ASSET.symbol; + const baseAssetDecimals = opts?.baseAssetDecimals ?? DEFAULT_BASE_PAYMENT_ASSET.decimals; + const formatRawAssetAmount = (amountRaw: bigint, decimals: number): string => { + const divisor = 10n ** BigInt(decimals); + const whole = amountRaw / divisor; + const remainder = amountRaw % divisor; + const scaledFraction = decimals >= 6 + ? remainder / 10n ** BigInt(decimals - 6) + : remainder * 10n ** BigInt(6 - decimals); + return `${whole.toString()}.${scaledFraction.toString().padStart(6, "0")}`; + }; try { // Try to parse the error JSON const parsed = JSON.parse(errorBody) as { @@ -208,22 +227,22 @@ function transformPaymentError(errorBody: string): string { /insufficient balance:\s*(\d+)\s*<\s*(\d+)/i, ); if (balanceMatch) { - const currentMicros = parseInt(balanceMatch[1], 10); - const requiredMicros = parseInt(balanceMatch[2], 10); - const currentUSD = (currentMicros / 1_000_000).toFixed(6); - const requiredUSD = (requiredMicros / 1_000_000).toFixed(6); + const currentRaw = BigInt(balanceMatch[1]); + const requiredRaw = BigInt(balanceMatch[2]); + const currentUSD = formatRawAssetAmount(currentRaw, baseAssetDecimals); + const requiredUSD = formatRawAssetAmount(requiredRaw, baseAssetDecimals); const wallet = innerJson.payer || "unknown"; const shortWallet = wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet; return JSON.stringify({ error: { - message: `Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`, + message: `Insufficient ${baseAssetSymbol} balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`, type: "insufficient_funds", wallet: wallet, current_balance_usd: currentUSD, required_usd: requiredUSD, - help: `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free`, + help: `Fund wallet ${shortWallet} with ${baseAssetSymbol} on Base, or use free model: /model free`, }, }); } @@ -352,6 +371,17 @@ function transformPaymentError(errorBody: string): string { return errorBody; } +function formatStableAmount(amountRaw: bigint, decimals: number): string { + const divisor = 10n ** BigInt(decimals); + const whole = amountRaw / divisor; + const remainder = amountRaw % divisor; + const scaledFraction = + decimals >= 6 + ? remainder / 10n ** BigInt(decimals - 6) + : remainder * 10n ** BigInt(6 - decimals); + return `${whole.toString()}.${scaledFraction.toString().padStart(6, "0")}`; +} + /** * Semantic error categories from upstream provider responses. * Used to distinguish auth failures from rate limits from server errors @@ -534,7 +564,15 @@ export function getProxyPort(): number { */ async function checkExistingProxy( port: number, -): Promise<{ wallet: string; paymentChain?: string } | undefined> { +): Promise< + | { + wallet: string; + paymentChain?: string; + paymentAssets?: BasePaymentAsset[]; + selectedPaymentAsset?: string | BasePaymentAsset; + } + | undefined +> { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS); @@ -549,9 +587,19 @@ async function checkExistingProxy( status?: string; wallet?: string; paymentChain?: string; + paymentAssets?: BasePaymentAsset[]; + selectedPaymentAsset?: string | BasePaymentAsset; + paymentAsset?: string; + paymentAssetSymbol?: string; + paymentAssetDecimals?: number; }; if (data.status === "ok" && data.wallet) { - return { wallet: data.wallet, paymentChain: data.paymentChain }; + return { + wallet: data.wallet, + paymentChain: data.paymentChain, + paymentAssets: data.paymentAssets, + selectedPaymentAsset: data.selectedPaymentAsset ?? data.paymentAsset, + }; } } return undefined; @@ -1091,6 +1139,7 @@ function stripThinkingTokens(content: string): string { export type LowBalanceInfo = { balanceUSD: string; walletAddress: string; + assetSymbol: string; }; /** Callback info for insufficient funds error */ @@ -1098,6 +1147,7 @@ export type InsufficientFundsInfo = { balanceUSD: string; requiredUSD: string; walletAddress: string; + assetSymbol: string; }; /** @@ -1181,6 +1231,8 @@ export type ProxyHandle = { baseUrl: string; walletAddress: string; solanaAddress?: string; + paymentAsset?: BasePaymentAsset; + paymentAssets?: BasePaymentAsset[]; balanceMonitor: AnyBalanceMonitor; close: () => Promise; }; @@ -1240,8 +1292,9 @@ function mergeRoutingConfig(overrides?: Partial): RoutingConfig { } /** - * Estimate USDC cost for a request based on model pricing. - * Returns amount string in USDC smallest unit (6 decimals) or undefined if unknown. + * Estimate stablecoin cost for a request based on model pricing. + * Returns amount string in USD micros (6-decimal integer, i.e. 1 = $0.000001) or undefined if unknown. + * This is an internal unit used for balance checks; conversion to on-chain token units happens elsewhere. */ function estimateAmount( modelId: string, @@ -1259,7 +1312,7 @@ function estimateAmount( (estimatedInputTokens / 1_000_000) * model.inputPrice + (estimatedOutputTokens / 1_000_000) * model.outputPrice; - // Convert to USDC 6-decimal integer, add 20% buffer for estimation error + // Convert to USD micros (6-decimal integer), add 20% buffer for estimation error // Minimum 1000 ($0.001) to match CDP Facilitator's enforced minimum payment const amountMicros = Math.max(1000, Math.ceil(costUsd * 1.2 * 1_000_000)); return amountMicros.toString(); @@ -1462,6 +1515,12 @@ export async function startProxy(options: ProxyOptions): Promise { const apiBase = options.apiBase ?? (paymentChain === "solana" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API); + let activeBasePaymentAssets = + paymentChain === "base" + ? (await fetchBasePaymentAssets(apiBase).catch(() => undefined)) ?? [DEFAULT_BASE_PAYMENT_ASSET] + : [DEFAULT_BASE_PAYMENT_ASSET]; + let activeBasePaymentAsset = activeBasePaymentAssets[0] ?? DEFAULT_BASE_PAYMENT_ASSET; + let lastSelectedBasePaymentAsset = activeBasePaymentAsset; if (paymentChain === "solana" && !solanaPrivateKeyBytes) { console.warn( `[ClawRouter] ⚠ Payment chain is Solana but no mnemonic found — falling back to Base (EVM).`, @@ -1477,30 +1536,29 @@ export async function startProxy(options: ProxyOptions): Promise { // Determine port: options.port > env var > default const listenPort = options.port ?? getProxyPort(); - // Check if a proxy is already running on this port - const existingProxy = await checkExistingProxy(listenPort); - if (existingProxy) { - // Proxy already running — reuse it instead of failing with EADDRINUSE + const buildReuseHandle = async (existingProxyData: { + wallet: string; + paymentChain?: string; + paymentAssets?: BasePaymentAsset[]; + selectedPaymentAsset?: string | BasePaymentAsset; + }): Promise => { const account = privateKeyToAccount(walletKey as `0x${string}`); const baseUrl = `http://127.0.0.1:${listenPort}`; - // Verify the existing proxy is using the same wallet (or warn if different) - if (existingProxy.wallet !== account.address) { + if (existingProxyData.wallet !== account.address) { console.warn( - `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account.address}. Reusing existing proxy.`, + `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxyData.wallet}, but current config uses ${account.address}. Reusing existing proxy.`, ); } - // Verify the existing proxy is using the same payment chain - if (existingProxy.paymentChain) { - if (existingProxy.paymentChain !== paymentChain) { + if (existingProxyData.paymentChain) { + if (existingProxyData.paymentChain !== paymentChain) { throw new Error( - `Existing proxy on port ${listenPort} is using ${existingProxy.paymentChain} but ${paymentChain} was requested. ` + + `Existing proxy on port ${listenPort} is using ${existingProxyData.paymentChain} but ${paymentChain} was requested. ` + `Stop the existing proxy first or use a different port.`, ); } } else if (paymentChain !== "base") { - // Old proxy doesn't report chain — assume Base. Reject if Solana was requested. console.warn( `[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`, ); @@ -1510,7 +1568,6 @@ export async function startProxy(options: ProxyOptions): Promise { ); } - // Derive Solana address if keys are available (for wallet status display) let reuseSolanaAddress: string | undefined; if (solanaPrivateKeyBytes) { const { createKeyPairSignerFromPrivateKeyBytes } = await import("@solana/kit"); @@ -1518,13 +1575,26 @@ export async function startProxy(options: ProxyOptions): Promise { reuseSolanaAddress = solanaSigner.address; } - // Use chain-appropriate balance monitor (lazy import to avoid loading @solana/kit on Base chain) - let balanceMonitor: AnyBalanceMonitor; + let reuseBalanceMonitor: AnyBalanceMonitor; if (paymentChain === "solana" && reuseSolanaAddress) { const { SolanaBalanceMonitor } = await import("./solana-balance.js"); - balanceMonitor = new SolanaBalanceMonitor(reuseSolanaAddress); + reuseBalanceMonitor = new SolanaBalanceMonitor(reuseSolanaAddress); } else { - balanceMonitor = new BalanceMonitor(account.address); + if (existingProxyData.paymentAssets?.length) { + activeBasePaymentAssets = existingProxyData.paymentAssets; + } + const selectedPaymentAssetId = + typeof existingProxyData.selectedPaymentAsset === "string" + ? existingProxyData.selectedPaymentAsset.toLowerCase() + : existingProxyData.selectedPaymentAsset?.asset?.toLowerCase(); + const selectedPaymentAsset = selectedPaymentAssetId + ? activeBasePaymentAssets.find((asset) => asset.asset.toLowerCase() === selectedPaymentAssetId) + : undefined; + if (selectedPaymentAsset) { + activeBasePaymentAsset = selectedPaymentAsset; + lastSelectedBasePaymentAsset = selectedPaymentAsset; + } + reuseBalanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset); } options.onReady?.(listenPort); @@ -1532,13 +1602,21 @@ export async function startProxy(options: ProxyOptions): Promise { return { port: listenPort, baseUrl, - walletAddress: existingProxy.wallet, + walletAddress: existingProxyData.wallet, solanaAddress: reuseSolanaAddress, - balanceMonitor, + paymentAsset: paymentChain === "base" ? activeBasePaymentAsset : undefined, + paymentAssets: paymentChain === "base" ? activeBasePaymentAssets : undefined, + balanceMonitor: reuseBalanceMonitor, close: async () => { // No-op: we didn't start this proxy, so we shouldn't close it }, }; + }; + + // Check if a proxy is already running on this port + const existingProxy = await checkExistingProxy(listenPort); + if (existingProxy) { + return buildReuseHandle(existingProxy); } // Create x402 payment client with EVM scheme (always available) @@ -1565,18 +1643,35 @@ export async function startProxy(options: ProxyOptions): Promise { // Log which chain is used for each payment and capture actual payment amount x402.onAfterPaymentCreation(async (context) => { const network = context.selectedRequirements.network; + if (network.startsWith("eip155")) { + activeBasePaymentAssets = + (await fetchBasePaymentAssets(apiBase).catch(() => undefined)) ?? activeBasePaymentAssets; + const refreshedActiveAsset = activeBasePaymentAssets.find( + (asset) => asset.asset.toLowerCase() === activeBasePaymentAsset.asset.toLowerCase(), + ); + if (refreshedActiveAsset) { + activeBasePaymentAsset = refreshedActiveAsset; + } + } const chain = network.startsWith("eip155") ? "Base (EVM)" : network.startsWith("solana") ? "Solana" : network; - // Capture actual payment amount in USD (amount is in USDC micro units, 6 decimals) - const amountMicros = parseInt(context.selectedRequirements.amount || "0", 10); - const amountUsd = amountMicros / 1_000_000; + const amountRaw = BigInt(context.selectedRequirements.amount || "0"); + const selectedRequirementsWithDecimals = context.selectedRequirements as { decimals?: number }; + const amountDecimals = + selectedRequirementsWithDecimals.decimals ?? + (network.startsWith("eip155") ? activeBasePaymentAsset.decimals : 6); + const amountUsdText = formatStableAmount(amountRaw, amountDecimals); + const amountUsd = Number.parseFloat(amountUsdText); // Write to request-scoped store (if available) const store = paymentStore.getStore(); - if (store) store.amountUsd = amountUsd; - console.log(`[ClawRouter] Payment signed on ${chain} (${network}) — $${amountUsd.toFixed(6)}`); + if (store) { + store.amountUsd = amountUsd; + store.amountUsdText = amountUsdText; + } + console.log(`[ClawRouter] Payment signed on ${chain} (${network}) — $${amountUsdText}`); }); const payFetch = createPayFetchWithPreAuth(fetch, x402, undefined, { @@ -1591,7 +1686,7 @@ export async function startProxy(options: ProxyOptions): Promise { const { SolanaBalanceMonitor } = await import("./solana-balance.js"); balanceMonitor = new SolanaBalanceMonitor(solanaAddress); } else { - balanceMonitor = new BalanceMonitor(account.address); + balanceMonitor = new BalanceMonitor(account.address, activeBasePaymentAsset); } // Build router options (100% local — no external API calls for routing) @@ -1619,7 +1714,7 @@ export async function startProxy(options: ProxyOptions): Promise { const server = createServer((req: IncomingMessage, res: ServerResponse) => { // Wrap in paymentStore.run() so x402 hook can write actual payment amount per-request - paymentStore.run({ amountUsd: 0 }, async () => { + paymentStore.run({ amountUsd: 0, amountUsdText: "0.000000" }, async () => { // Add stream error handlers to prevent server crashes req.on("error", (err) => { console.error(`[ClawRouter] Request stream error: ${err.message}`); @@ -1657,16 +1752,45 @@ export async function startProxy(options: ProxyOptions): Promise { wallet: account.address, paymentChain, }; + if (paymentChain === "base") { + response.paymentAsset = activeBasePaymentAsset.asset; + response.paymentAssetSymbol = activeBasePaymentAsset.symbol; + response.paymentAssetDecimals = activeBasePaymentAsset.decimals; + response.paymentAssets = activeBasePaymentAssets; + response.selectedPaymentAsset = lastSelectedBasePaymentAsset.asset; + response.selectedPaymentAssetSymbol = lastSelectedBasePaymentAsset.symbol; + } if (solanaAddress) { response.solana = solanaAddress; } if (full) { try { - const balanceInfo = await balanceMonitor.checkBalance(); - response.balance = balanceInfo.balanceUSD; - response.isLow = balanceInfo.isLow; - response.isEmpty = balanceInfo.isEmpty; + if (paymentChain === "base") { + const assetBalances = await Promise.all( + activeBasePaymentAssets.map(async (asset) => { + const monitor = new BalanceMonitor(account.address, asset); + const balanceInfo = await monitor.checkBalance(); + return { + asset: asset.asset, + symbol: asset.symbol, + decimals: asset.decimals, + balance: balanceInfo.balanceUSD, + isLow: balanceInfo.isLow, + isEmpty: balanceInfo.isEmpty, + }; + }), + ); + response.assetBalances = assetBalances; + response.balance = assetBalances[0]?.balance ?? "$0.00"; + response.isLow = assetBalances[0]?.isLow ?? true; + response.isEmpty = assetBalances.every((asset) => asset.isEmpty); + } else { + const balanceInfo = await balanceMonitor.checkBalance(); + response.balance = balanceInfo.balanceUSD; + response.isLow = balanceInfo.isLow; + response.isEmpty = balanceInfo.isEmpty; + } } catch { response.balanceError = "Could not fetch balance"; } @@ -2045,47 +2169,53 @@ export async function startProxy(options: ProxyOptions): Promise { return; } - // Only proxy paths starting with /v1 - if (!req.url?.startsWith("/v1")) { - res.writeHead(404, { "Content-Type": "application/json" }); - res.end(JSON.stringify({ error: "Not found" })); - return; - } + // Only proxy paths starting with /v1 + if (!req.url?.startsWith("/v1")) { + res.writeHead(404, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Not found" })); + return; + } - try { - await proxyRequest( - req, - res, - apiBase, - payFetch, - options, - routerOpts, - deduplicator, - balanceMonitor, - sessionStore, - responseCache, - sessionJournal, - ); - } catch (err) { - const error = err instanceof Error ? err : new Error(String(err)); - options.onError?.(error); + try { + await proxyRequest( + req, + res, + apiBase, + payFetch, + options, + routerOpts, + deduplicator, + balanceMonitor, + sessionStore, + responseCache, + sessionJournal, + () => activeBasePaymentAsset.symbol, + () => activeBasePaymentAssets, + (asset) => { + lastSelectedBasePaymentAsset = asset; + activeBasePaymentAsset = asset; + }, + ); + } catch (err) { + const error = err instanceof Error ? err : new Error(String(err)); + options.onError?.(error); - if (!res.headersSent) { - res.writeHead(502, { "Content-Type": "application/json" }); - res.end( - JSON.stringify({ - error: { message: `Proxy error: ${error.message}`, type: "proxy_error" }, - }), - ); - } else if (!res.writableEnded) { - // Headers already sent (streaming) — send error as SSE event - res.write( - `data: ${JSON.stringify({ error: { message: error.message, type: "proxy_error" } })}\n\n`, - ); - res.write("data: [DONE]\n\n"); - res.end(); - } + if (!res.headersSent) { + res.writeHead(502, { "Content-Type": "application/json" }); + res.end( + JSON.stringify({ + error: { message: `Proxy error: ${error.message}`, type: "proxy_error" }, + }), + ); + } else if (!res.writableEnded) { + // Headers already sent (streaming) — send error as SSE event + res.write( + `data: ${JSON.stringify({ error: { message: error.message, type: "proxy_error" } })}\n\n`, + ); + res.write("data: [DONE]\n\n"); + res.end(); } + } }); // end paymentStore.run() }); @@ -2107,6 +2237,8 @@ export async function startProxy(options: ProxyOptions): Promise { code: "REUSE_EXISTING", wallet: existingProxy2.wallet, existingChain: existingProxy2.paymentChain, + paymentAssets: existingProxy2.paymentAssets, + selectedPaymentAsset: existingProxy2.selectedPaymentAsset, }); return; } @@ -2150,6 +2282,8 @@ export async function startProxy(options: ProxyOptions): Promise { code?: string; wallet?: string; existingChain?: string; + paymentAssets?: BasePaymentAsset[]; + selectedPaymentAsset?: string | BasePaymentAsset; attempt?: number; }; @@ -2163,18 +2297,12 @@ export async function startProxy(options: ProxyOptions): Promise { ); } - // Proxy is running, reuse it - const baseUrl = `http://127.0.0.1:${listenPort}`; - options.onReady?.(listenPort); - return { - port: listenPort, - baseUrl, - walletAddress: error.wallet, - balanceMonitor, - close: async () => { - // No-op: we didn't start this proxy, so we shouldn't close it - }, - }; + return buildReuseHandle({ + wallet: error.wallet, + paymentChain: error.existingChain, + paymentAssets: error.paymentAssets, + selectedPaymentAsset: error.selectedPaymentAsset, + }); } if (error.code === "RETRY") { @@ -2250,6 +2378,8 @@ export async function startProxy(options: ProxyOptions): Promise { baseUrl, walletAddress: account.address, solanaAddress, + paymentAsset: paymentChain === "base" ? activeBasePaymentAsset : undefined, + paymentAssets: paymentChain === "base" ? activeBasePaymentAssets : undefined, balanceMonitor, close: () => new Promise((res, rej) => { @@ -2429,6 +2559,9 @@ async function proxyRequest( sessionStore: SessionStore, responseCache: ResponseCache, sessionJournal: SessionJournal, + getBaseAssetSymbol: () => string, + getBasePaymentAssets: () => BasePaymentAsset[], + onBaseAssetSelected: (asset: BasePaymentAsset) => void, ): Promise { const startTime = Date.now(); @@ -2462,6 +2595,8 @@ async function proxyRequest( let accumulatedContent = ""; // For session journal event extraction let responseInputTokens: number | undefined; let responseOutputTokens: number | undefined; + let requestBalanceMonitor = balanceMonitor; + let requestBasePaymentAsset = getBasePaymentAssets()[0]; const isChatCompletion = req.url?.includes("/chat/completions"); // Extract session ID early for journal operations (header-only at this point) @@ -3436,8 +3571,40 @@ async function proxyRequest( const bufferedCostMicros = (estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100))) / 100n; + if (balanceMonitor instanceof BalanceMonitor) { + const baseAssets = getBasePaymentAssets(); + let selected: + | { + asset: BasePaymentAsset; + monitor: BalanceMonitor; + sufficiency: Awaited>; + } + | undefined; + + for (const asset of baseAssets) { + const monitor = balanceMonitor.getSharedMonitorForAsset(asset); + const sufficiency = await monitor.checkSufficient(bufferedCostMicros); + if (!selected) { + selected = { asset, monitor, sufficiency }; + } + if (sufficiency.sufficient) { + selected = { asset, monitor, sufficiency }; + break; + } + } + + if (selected) { + requestBasePaymentAsset = selected.asset; + requestBalanceMonitor = selected.monitor; + onBaseAssetSelected(selected.asset); + console.log( + `[ClawRouter] Base payment asset selected: ${selected.asset.symbol} (${selected.sufficiency.info.balanceUSD})`, + ); + } + } + // Check balance before proceeding (using buffered amount) - const sufficiency = await balanceMonitor.checkSufficient(bufferedCostMicros); + const sufficiency = await requestBalanceMonitor.checkSufficient(bufferedCostMicros); if (sufficiency.info.isEmpty || !sufficiency.sufficient) { // Wallet is empty or insufficient — fallback to free model @@ -3461,12 +3628,14 @@ async function proxyRequest( options.onLowBalance?.({ balanceUSD: sufficiency.info.balanceUSD, walletAddress: sufficiency.info.walletAddress, + assetSymbol: sufficiency.info.assetSymbol, }); } else if (sufficiency.info.isLow) { // Balance is low but sufficient — warn and proceed options.onLowBalance?.({ balanceUSD: sufficiency.info.balanceUSD, walletAddress: sufficiency.info.walletAddress, + assetSymbol: sufficiency.info.assetSymbol, }); } } @@ -3948,7 +4117,7 @@ async function proxyRequest( continue; } // Free model not in chain — add it and try - if (freeIdx === -1) { + if (freeIdx === -1 && !excludeList.has(FREE_MODEL)) { modelsToTry.push(FREE_MODEL); console.log(`[ClawRouter] Payment error — appending free model: ${FREE_MODEL}`); continue; @@ -4124,7 +4293,10 @@ async function proxyRequest( const errStatus = lastError?.status || 502; // Transform payment errors into user-friendly messages - const transformedErr = transformPaymentError(rawErrBody); + const transformedErr = transformPaymentError(rawErrBody, { + baseAssetSymbol: requestBasePaymentAsset.symbol, + baseAssetDecimals: requestBasePaymentAsset.decimals, + }); if (headersSentEarly) { // Streaming: send error as SSE event @@ -4530,7 +4702,7 @@ async function proxyRequest( // --- Optimistic balance deduction after successful response --- if (estimatedCostMicros !== undefined) { - balanceMonitor.deductEstimated(estimatedCostMicros); + requestBalanceMonitor.deductEstimated(estimatedCostMicros); } // Mark request as completed (for client disconnect cleanup) @@ -4549,7 +4721,7 @@ async function proxyRequest( deduplicator.removeInflight(dedupKey); // Invalidate balance cache on payment failure (might be out of date) - balanceMonitor.invalidate(); + requestBalanceMonitor.invalidate(); // Convert abort error to more descriptive timeout error if (err instanceof Error && err.name === "AbortError") { diff --git a/src/solana-balance.ts b/src/solana-balance.ts index 9f62a06..c34b090 100644 --- a/src/solana-balance.ts +++ b/src/solana-balance.ts @@ -15,6 +15,7 @@ const CACHE_TTL_MS = 30_000; export type SolanaBalanceInfo = { balance: bigint; balanceUSD: string; + assetSymbol: string; isLow: boolean; isEmpty: boolean; walletAddress: string; @@ -102,6 +103,10 @@ export class SolanaBalanceMonitor { return this.walletAddress; } + getAssetSymbol(): string { + return "USDC"; + } + /** * Check native SOL balance (in lamports). Useful for detecting users who * funded with SOL instead of USDC. @@ -171,6 +176,7 @@ export class SolanaBalanceMonitor { return { balance, balanceUSD: `$${dollars.toFixed(2)}`, + assetSymbol: "USDC", isLow: balance < 1_000_000n, isEmpty: balance < 100n, walletAddress: this.walletAddress,